context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Emulation.Hosting
{
using System;
using System.Collections.Generic;
using System.IO;
public sealed class BinaryBlob
{
//
// State
//
private readonly byte[] m_data;
//
// Constructor Methods
//
public BinaryBlob( int size )
{
m_data = new byte[size];
}
public BinaryBlob( byte[] data )
{
m_data = data;
}
//
// Helper Methods
//
public BinaryBlob Extract( int offset ,
int count )
{
if(offset == 0 && count == this.Size)
{
return this;
}
var bb = new BinaryBlob( count );
for(int pos = 0; pos < count; pos++)
{
bb.WriteUInt8( this.ReadUInt8( pos + offset ), pos );
}
return bb;
}
public void Insert( BinaryBlob bb ,
int offset )
{
Insert( bb, offset, bb.Size );
}
public void Insert( BinaryBlob bb ,
int offset ,
int count )
{
for(int pos = 0; pos < count; pos++)
{
this.WriteUInt8( bb.ReadUInt8( pos ), pos + offset );
}
}
//--//
public byte ReadUInt8( int offset )
{
if(offset >= 0 && offset < m_data.Length)
{
return m_data[offset];
}
return 0;
}
public ushort ReadUInt16( int offset )
{
byte partLo = ReadUInt8( offset );
byte partHi = ReadUInt8( offset + sizeof(byte) );
return (ushort)(((uint)partHi << 8) | (uint)partLo);
}
public uint ReadUInt32( int offset )
{
ushort partLo = ReadUInt16( offset );
ushort partHi = ReadUInt16( offset + sizeof(ushort) );
return (((uint)partHi << 16) | (uint)partLo);
}
public ulong ReadUInt64( int offset )
{
uint partLo = ReadUInt32( offset );
uint partHi = ReadUInt32( offset + sizeof(uint) );
return (((ulong)partHi << 32) | (ulong)partLo);
}
public byte[] ReadBlock( int offset ,
int count )
{
var res = new byte[count];
for(int pos = 0; pos < count; pos++)
{
res[pos] = this.ReadUInt8( offset + pos );
}
return res;
}
//--//
public void WriteUInt8( byte val ,
int offset )
{
if(offset >= 0 && offset < m_data.Length)
{
m_data[offset] = val;
}
}
public void WriteUInt16( ushort val ,
int offset )
{
WriteUInt8( (byte) val , offset );
WriteUInt8( (byte)(val >> 8), offset + sizeof(byte) );
}
public void WriteUInt32( uint val ,
int offset )
{
WriteUInt16( (ushort) val , offset );
WriteUInt16( (ushort)(val >> 16), offset + sizeof(ushort) );
}
public void WriteUInt64( ulong val ,
int offset )
{
WriteUInt32( (uint) val , offset );
WriteUInt32( (uint)(val >> 32), offset + sizeof(uint) );
}
//--//
public void WriteBlock( byte[] buf ,
int offset )
{
foreach(var val in buf)
{
WriteUInt8( val, offset++ );
}
}
//--//
public static BinaryBlob Wrap( byte value )
{
var bb = new BinaryBlob( sizeof(byte) );
bb.WriteUInt8( value, 0 );
return bb;
}
public static BinaryBlob Wrap( ushort value )
{
var bb = new BinaryBlob( sizeof(ushort) );
bb.WriteUInt16( value, 0 );
return bb;
}
public static BinaryBlob Wrap( uint value )
{
var bb = new BinaryBlob( sizeof(uint) );
bb.WriteUInt32( value, 0 );
return bb;
}
public static BinaryBlob Wrap( uint valueLo ,
uint valueHi )
{
var bb = new BinaryBlob( sizeof(ulong) );
bb.WriteUInt32( valueLo, 0 );
bb.WriteUInt32( valueHi, 0 + sizeof(uint) );
return bb;
}
public static BinaryBlob Wrap( ulong value )
{
var bb = new BinaryBlob( sizeof(ulong) );
bb.WriteUInt64( value, 0 );
return bb;
}
public static BinaryBlob Wrap( object value )
{
if(value is bool)
{
return Wrap( (byte)((bool)value ? 1 : 0) );
}
if(value is byte)
{
return Wrap( (byte)value );
}
if(value is sbyte)
{
return Wrap( (byte)(sbyte)value );
}
if(value is char)
{
return Wrap( (ushort)(char)value );
}
if(value is short)
{
return Wrap( (ushort)(short)value );
}
if(value is ushort)
{
return Wrap( (ushort)value );
}
if(value is int)
{
return Wrap( (uint)(int)value );
}
if(value is uint)
{
return Wrap( (uint)value );
}
if(value is long)
{
return Wrap( (ulong)(long)value );
}
if(value is ulong)
{
return Wrap( (ulong)value );
}
if(value is float)
{
return Wrap( DataConversion.GetFloatAsBytes( (float)value ));
}
if(value is double)
{
return Wrap( DataConversion.GetDoubleAsBytes( (double)value ));
}
return null;
}
//
// Access Methods
//
public byte[] Payload
{
get
{
return m_data;
}
}
public int Size
{
get
{
return m_data.Length;
}
}
}
}
| |
// ScriptMetadata.cs
// Script#/Libraries/CoreLib
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices {
/// <summary>
/// This attribute can be placed on types in system script assemblies that should not
/// be imported. It is only meant to be used within mscorlib.dll.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
[NonScriptable]
public sealed class NonScriptableAttribute : Attribute {
}
/// <summary>
/// This attribute can be placed on types that should not be emitted into generated
/// script, as they represent existing script or native types. All members without another naming attribute are considered to use [PreserveName].
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct)]
[NonScriptable]
public sealed class ImportedAttribute : Attribute {
/// <summary>
/// Indicates that the type obeys the Saltarelle type system. If false (the default), the type is ignored in inheritance lists, casts to it is a no-op, and Object will be used if the type is used as a generic argument.
/// The default is false. Requiring this to be set should be very uncommon.
/// </summary>
public bool ObeysTypeSystem { get; set; }
/// <summary>
/// Code used to check whether an object is of this type. Can use the placeholder {this} to reference the object being checked, as well as all type parameter for the type.
/// </summary>
public string TypeCheckCode { get; set; }
}
/// <summary>
/// Marks an assembly as a script assembly that can be used with Script#.
/// Additionally, each script must have a unique name that can be used as
/// a dependency name.
/// This name is also used to generate unique names for internal types defined
/// within the assembly. The ScriptQualifier attribute can be used to provide a
/// shorter name if needed.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
[NonScriptable]
public sealed class ScriptAssemblyAttribute : Attribute {
public ScriptAssemblyAttribute(string name) {
Name = name;
}
public string Name { get; private set; }
}
/// <summary>
/// Provides a prefix to use when generating types internal to this assembly so that
/// they can be unique within a given a script namespace.
/// The specified prefix overrides the script name provided in the ScriptAssembly
/// attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
[NonScriptable]
public sealed class ScriptQualifierAttribute : Attribute {
public ScriptQualifierAttribute(string prefix) {
Prefix = prefix;
}
public string Prefix { get; private set; }
}
/// <summary>
/// This attribute indicates that the namespace of type within a system assembly
/// should be ignored at script generation time. It is useful for creating namespaces
/// for the purpose of c# code that don't exist at runtime.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Struct, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class IgnoreNamespaceAttribute : Attribute {
}
/// <summary>
/// Specifies the namespace that should be used in generated script. The script namespace
/// is typically a short name, that is often shared across multiple assemblies.
/// The developer is responsible for ensuring that public types across assemblies that share
/// a script namespace are unique.
/// For internal types, the ScriptQualifier attribute can be used to provide a short prefix
/// to generate unique names.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)]
[NonScriptable]
public sealed class ScriptNamespaceAttribute : Attribute {
public ScriptNamespaceAttribute(string name) {
Name = name;
}
public string Name { get; private set; }
}
/// <summary>
/// This attribute can be placed on a static class that only contains static string
/// fields representing a set of resource strings.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
[NonScriptable]
public sealed class ResourcesAttribute : Attribute {
}
/// <summary>
/// This attribute turns methods on a static class as global methods in the generated
/// script. Note that the class must be static, and must contain only methods.
/// </summary>
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
[NonScriptable]
public sealed class GlobalMethodsAttribute : Attribute {
}
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
[NonScriptable]
public sealed class MixinAttribute : Attribute {
public MixinAttribute(string expression) {
Expression = expression;
}
public string Expression { get; private set; }
}
/// <summary>
/// This attribute marks an enumeration type within a system assembly as as a set of
/// names. Rather than the specific value, the name of the enumeration field is
/// used as a string.
/// </summary>
[AttributeUsage(AttributeTargets.Enum, Inherited = false, AllowMultiple = false)]
[NonScriptable]
public sealed class NamedValuesAttribute : Attribute {
}
/// <summary>
/// This attribute marks an enumeration type within a system assembly as as a set of
/// numeric values. Rather than the enum field, the value of the enumeration field is
/// used as a literal.
/// </summary>
[AttributeUsage(AttributeTargets.Enum, Inherited = false, AllowMultiple = false)]
[NonScriptable]
public sealed class NumericValuesAttribute : Attribute {
}
/// <summary>
/// This attribute allows defining an alternate method signature that is not generated
/// into script, but can be used for defining overloads to enable optional parameter semantics
/// for a method. It must be applied on a method defined as extern, since an alternate signature
/// method does not contain an actual method body.
/// </summary>
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class AlternateSignatureAttribute : Attribute {
}
/// <summary>
/// This attribute denotes a C# property that manifests like a field in the generated
/// JavaScript (i.e. is not accessed via get/set methods). This is really meant only
/// for use when defining OM corresponding to native objects exposed to script.
/// If no other name is specified (and the property is not an indexer), the field is treated as if it were decorated with a [PreserveName] attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class IntrinsicPropertyAttribute : Attribute {
}
/// <summary>
/// Allows specifying the name to use for a type or member in the generated script.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Event | AttributeTargets.Constructor, Inherited = false, AllowMultiple = false)]
[NonScriptable]
public sealed class ScriptNameAttribute : Attribute {
public ScriptNameAttribute(string name) {
Name = name;
}
public string Name { get; private set; }
}
/// <summary>
/// This attribute allows suppressing the default behavior of converting
/// member names to camel-cased equivalents in the generated JavaScript.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class PreserveCaseAttribute : Attribute {
}
/// <summary>
/// This attribute allows suppressing the default behavior of converting
/// member names of attached type to camel-cased equivalents in the generated JavaScript.
/// When applied to an assembly, all types in the assembly are considered to have this
/// attribute by default</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Assembly, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class PreserveMemberCaseAttribute : Attribute {
public PreserveMemberCaseAttribute() {
Preserve = true;
}
public PreserveMemberCaseAttribute(bool preserve) {
Preserve = preserve;
}
public bool Preserve { get; private set; }
}
/// <summary>
/// This attribute allows suppressing the default behavior of minimizing
/// private type names and member names in the generated JavaScript.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class PreserveNameAttribute : Attribute {
}
/// <summary>
/// This attribute allows public symbols inside an assembly to be minimized, in addition to non-public ones, when generating release scripts.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
[NonScriptable]
public sealed class MinimizePublicNamesAttribute : Attribute {
}
/// <summary>
/// This attribute allows specifying a script name for an imported method.
/// The method is interpreted as a global method. As a result it this attribute
/// only applies to static methods.
/// </summary>
// REVIEW: Eventually do we want to support this on properties/field and instance methods as well?
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class ScriptAliasAttribute : Attribute {
public ScriptAliasAttribute(string alias) {
Alias = alias;
}
public string Alias { get; private set; }
}
/// <summary>
/// This attributes causes a method to not be invoked. The method must either be a static method with one argument (in case Foo.M(x) will become x), or an instance method with no arguments (in which x.M() will become x).
/// Can also be applied to a constructor, in which case the constructor will not be called if used as an initializer (": base()" or ": this()").
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class ScriptSkipAttribute : Attribute {
}
/// <summary>
/// The method is implemented as inline code, eg Debugger.Break() => debugger. Can use the parameters {this} (for instance methods), as well as all typenames and argument names in braces (eg. {arg0}, {TArg0}).
/// If a parameter name is preceeded by an @ sign, {@arg0}, that argument must be a literal string during invocation, and the supplied string will be inserted as an identifier into the script (eg '{this}.set_{@arg0}({arg1})' can transform the call 'c.F("MyProp", v)' to 'c.set_MyProp(v)'.
/// If a parameter name is preceeded by an asterisk {*arg} that parameter must be a param array, and all invocations of the method must use the expanded invocation form. The entire array supplied for the parameter will be inserted into the call. Pretend that the parameter is a normal parameter, and commas will be inserted or omitted at the correct locations.
/// The format string can also use identifiers starting with a dollar {$Namespace.Name} to construct type references. The name must be the fully qualified type name in this case.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class InlineCodeAttribute : Attribute {
public InlineCodeAttribute(string code) {
Code = code;
}
public string Code { get; private set; }
/// <summary>
/// If set, a method with this name will be generated from the method source.
/// </summary>
public string GeneratedMethodName { get; set; }
/// <summary>
/// This code is used when the method is invoked non-virtually (eg. in a base.Method() call).
/// </summary>
public string NonVirtualCode { get; set; }
}
/// <summary>
/// This attribute specifies that a static method should be treated as an instance method on its first argument. This means that <c>MyClass.Method(x, a, b)</c> will be transformed to <c>x.Method(a, b)</c>.
/// If no other name-preserving attribute is used on the member, it will be treated as if it were decorated with a [PreserveNameAttribute].
/// Useful for extension methods.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class InstanceMethodOnFirstArgumentAttribute : Attribute {
}
/// <summary>
/// This attribute specifies that a generic type or method should have script generated as if it was a non-generic one. Any uses of the type arguments inside the method (eg. <c>typeof(T)</c>, or calling another generic method with T as a type argument) will cause runtime errors.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class IncludeGenericArgumentsAttribute : Attribute {
public IncludeGenericArgumentsAttribute() {
Include = true;
}
public IncludeGenericArgumentsAttribute(bool include) {
Include = include;
}
public bool Include { get; private set; }
}
/// <summary>
/// This enum defines the possibilities for default values for generic argument handling in an assembly.
/// </summary>
[NonScriptable]
public enum GenericArgumentsDefault {
/// <summary>
/// Include generic arguments for all types that are not [Imported]
/// </summary>
IncludeExceptImported,
/// <summary>
/// Ignore generic arguments by default (this is the default)
/// </summary>
Ignore,
/// <summary>
/// Require an <see cref="IncludeGenericArgumentsAttribute"/> for all generic types/methods, excepts those that are imported, which will default to ignore their generic arguments.
/// </summary>
RequireExplicitSpecification,
}
/// <summary>
/// This attribute indicates whether generic arguments for types and methods are included, but can always be overridden by specifying an <see cref="IncludeGenericArgumentsAttribute"/> on types or methods.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly)]
[NonScriptable]
public sealed class IncludeGenericArgumentsDefaultAttribute : Attribute {
public GenericArgumentsDefault TypeDefault { get; set; }
public GenericArgumentsDefault MethodDefault { get; set; }
}
/// <summary>
/// This attribute indicates that a user-defined operator should be compiled as if it were builtin (eg. op_Addition(a, b) => a + b). It can only be used on non-conversion operator methods.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class IntrinsicOperatorAttribute : Attribute {
}
/// <summary>
/// This attribute can be applied to a method with a "params" parameter to make the param array be expanded in script (eg. given 'void F(int a, params int[] b)', the invocation 'F(1, 2, 3)' will be translated to 'F(1, [2, 3])' without this attribute, but 'F(1, 2, 3)' with this attribute.
/// Methods with this attribute can only be invoked in the expanded form.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Delegate, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class ExpandParamsAttribute : Attribute {
}
/// <summary>
/// Indicates that the Javascript 'this' should appear as the first argument to the delegate.
/// </summary>
[AttributeUsage(AttributeTargets.Delegate)]
[NonScriptable]
public sealed class BindThisToFirstParameterAttribute : Attribute {
}
/// <summary>
/// If this attribute is applied to a constructor for a serializable type, it means that the constructor will not be called, but rather an object initializer will be created. Eg. 'new MyRecord(1, "X")' can become '{ a: 1, b: 'X' }'.
/// All parameters must have a field or property with the same (case-insensitive) name, of the same type.
/// This attribute is implicit on constructors of imported serializable types.
/// </summary>
[AttributeUsage(AttributeTargets.Constructor, Inherited = true, AllowMultiple = false)]
[NonScriptable]
public sealed class ObjectLiteralAttribute : Attribute {
}
/// <summary>
/// This attribute can be specified on an assembly to specify additional compatibility options to help migrating from Script#.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly)]
[NonScriptable]
public sealed class ScriptSharpCompatibilityAttribute : Attribute {
/// <summary>
/// If true, code will not be generated for casts of type '(MyClass)someValue'. Code will still be generated for 'someValue is MyClass' and 'someValue as MyClass'.
/// </summary>
public bool OmitDowncasts { get; set; }
/// <summary>
/// If true, code will not be generated to verify that a nullable value is not null before converting it to its underlying type.
/// </summary>
public bool OmitNullableChecks { get; set; }
}
/// <summary>
/// If a constructor for a value type takes an instance of this type as a parameter, any attribute applied to that constructor will instead be applied to the default (undeclarable) constructor.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Imported]
public sealed class DummyTypeUsedToAddAttributeToDefaultValueTypeConstructor {
private DummyTypeUsedToAddAttributeToDefaultValueTypeConstructor() {}
}
/// <summary>
/// Specifies that a type is defined in a module, which should be imported by a require() call.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Assembly)]
[NonScriptable]
public sealed class ModuleNameAttribute : Attribute {
public ModuleNameAttribute(string moduleName) {
this.ModuleName = moduleName;
}
public string ModuleName { get; private set; }
}
/// <summary>
/// When specified on an assembly, Javascript that adheres to the AMD pattern (require/define) will be generated.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly)]
[NonScriptable]
public sealed class AsyncModuleAttribute : Attribute {
}
/// <summary>
/// Can be applied to a GetEnumerator() method to indicate that that array-style enumeration should be used.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
[NonScriptable]
public sealed class EnumerateAsArrayAttribute : Attribute {
}
/// <summary>
/// Can be applied to a const field to indicate that the literal value of the constant should always be used instead of the symbolic field name.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
[NonScriptable]
public sealed class InlineConstantAttribute : Attribute {
}
/// <summary>
/// Can be applied to a member to indicate that metadata for the member should be included in the compiled script.
/// </summary>
[AttributeUsage(AttributeTargets.All)]
[NonScriptable]
public sealed class ReflectableAttribute : Attribute {
public bool Reflectable { get; private set; }
public ReflectableAttribute() {
Reflectable = true;
}
public ReflectableAttribute(bool reflectable) {
Reflectable = reflectable;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Linq;
using Android.App;
using Android.Content;
using Android.Content.Res;
using Android.OS;
using Android.Views;
using Android.Widget;
namespace Xamarin.Forms.Platform.Android
{
public class FormsApplicationActivity : Activity, IDeviceInfoProvider, IStartActivityForResult
{
public delegate bool BackButtonPressedEventHandler(object sender, EventArgs e);
readonly ConcurrentDictionary<int, Action<Result, Intent>> _activityResultCallbacks = new ConcurrentDictionary<int, Action<Result, Intent>>();
Application _application;
Platform _canvas;
AndroidApplicationLifecycleState _currentState;
LinearLayout _layout;
int _nextActivityResultCallbackKey;
AndroidApplicationLifecycleState _previousState;
protected FormsApplicationActivity()
{
_previousState = AndroidApplicationLifecycleState.Uninitialized;
_currentState = AndroidApplicationLifecycleState.Uninitialized;
}
public event EventHandler ConfigurationChanged;
int IStartActivityForResult.RegisterActivityResultCallback(Action<Result, Intent> callback)
{
int requestCode = _nextActivityResultCallbackKey;
while (!_activityResultCallbacks.TryAdd(requestCode, callback))
{
_nextActivityResultCallbackKey += 1;
requestCode = _nextActivityResultCallbackKey;
}
_nextActivityResultCallbackKey += 1;
return requestCode;
}
void IStartActivityForResult.UnregisterActivityResultCallback(int requestCode)
{
Action<Result, Intent> callback;
_activityResultCallbacks.TryRemove(requestCode, out callback);
}
public static event BackButtonPressedEventHandler BackPressed;
public override void OnBackPressed()
{
if (BackPressed != null && BackPressed(this, EventArgs.Empty))
return;
base.OnBackPressed();
}
public override void OnConfigurationChanged(Configuration newConfig)
{
base.OnConfigurationChanged(newConfig);
EventHandler handler = ConfigurationChanged;
if (handler != null)
handler(this, new EventArgs());
}
// FIXME: THIS SHOULD NOT BE MANDATORY
// or
// This should be specified in an interface and formalized, perhaps even provide a stock AndroidActivity users
// can derive from to avoid having to do any work.
public override bool OnOptionsItemSelected(IMenuItem item)
{
if (item.ItemId == global::Android.Resource.Id.Home)
_canvas.SendHomeClicked();
return base.OnOptionsItemSelected(item);
}
public override bool OnPrepareOptionsMenu(IMenu menu)
{
_canvas.PrepareMenu(menu);
return base.OnPrepareOptionsMenu(menu);
}
[Obsolete("Please use protected LoadApplication (Application app) instead")]
public void SetPage(Page page)
{
var application = new DefaultApplication { MainPage = page };
LoadApplication(application);
}
protected void LoadApplication(Application application)
{
if (application == null)
throw new ArgumentNullException("application");
_application = application;
Xamarin.Forms.Application.Current = application;
application.PropertyChanged += AppOnPropertyChanged;
SetMainPage();
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
Action<Result, Intent> callback;
if (_activityResultCallbacks.TryGetValue(requestCode, out callback))
callback(resultCode, data);
}
protected override void OnCreate(Bundle savedInstanceState)
{
Window.RequestFeature(WindowFeatures.IndeterminateProgress);
base.OnCreate(savedInstanceState);
_layout = new LinearLayout(BaseContext);
SetContentView(_layout);
Xamarin.Forms.Application.ClearCurrent();
_previousState = _currentState;
_currentState = AndroidApplicationLifecycleState.OnCreate;
OnStateChanged();
}
protected override void OnDestroy()
{
// may never be called
base.OnDestroy();
MessagingCenter.Unsubscribe<Page, AlertArguments>(this, Page.AlertSignalName);
MessagingCenter.Unsubscribe<Page, bool>(this, Page.BusySetSignalName);
MessagingCenter.Unsubscribe<Page, ActionSheetArguments>(this, Page.ActionSheetSignalName);
if (_canvas != null)
((IDisposable)_canvas).Dispose();
}
protected override void OnPause()
{
_layout.HideKeyboard(true);
// Stop animations or other ongoing actions that could consume CPU
// Commit unsaved changes, build only if users expect such changes to be permanently saved when thy leave such as a draft email
// Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources that may affect battery life when your activity is paused.
// Avoid writing to permanent storage and CPU intensive tasks
base.OnPause();
_previousState = _currentState;
_currentState = AndroidApplicationLifecycleState.OnPause;
OnStateChanged();
}
protected override void OnRestart()
{
base.OnRestart();
_previousState = _currentState;
_currentState = AndroidApplicationLifecycleState.OnRestart;
OnStateChanged();
}
protected override void OnResume()
{
// counterpart to OnPause
base.OnResume();
_previousState = _currentState;
_currentState = AndroidApplicationLifecycleState.OnResume;
OnStateChanged();
}
protected override void OnStart()
{
base.OnStart();
_previousState = _currentState;
_currentState = AndroidApplicationLifecycleState.OnStart;
OnStateChanged();
}
// Scenarios that stop and restart you app
// -- Switches from your app to another app, activity restarts when clicking on the app again.
// -- Action in your app that starts a new Activity, the current activity is stopped and the second is created, pressing back restarts the activity
// -- The user recieves a phone call while using your app on his or her phone
protected override void OnStop()
{
// writing to storage happens here!
// full UI obstruction
// users focus in another activity
// perform heavy load shutdown operations
// clean up resources
// clean up everything that may leak memory
base.OnStop();
_previousState = _currentState;
_currentState = AndroidApplicationLifecycleState.OnStop;
OnStateChanged();
}
void AppOnPropertyChanged(object sender, PropertyChangedEventArgs args)
{
if (args.PropertyName == "MainPage")
InternalSetPage(_application.MainPage);
}
void InternalSetPage(Page page)
{
if (!Forms.IsInitialized)
throw new InvalidOperationException("Call Forms.Init (Activity, Bundle) before this");
if (_canvas != null)
{
_canvas.SetPage(page);
return;
}
var busyCount = 0;
MessagingCenter.Subscribe(this, Page.BusySetSignalName, (Page sender, bool enabled) =>
{
busyCount = Math.Max(0, enabled ? busyCount + 1 : busyCount - 1);
if (!Forms.SupportsProgress)
return;
SetProgressBarIndeterminate(true);
UpdateProgressBarVisibility(busyCount > 0);
});
UpdateProgressBarVisibility(busyCount > 0);
MessagingCenter.Subscribe(this, Page.AlertSignalName, (Page sender, AlertArguments arguments) =>
{
AlertDialog alert = new AlertDialog.Builder(this).Create();
alert.SetTitle(arguments.Title);
alert.SetMessage(arguments.Message);
if (arguments.Accept != null)
alert.SetButton((int)DialogButtonType.Positive, arguments.Accept, (o, args) => arguments.SetResult(true));
alert.SetButton((int)DialogButtonType.Negative, arguments.Cancel, (o, args) => arguments.SetResult(false));
alert.CancelEvent += (o, args) => { arguments.SetResult(false); };
alert.Show();
});
MessagingCenter.Subscribe(this, Page.ActionSheetSignalName, (Page sender, ActionSheetArguments arguments) =>
{
var builder = new AlertDialog.Builder(this);
builder.SetTitle(arguments.Title);
string[] items = arguments.Buttons.ToArray();
builder.SetItems(items, (sender2, args) => { arguments.Result.TrySetResult(items[args.Which]); });
if (arguments.Cancel != null)
builder.SetPositiveButton(arguments.Cancel, delegate { arguments.Result.TrySetResult(arguments.Cancel); });
if (arguments.Destruction != null)
builder.SetNegativeButton(arguments.Destruction, delegate { arguments.Result.TrySetResult(arguments.Destruction); });
AlertDialog dialog = builder.Create();
builder.Dispose();
//to match current functionality of renderer we set cancelable on outside
//and return null
dialog.SetCanceledOnTouchOutside(true);
dialog.CancelEvent += (sender3, e) => { arguments.SetResult(null); };
dialog.Show();
});
_canvas = new Platform(this);
if (_application != null)
_application.Platform = _canvas;
_canvas.SetPage(page);
_layout.AddView(_canvas.GetViewGroup());
}
async void OnStateChanged()
{
if (_application == null)
return;
if (_previousState == AndroidApplicationLifecycleState.OnCreate && _currentState == AndroidApplicationLifecycleState.OnStart)
_application.SendStart();
else if (_previousState == AndroidApplicationLifecycleState.OnStop && _currentState == AndroidApplicationLifecycleState.OnRestart)
_application.SendResume();
else if (_previousState == AndroidApplicationLifecycleState.OnPause && _currentState == AndroidApplicationLifecycleState.OnStop)
await _application.SendSleepAsync();
}
void SetMainPage()
{
InternalSetPage(_application.MainPage);
}
void UpdateProgressBarVisibility(bool isBusy)
{
if (!Forms.SupportsProgress)
return;
SetProgressBarIndeterminateVisibility(isBusy);
}
internal class DefaultApplication : Application
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Numerics.Tests
{
public partial class parseTest
{
private readonly static int s_samples = 10;
private readonly static Random s_random = new Random(100);
// Invariant culture is commonly used for (de-)serialization and similar to en-US
// Ukrainian (Ukraine) added to catch regressions (issue #1642)
// Current cultue to get additional value out of glob/loc test runs
public static IEnumerable<object[]> Cultures
{
get
{
yield return new object[] { CultureInfo.InvariantCulture };
yield return new object[] { new CultureInfo("uk-UA") };
if (CultureInfo.CurrentCulture.ToString() != "uk-UA")
yield return new object[] { CultureInfo.CurrentCulture };
}
}
[Theory]
[MemberData(nameof(Cultures))]
[OuterLoop]
public static void RunParseToStringTests(CultureInfo culture)
{
RemoteExecutor.Invoke((cultureName) =>
{
byte[] tempByteArray1 = new byte[0];
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(cultureName);
//default style
VerifyDefaultParse(s_random);
//single NumberStyles
VerifyNumberStyles(NumberStyles.None, s_random);
VerifyNumberStyles(NumberStyles.AllowLeadingWhite, s_random);
VerifyNumberStyles(NumberStyles.AllowTrailingWhite, s_random);
VerifyNumberStyles(NumberStyles.AllowLeadingSign, s_random);
VerifyNumberStyles(NumberStyles.AllowTrailingSign, s_random);
VerifyNumberStyles(NumberStyles.AllowParentheses, s_random);
VerifyNumberStyles(NumberStyles.AllowDecimalPoint, s_random);
VerifyNumberStyles(NumberStyles.AllowThousands, s_random);
VerifyNumberStyles(NumberStyles.AllowExponent, s_random);
VerifyNumberStyles(NumberStyles.AllowCurrencySymbol, s_random);
VerifyNumberStyles(NumberStyles.AllowHexSpecifier, s_random);
//composite NumberStyles
VerifyNumberStyles(NumberStyles.Integer, s_random);
VerifyNumberStyles(NumberStyles.HexNumber, s_random);
VerifyNumberStyles(NumberStyles.Number, s_random);
VerifyNumberStyles(NumberStyles.Float, s_random);
VerifyNumberStyles(NumberStyles.Currency, s_random);
VerifyNumberStyles(NumberStyles.Any, s_random);
//invalid number style
// ******InvalidNumberStyles
NumberStyles invalid = (NumberStyles)0x7c00;
AssertExtensions.Throws<ArgumentException>(null, () =>
{
BigInteger.Parse("1", invalid).ToString("d");
});
AssertExtensions.Throws<ArgumentException>(null, () =>
{
BigInteger junk;
BigInteger.TryParse("1", invalid, null, out junk);
Assert.Equal(junk.ToString("d"), "1");
});
//FormatProvider tests
RunFormatProviderParseStrings();
}, culture.ToString()).Dispose();
}
private static void RunFormatProviderParseStrings()
{
NumberFormatInfo nfi = new NumberFormatInfo();
nfi = MarkUp(nfi);
//Currencies
// ***************************
// *** FormatProvider - Currencies
// ***************************
VerifyFormatParse("@ 12#34#56!", NumberStyles.Any, nfi, new BigInteger(123456));
VerifyFormatParse("(12#34#56!@)", NumberStyles.Any, nfi, new BigInteger(-123456));
//Numbers
// ***************************
// *** FormatProvider - Numbers
// ***************************
VerifySimpleFormatParse(">1234567", nfi, new BigInteger(1234567));
VerifySimpleFormatParse("<1234567", nfi, new BigInteger(-1234567));
VerifyFormatParse("123&4567^", NumberStyles.Any, nfi, new BigInteger(1234567));
VerifyFormatParse("123&4567^ <", NumberStyles.Any, nfi, new BigInteger(-1234567));
}
private static void VerifyDefaultParse(Random random)
{
// BasicTests
VerifyFailParseToString(null, typeof(ArgumentNullException));
VerifyFailParseToString(string.Empty, typeof(FormatException));
VerifyParseToString("0");
VerifyParseToString("000");
VerifyParseToString("1");
VerifyParseToString("001");
// SimpleNumbers - Small
for (int i = 0; i < s_samples; i++)
{
VerifyParseToString(GetDigitSequence(1, 10, random));
}
// SimpleNumbers - Large
for (int i = 0; i < s_samples; i++)
{
VerifyParseToString(GetDigitSequence(100, 1000, random));
}
// Leading White
for (int i = 0; i < s_samples; i++)
{
VerifyParseToString("\u0009\u0009\u0009" + GetDigitSequence(1, 100, random));
VerifyParseToString("\u000A\u000A\u000A" + GetDigitSequence(1, 100, random));
VerifyParseToString("\u000B\u000B\u000B" + GetDigitSequence(1, 100, random));
VerifyParseToString("\u000C\u000C\u000C" + GetDigitSequence(1, 100, random));
VerifyParseToString("\u000D\u000D\u000D" + GetDigitSequence(1, 100, random));
VerifyParseToString("\u0020\u0020\u0020" + GetDigitSequence(1, 100, random));
}
// Trailing White
for (int i = 0; i < s_samples; i++)
{
VerifyParseToString(GetDigitSequence(1, 100, random) + "\u0009\u0009\u0009");
VerifyParseToString(GetDigitSequence(1, 100, random) + "\u000A\u000A\u000A");
VerifyParseToString(GetDigitSequence(1, 100, random) + "\u000B\u000B\u000B");
VerifyParseToString(GetDigitSequence(1, 100, random) + "\u000C\u000C\u000C");
VerifyParseToString(GetDigitSequence(1, 100, random) + "\u000D\u000D\u000D");
VerifyParseToString(GetDigitSequence(1, 100, random) + "\u0020\u0020\u0020");
}
// Leading Sign
for (int i = 0; i < s_samples; i++)
{
VerifyParseToString(CultureInfo.CurrentCulture.NumberFormat.NegativeSign + GetDigitSequence(1, 100, random));
VerifyParseToString(CultureInfo.CurrentCulture.NumberFormat.PositiveSign + GetDigitSequence(1, 100, random));
}
// Trailing Sign
for (int i = 0; i < s_samples; i++)
{
VerifyFailParseToString(GetDigitSequence(1, 100, random) + CultureInfo.CurrentCulture.NumberFormat.NegativeSign, typeof(FormatException));
VerifyFailParseToString(GetDigitSequence(1, 100, random) + CultureInfo.CurrentCulture.NumberFormat.PositiveSign, typeof(FormatException));
}
// Parentheses
for (int i = 0; i < s_samples; i++)
{
VerifyFailParseToString("(" + GetDigitSequence(1, 100, random) + ")", typeof(FormatException));
}
// Decimal Point - end
for (int i = 0; i < s_samples; i++)
{
VerifyFailParseToString(GetDigitSequence(1, 100, random) + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, typeof(FormatException));
}
// Decimal Point - middle
for (int i = 0; i < s_samples; i++)
{
VerifyFailParseToString(GetDigitSequence(1, 100, random) + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator + "000", typeof(FormatException));
}
// Decimal Point - non-zero decimal
for (int i = 0; i < s_samples; i++)
{
VerifyFailParseToString(GetDigitSequence(1, 100, random) + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator + GetDigitSequence(20, 25, random), typeof(FormatException));
}
// Thousands
for (int i = 0; i < s_samples; i++)
{
int[] sizes = null;
string seperator = null;
string digits = null;
sizes = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes;
seperator = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator;
digits = GenerateGroups(sizes, seperator, random);
VerifyFailParseToString(digits, typeof(FormatException));
}
// Exponent
for (int i = 0; i < s_samples; i++)
{
VerifyFailParseToString(GetDigitSequence(1, 100, random) + "e" + CultureInfo.CurrentCulture.NumberFormat.PositiveSign + GetDigitSequence(1, 3, random), typeof(FormatException));
VerifyFailParseToString(GetDigitSequence(1, 100, random) + "e" + CultureInfo.CurrentCulture.NumberFormat.NegativeSign + GetDigitSequence(1, 3, random), typeof(FormatException));
}
// Currency Symbol
for (int i = 0; i < s_samples; i++)
{
VerifyFailParseToString(CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol + GetDigitSequence(1, 100, random), typeof(FormatException));
}
// Hex Specifier
for (int i = 0; i < s_samples; i++)
{
VerifyFailParseToString(GetHexDigitSequence(1, 100, random), typeof(FormatException));
}
// Invalid Chars
for (int i = 0; i < s_samples; i++)
{
VerifyFailParseToString(GetDigitSequence(1, 50, random) + GetRandomInvalidChar(random) + GetDigitSequence(1, 50, random), typeof(FormatException));
}
}
private static void VerifyNumberStyles(NumberStyles ns, Random random)
{
VerifyParseToString(null, ns, false, null);
VerifyParseToString(string.Empty, ns, false);
VerifyParseToString("0", ns, true);
VerifyParseToString("000", ns, true);
VerifyParseToString("1", ns, true);
VerifyParseToString("001", ns, true);
// SimpleNumbers - Small
for (int i = 0; i < s_samples; i++)
{
VerifyParseToString(GetDigitSequence(1, 10, random), ns, true);
}
// SimpleNumbers - Large
for (int i = 0; i < s_samples; i++)
{
VerifyParseToString(GetDigitSequence(100, 1000, random), ns, true);
}
// Leading White
for (int i = 0; i < s_samples; i++)
{
VerifyParseToString("\u0009\u0009\u0009" + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowLeadingWhite) != 0));
VerifyParseToString("\u000A\u000A\u000A" + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowLeadingWhite) != 0));
VerifyParseToString("\u000B\u000B\u000B" + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowLeadingWhite) != 0));
VerifyParseToString("\u000C\u000C\u000C" + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowLeadingWhite) != 0));
VerifyParseToString("\u000D\u000D\u000D" + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowLeadingWhite) != 0));
VerifyParseToString("\u0020\u0020\u0020" + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowLeadingWhite) != 0));
}
// Trailing White
for (int i = 0; i < s_samples; i++)
{
VerifyParseToString(GetDigitSequence(1, 100, random) + "\u0009\u0009\u0009", ns, FailureNotExpectedForTrailingWhite(ns, false));
VerifyParseToString(GetDigitSequence(1, 100, random) + "\u000A\u000A\u000A", ns, FailureNotExpectedForTrailingWhite(ns, false));
VerifyParseToString(GetDigitSequence(1, 100, random) + "\u000B\u000B\u000B", ns, FailureNotExpectedForTrailingWhite(ns, false));
VerifyParseToString(GetDigitSequence(1, 100, random) + "\u000C\u000C\u000C", ns, FailureNotExpectedForTrailingWhite(ns, false));
VerifyParseToString(GetDigitSequence(1, 100, random) + "\u000D\u000D\u000D", ns, FailureNotExpectedForTrailingWhite(ns, false));
VerifyParseToString(GetDigitSequence(1, 100, random) + "\u0020\u0020\u0020", ns, FailureNotExpectedForTrailingWhite(ns, true));
}
// Leading Sign
for (int i = 0; i < s_samples; i++)
{
VerifyParseToString(CultureInfo.CurrentCulture.NumberFormat.NegativeSign + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowLeadingSign) != 0));
VerifyParseToString(CultureInfo.CurrentCulture.NumberFormat.PositiveSign + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowLeadingSign) != 0));
}
// Trailing Sign
for (int i = 0; i < s_samples; i++)
{
VerifyParseToString(GetDigitSequence(1, 100, random) + CultureInfo.CurrentCulture.NumberFormat.NegativeSign, ns, ((ns & NumberStyles.AllowTrailingSign) != 0));
VerifyParseToString(GetDigitSequence(1, 100, random) + CultureInfo.CurrentCulture.NumberFormat.PositiveSign, ns, ((ns & NumberStyles.AllowTrailingSign) != 0));
}
// Parentheses
for (int i = 0; i < s_samples; i++)
{
VerifyParseToString("(" + GetDigitSequence(1, 100, random) + ")", ns, ((ns & NumberStyles.AllowParentheses) != 0));
}
// Decimal Point - end
for (int i = 0; i < s_samples; i++)
{
VerifyParseToString(GetDigitSequence(1, 100, random) + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, ns, ((ns & NumberStyles.AllowDecimalPoint) != 0));
}
// Decimal Point - middle
for (int i = 0; i < s_samples; i++)
{
string digits = GetDigitSequence(1, 100, random);
VerifyParseToString(digits + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator + "000", ns, ((ns & NumberStyles.AllowDecimalPoint) != 0), digits);
}
// Decimal Point - non-zero decimal
for (int i = 0; i < s_samples; i++)
{
string digits = GetDigitSequence(1, 100, random);
VerifyParseToString(digits + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator + GetDigitSequence(20, 25, random), ns, false, digits);
}
// Thousands
for (int i = 0; i < s_samples; i++)
{
int[] sizes = null;
string seperator = null;
string digits = null;
sizes = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes;
seperator = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator;
digits = GenerateGroups(sizes, seperator, random);
VerifyParseToString(digits, ns, ((ns & NumberStyles.AllowThousands) != 0));
}
// Exponent
for (int i = 0; i < s_samples; i++)
{
string digits = GetDigitSequence(1, 100, random);
string exp = GetDigitSequence(1, 3, random);
int expValue = int.Parse(exp);
string zeros = new string('0', expValue);
//Positive Exponents
VerifyParseToString(digits + "e" + CultureInfo.CurrentCulture.NumberFormat.PositiveSign + exp, ns, ((ns & NumberStyles.AllowExponent) != 0), digits + zeros);
//Negative Exponents
bool valid = ((ns & NumberStyles.AllowExponent) != 0);
for (int j = digits.Length; (valid && (j > 0) && (j > digits.Length - expValue)); j--)
{
if (digits[j - 1] != '0')
{
valid = false;
}
}
if (digits.Length - int.Parse(exp) > 0)
{
VerifyParseToString(digits + "e" + CultureInfo.CurrentCulture.NumberFormat.NegativeSign + exp, ns, valid, digits.Substring(0, digits.Length - int.Parse(exp)));
}
else
{
VerifyParseToString(digits + "e" + CultureInfo.CurrentCulture.NumberFormat.NegativeSign + exp, ns, valid, "0");
}
}
// Currency Symbol
for (int i = 0; i < s_samples; i++)
{
VerifyParseToString(CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowCurrencySymbol) != 0));
}
// Hex Specifier
for (int i = 0; i < s_samples; i++)
{
VerifyParseToString(GetHexDigitSequence(1, 15, random) + "A", ns, ((ns & NumberStyles.AllowHexSpecifier) != 0));
}
// Invalid Chars
for (int i = 0; i < s_samples; i++)
{
VerifyParseToString(GetDigitSequence(1, 100, random) + GetRandomInvalidChar(random) + GetDigitSequence(1, 10, random), ns, false);
}
}
private static void VerifyParseToString(string num1)
{
BigInteger test;
Eval(BigInteger.Parse(num1), Fix(num1.Trim()));
Assert.True(BigInteger.TryParse(num1, out test));
Eval(test, Fix(num1.Trim()));
}
private static void VerifyFailParseToString(string num1, Type expectedExceptionType)
{
BigInteger test;
Assert.False(BigInteger.TryParse(num1, out test), string.Format("Expected TryParse to fail on {0}", num1));
if (num1 == null)
{
Assert.Throws<ArgumentNullException>(() => { BigInteger.Parse(num1).ToString("d"); });
}
else
{
Assert.Throws<FormatException>(() => { BigInteger.Parse(num1).ToString("d"); });
}
}
private static void VerifyParseToString(string num1, NumberStyles ns, bool failureNotExpected)
{
VerifyParseToString(num1, ns, failureNotExpected, Fix(num1.Trim(), ((ns & NumberStyles.AllowHexSpecifier) != 0), failureNotExpected));
}
static partial void VerifyParseSpanToString(string num1, NumberStyles ns, bool failureNotExpected, string expected);
private static void VerifyParseToString(string num1, NumberStyles ns, bool failureNotExpected, string expected)
{
BigInteger test;
if (failureNotExpected)
{
Eval(BigInteger.Parse(num1, ns), expected);
Assert.True(BigInteger.TryParse(num1, ns, null, out test));
Eval(test, expected);
}
else
{
if (num1 == null)
{
Assert.Throws<ArgumentNullException>(() => { BigInteger.Parse(num1, ns); });
}
else
{
Assert.Throws<FormatException>(() => { BigInteger.Parse(num1, ns); });
}
Assert.False(BigInteger.TryParse(num1, ns, null, out test), string.Format("Expected TryParse to fail on {0}", num1));
}
if (num1 != null)
{
VerifyParseSpanToString(num1, ns, failureNotExpected, expected);
}
}
static partial void VerifySimpleFormatParseSpan(string num1, NumberFormatInfo nfi, BigInteger expected, bool failureExpected);
private static void VerifySimpleFormatParse(string num1, NumberFormatInfo nfi, BigInteger expected, bool failureExpected = false)
{
BigInteger test;
if (!failureExpected)
{
Assert.Equal(expected, BigInteger.Parse(num1, nfi));
Assert.True(BigInteger.TryParse(num1, NumberStyles.Any, nfi, out test));
Assert.Equal(expected, test);
}
else
{
Assert.Throws<FormatException>(() => { BigInteger.Parse(num1, nfi); });
Assert.False(BigInteger.TryParse(num1, NumberStyles.Any, nfi, out test), string.Format("Expected TryParse to fail on {0}", num1));
}
if (num1 != null)
{
VerifySimpleFormatParseSpan(num1, nfi, expected, failureExpected);
}
}
static partial void VerifyFormatParseSpan(string s, NumberStyles ns, NumberFormatInfo nfi, BigInteger expected, bool failureExpected);
private static void VerifyFormatParse(string num1, NumberStyles ns, NumberFormatInfo nfi, BigInteger expected, bool failureExpected = false)
{
BigInteger test;
if (!failureExpected)
{
Assert.Equal(expected, BigInteger.Parse(num1, ns, nfi));
Assert.True(BigInteger.TryParse(num1, NumberStyles.Any, nfi, out test));
Assert.Equal(expected, test);
}
else
{
Assert.Throws<FormatException>(() => { BigInteger.Parse(num1, ns, nfi); });
Assert.False(BigInteger.TryParse(num1, ns, nfi, out test), string.Format("Expected TryParse to fail on {0}", num1));
}
if (num1 != null)
{
VerifyFormatParseSpan(num1, ns, nfi, expected, failureExpected);
}
}
private static string GetDigitSequence(int min, int max, Random random)
{
string result = string.Empty;
string[] digits = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
int size = random.Next(min, max);
for (int i = 0; i < size; i++)
{
result += digits[random.Next(0, digits.Length)];
if (i == 0)
{
while (result == "0")
{
result = digits[random.Next(0, digits.Length)];
}
}
}
return result;
}
private static string GetHexDigitSequence(int min, int max, Random random)
{
string result = string.Empty;
string[] digits = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
int size = random.Next(min, max);
bool hasHexCharacter = false;
while (!hasHexCharacter)
{
for (int i = 0; i < size; i++)
{
int j = random.Next(0, digits.Length);
result += digits[j];
if (j > 9)
{
hasHexCharacter = true;
}
}
}
return result;
}
private static string GetRandomInvalidChar(Random random)
{
char[] digits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F' };
char result = '5';
while (result == '5')
{
result = unchecked((char)random.Next());
for (int i = 0; i < digits.Length; i++)
{
if (result == (char)digits[i])
{
result = '5';
}
}
// Remove the comma: 'AllowThousands' NumberStyle does not enforce the GroupSizes.
if (result == ',')
{
result = '5';
}
}
string res = new string(result, 1);
return res;
}
private static string Fix(string input)
{
return Fix(input, false);
}
private static string Fix(string input, bool isHex)
{
return Fix(input, isHex, true);
}
private static string Fix(string input, bool isHex, bool failureNotExpected)
{
string output = input;
if (failureNotExpected)
{
if (isHex)
{
output = ConvertHexToDecimal(output);
}
while (output.StartsWith("0") & (output.Length > 1))
{
output = output.Substring(1);
}
List<char> out2 = new List<char>();
for (int i = 0; i < output.Length; i++)
{
if ((output[i] >= '0') & (output[i] <= '9'))
{
out2.Add(output[i]);
}
}
output = new string(out2.ToArray());
}
return output;
}
private static string ConvertHexToDecimal(string input)
{
char[] inArr = input.ToCharArray();
bool isNeg = false;
if (inArr.Length > 0)
{
if (int.Parse("0" + inArr[0], NumberStyles.AllowHexSpecifier) > 7)
{
isNeg = true;
for (int i = 0; i < inArr.Length; i++)
{
int digit = int.Parse("0" + inArr[i], NumberStyles.AllowHexSpecifier);
digit = 15 - digit;
inArr[i] = digit.ToString("x")[0];
}
}
}
BigInteger x = 0;
BigInteger baseNum = 1;
for (int i = inArr.Length - 1; i >= 0; i--)
{
try
{
BigInteger x2 = (int.Parse(new string(new char[] { inArr[i] }), NumberStyles.AllowHexSpecifier) * baseNum);
x = x + x2;
}
catch (FormatException)
{
// left blank char is not a hex character;
}
baseNum = baseNum * 16;
}
if (isNeg)
{
x = x + 1;
}
List<char> number = new List<char>();
if (x == 0)
{
number.Add('0');
}
else
{
while (x > 0)
{
number.Add((x % 10).ToString().ToCharArray()[0]);
x = x / 10;
}
number.Reverse();
}
string y2 = new string(number.ToArray());
if (isNeg)
{
y2 = CultureInfo.CurrentCulture.NumberFormat.NegativeSign.ToCharArray() + y2;
}
return y2;
}
private static string GenerateGroups(int[] sizes, string seperator, Random random)
{
List<int> total_sizes = new List<int>();
int total;
int num_digits = random.Next(10, 100);
string digits = string.Empty;
total = 0;
total_sizes.Add(0);
for (int j = 0; ((j < (sizes.Length - 1)) && (total < 101)); j++)
{
total += sizes[j];
total_sizes.Add(total);
}
if (total < 101)
{
if (sizes[sizes.Length - 1] == 0)
{
total_sizes.Add(101);
}
else
{
while (total < 101)
{
total += sizes[sizes.Length - 1];
total_sizes.Add(total);
}
}
}
bool first = true;
for (int j = total_sizes.Count - 1; j > 0; j--)
{
if ((first) && (total_sizes[j] >= num_digits))
{
continue;
}
int group_size = num_digits - total_sizes[j - 1];
if (first)
{
digits += GetDigitSequence(group_size, group_size, random);
first = false;
}
else
{
//Generate an extra character since the first character of GetDigitSequence is non-zero.
digits += GetDigitSequence(group_size + 1, group_size + 1, random).Substring(1);
}
num_digits -= group_size;
if (num_digits > 0)
{
digits += seperator;
}
}
return digits;
}
private static NumberFormatInfo MarkUp(NumberFormatInfo nfi)
{
nfi.CurrencyDecimalDigits = 0;
nfi.CurrencyDecimalSeparator = "!";
nfi.CurrencyGroupSeparator = "#";
nfi.CurrencyGroupSizes = new int[] { 2 };
nfi.CurrencyNegativePattern = 4;
nfi.CurrencyPositivePattern = 2;
nfi.CurrencySymbol = "@";
nfi.NumberDecimalDigits = 0;
nfi.NumberDecimalSeparator = "^";
nfi.NumberGroupSeparator = "&";
nfi.NumberGroupSizes = new int[] { 4 };
nfi.NumberNegativePattern = 4;
nfi.PercentDecimalDigits = 0;
nfi.PercentDecimalSeparator = "*";
nfi.PercentGroupSeparator = "+";
nfi.PercentGroupSizes = new int[] { 5 };
nfi.PercentNegativePattern = 2;
nfi.PercentPositivePattern = 2;
nfi.PercentSymbol = "?";
nfi.PerMilleSymbol = "~";
nfi.NegativeSign = "<";
nfi.PositiveSign = ">";
return nfi;
}
// We need to account for cultures like fr-FR and uk-UA that use the no-break space (NBSP, 0xA0)
// character as the group separator. Because NBSP cannot be (easily) entered by the end user we
// accept regular spaces (SP, 0x20) as group separators for those cultures which means that
// trailing SP characters will be interpreted as group separators rather than whitespace.
//
// See also System.Globalization.FormatProvider+Number.MatchChars(char*, char*)
private static bool FailureNotExpectedForTrailingWhite(NumberStyles ns, bool spaceOnlyTrail)
{
if (spaceOnlyTrail && (ns & NumberStyles.AllowThousands) != 0)
{
if ((ns & NumberStyles.AllowCurrencySymbol) != 0)
{
if (CultureInfo.CurrentCulture.NumberFormat.CurrencyGroupSeparator == "\u00A0")
return true;
}
else
{
if (CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator == "\u00A0")
return true;
}
}
return (ns & NumberStyles.AllowTrailingWhite) != 0;
}
private static void Eval(BigInteger x, string expected)
{
bool IsPos = (x >= 0);
if (!IsPos)
{
x = -x;
}
if (x == 0)
{
Assert.Equal(expected, "0");
}
else
{
List<char> number = new List<char>();
while (x > 0)
{
number.Add((x % 10).ToString().ToCharArray()[0]);
x = x / 10;
}
number.Reverse();
string actual = new string(number.ToArray());
Assert.Equal(expected, actual);
}
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using ILMerging;
using Microsoft.Win32;
using Mono.Cecil;
using Mono.Linker;
using Mono.Linker.Steps;
using Mono.Options;
namespace SharpPak
{
/// <summary>
/// SharpPak application is able to pack/link into a single executable a SharpDX application
/// without requiring additional dependencies.
/// </summary>
public class SharpPakApp
{
public SharpPakApp()
{
OutputDirectory = "Output";
AssembliesToLink = new List<string>();
}
/// <summary>
/// Gets or sets the output directory.
/// </summary>
/// <value>The output directory.</value>
public string OutputDirectory { get; set; }
/// <summary>
/// Gets or sets the path to the main assembly to pack.
/// </summary>
/// <value>The main assembly to pack.</value>
public string MainAssembly { get; set; }
/// <summary>
/// Gets or sets the paths to the assemblies to merge into the main assembly.
/// </summary>
/// <value>The assemblies to merge into the main assembly.</value>
public List<string> AssembliesToLink { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [auto references].
/// </summary>
/// <value><c>true</c> if [auto references]; otherwise, <c>false</c>.</value>
public bool AutoReferences { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [no linker].
/// </summary>
/// <value><c>true</c> if [no linker]; otherwise, <c>false</c>.</value>
public bool NoLinker { get; set; }
/// <summary>
/// Print usages the error.
/// </summary>
/// <param name="error">The error.</param>
private static void UsageError(string error)
{
var exeName = Path.GetFileName(Assembly.GetEntryAssembly().Location);
Console.Write("{0}: ", exeName);
Console.WriteLine(error);
Console.WriteLine("Use {0} --help' for more information.", exeName);
Environment.Exit(1);
}
/// <summary>
/// Parses the command line arguments.
/// </summary>
/// <param name="args">The args.</param>
public void ParseArguments(string[] args)
{
var showHelp = false;
var options = new OptionSet()
{
"Copyright (c) 2010-2014 SharpDX - Alexandre Mutel",
"Usage: SharpPak [options]* MainAssembly.exe/dll [ Assembly1.dll...]*",
"Assembly linker for SharpDX applications",
"",
"options:",
{"a|auto", "Embed automatically all referenced assemblies [default: false]", opt => AutoReferences = opt != null},
{"n|nolinker", "Perform no linker [default: false]", opt => NoLinker = opt != null},
{"o|output=", "Specify the output directory [default: Output]", opt => OutputDirectory = opt},
{"h|help", "Show this message and exit", opt => showHelp = opt != null},
// default
{"<>", opt => AssembliesToLink.AddRange(opt.Split(' ', '\t')) },
};
try
{
options.Parse(args);
}
catch (OptionException e)
{
UsageError(e.Message);
}
if (showHelp)
{
options.WriteOptionDescriptions(Console.Out);
Environment.Exit(0);
}
if (AssembliesToLink.Count == 0)
UsageError("MainAssembly file to pack is missing");
MainAssembly = AssembliesToLink[0];
AssembliesToLink.RemoveAt(0);
}
private void AddAssemblies(AssemblyDefinition assembly,
List<string> paths,
string fromDirectory,
string[] includeMergeListRegex)
{
var hashSet = new HashSet<AssemblyDefinition>();
AddAssemblies(assembly, paths, fromDirectory, includeMergeListRegex, hashSet);
}
private void AddAssemblies(AssemblyDefinition assembly, List<string> paths, string fromDirectory, string[] includeMergeListRegex, HashSet<AssemblyDefinition> added)
{
if(added.Contains(assembly))
return;
added.Add(assembly);
var directoryOfAssembly = Path.GetDirectoryName(assembly.MainModule.FullyQualifiedName);
if (fromDirectory == directoryOfAssembly)
{
if(!paths.Contains(assembly.MainModule.FullyQualifiedName))
{
paths.Add(assembly.MainModule.FullyQualifiedName);
}
}
// Load SharpDX assemblies
foreach (var assemblyRef in assembly.MainModule.AssemblyReferences)
{
bool isAssemblyAdded = false;
foreach (var regexIncludeStr in includeMergeListRegex)
{
var regexInclude = new Regex(regexIncludeStr);
if (regexInclude.Match(assemblyRef.Name).Success)
{
var assemblyDefRef = assembly.MainModule.AssemblyResolver.Resolve(assemblyRef);
AddAssemblies(assemblyDefRef, paths, fromDirectory, includeMergeListRegex, added);
isAssemblyAdded = true;
break;
}
}
if (!isAssemblyAdded && AutoReferences)
{
var assemblyDefRef = assembly.MainModule.AssemblyResolver.Resolve(assemblyRef);
AddAssemblies(assemblyDefRef, paths, fromDirectory, includeMergeListRegex, added);
}
}
}
/// <summary>
/// Performs packing.
/// </summary>
public void Run()
{
// Steps
// 1) Mono.Cecil: Determine assembly dependencies
// 2) ILMerge: Merge exe into a single assembly
// 3) Mono.Linker
var includeMergeListRegex = new string[] { @"SharpDX\..*" };
// Step 1 : Mono.Cecil: Determine assembly dependencies
var assembly = AssemblyDefinition.ReadAssembly(MainAssembly);
var corlib = (AssemblyNameReference)assembly.MainModule.TypeSystem.Corlib;
bool isNet40 = corlib.Version.Major == 4;
var paths = new List<string>();
var fromDirectory = Path.GetDirectoryName(assembly.MainModule.FullyQualifiedName);
// Load SharpDX assemblies
AddAssemblies(assembly, paths, fromDirectory, includeMergeListRegex);
// Load assemblies to link
foreach (var assemblyToLinkName in AssembliesToLink)
{
var assemblyToLink = AssemblyDefinition.ReadAssembly(assemblyToLinkName);
paths.Add(assemblyToLink.MainModule.FullyQualifiedName);
}
// Step 2: ILMerge: Merge exe into a single assembly
var merge = new ILMerge();
String[] files = paths.ToArray();
if (!Directory.Exists(OutputDirectory))
Directory.CreateDirectory(OutputDirectory);
//Here we get the first file name (which was the .exe file) and use that
// as the output
String strOutputFile = System.IO.Path.GetFileName(files[0]);
merge.OutputFile = OutputDirectory + "\\" + strOutputFile;
merge.SetInputAssemblies(files);
merge.DebugInfo = false;
merge.CopyAttributes = true;
merge.AllowMultipleAssemblyLevelAttributes = true;
merge.XmlDocumentation = false;
// Special case for v4 framework
// See http://research.microsoft.com/en-us/people/mbarnett/ilmerge.aspx
if (isNet40)
{
// Retrieve the install root path for the framework
string installRoot = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\.NetFramework", false).GetValue("InstallRoot").ToString();
var directorties = Directory.GetDirectories(installRoot, "v4.*");
if (directorties.Length == 0)
UsageError(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Cannot found any .Net 4.0 directory from [{0}] ", installRoot));
merge.SetTargetPlatform("v4", directorties[0]);
}
merge.Merge();
// Step 3: Mono.Linker
if (!NoLinker)
{
var pipeline = GetStandardPipeline();
var context = new LinkContext(pipeline) {CoreAction = AssemblyAction.Skip, OutputDirectory = OutputDirectory};
context.OutputDirectory = OutputDirectory;
var mainAssemblyDirectory = new DirectoryInfo(Path.GetDirectoryName(Path.GetFullPath(MainAssembly)));
context.Resolver.AddSearchDirectory(mainAssemblyDirectory.FullName);
// Load assembly merged previously by ILMerge
var mergedAssemblyDefinition = context.Resolve(merge.OutputFile);
// Create Mono.Linker default pipeline
pipeline = GetStandardPipeline();
pipeline.PrependStep(new ResolveFromAssemblyStep(mergedAssemblyDefinition));
// Add custom step for ComObject constructors
pipeline.AddStepBefore(typeof (SweepStep), new ComObjectStep());
pipeline.Process(context);
}
Console.WriteLine("Assembly successfully packed to [{0}]", merge.OutputFile);
}
static Pipeline GetStandardPipeline()
{
var pipeline = new Pipeline();
pipeline.AppendStep(new LoadReferencesStep());
pipeline.AppendStep(new BlacklistStep());
pipeline.AppendStep(new TypeMapStep());
pipeline.AppendStep(new MarkStep());
pipeline.AppendStep(new SweepStep());
pipeline.AppendStep(new CleanStep());
pipeline.AppendStep(new RegenerateGuidStep());
pipeline.AppendStep(new OutputStep());
return pipeline;
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Material sourced from the bluePortal project (http://blueportal.codeplex.com).
// Licensed under the Microsoft Public License (available at http://www.opensource.org/licenses/ms-pl.html).
using System;
using System.Data;
using System.Collections;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace CSSFriendly
{
public class GridViewAdapter : System.Web.UI.WebControls.Adapters.WebControlAdapter
{
private WebControlAdapterExtender _extender = null;
private WebControlAdapterExtender Extender
{
get
{
if (((_extender == null) && (Control != null)) ||
((_extender != null) && (Control != _extender.AdaptedControl)))
{
_extender = new WebControlAdapterExtender(Control);
}
System.Diagnostics.Debug.Assert(_extender != null, "CSS Friendly adapters internal error", "Null extender instance");
return _extender;
}
}
/// ///////////////////////////////////////////////////////////////////////////////
/// PROTECTED
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Extender.AdapterEnabled)
{
RegisterScripts();
}
}
protected override void RenderBeginTag(HtmlTextWriter writer)
{
if (Extender.AdapterEnabled)
{
Extender.RenderBeginTag(writer, "AspNet-GridView");
}
else
{
base.RenderBeginTag(writer);
}
}
protected override void RenderEndTag(HtmlTextWriter writer)
{
if (Extender.AdapterEnabled)
{
Extender.RenderEndTag(writer);
}
else
{
base.RenderEndTag(writer);
}
}
protected override void RenderContents(HtmlTextWriter writer)
{
if (Extender.AdapterEnabled)
{
GridView gridView = Control as GridView;
if (gridView != null)
{
writer.Indent++;
WritePagerSection(writer, PagerPosition.Top);
writer.WriteLine();
writer.WriteBeginTag("table");
writer.WriteAttribute("id", gridView.ClientID);
writer.WriteAttribute("cellpadding", "0");
writer.WriteAttribute("cellspacing", "0");
writer.WriteAttribute("summary", Control.ToolTip);
writer.Write(HtmlTextWriter.TagRightChar);
writer.Indent++;
ArrayList rows = new ArrayList();
GridViewRowCollection gvrc = null;
///////////////////// HEAD /////////////////////////////
rows.Clear();
if (gridView.ShowHeader && (gridView.HeaderRow != null))
{
rows.Add(gridView.HeaderRow);
}
gvrc = new GridViewRowCollection(rows);
WriteRows(writer, gridView, gvrc, "thead");
///////////////////// FOOT /////////////////////////////
rows.Clear();
if (gridView.ShowFooter && (gridView.FooterRow != null))
{
rows.Add(gridView.FooterRow);
}
gvrc = new GridViewRowCollection(rows);
WriteRows(writer, gridView, gvrc, "tfoot");
///////////////////// BODY /////////////////////////////
WriteRows(writer, gridView, gridView.Rows, "tbody");
////////////////////////////////////////////////////////
writer.Indent--;
writer.WriteLine();
writer.WriteEndTag("table");
WriteEmptyTextSection(writer);
WritePagerSection(writer, PagerPosition.Bottom);
writer.Indent--;
writer.WriteLine();
}
}
else
{
base.RenderContents(writer);
}
}
/// ///////////////////////////////////////////////////////////////////////////////
/// PRIVATE
private void RegisterScripts()
{
}
private void WriteRows(HtmlTextWriter writer, GridView gridView, GridViewRowCollection rows, string tableSection)
{
if (rows.Count > 0)
{
writer.WriteLine();
writer.WriteBeginTag(tableSection);
writer.Write(HtmlTextWriter.TagRightChar);
writer.Indent++;
foreach (GridViewRow row in rows)
{
writer.WriteLine();
writer.WriteBeginTag("tr");
string className = GetRowClass(gridView, row);
if (!String.IsNullOrEmpty(className))
{
writer.WriteAttribute("class", className);
}
writer.Write(HtmlTextWriter.TagRightChar);
writer.Indent++;
int i = 0;
foreach (TableCell cell in row.Cells)
{
if (!gridView.Columns[i++].Visible)
continue;
DataControlFieldCell fieldCell = cell as DataControlFieldCell;
if(tableSection == "tbody" && fieldCell != null
&& (fieldCell.Text.Trim() == "") && fieldCell.Controls.Count == 0)
cell.Controls.Add(new LiteralControl("<div style=\"width:1px;height:1px;\"> </div>"));
else if (tableSection == "thead" && fieldCell != null
&& !String.IsNullOrEmpty(gridView.SortExpression)
&& fieldCell.ContainingField.SortExpression == gridView.SortExpression)
{
cell.Attributes["class"] = "AspNet-GridView-Sort";
}
if ((fieldCell != null) && (fieldCell.ContainingField != null))
{
DataControlField field = fieldCell.ContainingField;
if (!field.Visible)
{
cell.Visible = false;
}
if (field.ItemStyle.Width != Unit.Empty)
cell.Style["width"] = field.ItemStyle.Width.ToString();
if (!field.ItemStyle.Wrap)
cell.Style["white-space"] = "nowrap";
if ((field.ItemStyle != null) && (!String.IsNullOrEmpty(field.ItemStyle.CssClass)))
{
if (!String.IsNullOrEmpty(cell.CssClass))
{
cell.CssClass += " ";
}
cell.CssClass += field.ItemStyle.CssClass;
}
}
writer.WriteLine();
cell.RenderControl(writer);
}
writer.Indent--;
writer.WriteLine();
writer.WriteEndTag("tr");
}
writer.Indent--;
writer.WriteLine();
writer.WriteEndTag(tableSection);
}
}
private string GetRowClass(GridView gridView, GridViewRow row)
{
string className = "";
if ((row.RowState & DataControlRowState.Alternate) == DataControlRowState.Alternate)
{
className += " AspNet-GridView-Alternate ";
if (gridView.AlternatingRowStyle != null)
{
className += gridView.AlternatingRowStyle.CssClass;
}
}
if ((row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
className += " AspNet-GridView-Edit ";
if (gridView.EditRowStyle != null)
{
className += gridView.EditRowStyle.CssClass;
}
}
if ((row.RowState & DataControlRowState.Insert) == DataControlRowState.Insert)
{
className += " AspNet-GridView-Insert ";
}
if ((row.RowState & DataControlRowState.Selected) == DataControlRowState.Selected)
{
className += " AspNet-GridView-Selected ";
if (gridView.SelectedRowStyle != null)
{
className += gridView.SelectedRowStyle.CssClass;
}
}
return className.Trim();
}
private void WriteEmptyTextSection(HtmlTextWriter writer)
{
GridView gridView = Control as GridView;
if (gridView != null && gridView.Rows.Count == 0)
{
string className = "AspNet-GridView-Empty";
writer.WriteLine();
writer.WriteBeginTag("div");
writer.WriteAttribute("class", className);
writer.Write(HtmlTextWriter.TagRightChar);
writer.Indent++;
writer.Write(gridView.EmptyDataText);
writer.Indent--;
writer.WriteLine();
writer.WriteEndTag("div");
}
}
private void WritePagerSection(HtmlTextWriter writer, PagerPosition pos)
{
GridView gridView = Control as GridView;
if ((gridView != null) &&
gridView.AllowPaging &&
((gridView.PagerSettings.Position == pos) || (gridView.PagerSettings.Position == PagerPosition.TopAndBottom)))
{
Table innerTable = null;
if ((pos == PagerPosition.Top) &&
(gridView.TopPagerRow != null) &&
(gridView.TopPagerRow.Cells.Count == 1) &&
(gridView.TopPagerRow.Cells[0].Controls.Count == 1) &&
typeof(Table).IsAssignableFrom(gridView.TopPagerRow.Cells[0].Controls[0].GetType()))
{
innerTable = gridView.TopPagerRow.Cells[0].Controls[0] as Table;
}
else if ((pos == PagerPosition.Bottom) &&
(gridView.BottomPagerRow != null) &&
(gridView.BottomPagerRow.Cells.Count == 1) &&
(gridView.BottomPagerRow.Cells[0].Controls.Count == 1) &&
typeof(Table).IsAssignableFrom(gridView.BottomPagerRow.Cells[0].Controls[0].GetType()))
{
innerTable = gridView.BottomPagerRow.Cells[0].Controls[0] as Table;
}
if ((innerTable != null) && (innerTable.Rows.Count == 1))
{
string className = "AspNet-GridView-Pagination AspNet-GridView-";
className += (pos == PagerPosition.Top) ? "Top " : "Bottom ";
if (gridView.PagerStyle != null)
{
className += gridView.PagerStyle.CssClass;
}
className = className.Trim();
writer.WriteLine();
writer.WriteBeginTag("div");
writer.WriteAttribute("class", className);
writer.Write(HtmlTextWriter.TagRightChar);
writer.Indent++;
TableRow row = innerTable.Rows[0];
foreach (TableCell cell in row.Cells)
{
foreach (Control ctrl in cell.Controls)
{
writer.WriteLine();
ctrl.RenderControl(writer);
}
}
writer.Indent--;
writer.WriteLine();
writer.WriteEndTag("div");
}
}
}
}
}
| |
/*
* REST API Documentation for the MOTI School Bus Application
*
* The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
namespace SchoolBusAPI.Models
{
/// <summary>
///
/// </summary>
public partial class SchoolBusOwnerAttachment : IEquatable<SchoolBusOwnerAttachment>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public SchoolBusOwnerAttachment()
{
this.Id = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="SchoolBusOwnerAttachment" /> class.
/// </summary>
/// <param name="Id">Primary Key (required).</param>
/// <param name="SchoolBusOwner">SchoolBusOwner.</param>
/// <param name="InternalFileName">The physical location of the attachment on the file system..</param>
/// <param name="ExternalFileName">The name of the attachment as defined by the user in uploading the document..</param>
/// <param name="Description">A note about the attachment, optionally maintained by the user..</param>
public SchoolBusOwnerAttachment(int Id, SchoolBusOwner SchoolBusOwner = null, string InternalFileName = null, string ExternalFileName = null, string Description = null)
{
this.Id = Id;
this.SchoolBusOwner = SchoolBusOwner;
this.InternalFileName = InternalFileName;
this.ExternalFileName = ExternalFileName;
this.Description = Description;
}
/// <summary>
/// Primary Key
/// </summary>
/// <value>Primary Key</value>
[MetaDataExtension (Description = "Primary Key")]
public int Id { get; set; }
/// <summary>
/// Gets or Sets SchoolBusOwner
/// </summary>
public SchoolBusOwner SchoolBusOwner { get; set; }
[ForeignKey("SchoolBusOwner")]
public int? SchoolBusOwnerRefId { get; set; }
/// <summary>
/// The physical location of the attachment on the file system.
/// </summary>
/// <value>The physical location of the attachment on the file system.</value>
[MetaDataExtension (Description = "The physical location of the attachment on the file system.")]
public string InternalFileName { get; set; }
/// <summary>
/// The name of the attachment as defined by the user in uploading the document.
/// </summary>
/// <value>The name of the attachment as defined by the user in uploading the document.</value>
[MetaDataExtension (Description = "The name of the attachment as defined by the user in uploading the document.")]
public string ExternalFileName { get; set; }
/// <summary>
/// A note about the attachment, optionally maintained by the user.
/// </summary>
/// <value>A note about the attachment, optionally maintained by the user.</value>
[MetaDataExtension (Description = "A note about the attachment, optionally maintained by the user.")]
public string Description { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class SchoolBusOwnerAttachment {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" SchoolBusOwner: ").Append(SchoolBusOwner).Append("\n");
sb.Append(" InternalFileName: ").Append(InternalFileName).Append("\n");
sb.Append(" ExternalFileName: ").Append(ExternalFileName).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((SchoolBusOwnerAttachment)obj);
}
/// <summary>
/// Returns true if SchoolBusOwnerAttachment instances are equal
/// </summary>
/// <param name="other">Instance of SchoolBusOwnerAttachment to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(SchoolBusOwnerAttachment other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.Id == other.Id ||
this.Id.Equals(other.Id)
) &&
(
this.SchoolBusOwner == other.SchoolBusOwner ||
this.SchoolBusOwner != null &&
this.SchoolBusOwner.Equals(other.SchoolBusOwner)
) &&
(
this.InternalFileName == other.InternalFileName ||
this.InternalFileName != null &&
this.InternalFileName.Equals(other.InternalFileName)
) &&
(
this.ExternalFileName == other.ExternalFileName ||
this.ExternalFileName != null &&
this.ExternalFileName.Equals(other.ExternalFileName)
) &&
(
this.Description == other.Description ||
this.Description != null &&
this.Description.Equals(other.Description)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + this.Id.GetHashCode();
if (this.SchoolBusOwner != null)
{
hash = hash * 59 + this.SchoolBusOwner.GetHashCode();
}
if (this.InternalFileName != null)
{
hash = hash * 59 + this.InternalFileName.GetHashCode();
}
if (this.ExternalFileName != null)
{
hash = hash * 59 + this.ExternalFileName.GetHashCode();
}
if (this.Description != null)
{
hash = hash * 59 + this.Description.GetHashCode();
}
return hash;
}
}
#region Operators
public static bool operator ==(SchoolBusOwnerAttachment left, SchoolBusOwnerAttachment right)
{
return Equals(left, right);
}
public static bool operator !=(SchoolBusOwnerAttachment left, SchoolBusOwnerAttachment right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Services.Connectors.Simulation;
using OpenSim.Services.Interfaces;
using System;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Net;
using System.Reflection;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Services.Connectors.Hypergrid
{
public class GatekeeperServiceConnector : SimulationServiceConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static UUID m_HGMapImage = new UUID("00000000-0000-1111-9999-000000000013");
private IAssetService m_AssetService;
public GatekeeperServiceConnector()
: base()
{
}
public GatekeeperServiceConnector(IAssetService assService)
{
m_AssetService = assService;
}
public GridRegion GetHyperlinkRegion(GridRegion gatekeeper, UUID regionID, UUID agentID, string agentHomeURI, out string message)
{
Hashtable hash = new Hashtable();
hash["region_uuid"] = regionID.ToString();
if (agentID != UUID.Zero)
{
hash["agent_id"] = agentID.ToString();
if (agentHomeURI != null)
hash["agent_home_uri"] = agentHomeURI;
}
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("get_region", paramList);
m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: contacting " + gatekeeper.ServerURI);
XmlRpcResponse response = null;
try
{
response = request.Send(gatekeeper.ServerURI, 10000);
}
catch (Exception e)
{
message = "Error contacting grid.";
m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: Exception " + e.Message);
return null;
}
if (response.IsFault)
{
message = "Error contacting grid.";
m_log.ErrorFormat("[GATEKEEPER SERVICE CONNECTOR]: remote call returned an error: {0}", response.FaultString);
return null;
}
hash = (Hashtable)response.Value;
//foreach (Object o in hash)
// m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value);
try
{
bool success = false;
Boolean.TryParse((string)hash["result"], out success);
if (hash["message"] != null)
message = (string)hash["message"];
else if (success)
message = null;
else
message = "The teleport destination could not be found."; // probably the dest grid is old and doesn't send 'message', but the most common problem is that the region is unavailable
if (success)
{
GridRegion region = new GridRegion();
UUID.TryParse((string)hash["uuid"], out region.RegionID);
//m_log.Debug(">> HERE, uuid: " + region.RegionID);
int n = 0;
if (hash["x"] != null)
{
Int32.TryParse((string)hash["x"], out n);
region.RegionLocX = n;
//m_log.Debug(">> HERE, x: " + region.RegionLocX);
}
if (hash["y"] != null)
{
Int32.TryParse((string)hash["y"], out n);
region.RegionLocY = n;
//m_log.Debug(">> HERE, y: " + region.RegionLocY);
}
if (hash["size_x"] != null)
{
Int32.TryParse((string)hash["size_x"], out n);
region.RegionSizeX = n;
//m_log.Debug(">> HERE, x: " + region.RegionLocX);
}
if (hash["size_y"] != null)
{
Int32.TryParse((string)hash["size_y"], out n);
region.RegionSizeY = n;
//m_log.Debug(">> HERE, y: " + region.RegionLocY);
}
if (hash["region_name"] != null)
{
region.RegionName = (string)hash["region_name"];
//m_log.Debug(">> HERE, region_name: " + region.RegionName);
}
if (hash["hostname"] != null)
{
region.ExternalHostName = (string)hash["hostname"];
//m_log.Debug(">> HERE, hostname: " + region.ExternalHostName);
}
if (hash["http_port"] != null)
{
uint p = 0;
UInt32.TryParse((string)hash["http_port"], out p);
region.HttpPort = p;
//m_log.Debug(">> HERE, http_port: " + region.HttpPort);
}
if (hash["internal_port"] != null)
{
int p = 0;
Int32.TryParse((string)hash["internal_port"], out p);
region.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), p);
//m_log.Debug(">> HERE, internal_port: " + region.InternalEndPoint);
}
if (hash["server_uri"] != null)
{
region.ServerURI = (string)hash["server_uri"];
//m_log.Debug(">> HERE, server_uri: " + region.ServerURI);
}
// Successful return
return region;
}
}
catch (Exception e)
{
message = "Error parsing response from grid.";
m_log.Error("[GATEKEEPER SERVICE CONNECTOR]: Got exception while parsing hyperlink response " + e.StackTrace);
return null;
}
return null;
}
public UUID GetMapImage(UUID regionID, string imageURL, string storagePath)
{
if (m_AssetService == null)
{
m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: No AssetService defined. Map tile not retrieved.");
return m_HGMapImage;
}
UUID mapTile = m_HGMapImage;
string filename = string.Empty;
try
{
WebClient c = new WebClient();
string name = regionID.ToString();
filename = Path.Combine(storagePath, name + ".jpg");
m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: Map image at {0}, cached at {1}", imageURL, filename);
if (!File.Exists(filename))
{
m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: downloading...");
c.DownloadFile(imageURL, filename);
}
else
{
m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: using cached image");
}
byte[] imageData = null;
using (Bitmap bitmap = new Bitmap(filename))
{
//m_log.Debug("Size: " + m.PhysicalDimension.Height + "-" + m.PhysicalDimension.Width);
imageData = OpenJPEG.EncodeFromImage(bitmap, true);
}
AssetBase ass = new AssetBase(UUID.Random(), "region " + name, (sbyte)AssetType.Texture, regionID.ToString());
// !!! for now
//info.RegionSettings.TerrainImageID = ass.FullID;
ass.Data = imageData;
mapTile = ass.FullID;
// finally
m_AssetService.Store(ass);
}
catch // LEGIT: Catching problems caused by OpenJPEG p/invoke
{
m_log.Info("[GATEKEEPER SERVICE CONNECTOR]: Failed getting/storing map image, because it is probably already in the cache");
}
return mapTile;
}
public bool LinkRegion(GridRegion info, out UUID regionID, out ulong realHandle, out string externalName, out string imageURL, out string reason)
{
regionID = UUID.Zero;
imageURL = string.Empty;
realHandle = 0;
externalName = string.Empty;
reason = string.Empty;
Hashtable hash = new Hashtable();
hash["region_name"] = info.RegionName;
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("link_region", paramList);
m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: Linking to " + info.ServerURI);
XmlRpcResponse response = null;
try
{
response = request.Send(info.ServerURI, 10000);
}
catch (Exception e)
{
m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: Exception " + e.Message);
reason = "Error contacting remote server";
return false;
}
if (response.IsFault)
{
reason = response.FaultString;
m_log.ErrorFormat("[GATEKEEPER SERVICE CONNECTOR]: remote call returned an error: {0}", response.FaultString);
return false;
}
hash = (Hashtable)response.Value;
//foreach (Object o in hash)
// m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value);
try
{
bool success = false;
Boolean.TryParse((string)hash["result"], out success);
if (success)
{
UUID.TryParse((string)hash["uuid"], out regionID);
//m_log.Debug(">> HERE, uuid: " + regionID);
if ((string)hash["handle"] != null)
{
realHandle = Convert.ToUInt64((string)hash["handle"]);
//m_log.Debug(">> HERE, realHandle: " + realHandle);
}
if (hash["region_image"] != null)
{
imageURL = (string)hash["region_image"];
//m_log.Debug(">> HERE, imageURL: " + imageURL);
}
if (hash["external_name"] != null)
{
externalName = (string)hash["external_name"];
//m_log.Debug(">> HERE, externalName: " + externalName);
}
}
}
catch (Exception e)
{
reason = "Error parsing return arguments";
m_log.Error("[GATEKEEPER SERVICE CONNECTOR]: Got exception while parsing hyperlink response " + e.StackTrace);
return false;
}
return true;
}
protected override string AgentPath()
{
return "foreignagent/";
}
protected override string ObjectPath()
{
return "foreignobject/";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ----------------------------------------------------------------------------------
// Interop library code
//
// Type marshalling helpers used by MCG
//
// NOTE:
// These source code are being published to InternalAPIs and consumed by RH builds
// Use PublishInteropAPI.bat to keep the InternalAPI copies in sync
// ----------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Threading;
using System.Text;
using System.Runtime;
using System.Diagnostics.Contracts;
using Internal.NativeFormat;
using System.Runtime.CompilerServices;
namespace System.Runtime.InteropServices
{
internal static class McgTypeHelpers
{
static readonly Type[] s_wellKnownTypes = new Type[]
{
typeof(Boolean),
typeof(Char),
typeof(Byte),
typeof(Int16),
typeof(UInt16),
typeof(Int32),
typeof(UInt32),
typeof(Int64),
typeof(UInt64),
typeof(Single),
typeof(Double),
typeof(String),
typeof(Object),
typeof(Guid)
};
static readonly string[] s_wellKnownTypeNames = new string[]
{
"Boolean",
"Char16",
"UInt8",
"Int16",
"UInt16",
"Int32",
"UInt32",
"Int64",
"UInt64",
"Single",
"Double",
"String",
"Object",
"Guid"
};
private const string PseudonymPrefix = "System.Runtime.InteropServices.RuntimePseudonyms.";
#if ENABLE_WINRT
/// <summary>
/// A 'fake' System.Type instance for native WinMD types (metadata types) that are not needed in
/// managed code, which means it is:
/// 1. Imported in MCG, but reduced away by reducer
/// 2. Not imported by MCG at all
/// In either case, it is possible that it is needed only in native code, and native code can return
/// a IXamlType instance to C# xaml compiler generated code that attempts to call get_UnderlyingType
/// which tries to convert a TypeName to System.Type and then stick it into a cache. In order to make
/// such scenario work, we need to create a fake System.Type instance that is unique to the name
/// and is roundtrippable.
/// As long as it is only used in the cache scenarios in xaml compiler generated code, we should be
/// fine. Any other attempt to use such types will surely result an exception
/// NOTE: in order to avoid returning fake types for random non-existent metadata types, we look
/// in McgAdditionalClassData (which encodes all interesting class data) before we create such fake
/// types
/// </summary>
class McgFakeMetadataType
#if RHTESTCL
: Type
#else
: TypeInfo
#endif
{
/// <summary>
/// Full type name of the WinMD type
/// </summary>
string _fullTypeName;
public McgFakeMetadataType(string fullTypeName, TypeKind typeKind)
#if RHTESTCL
: base(default(RuntimeTypeHandle))
#else
: base()
#endif
{
_fullTypeName = fullTypeName;
TypeKind = typeKind;
}
public TypeKind TypeKind { get; private set; }
#if RHTESTCL
public string FullName { get { return _fullTypeName; } }
#else
public override Assembly Assembly { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override String AssemblyQualifiedName { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override Type BaseType { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override Type DeclaringType { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override String FullName { get { return _fullTypeName; } }
public override int GenericParameterPosition { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override Type[] GenericTypeArguments { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override Guid GUID { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override bool IsConstructedGenericType { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override bool IsGenericParameter { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override String Name { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override String Namespace { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override Type UnderlyingSystemType { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override int GetArrayRank() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type GetElementType() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override EventInfo GetEvent(string name, BindingFlags bindingAttr) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override FieldInfo GetField(string name, BindingFlags bindingAttr) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type GetGenericTypeDefinition() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type GetInterface(string name, bool ignoreCase) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type[] GetInterfaces() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type GetNestedType(string name, BindingFlags bindingAttr) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override object[] GetCustomAttributes(bool inherit) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override bool IsDefined(Type attributeType, bool inherit) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type MakeArrayType() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type MakeArrayType(int rank) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type MakeByRefType() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type MakeGenericType(params Type[] typeArguments) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type MakePointerType() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Module Module { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override String ToString()
{
return "Type: " + _fullTypeName;
}
public override bool Equals(Object o)
{
if (o == null)
return false;
//
// We guarantee uniqueness in Mcg marshalling code
//
if (o == (object)this) // cast to object added so keep C# from warning us that we don't look like we know which operator== we want to call.
return true;
return false;
}
public override int GetHashCode()
{
return _fullTypeName.GetHashCode();
}
protected override TypeAttributes GetAttributeFlagsImpl() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
protected override bool IsPrimitiveImpl() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
protected override bool HasElementTypeImpl() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
protected override bool IsCOMObjectImpl() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
protected override bool IsArrayImpl() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
protected override bool IsByRefImpl() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
protected override bool IsPointerImpl() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
#endif //RHTESTCL
}
internal static unsafe void TypeToTypeName(
Type type,
out HSTRING nativeTypeName,
out int nativeTypeKind)
{
if (type == null)
{
nativeTypeName.handle = default(IntPtr);
nativeTypeKind = (int)TypeKind.Custom;
}
else
{
McgFakeMetadataType fakeType = type as McgFakeMetadataType;
if (fakeType != null)
{
//
// Handle round tripping fake types
// See McgFakeMetadataType for details
//
nativeTypeKind = (int)fakeType.TypeKind;
nativeTypeName = McgMarshal.StringToHString(fakeType.FullName);
}
else
{
string typeName;
TypeKind typeKind;
TypeToTypeName(type.TypeHandle, out typeName, out typeKind);
nativeTypeName = McgMarshal.StringToHString(typeName);
nativeTypeKind = (int)typeKind;
}
}
}
#endif //!CORECLR
private static unsafe void TypeToTypeName(
RuntimeTypeHandle typeHandle,
out string typeName,
out TypeKind typeKind)
{
//
// Primitive types
//
for (int i = 0; i < s_wellKnownTypes.Length; i++)
{
if (s_wellKnownTypes[i].TypeHandle.Equals(typeHandle))
{
typeName = s_wellKnownTypeNames[i];
typeKind = TypeKind.Primitive;
return;
}
}
//
// User-imported types
//
bool isWinRT;
string name = McgModuleManager.GetTypeName(typeHandle, out isWinRT);
if (name != null)
{
typeName = name;
typeKind =
(isWinRT ?
TypeKind.Metadata :
TypeKind.Custom);
return;
}
//
// Handle managed types
//
typeName = GetCustomTypeName(typeHandle);
typeKind = TypeKind.Custom;
}
static System.Collections.Generic.Internal.Dictionary<string, Type> s_fakeTypeMap
= new Collections.Generic.Internal.Dictionary<string, Type>();
static Lock s_fakeTypeMapLock = new Lock();
static System.Collections.Generic.Internal.Dictionary<RuntimeTypeHandle, Type> s_realToFakeTypeMap
= new System.Collections.Generic.Internal.Dictionary<RuntimeTypeHandle, Type>();
#if ENABLE_WINRT
/// <summary>
/// Returns a type usable in XAML roundtripping whether it's reflectable or not
/// </summary>
/// <param name="realType">Type for the real object</param>
/// <returns>realType if realType is reflectable, otherwise a fake type that can be roundtripped
/// and won't throw for XAML usage.</returns>
internal static Type GetReflectableOrFakeType(Type realType)
{
#if !RHTESTCL
if(realType.SupportsReflection())
{
return realType;
}
#endif
s_fakeTypeMapLock.Acquire();
try
{
Type fakeType;
RuntimeTypeHandle realTypeHandle = realType.TypeHandle;
if (s_realToFakeTypeMap.TryGetValue(realTypeHandle, out fakeType))
{
return fakeType;
}
string pseudonym = GetPseudonymForType(realTypeHandle, /* useFake: */ true);
fakeType = new McgFakeMetadataType(pseudonym, TypeKind.Custom);
s_realToFakeTypeMap.Add(realTypeHandle, fakeType);
s_fakeTypeMap.Add(pseudonym, fakeType);
return fakeType;
}
finally
{
s_fakeTypeMapLock.Release();
}
}
/// <summary>
/// Internal help for dynamic boxing
/// This method is only works for native type name
/// </summary>
/// <param name="typeName">native type name</param>
/// <returns>valid type if found; or null</returns>
internal static Type GetTypeByName(string typeName)
{
//
// Well-known types
//
for (int i = 0; i < s_wellKnownTypeNames.Length; i++)
{
if (s_wellKnownTypeNames[i] == typeName)
{
return s_wellKnownTypes[i];
}
}
// user imported type
bool isWinRT;
return McgModuleManager.GetTypeFromName(typeName, out isWinRT);
}
internal static unsafe Type TypeNameToType(HSTRING nativeTypeName, int nativeTypeKind)
{
string name = McgMarshal.HStringToString(nativeTypeName);
if (!string.IsNullOrEmpty(name))
{
//
// Well-known types
//
for (int i = 0; i < s_wellKnownTypeNames.Length; i++)
{
if (s_wellKnownTypeNames[i] == name)
{
if (nativeTypeKind != (int)TypeKind.Primitive)
throw new ArgumentException(SR.Arg_UnexpectedTypeKind);
return s_wellKnownTypes[i];
}
}
if (nativeTypeKind == (int)TypeKind.Primitive)
{
//
// We've scanned all primitive types that we know of and came back nothing
//
throw new ArgumentException("Unrecognized primitive type name");
}
//
// User-imported types
// Try to get a type if MCG knows what this is
// If the returned type does not have metadata, the type is no good as Jupiter needs to pass
// it to XAML type provider code which needs to call FullName on it
//
bool isWinRT;
Type type = McgModuleManager.GetTypeFromName(name, out isWinRT);
#if !RHTESTCL
if (type != null && !type.SupportsReflection())
type = null;
#endif
//
// If we got back a type that is valid (not reduced)
//
if (type != null && !type.TypeHandle.Equals(McgModule.s_DependencyReductionTypeRemovedTypeHandle))
{
if (nativeTypeKind !=
(int)
(isWinRT ? TypeKind.Metadata : TypeKind.Custom))
throw new ArgumentException(SR.Arg_UnexpectedTypeKind);
return type;
}
if (nativeTypeKind == (int)TypeKind.Metadata)
{
//
// Handle converting native WinMD type names to fake McgFakeMetadataType to make C# xaml
// compiler happy
// See McgFakeMetadataType for more details
//
s_fakeTypeMapLock.Acquire();
try
{
if (s_fakeTypeMap.TryGetValue(name, out type))
{
return type;
}
else
{
type = new McgFakeMetadataType(name, TypeKind.Metadata);
s_fakeTypeMap.Add(name, type);
return type;
}
}
finally
{
s_fakeTypeMapLock.Release();
}
}
if (nativeTypeKind != (int)TypeKind.Custom)
throw new ArgumentException(SR.Arg_UnrecognizedTypeName);
//
// Arbitrary managed types. See comment in TypeToTypeName.
//
return StringToCustomType(name);
}
return null;
}
#endif
private static string GetCustomTypeName(RuntimeTypeHandle type)
{
//
// For types loaded by the runtime, we may not have metadata from which to get the name.
// So we use the RuntimeTypeHandle instead. For types loaded via reflection, we may not
// have a RuntimeTypeHandle, in which case we will try to use the name.
//
#if !RHTESTCL
Type realType = InteropExtensions.GetTypeFromHandle(type);
if (realType.SupportsReflection())
{
//
// Managed types that has reflection metadata
//
// Use the fully assembly qualified name to make Jupiter happy as Jupiter might parse the
// name (!!) to extract the assembly name to look up files from directory with the same
// name. A bug has filed to them to fix this for the next release, because the format
// of Custom TypeKind is up to the interpretation of the projection layer and is supposed
// to be an implementation detail
// NOTE: The try/catch is added as a fail-safe
//
try
{
return realType.AssemblyQualifiedName;
}
catch (MissingMetadataException ex)
{
ExternalInterop.OutputDebugString(
SR.Format(SR.TypeNameMarshalling_MissingMetadata, ex.Message)
);
}
}
#endif
return GetPseudonymForType(type, /* useFake: */ false);
}
private static string GetPseudonymForType(RuntimeTypeHandle type, bool useFake)
{
// I'd really like to use the standard .net string formatting stuff here,
// but not enough of it is supported by rhtestcl.
ulong value = (ulong)type.GetRawValue();
StringBuilder sb = new StringBuilder(PseudonymPrefix, PseudonymPrefix.Length + 17);
if(useFake)
{
sb.Append('f');
}
else
{
sb.Append('r');
}
// append 64 bits, high to low, one nibble at a time
for (int shift = 60; shift >= 0; shift -= 4)
{
ulong nibble = (value >> shift) & 0xf;
if (nibble < 10)
sb.Append((char)(nibble + '0'));
else
sb.Append((char)((nibble - 10) + 'A'));
}
string result = sb.ToString();
return result;
}
private static Type StringToCustomType(string s)
{
ulong value = 0;
if (s.StartsWith(PseudonymPrefix))
{
//
// This is a name created from a RuntimeTypeHandle that does not have reflection metadata
//
if (s.Length != PseudonymPrefix.Length + 17)
throw new ArgumentException(SR.Arg_InvalidCustomTypeNameValue);
bool useFake = s[PseudonymPrefix.Length] == 'f';
if (useFake)
{
s_fakeTypeMapLock.Acquire();
try
{
return s_fakeTypeMap[s];
}
finally
{
s_fakeTypeMapLock.Release();
}
}
for (int i = PseudonymPrefix.Length + 1; i < s.Length; i++)
{
char c = s[i];
ulong nibble;
if (c >= '0' && c <= '9')
nibble = (ulong)(c - '0');
else if (c >= 'A' && c <= 'F')
nibble = (ulong)(c - 'A') + 10;
else
throw new ArgumentException(SR.Arg_InvalidCustomTypeNameValue);
value = (value << 4) | nibble;
}
return InteropExtensions.GetTypeFromHandle((IntPtr)value);
}
#if !RHTESTCL
else
{
//
// Try reflection
// If reflection failed, this is a type name that we don't know about
// In theory we could support round tripping of such types.
//
Type reflectType = Type.GetType(s);
if (reflectType == null)
throw new ArgumentException("Unrecognized custom TypeName");
return reflectType;
}
#else
else
{
return null;
}
#endif
}
/// <summary>
/// Try to get Diagnostic String for given RuntimeTypeHandle
/// Diagnostic usually means MissingMetadata Message
/// </summary>
/// <param name="interfaceType"></param>
/// <returns></returns>
public static string GetDiagnosticMessageForMissingType(RuntimeTypeHandle interfaceType)
{
#if ENABLE_WINRT
string msg = string.Empty;
try
{
// case 1: missing reflection metadata for interfaceType
// if this throws, we just return MissMetadataException Message
string typeName = interfaceType.GetDisplayName();
// case 2: if intefaceType is ICollection<T>/IReadOnlyCollection<T>,
// we need to find out its corresponding WinRT Interface and ask users to root them.
// Current there is an issue for projected type in rd.xml file--if user specify IList<T> in rd.xml,
// DR will only root IList<T> instead of both IList<T> and IVector<T>
Type type = interfaceType.GetType();
if (InteropExtensions.IsGenericType(interfaceType)
&& type.GenericTypeArguments != null
&& type.GenericTypeArguments.Length == 1)
{
List<string> missTypeNames = new List<string>();
Type genericType = type.GetGenericTypeDefinition();
bool isICollectOfT = false;
bool isIReadOnlyCollectOfT = false;
if (genericType.TypeHandle.Equals(typeof(ICollection<>).TypeHandle))
{
isICollectOfT = true;
Type argType = type.GenericTypeArguments[0];
if (argType.IsConstructedGenericType && argType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
// the missing type could be either IMap<K,V> or IVector<IKeyValuePair<K,v>>
missTypeNames.Add(
McgTypeHelpers.ConstructGenericTypeFullName(
"Windows.Foundation.Collections.IMap",
new string[]
{
argType.GenericTypeArguments[0].ToString(),
argType.GenericTypeArguments[1].ToString()
}
)
);
missTypeNames.Add(
McgTypeHelpers.ConstructGenericTypeFullName(
"Windows.Foundation.Collections.IVector",
new String[]
{
McgTypeHelpers.ConstructGenericTypeFullName(
"Windows.Foundation.Collections.IKeyValuePair",
new string[]
{
argType.GenericTypeArguments[0].ToString(),
argType.GenericTypeArguments[1].ToString()
}
)
}
)
);
}
else
{
// the missing type is IVector<T>
missTypeNames.Add(
McgTypeHelpers.ConstructGenericTypeFullName(
"Windows.Foundation.Collections.IVector",
new string[]
{
argType.ToString()
}
)
);
}
} // genericType == typeof(ICollection<>)
else if (genericType == typeof(IReadOnlyCollection<>))
{
isIReadOnlyCollectOfT = true;
Type argType = type.GenericTypeArguments[0];
if (argType.IsConstructedGenericType && argType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
// the missing type could be either IVectorView<IKeyValuePair<K,v>> or IMapView<K,V>
missTypeNames.Add(
McgTypeHelpers.ConstructGenericTypeFullName(
"Windows.Foundation.Collections.IVectorView",
new String[]
{
McgTypeHelpers.ConstructGenericTypeFullName(
"Windows.Foundation.Collections.IKeyValuePair",
new string[]
{
argType.GenericTypeArguments[0].ToString(),
argType.GenericTypeArguments[1].ToString()
}
)
}
)
);
missTypeNames.Add(
McgTypeHelpers.ConstructGenericTypeFullName(
"Windows.Foundation.Collections.IMapView",
new string[]
{
argType.GenericTypeArguments[0].ToString(),
argType.GenericTypeArguments[1].ToString()
}
)
);
}
else
{
//the missing type is IVectorView<T>
missTypeNames.Add(
McgTypeHelpers.ConstructGenericTypeFullName(
"Windows.Foundation.Collections.IVectorView",
new string[]
{
argType.ToString()
}
)
);
}
}
if (isICollectOfT || isIReadOnlyCollectOfT)
{
// Concat all missing Type Names into one message
for (int i = 0; i < missTypeNames.Count; i++)
{
msg += SR.Format(SR.ComTypeMarshalling_MissingInteropData, missTypeNames[i]);
if (i != missTypeNames.Count - 1)
msg += Environment.NewLine;
}
return msg;
}
}
// case 3: We can get type name but not McgTypeInfo, maybe another case similar to case 2
// definitely is a bug.
msg = SR.Format(SR.ComTypeMarshalling_MissingInteropData, Type.GetTypeFromHandle(interfaceType));
}
catch (MissingMetadataException ex)
{
msg = ex.Message;
}
return msg;
#else
return interfaceType.ToString();
#endif //ENABLE_WINRT
}
// Construct Generic Type Full Name
private static string ConstructGenericTypeFullName(string genericTypeDefinitionFullName, string[] genericTypeArguments)
{
string fullName = genericTypeDefinitionFullName;
fullName += "<";
for (int i = 0; i < genericTypeArguments.Length; i++)
{
if (i != 0)
fullName += ",";
fullName += genericTypeArguments[i];
}
fullName += ">";
return fullName;
}
}
internal static class TypeHandleExtensions
{
internal static string GetDisplayName(this RuntimeTypeHandle handle)
{
#if ENABLE_WINRT
return Internal.Runtime.Augments.RuntimeAugments.GetLastResortString(handle);
#else
return handle.ToString();
#endif
}
internal static bool IsComClass(this RuntimeTypeHandle handle)
{
#if CORECLR
return InteropExtensions.IsClass(handle);
#else
return !InteropExtensions.IsInterface(handle) &&
!handle.IsValueType() &&
!InteropExtensions.AreTypesAssignable(handle, typeof(Delegate).TypeHandle);
#endif
}
internal static bool IsIJupiterObject(this RuntimeTypeHandle interfaceType)
{
#if ENABLE_WINRT
return interfaceType.Equals(InternalTypes.IJupiterObject);
#else
return false;
#endif
}
internal static bool IsIInspectable(this RuntimeTypeHandle interfaceType)
{
#if ENABLE_MIN_WINRT
return interfaceType.Equals(InternalTypes.IInspectable);
#else
return false;
#endif
}
#region "Interface Data"
internal static bool HasInterfaceData(this RuntimeTypeHandle interfaceType)
{
int moduleIndex, typeIndex;
return McgModuleManager.GetIndicesForInterface(interfaceType, out moduleIndex, out typeIndex);
}
internal static bool IsSupportIInspectable(this RuntimeTypeHandle interfaceType)
{
int moduleIndex, interfaceIndex;
if (McgModuleManager.GetIndicesForInterface(interfaceType, out moduleIndex, out interfaceIndex))
{
return McgModuleManager.GetInterfaceDataByIndex(moduleIndex, interfaceIndex).IsIInspectable;
}
#if ENABLE_WINRT
throw new MissingInteropDataException(SR.DelegateMarshalling_MissingInteropData, Type.GetTypeFromHandle(interfaceType));
#else
return false;
#endif
}
internal static bool HasDynamicAdapterClass(this RuntimeTypeHandle interfaceType)
{
int moduleIndex, interfaceIndex;
if (McgModuleManager.GetIndicesForInterface(interfaceType, out moduleIndex, out interfaceIndex))
{
return !McgModuleManager.GetInterfaceDataByIndex(moduleIndex, interfaceIndex).DynamicAdapterClassType.IsNull(); ;
}
#if !RHTESTCL && !CORECLR && !CORERT && ENABLE_MIN_WINRT
if (McgModuleManager.UseDynamicInterop && interfaceType.IsGenericType())
return false;
#endif
#if ENABLE_MIN_WINRT
throw new MissingInteropDataException(SR.DelegateMarshalling_MissingInteropData, Type.GetTypeFromHandle(interfaceType));
#else
Environment.FailFast("HasDynamicAdapterClass.");
return false;
#endif
}
internal static RuntimeTypeHandle GetDynamicAdapterClassType(this RuntimeTypeHandle interfaceType)
{
int moduleIndex, interfaceIndex;
if (McgModuleManager.GetIndicesForInterface(interfaceType, out moduleIndex, out interfaceIndex))
{
return McgModuleManager.GetInterfaceDataByIndex(moduleIndex, interfaceIndex).DynamicAdapterClassType;
}
return default(RuntimeTypeHandle);
}
internal static Guid GetInterfaceGuid(this RuntimeTypeHandle interfaceType)
{
int moduleIndex, interfaceIndex;
if (McgModuleManager.GetIndicesForInterface(interfaceType, out moduleIndex, out interfaceIndex))
{
return McgModuleManager.GetInterfaceDataByIndex(moduleIndex, interfaceIndex).ItfGuid;
}
#if !CORECLR && ENABLE_WINRT
// Fall back to dynamic interop to generate guid
// Currently dynamic interop wil generate guid for generic type(interface/delegate)
if(interfaceType.IsGenericType() && McgModuleManager.UseDynamicInterop)
{
return DynamicInteropGuidHelpers.GetGuid_NoThrow(interfaceType);
}
#endif
return default(Guid);
}
internal static IntPtr GetCcwVtableThunk(this RuntimeTypeHandle interfaceType)
{
int moduleIndex, interfaceIndex;
if (McgModuleManager.GetIndicesForInterface(interfaceType, out moduleIndex, out interfaceIndex))
{
return McgModuleManager.GetInterfaceDataByIndex(moduleIndex, interfaceIndex).CcwVtable;
}
return default(IntPtr);
}
static IntPtr[] SharedCCWList = new IntPtr[] {
#if ENABLE_WINRT
SharedCcw_IVector.GetVtable(),
SharedCcw_IVectorView.GetVtable(),
SharedCcw_IIterable.GetVtable(),
SharedCcw_IIterator.GetVtable(),
#if RHTESTCL || CORECLR
default(IntPtr),
#else
SharedCcw_AsyncOperationCompletedHandler.GetVtable(),
#endif
SharedCcw_IVector_Blittable.GetVtable(),
SharedCcw_IVectorView_Blittable.GetVtable(),
#if RHTESTCL || CORECLR
default(IntPtr)
#else
SharedCcw_IIterator_Blittable.GetVtable()
#endif
#endif //ENABLE_WINRT
};
internal static IntPtr GetCcwVtable(this RuntimeTypeHandle interfaceType)
{
int moduleIndex, interfaceIndex;
if (McgModuleManager.GetIndicesForInterface(interfaceType, out moduleIndex, out interfaceIndex))
{
McgInterfaceData interfaceData = McgModuleManager.GetInterfaceDataByIndex(moduleIndex, interfaceIndex);
McgInterfaceFlags flag = interfaceData.Flags & McgInterfaceFlags.SharedCCWMask;
if (flag != 0)
{
return SharedCCWList[(int)flag >> 4];
}
if (interfaceData.CcwVtable == IntPtr.Zero)
return IntPtr.Zero;
return CalliIntrinsics.Call__GetCcwVtable(interfaceData.CcwVtable);
}
return default(IntPtr);
}
internal static int GetMarshalIndex(this RuntimeTypeHandle interfaceType)
{
int moduleIndex, interfaceIndex;
if (McgModuleManager.GetIndicesForInterface(interfaceType, out moduleIndex, out interfaceIndex))
{
return McgModuleManager.GetInterfaceDataByIndex(moduleIndex, interfaceIndex).MarshalIndex;
}
return -1;
}
internal static McgInterfaceFlags GetInterfaceFlags(this RuntimeTypeHandle interfaceType)
{
int moduleIndex, interfaceIndex;
if (McgModuleManager.GetIndicesForInterface(interfaceType, out moduleIndex, out interfaceIndex))
{
return McgModuleManager.GetInterfaceDataByIndex(moduleIndex, interfaceIndex).Flags;
}
return default(McgInterfaceFlags);
}
internal static RuntimeTypeHandle GetDispatchClassType(this RuntimeTypeHandle interfaceType)
{
int moduleIndex, interfaceIndex;
if (McgModuleManager.GetIndicesForInterface(interfaceType, out moduleIndex, out interfaceIndex))
{
return McgModuleManager.GetInterfaceDataByIndex(moduleIndex, interfaceIndex).DispatchClassType;
}
return default(RuntimeTypeHandle);
}
internal static IntPtr GetDelegateInvokeStub(this RuntimeTypeHandle winrtDelegateType)
{
int moduleIndex, interfaceIndex;
if (McgModuleManager.GetIndicesForInterface(winrtDelegateType, out moduleIndex, out interfaceIndex))
{
return McgModuleManager.GetInterfaceDataByIndex(moduleIndex, interfaceIndex).DelegateInvokeStub;
}
return default(IntPtr);
}
#endregion
#region "Class Data"
internal static GCPressureRange GetGCPressureRange(this RuntimeTypeHandle classType)
{
int moduleIndex, classIndex;
if (McgModuleManager.GetIndicesForClass(classType, out moduleIndex, out classIndex))
{
return McgModuleManager.GetClassDataByIndex(moduleIndex, classIndex).GCPressureRange;
}
return GCPressureRange.None;
}
internal static bool IsSealed(this RuntimeTypeHandle classType)
{
int moduleIndex, classIndex;
if (McgModuleManager.GetIndicesForClass(classType, out moduleIndex, out classIndex))
{
return ((McgModuleManager.GetClassDataByIndex(moduleIndex, classIndex).Flags & McgClassFlags.IsSealed) != 0);
}
#if ENABLE_WINRT
throw new MissingInteropDataException(SR.DelegateMarshalling_MissingInteropData, Type.GetTypeFromHandle(classType));
#else
Environment.FailFast("IsSealed");
return false;
#endif
}
internal static ComMarshalingType GetMarshalingType(this RuntimeTypeHandle classType)
{
int moduleIndex, classIndex;
if (McgModuleManager.GetIndicesForClass(classType, out moduleIndex, out classIndex))
{
return McgModuleManager.GetClassDataByIndex(moduleIndex, classIndex).MarshalingType;
}
return ComMarshalingType.Unknown;
}
internal static RuntimeTypeHandle GetDefaultInterface(this RuntimeTypeHandle classType)
{
int moduleIndex, classIndex;
if (McgModuleManager.GetIndicesForClass(classType, out moduleIndex, out classIndex))
{
McgClassData classData = McgModuleManager.GetClassDataByIndex(moduleIndex, classIndex);
int defaultInterfaceIndex = classData.DefaultInterfaceIndex;
if (defaultInterfaceIndex >= 0)
{
return McgModuleManager.GetInterfaceDataByIndex(moduleIndex, defaultInterfaceIndex).ItfType;
}
else
{
return classData.DefaultInterfaceType;
}
}
return default(RuntimeTypeHandle);
}
/// <summary>
/// Fetch class(or Enum)'s WinRT type name to calculate GUID
/// </summary>
/// <param name="classType"></param>
/// <returns></returns>
internal static string GetWinRTTypeName(this RuntimeTypeHandle classType)
{
bool isWinRT;
return McgModuleManager.GetTypeName(classType, out isWinRT);
}
#endregion
#region "Generic Argument Data"
internal static RuntimeTypeHandle GetIteratorType(this RuntimeTypeHandle interfaceType)
{
McgGenericArgumentMarshalInfo mcgGenericArgumentMarshalInfo;
if (McgModuleManager.TryGetGenericArgumentMarshalInfo(interfaceType, out mcgGenericArgumentMarshalInfo))
{
return mcgGenericArgumentMarshalInfo.IteratorType;
}
return default(RuntimeTypeHandle);
}
internal static RuntimeTypeHandle GetElementClassType(this RuntimeTypeHandle interfaceType)
{
McgGenericArgumentMarshalInfo mcgGenericArgumentMarshalInfo;
if (McgModuleManager.TryGetGenericArgumentMarshalInfo(interfaceType, out mcgGenericArgumentMarshalInfo))
{
return mcgGenericArgumentMarshalInfo.ElementClassType;
}
return default(RuntimeTypeHandle);
}
internal static RuntimeTypeHandle GetElementInterfaceType(this RuntimeTypeHandle interfaceType)
{
McgGenericArgumentMarshalInfo mcgGenericArgumentMarshalInfo;
if (McgModuleManager.TryGetGenericArgumentMarshalInfo(interfaceType, out mcgGenericArgumentMarshalInfo))
{
return mcgGenericArgumentMarshalInfo.ElementInterfaceType;
}
return default(RuntimeTypeHandle);
}
internal static RuntimeTypeHandle GetVectorViewType(this RuntimeTypeHandle interfaceType)
{
McgGenericArgumentMarshalInfo mcgGenericArgumentMarshalInfo;
if (McgModuleManager.TryGetGenericArgumentMarshalInfo(interfaceType, out mcgGenericArgumentMarshalInfo))
{
return mcgGenericArgumentMarshalInfo.VectorViewType;
}
return default(RuntimeTypeHandle);
}
internal static RuntimeTypeHandle GetAsyncOperationType(this RuntimeTypeHandle interfaceType)
{
McgGenericArgumentMarshalInfo mcgGenericArgumentMarshalInfo;
if (McgModuleManager.TryGetGenericArgumentMarshalInfo(interfaceType, out mcgGenericArgumentMarshalInfo))
{
return mcgGenericArgumentMarshalInfo.AsyncOperationType;
}
return default(RuntimeTypeHandle);
}
internal static int GetByteSize(this RuntimeTypeHandle interfaceType)
{
McgGenericArgumentMarshalInfo mcgGenericArgumentMarshalInfo;
if (McgModuleManager.TryGetGenericArgumentMarshalInfo(interfaceType, out mcgGenericArgumentMarshalInfo))
{
return (int)mcgGenericArgumentMarshalInfo.ElementSize;
}
return -1;
}
#endregion
#region "CCWTemplate Data"
internal static string GetCCWRuntimeClassName(this RuntimeTypeHandle ccwType)
{
string ccwRuntimeClassName;
if (McgModuleManager.TryGetCCWRuntimeClassName(ccwType, out ccwRuntimeClassName))
return ccwRuntimeClassName;
return default(string);
}
internal static bool IsSupportCCWTemplate(this RuntimeTypeHandle ccwType)
{
int moduleIndex, ccwTemplateIndex;
return McgModuleManager.GetIndicesForCCWTemplate(ccwType, out moduleIndex, out ccwTemplateIndex);
}
internal static bool IsCCWWinRTType(this RuntimeTypeHandle ccwType)
{
int moduleIndex, ccwTemplateIndex;
if (McgModuleManager.GetIndicesForCCWTemplate(ccwType, out moduleIndex, out ccwTemplateIndex))
{
return McgModuleManager.GetCCWTemplateDataByIndex(moduleIndex, ccwTemplateIndex).IsWinRTType;
}
#if ENABLE_WINRT
throw new MissingInteropDataException(SR.DelegateMarshalling_MissingInteropData, Type.GetTypeFromHandle(ccwType));
#else
Environment.FailFast("IsCCWWinRTType");
return false;
#endif
}
internal static IEnumerable<RuntimeTypeHandle> GetImplementedInterfaces(this RuntimeTypeHandle ccwType)
{
int moduleIndex, ccwTemplateIndex;
if (McgModuleManager.GetIndicesForCCWTemplate(ccwType, out moduleIndex, out ccwTemplateIndex))
{
return McgModuleManager.GetImplementedInterfacesByIndex(moduleIndex, ccwTemplateIndex);
}
#if ENABLE_WINRT
throw new MissingInteropDataException(SR.DelegateMarshalling_MissingInteropData, Type.GetTypeFromHandle(ccwType));
#else
Environment.FailFast("GetImplementedInterfaces");
return null;
#endif
}
internal static RuntimeTypeHandle GetBaseClass(this RuntimeTypeHandle ccwType)
{
int moduleIndex, ccwTemplateIndex;
if (McgModuleManager.GetIndicesForCCWTemplate(ccwType, out moduleIndex, out ccwTemplateIndex))
{
CCWTemplateData ccwTemplate = McgModuleManager.GetCCWTemplateDataByIndex(moduleIndex, ccwTemplateIndex);
int parentCCWTemplateIndex = ccwTemplate.ParentCCWTemplateIndex;
if (parentCCWTemplateIndex >= 0)
{
return McgModuleManager.GetCCWTemplateDataByIndex(moduleIndex, parentCCWTemplateIndex).ClassType;
}
else if (!ccwTemplate.BaseType.Equals(default(RuntimeTypeHandle)))
{
return ccwTemplate.BaseType;
}
// doesn't have base class
return default(RuntimeTypeHandle);
}
#if ENABLE_WINRT
throw new MissingInteropDataException(SR.DelegateMarshalling_MissingInteropData, Type.GetTypeFromHandle(ccwType));
#else
Environment.FailFast("GetBaseClass");
return default(RuntimeTypeHandle);
#endif
}
private static void GetIIDsImpl(RuntimeTypeHandle typeHandle, System.Collections.Generic.Internal.List<Guid> iids)
{
RuntimeTypeHandle baseClass = typeHandle.GetBaseClass();
if (!baseClass.IsNull())
{
GetIIDsImpl(baseClass, iids);
}
foreach(RuntimeTypeHandle t in typeHandle.GetImplementedInterfaces())
{
if (t.IsInvalid())
continue;
Guid guid = t.GetInterfaceGuid();
//
// Retrieve the GUID and add it to the list
// Skip ICustomPropertyProvider - we've already added it as the first item
//
if (!InteropExtensions.GuidEquals(ref guid, ref Interop.COM.IID_ICustomPropertyProvider))
{
//
// Avoid duplicated ones
//
// The duplicates comes from duplicated interface declarations in the metadata across
// parent/child classes, as well as the "injected" override interfaces for protected
// virtual methods (for example, if a derived class implements a IShapeprotected internal
// method, it only implements a protected method and doesn't implement IShapeInternal
// directly, and we have to "inject" it in MCG
//
// Doing a linear lookup is slow, but people typically never call GetIIDs perhaps except
// for debugging purposes (because the GUIDs returned back aren't exactly useful and you
// can't map it back to type), so I don't care about perf here that much
//
if (!iids.Contains(guid))
iids.Add(guid);
}
}
}
/// <summary>
/// Return the list of IIDs
/// Used by IInspectable.GetIIDs implementation for every CCW
/// </summary>
internal static System.Collections.Generic.Internal.List<Guid> GetIIDs(this RuntimeTypeHandle ccwType)
{
System.Collections.Generic.Internal.List<Guid> iids = new System.Collections.Generic.Internal.List<Guid>();
// Every CCW implements ICPP
iids.Add(Interop.COM.IID_ICustomPropertyProvider);
// if there isn't any data about this type, just return empty list
if (!ccwType.IsSupportCCWTemplate())
return iids;
GetIIDsImpl(ccwType, iids);
return iids;
}
#endregion
#region "Struct Data"
internal static string StructWinRTName(this RuntimeTypeHandle structType)
{
#if ENABLE_MIN_WINRT
string typeName;
if (McgModuleManager.TryGetStructWinRTName(structType, out typeName))
return typeName;
#endif
return null;
}
#endregion
internal static bool IsInvalid(this RuntimeTypeHandle typeHandle)
{
if (typeHandle.IsNull())
return true;
if (typeHandle.Equals(typeof(DependencyReductionTypeRemoved).TypeHandle))
return true;
return false;
}
}
public static class TypeOfHelper
{
static void RuntimeTypeHandleOf_DidntGetTransformedAway()
{
#if !RHTESTCL
Debug.Assert(false);
#endif // RHTESTCL
}
public static RuntimeTypeHandle RuntimeTypeHandleOf(string typeName)
{
RuntimeTypeHandleOf_DidntGetTransformedAway();
return default(RuntimeTypeHandle);
}
public static RuntimeTypeHandle RuntimeTypeHandleOf(string typeName, string arg)
{
RuntimeTypeHandleOf_DidntGetTransformedAway();
return default(RuntimeTypeHandle);
}
public static RuntimeTypeHandle RuntimeTypeHandleOf(string typeName, string arg1, string arg2)
{
RuntimeTypeHandleOf_DidntGetTransformedAway();
return default(RuntimeTypeHandle);
}
public static RuntimeTypeHandle RuntimeTypeHandleOf(string typeName, string arg1, string arg2, string arg3)
{
RuntimeTypeHandleOf_DidntGetTransformedAway();
return default(RuntimeTypeHandle);
}
public static RuntimeTypeHandle RuntimeTypeHandleOf(string typeName, string arg1, string arg2, string arg3, string arg4)
{
RuntimeTypeHandleOf_DidntGetTransformedAway();
return default(RuntimeTypeHandle);
}
public static RuntimeTypeHandle RuntimeTypeHandleOf(string typeName, string arg1, string arg2, string arg3, string arg4, string arg5)
{
RuntimeTypeHandleOf_DidntGetTransformedAway();
return default(RuntimeTypeHandle);
}
public static RuntimeTypeHandle RuntimeTypeHandleOf(string typeName, string arg1, string arg2, string arg3, string arg4, string arg5, string arg6)
{
RuntimeTypeHandleOf_DidntGetTransformedAway();
return default(RuntimeTypeHandle);
}
public static Type TypeOf(string typeName)
{
RuntimeTypeHandleOf_DidntGetTransformedAway();
return default(Type);
}
}
}
| |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
namespace Cassandra
{
/// <summary>
/// Options related to connection pooling. <p> The driver uses connections in an
/// asynchronous way. Meaning that multiple requests can be submitted on the same
/// connection at the same time. This means that the driver only needs to
/// maintain a relatively small number of connections to each Cassandra host.
/// These options allow to control how many connections are kept exactly. </p><p> For
/// each host, the driver keeps a core amount of connections open at all time
/// (<link>PoolingOptions#getCoreConnectionsPerHost</link>). If the utilization
/// of those connections reaches a configurable threshold
/// (<link>PoolingOptions#getMaxSimultaneousRequestsPerConnectionTreshold</link>),
/// more connections are created up to a configurable maximum number of
/// connections (<link>PoolingOptions#getMaxConnectionPerHost</link>). Once more
/// than core connections have been created, connections in excess are reclaimed
/// if the utilization of opened connections drops below the configured threshold
/// (<link>PoolingOptions#getMinSimultaneousRequestsPerConnectionTreshold</link>).
/// </p><p> Each of these parameters can be separately set for <c>Local</c> and
/// <c>Remote</c> hosts (<link>HostDistance</link>). For
/// <c>Ignored</c> hosts, the default for all those settings is 0 and
/// cannot be changed.</p>
/// </summary>
public class PoolingOptions
{
//the defaults target small number concurrent requests (protocol 1 and 2) and multiple connections to a host
private const int DefaultMinRequests = 25;
private const int DefaultMaxRequests = 128;
private const int DefaultCorePoolLocal = 2;
private const int DefaultCorePoolRemote = 1;
private const int DefaultMaxPoolLocal = 8;
private const int DefaultMaxPoolRemote = 2;
private int _coreConnectionsForLocal = DefaultCorePoolLocal;
private int _coreConnectionsForRemote = DefaultCorePoolRemote;
private int _maxConnectionsForLocal = DefaultMaxPoolLocal;
private int _maxConnectionsForRemote = DefaultMaxPoolRemote;
private int _maxSimultaneousRequestsForLocal = DefaultMaxRequests;
private int _maxSimultaneousRequestsForRemote = DefaultMaxRequests;
private int _minSimultaneousRequestsForLocal = DefaultMinRequests;
private int _minSimultaneousRequestsForRemote = DefaultMinRequests;
private int? _heartBeatInterval;
/// <summary>
/// Number of simultaneous requests on a connection below which connections in
/// excess are reclaimed. <p> If an opened connection to an host at distance
/// <c>distance</c> handles less than this number of simultaneous requests
/// and there is more than <link>#GetCoreConnectionsPerHost</link> connections
/// open to this host, the connection is closed. </p><p> The default value for this
/// option is 25 for <c>Local</c> and <c>Remote</c> hosts.</p>
/// </summary>
/// <param name="distance"> the <c>HostDistance</c> for which to return this threshold.</param>
/// <returns>the configured threshold, or the default one if none have been set.</returns>
public int GetMinSimultaneousRequestsPerConnectionTreshold(HostDistance distance)
{
switch (distance)
{
case HostDistance.Local:
return _minSimultaneousRequestsForLocal;
case HostDistance.Remote:
return _minSimultaneousRequestsForRemote;
default:
return 0;
}
}
/// <summary>
/// Sets the number of simultaneous requests on a connection below which
/// connections in excess are reclaimed.
/// </summary>
/// <param name="distance"> the <c>HostDistance</c> for which to configure this
/// threshold. </param>
/// <param name="minSimultaneousRequests"> the value to set. </param>
///
/// <returns>this <c>PoolingOptions</c>. </returns>
public PoolingOptions SetMinSimultaneousRequestsPerConnectionTreshold(HostDistance distance, int minSimultaneousRequests)
{
switch (distance)
{
case HostDistance.Local:
_minSimultaneousRequestsForLocal = minSimultaneousRequests;
break;
case HostDistance.Remote:
_minSimultaneousRequestsForRemote = minSimultaneousRequests;
break;
default:
throw new ArgumentOutOfRangeException("Cannot set min streams per connection threshold for " + distance + " hosts");
}
return this;
}
/// <summary>
/// Number of simultaneous requests on all connections to an host after which
/// more connections are created. <p> If all the connections opened to an host at
/// distance <c>* distance</c> connection are handling more than this
/// number of simultaneous requests and there is less than
/// <link>#getMaxConnectionPerHost</link> connections open to this host, a new
/// connection is open. </p><p> Note that a given connection cannot handle more than
/// 128 simultaneous requests (protocol limitation). </p><p> The default value for
/// this option is 100 for <c>Local</c> and <c>Remote</c> hosts.</p>
/// </summary>
/// <param name="distance"> the <c>HostDistance</c> for which to return this threshold.</param>
/// <returns>the configured threshold, or the default one if none have been set.</returns>
public int GetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance distance)
{
switch (distance)
{
case HostDistance.Local:
return _maxSimultaneousRequestsForLocal;
case HostDistance.Remote:
return _maxSimultaneousRequestsForRemote;
default:
return 0;
}
}
/// <summary>
/// Sets number of simultaneous requests on all connections to an host after
/// which more connections are created.
/// </summary>
/// <param name="distance"> the <c>HostDistance</c> for which to configure this
/// threshold. </param>
/// <param name="maxSimultaneousRequests"> the value to set. </param>
///
/// <returns>this <c>PoolingOptions</c>. </returns>
/// <throws name="IllegalArgumentException"> if <c>distance == HostDistance.Ignore</c>.</throws>
public PoolingOptions SetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance distance, int maxSimultaneousRequests)
{
switch (distance)
{
case HostDistance.Local:
_maxSimultaneousRequestsForLocal = maxSimultaneousRequests;
break;
case HostDistance.Remote:
_maxSimultaneousRequestsForRemote = maxSimultaneousRequests;
break;
default:
throw new ArgumentOutOfRangeException("Cannot set max streams per connection threshold for " + distance + " hosts");
}
return this;
}
/// <summary>
/// The core number of connections per host. <p> For the provided
/// <c>distance</c>, this correspond to the number of connections initially
/// created and kept open to each host of that distance.</p>
/// </summary>
/// <param name="distance"> the <c>HostDistance</c> for which to return this threshold.
/// </param>
///
/// <returns>the core number of connections per host at distance
/// <c>distance</c>.</returns>
public int GetCoreConnectionsPerHost(HostDistance distance)
{
switch (distance)
{
case HostDistance.Local:
return _coreConnectionsForLocal;
case HostDistance.Remote:
return _coreConnectionsForRemote;
default:
return 0;
}
}
/// <summary>
/// Sets the core number of connections per host.
/// </summary>
/// <param name="distance"> the <c>HostDistance</c> for which to set this threshold.
/// </param>
/// <param name="coreConnections"> the value to set </param>
///
/// <returns>this <c>PoolingOptions</c>. </returns>
/// <throws name="IllegalArgumentException"> if <c>distance == HostDistance.Ignored</c>.</throws>
public PoolingOptions SetCoreConnectionsPerHost(HostDistance distance, int coreConnections)
{
switch (distance)
{
case HostDistance.Local:
_coreConnectionsForLocal = coreConnections;
break;
case HostDistance.Remote:
_coreConnectionsForRemote = coreConnections;
break;
default:
throw new ArgumentOutOfRangeException("Cannot set core connections per host for " + distance + " hosts");
}
return this;
}
/// <summary>
/// The maximum number of connections per host. <p> For the provided
/// <c>distance</c>, this correspond to the maximum number of connections
/// that can be created per host at that distance.</p>
/// </summary>
/// <param name="distance"> the <c>HostDistance</c> for which to return this threshold.
/// </param>
///
/// <returns>the maximum number of connections per host at distance
/// <c>distance</c>.</returns>
public int GetMaxConnectionPerHost(HostDistance distance)
{
switch (distance)
{
case HostDistance.Local:
return _maxConnectionsForLocal;
case HostDistance.Remote:
return _maxConnectionsForRemote;
default:
return 0;
}
}
/// <summary>
/// Sets the maximum number of connections per host.
/// </summary>
/// <param name="distance"> the <c>HostDistance</c> for which to set this threshold.
/// </param>
/// <param name="maxConnections"> the value to set </param>
///
/// <returns>this <c>PoolingOptions</c>. </returns>
public PoolingOptions SetMaxConnectionsPerHost(HostDistance distance, int maxConnections)
{
switch (distance)
{
case HostDistance.Local:
_maxConnectionsForLocal = maxConnections;
break;
case HostDistance.Remote:
_maxConnectionsForRemote = maxConnections;
break;
default:
throw new ArgumentOutOfRangeException("Cannot set max connections per host for " + distance + " hosts");
}
return this;
}
/// <summary>
/// Gets the amount of idle time in milliseconds that has to pass before the driver issues a request on an active connection to avoid idle time disconnections.
/// </summary>
public int? GetHeartBeatInterval()
{
return _heartBeatInterval;
}
/// <summary>
/// Sets the amount of idle time in milliseconds that has to pass before the driver issues a request on an active connection to avoid idle time disconnections.
/// <remarks>When set to 0 the heartbeat functionality at connection level is disabled.</remarks>
/// </summary>
public PoolingOptions SetHeartBeatInterval(int value)
{
_heartBeatInterval = value;
return this;
}
/// <summary>
/// Gets the default protocol options by protocol version
/// </summary>
internal static PoolingOptions GetDefault(byte protocolVersion)
{
if (protocolVersion < 3)
{
//New instance of pooling options with default values
return new PoolingOptions();
}
else
{
//New instance of pooling options with default values for high number of concurrent requests
return new PoolingOptions()
.SetCoreConnectionsPerHost(HostDistance.Local, 1)
.SetMaxConnectionsPerHost(HostDistance.Local, 2)
.SetMaxConnectionsPerHost(HostDistance.Remote, 1)
.SetMaxConnectionsPerHost(HostDistance.Remote, 1)
.SetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance.Local, 1500)
.SetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance.Remote, 1500);
}
}
}
}
| |
namespace Steamworks {
[System.Serializable]
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 4)]
public struct CSteamID : System.IEquatable<CSteamID>, System.IComparable<CSteamID> {
public static readonly CSteamID Nil = new CSteamID();
public static readonly CSteamID OutofDateGS = new CSteamID(new AccountID_t(0), 0, EUniverse.k_EUniverseInvalid, EAccountType.k_EAccountTypeInvalid);
public static readonly CSteamID LanModeGS = new CSteamID(new AccountID_t(0), 0, EUniverse.k_EUniversePublic, EAccountType.k_EAccountTypeInvalid);
public static readonly CSteamID NotInitYetGS = new CSteamID(new AccountID_t(1), 0, EUniverse.k_EUniverseInvalid, EAccountType.k_EAccountTypeInvalid);
public static readonly CSteamID NonSteamGS = new CSteamID(new AccountID_t(2), 0, EUniverse.k_EUniverseInvalid, EAccountType.k_EAccountTypeInvalid);
public ulong m_SteamID;
public CSteamID(AccountID_t unAccountID, EUniverse eUniverse, EAccountType eAccountType) {
m_SteamID = 0;
Set(unAccountID, eUniverse, eAccountType);
}
public CSteamID(AccountID_t unAccountID, uint unAccountInstance, EUniverse eUniverse, EAccountType eAccountType) {
m_SteamID = 0;
#if _SERVER && Assert
Assert( ! ( ( EAccountType.k_EAccountTypeIndividual == eAccountType ) && ( unAccountInstance > k_unSteamUserWebInstance ) ) ); // enforce that for individual accounts, instance is always 1
#endif // _SERVER
InstancedSet(unAccountID, unAccountInstance, eUniverse, eAccountType);
}
public CSteamID(ulong ulSteamID) {
m_SteamID = ulSteamID;
}
public void Set(AccountID_t unAccountID, EUniverse eUniverse, EAccountType eAccountType) {
SetAccountID(unAccountID);
SetEUniverse(eUniverse);
SetEAccountType(eAccountType);
if (eAccountType == EAccountType.k_EAccountTypeClan || eAccountType == EAccountType.k_EAccountTypeGameServer) {
SetAccountInstance(0);
}
else {
SetAccountInstance(Constants.k_unSteamUserDefaultInstance);
}
}
public void InstancedSet(AccountID_t unAccountID, uint unInstance, EUniverse eUniverse, EAccountType eAccountType) {
SetAccountID(unAccountID);
SetEUniverse(eUniverse);
SetEAccountType(eAccountType);
SetAccountInstance(unInstance);
}
public void Clear() {
m_SteamID = 0;
}
public void CreateBlankAnonLogon(EUniverse eUniverse) {
SetAccountID(new AccountID_t(0));
SetEUniverse(eUniverse);
SetEAccountType(EAccountType.k_EAccountTypeAnonGameServer);
SetAccountInstance(0);
}
public void CreateBlankAnonUserLogon(EUniverse eUniverse) {
SetAccountID(new AccountID_t(0));
SetEUniverse(eUniverse);
SetEAccountType(EAccountType.k_EAccountTypeAnonUser);
SetAccountInstance(0);
}
//-----------------------------------------------------------------------------
// Purpose: Is this an anonymous game server login that will be filled in?
//-----------------------------------------------------------------------------
public bool BBlankAnonAccount() {
return GetAccountID() == new AccountID_t(0) && BAnonAccount() && GetUnAccountInstance() == 0;
}
//-----------------------------------------------------------------------------
// Purpose: Is this a game server account id? (Either persistent or anonymous)
//-----------------------------------------------------------------------------
public bool BGameServerAccount() {
return GetEAccountType() == EAccountType.k_EAccountTypeGameServer || GetEAccountType() == EAccountType.k_EAccountTypeAnonGameServer;
}
//-----------------------------------------------------------------------------
// Purpose: Is this a persistent (not anonymous) game server account id?
//-----------------------------------------------------------------------------
public bool BPersistentGameServerAccount() {
return GetEAccountType() == EAccountType.k_EAccountTypeGameServer;
}
//-----------------------------------------------------------------------------
// Purpose: Is this an anonymous game server account id?
//-----------------------------------------------------------------------------
public bool BAnonGameServerAccount() {
return GetEAccountType() == EAccountType.k_EAccountTypeAnonGameServer;
}
//-----------------------------------------------------------------------------
// Purpose: Is this a content server account id?
//-----------------------------------------------------------------------------
public bool BContentServerAccount() {
return GetEAccountType() == EAccountType.k_EAccountTypeContentServer;
}
//-----------------------------------------------------------------------------
// Purpose: Is this a clan account id?
//-----------------------------------------------------------------------------
public bool BClanAccount() {
return GetEAccountType() == EAccountType.k_EAccountTypeClan;
}
//-----------------------------------------------------------------------------
// Purpose: Is this a chat account id?
//-----------------------------------------------------------------------------
public bool BChatAccount() {
return GetEAccountType() == EAccountType.k_EAccountTypeChat;
}
//-----------------------------------------------------------------------------
// Purpose: Is this a chat account id?
//-----------------------------------------------------------------------------
public bool IsLobby() {
return (GetEAccountType() == EAccountType.k_EAccountTypeChat)
&& (GetUnAccountInstance() & (int)EChatSteamIDInstanceFlags.k_EChatInstanceFlagLobby) != 0;
}
//-----------------------------------------------------------------------------
// Purpose: Is this an individual user account id?
//-----------------------------------------------------------------------------
public bool BIndividualAccount() {
return GetEAccountType() == EAccountType.k_EAccountTypeIndividual || GetEAccountType() == EAccountType.k_EAccountTypeConsoleUser;
}
//-----------------------------------------------------------------------------
// Purpose: Is this an anonymous account?
//-----------------------------------------------------------------------------
public bool BAnonAccount() {
return GetEAccountType() == EAccountType.k_EAccountTypeAnonUser || GetEAccountType() == EAccountType.k_EAccountTypeAnonGameServer;
}
//-----------------------------------------------------------------------------
// Purpose: Is this an anonymous user account? ( used to create an account or reset a password )
//-----------------------------------------------------------------------------
public bool BAnonUserAccount() {
return GetEAccountType() == EAccountType.k_EAccountTypeAnonUser;
}
//-----------------------------------------------------------------------------
// Purpose: Is this a faked up Steam ID for a PSN friend account?
//-----------------------------------------------------------------------------
public bool BConsoleUserAccount() {
return GetEAccountType() == EAccountType.k_EAccountTypeConsoleUser;
}
public void SetAccountID(AccountID_t other) {
m_SteamID = (m_SteamID & ~(0xFFFFFFFFul << (ushort)0)) | (((ulong)(other) & 0xFFFFFFFFul) << (ushort)0);
}
public void SetAccountInstance(uint other) {
m_SteamID = (m_SteamID & ~(0xFFFFFul << (ushort)32)) | (((ulong)(other) & 0xFFFFFul) << (ushort)32);
}
// This is a non standard/custom function not found in C++ Steamworks
public void SetEAccountType(EAccountType other) {
m_SteamID = (m_SteamID & ~(0xFul << (ushort)52)) | (((ulong)(other) & 0xFul) << (ushort)52);
}
public void SetEUniverse(EUniverse other) {
m_SteamID = (m_SteamID & ~(0xFFul << (ushort)56)) | (((ulong)(other) & 0xFFul) << (ushort)56);
}
public AccountID_t GetAccountID() {
return new AccountID_t((uint)(m_SteamID & 0xFFFFFFFFul));
}
public uint GetUnAccountInstance() {
return (uint)((m_SteamID >> 32) & 0xFFFFFul);
}
public EAccountType GetEAccountType() {
return (EAccountType)((m_SteamID >> 52) & 0xFul);
}
public EUniverse GetEUniverse() {
return (EUniverse)((m_SteamID >> 56) & 0xFFul);
}
public bool IsValid() {
if (GetEAccountType() <= EAccountType.k_EAccountTypeInvalid || GetEAccountType() >= EAccountType.k_EAccountTypeMax)
return false;
if (GetEUniverse() <= EUniverse.k_EUniverseInvalid || GetEUniverse() >= EUniverse.k_EUniverseMax)
return false;
if (GetEAccountType() == EAccountType.k_EAccountTypeIndividual) {
if (GetAccountID() == new AccountID_t(0) || GetUnAccountInstance() > Constants.k_unSteamUserDefaultInstance)
return false;
}
if (GetEAccountType() == EAccountType.k_EAccountTypeClan) {
if (GetAccountID() == new AccountID_t(0) || GetUnAccountInstance() != 0)
return false;
}
if (GetEAccountType() == EAccountType.k_EAccountTypeGameServer) {
if (GetAccountID() == new AccountID_t(0))
return false;
// Any limit on instances? We use them for local users and bots
}
return true;
}
#region Overrides
public override string ToString() {
return m_SteamID.ToString();
}
public override bool Equals(object other) {
return other is CSteamID && this == (CSteamID)other;
}
public override int GetHashCode() {
return m_SteamID.GetHashCode();
}
public static bool operator ==(CSteamID x, CSteamID y) {
return x.m_SteamID == y.m_SteamID;
}
public static bool operator !=(CSteamID x, CSteamID y) {
return !(x == y);
}
public static explicit operator CSteamID(ulong value) {
return new CSteamID(value);
}
public static explicit operator ulong(CSteamID that) {
return that.m_SteamID;
}
public bool Equals(CSteamID other) {
return m_SteamID == other.m_SteamID;
}
public int CompareTo(CSteamID other) {
return m_SteamID.CompareTo(other.m_SteamID);
}
#endregion
}
}
#endif // !DISABLESTEAMWORKS
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Targets.Wrappers
{
using System;
using System.Threading;
using NLog.Common;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System.Collections.Generic;
using Xunit;
public class AsyncTargetWrapperTests : NLogTestBase
{
[Fact]
public void AsyncTargetWrapperInitTest()
{
var myTarget = new MyTarget();
var targetWrapper = new AsyncTargetWrapper(myTarget, 300, AsyncTargetWrapperOverflowAction.Grow);
Assert.Equal(AsyncTargetWrapperOverflowAction.Grow, targetWrapper.OverflowAction);
Assert.Equal(300, targetWrapper.QueueLimit);
Assert.Equal(50, targetWrapper.TimeToSleepBetweenBatches);
Assert.Equal(100, targetWrapper.BatchSize);
}
[Fact]
public void AsyncTargetWrapperInitTest2()
{
var myTarget = new MyTarget();
var targetWrapper = new AsyncTargetWrapper()
{
WrappedTarget = myTarget,
};
Assert.Equal(AsyncTargetWrapperOverflowAction.Discard, targetWrapper.OverflowAction);
Assert.Equal(10000, targetWrapper.QueueLimit);
Assert.Equal(50, targetWrapper.TimeToSleepBetweenBatches);
Assert.Equal(100, targetWrapper.BatchSize);
}
/// <summary>
/// Test for https://github.com/NLog/NLog/issues/1069
/// </summary>
[Fact]
public void AsyncTargetWrapperInitTest_WhenTimeToSleepBetweenBatchesIsEqualToZero_ShouldThrowNLogConfigurationException() {
LogManager.ThrowConfigExceptions = true;
var myTarget = new MyTarget();
var targetWrapper = new AsyncTargetWrapper() {
WrappedTarget = myTarget,
TimeToSleepBetweenBatches = 0,
};
Assert.Throws<NLogConfigurationException>(() => targetWrapper.Initialize(null));
}
[Fact]
public void AsyncTargetWrapperSyncTest1()
{
var myTarget = new MyTarget();
var targetWrapper = new AsyncTargetWrapper
{
WrappedTarget = myTarget,
Name = "AsyncTargetWrapperSyncTest1_Wrapper",
};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
var logEvent = new LogEventInfo();
Exception lastException = null;
ManualResetEvent continuationHit = new ManualResetEvent(false);
Thread continuationThread = null;
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationThread = Thread.CurrentThread;
continuationHit.Set();
};
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
// continuation was not hit
Assert.True(continuationHit.WaitOne(2000));
Assert.NotSame(continuationThread, Thread.CurrentThread);
Assert.Null(lastException);
Assert.Equal(1, myTarget.WriteCount);
continuationHit.Reset();
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.NotSame(continuationThread, Thread.CurrentThread);
Assert.Null(lastException);
Assert.Equal(2, myTarget.WriteCount);
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperAsyncTest1()
{
var myTarget = new MyAsyncTarget();
var targetWrapper = new AsyncTargetWrapper(myTarget) { Name = "AsyncTargetWrapperAsyncTest1_Wrapper" };
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.True(continuationHit.WaitOne());
Assert.Null(lastException);
Assert.Equal(1, myTarget.WriteCount);
continuationHit.Reset();
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(2, myTarget.WriteCount);
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperAsyncWithExceptionTest1()
{
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true,
};
var targetWrapper = new AsyncTargetWrapper(myTarget) {Name = "AsyncTargetWrapperAsyncWithExceptionTest1_Wrapper"};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.True(continuationHit.WaitOne());
Assert.NotNull(lastException);
Assert.IsType(typeof(InvalidOperationException), lastException);
// no flush on exception
Assert.Equal(0, myTarget.FlushCount);
Assert.Equal(1, myTarget.WriteCount);
continuationHit.Reset();
lastException = null;
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.NotNull(lastException);
Assert.IsType(typeof(InvalidOperationException), lastException);
Assert.Equal(0, myTarget.FlushCount);
Assert.Equal(2, myTarget.WriteCount);
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperFlushTest()
{
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true
};
var targetWrapper = new AsyncTargetWrapper(myTarget)
{
Name = "AsyncTargetWrapperFlushTest_Wrapper",
OverflowAction = AsyncTargetWrapperOverflowAction.Grow
};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
List<Exception> exceptions = new List<Exception>();
int eventCount = 5000;
for (int i = 0; i < eventCount; ++i)
{
targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(
ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
}
}));
}
Exception lastException = null;
ManualResetEvent mre = new ManualResetEvent(false);
string internalLog = RunAndCaptureInternalLog(
() =>
{
targetWrapper.Flush(
cont =>
{
try
{
// by this time all continuations should be completed
Assert.Equal(eventCount, exceptions.Count);
// with just 1 flush of the target
Assert.Equal(1, myTarget.FlushCount);
// and all writes should be accounted for
Assert.Equal(eventCount, myTarget.WriteCount);
}
catch (Exception ex)
{
lastException = ex;
}
finally
{
mre.Set();
}
});
Assert.True(mre.WaitOne());
},
LogLevel.Trace);
if (lastException != null)
{
Assert.True(false, lastException.ToString() + "\r\n" + internalLog);
}
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperCloseTest()
{
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true
};
var targetWrapper = new AsyncTargetWrapper(myTarget)
{
OverflowAction = AsyncTargetWrapperOverflowAction.Grow,
TimeToSleepBetweenBatches = 1000,
Name = "AsyncTargetWrapperCloseTest_Wrapper",
};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { }));
// quickly close the target before the timer elapses
targetWrapper.Close();
}
[Fact]
public void AsyncTargetWrapperExceptionTest()
{
var targetWrapper = new AsyncTargetWrapper
{
OverflowAction = AsyncTargetWrapperOverflowAction.Grow,
TimeToSleepBetweenBatches = 500,
WrappedTarget = new DebugTarget(),
Name = "AsyncTargetWrapperExceptionTest_Wrapper"
};
LogManager.ThrowExceptions = false;
targetWrapper.Initialize(null);
// null out wrapped target - will cause exception on the timer thread
targetWrapper.WrappedTarget = null;
string internalLog = RunAndCaptureInternalLog(
() =>
{
targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { }));
targetWrapper.Close();
},
LogLevel.Trace);
Assert.True(internalLog.Contains("AsyncWrapper 'AsyncTargetWrapperExceptionTest_Wrapper': WrappedTarget is NULL"), internalLog);
}
[Fact]
public void FlushingMultipleTimesSimultaneous()
{
var asyncTarget = new AsyncTargetWrapper
{
TimeToSleepBetweenBatches = 2000,
WrappedTarget = new DebugTarget(),
Name = "FlushingMultipleTimesSimultaneous_Wrapper"
};
asyncTarget.Initialize(null);
try
{
asyncTarget.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { }));
var firstContinuationCalled = false;
var secondContinuationCalled = false;
var firstContinuationResetEvent = new ManualResetEvent(false);
var secondContinuationResetEvent = new ManualResetEvent(false);
asyncTarget.Flush(ex =>
{
firstContinuationCalled = true;
firstContinuationResetEvent.Set();
});
asyncTarget.Flush(ex =>
{
secondContinuationCalled = true;
secondContinuationResetEvent.Set();
});
firstContinuationResetEvent.WaitOne();
secondContinuationResetEvent.WaitOne();
Assert.True(firstContinuationCalled);
Assert.True(secondContinuationCalled);
}
finally
{
asyncTarget.Close();
}
}
class MyAsyncTarget : Target
{
public int FlushCount;
public int WriteCount;
protected override void Write(LogEventInfo logEvent)
{
throw new NotSupportedException();
}
protected override void Write(AsyncLogEventInfo logEvent)
{
Assert.True(this.FlushCount <= this.WriteCount);
Interlocked.Increment(ref this.WriteCount);
ThreadPool.QueueUserWorkItem(
s =>
{
if (this.ThrowExceptions)
{
logEvent.Continuation(new InvalidOperationException("Some problem!"));
logEvent.Continuation(new InvalidOperationException("Some problem!"));
}
else
{
logEvent.Continuation(null);
logEvent.Continuation(null);
}
});
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
Interlocked.Increment(ref this.FlushCount);
ThreadPool.QueueUserWorkItem(
s => asyncContinuation(null));
}
public bool ThrowExceptions { get; set; }
}
class MyTarget : Target
{
public int FlushCount { get; set; }
public int WriteCount { get; set; }
protected override void Write(LogEventInfo logEvent)
{
Assert.True(this.FlushCount <= this.WriteCount);
this.WriteCount++;
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
this.FlushCount++;
asyncContinuation(null);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using MbUnit.Framework;
using Moq;
using Subtext.Configuration;
using Subtext.Extensibility;
using Subtext.Framework;
using Subtext.Framework.Components;
using Subtext.Framework.Configuration;
using Subtext.Framework.Exceptions;
using Subtext.Framework.Providers;
using Subtext.Framework.Services;
using Subtext.Framework.Services.SearchEngine;
namespace UnitTests.Subtext.Framework.Services
{
[TestFixture]
public class EntryPublisherTests
{
[Test]
public void Ctor_WithNullContext_ThrowsArgumentNullException()
{
UnitTestHelper.AssertThrowsArgumentNullException(
() =>
new EntryPublisher(null, EmptyTextTransformation.Instance,
new SlugGenerator(FriendlyUrlSettings.Settings),null));
}
[Test]
public void Publish_WithTransformations_RunsTransformationAgainstEntryBody()
{
//arrange
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null));
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var transform = new Mock<ITextTransformation>();
var searchengine = new Mock<IIndexingService>();
transform.Setup(t => t.Transform(It.IsAny<string>())).Returns<string>(s => s + "t1");
var publisher = new EntryPublisher(context.Object, transform.Object, null, searchengine.Object);
var entry = new Entry(PostType.BlogPost) {Title = "Test", Body = "test"};
entry.Blog = new Blog() {Title = "MyTestBlog"};
//act
publisher.Publish(entry);
//assert
Assert.AreEqual("testt1", entry.Body);
}
[Test]
public void Publish_WithEntryTitleButNoSlug_CreatesSlug()
{
//arrange
var entry = new Entry(PostType.BlogPost) {Title = "this is a test"};
entry.Blog = new Blog() { Title = "MyTestBlog" };
var slugGenerator = new Mock<ISlugGenerator>();
slugGenerator.Setup(g => g.GetSlugFromTitle(entry)).Returns("this-is-a-test");
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null));
var context = new Mock<ISubtextContext>();
var searchengine = new Mock<IIndexingService>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var publisher = new EntryPublisher(context.Object, null, slugGenerator.Object, searchengine.Object);
//act
publisher.Publish(entry);
//assert
Assert.AreEqual("this-is-a-test", entry.EntryName);
}
[Test]
public void Publish_WithEntryTitleAndSlug_DoesNotOverideSlug()
{
//arrange
var entry = new Entry(PostType.BlogPost) {Title = "this is a test", EntryName = "testing"};
entry.Blog = new Blog() { Title = "MyTestBlog" };
var slugGenerator = new Mock<ISlugGenerator>();
slugGenerator.Setup(g => g.GetSlugFromTitle(entry)).Returns("this-is-a-test");
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null));
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var searchengine = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, null, slugGenerator.Object, searchengine.Object);
//act
publisher.Publish(entry);
//assert
Assert.AreEqual("testing", entry.EntryName);
}
[Test]
public void Publish_WithEntry_SavesInRepository()
{
//arrange
Entry savedEntry = null;
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null)).Callback<Entry, IEnumerable<int>>(
(e, i) => savedEntry = e);
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var searchengine = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, null, null,searchengine.Object);
var entry = new Entry(PostType.BlogPost) {Title = "this is a test"};
entry.Blog = new Blog() { Title = "MyTestBlog" };
//act
publisher.Publish(entry);
//assert
Assert.AreEqual(entry, savedEntry);
}
[Test]
public void Publish_WithEntry_SetsDateCreatedToBlogCurrentTimeZoneTime()
{
//arrange
DateTime currentTime = DateTime.Now;
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null));
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(currentTime);
context.Setup(c => c.Repository).Returns(repository.Object);
var searchengine = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, null, null, searchengine.Object);
var entry = new Entry(PostType.BlogPost) {Title = "this is a test"};
entry.Blog = new Blog() { Title = "MyTestBlog" };
//act
publisher.Publish(entry);
//assert
Assert.AreEqual(currentTime, entry.DateCreated);
//cheating by shoving this extra assert here. MUAHAHAHA!!! ;)
Assert.IsTrue(NullValue.IsNull(entry.DateSyndicated));
}
[Test]
public void Publish_WithActiveEntryAndIncludeInSyndication_SetsDateSyndicatedToBlogCurrentTimeZoneTime()
{
//arrange
var currentTime = DateTime.Now;
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null));
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(currentTime);
context.Setup(c => c.Repository).Returns(repository.Object);
var searchengine = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, null, null, searchengine.Object);
var entry = new Entry(PostType.BlogPost) {Title = "this is a test", IsActive = true, IncludeInMainSyndication = true};
entry.Blog = new Blog() { Title = "MyTestBlog" };
//act
publisher.Publish(entry);
//assert
Assert.AreEqual(currentTime, entry.DateSyndicated);
}
[Test]
public void Publish_WithEntryHavingCategories_CreatesEntryWithAssociatedCategoryIds()
{
//arrange
DateTime currentTime = DateTime.Now;
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.GetLinkCategory("category1", true)).Returns(new LinkCategory(11, "category1"));
repository.Setup(r => r.GetLinkCategory("category2", true)).Returns(new LinkCategory(22, "category2"));
repository.Setup(r => r.GetLinkCategory("category3", true)).Returns(new LinkCategory(33, "category3"));
IEnumerable<int> categoryIds = null;
repository.Setup(r => r.Create(It.IsAny<Entry>(), It.IsAny<IEnumerable<int>>())).Callback
<Entry, IEnumerable<int>>((e, ids) => categoryIds = ids);
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(currentTime);
context.Setup(c => c.Repository).Returns(repository.Object);
var searchengine = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, null, null, searchengine.Object);
var entry = new Entry(PostType.BlogPost) {Title = "this is a test"};
entry.Blog = new Blog() { Title = "MyTestBlog" };
entry.Categories.Add("category1");
entry.Categories.Add("category2");
entry.Categories.Add("category3");
//act
publisher.Publish(entry);
//assert
Assert.AreEqual(11, categoryIds.First());
Assert.AreEqual(22, categoryIds.ElementAt(1));
Assert.AreEqual(33, categoryIds.ElementAt(2));
}
[Test]
public void Publish_WithEntryBodyHavingTags_SetsEntryTags()
{
//arrange
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null));
IEnumerable<string> tagNames = null;
repository.Setup(r => r.SetEntryTagList(It.IsAny<int>(), It.IsAny<IEnumerable<string>>()))
.Callback<int, IEnumerable<string>>((i, t) => tagNames = t);
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var searchengine = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, null, null,searchengine.Object);
var entry = new Entry(PostType.BlogPost) {Title = "this is a test", Body = ""};
entry.Blog = new Blog() { Title = "MyTestBlog" };
//act
publisher.Publish(entry);
//assert
Assert.IsNotNull(tagNames);
}
[Test]
public void Publish_WithEntry_AddsToSearchEngine()
{
//arrange
var searchEngineService = new Mock<IIndexingService>();
Entry searchEngineEntry = null;
searchEngineService.Setup(s => s.AddPost(It.IsAny<Entry>(),It.IsAny<IList<string>>()))
.Callback<Entry, IList<string>>((e,l) => searchEngineEntry = e);
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null));
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var publisher = new EntryPublisher(context.Object, null, null, searchEngineService.Object);
var entry = new Entry(PostType.BlogPost) { Title = "this is a test", Body = "", IsActive=true };
entry.Blog = new Blog() { Title = "MyTestBlog" };
//act
publisher.Publish(entry);
//assert
Assert.IsNotNull(searchEngineEntry);
}
[Test]
public void Publish_WithScriptTagsAllowed_AllowsScriptTagInBody()
{
//arrange
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null));
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var searchEngineService = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, null, null, searchEngineService.Object);
var entry = new Entry(PostType.BlogPost) {Title = "this is a test", Body = "Some <script></script> Body"};
entry.Blog = new Blog() { Title = "MyTestBlog" };
Config.Settings.AllowScriptsInPosts = true;
//act
publisher.Publish(entry);
//assert
//no exception thrown.
}
[Test]
public void Publish_WithNullEntry_ThrowsArgumentNullException()
{
//arrange
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null));
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var searchEngineService = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, null, null, searchEngineService.Object);
//act, assert
UnitTestHelper.AssertThrowsArgumentNullException(() => publisher.Publish(null));
}
[Test]
public void Publish_WithEntryHavingPostTypeNone_ThrowsArgumentException()
{
//arrange
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null));
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var searchEngineService = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, null, null,searchEngineService.Object);
//act, assert
UnitTestHelper.AssertThrows<ArgumentException>(() => publisher.Publish(new Entry(PostType.None)));
}
[Test]
public void Publish_WithDuplicateEntryName_ThrowsException()
{
//arrange
var repository = new Mock<ObjectProvider>();
var exception = new Mock<DbException>();
exception.Setup(e => e.Message).Returns("pick a unique EntryName");
repository.Setup(r => r.Create(It.IsAny<Entry>(), null)).Throws(exception.Object);
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var searchEngineService = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, null, null, searchEngineService.Object);
var entry = new Entry(PostType.BlogPost) {Title = "this is a test", EntryName = "test"};
entry.Blog = new Blog() { Title = "MyTestBlog" };
//act, assert
UnitTestHelper.AssertThrows<DuplicateEntryException>(() =>
publisher.Publish(entry)
);
}
[Test]
public void Publish_WithRepositoryThrowingException_PropagatesException()
{
//arrange
var repository = new Mock<ObjectProvider>();
var exception = new Mock<DbException>();
exception.Setup(e => e.Message).Returns("unknown");
repository.Setup(r => r.Create(It.IsAny<Entry>(), null)).Throws(exception.Object);
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var searchEngineService = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, null, null,searchEngineService.Object);
var entry = new Entry(PostType.BlogPost) {Title = "this is a test", EntryName = "test"};
entry.Blog = new Blog() { Title = "MyTestBlog" };
//act, assert
UnitTestHelper.AssertThrows<DbException>(() =>
publisher.Publish(entry)
);
}
[Test]
public void Publish_WithScriptTagInBody_ThrowsException()
{
//arrange
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null));
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var searchEngineService = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, null, null, searchEngineService.Object);
var entry = new Entry(PostType.BlogPost) {Title = "this is a test", Body = "Some <script></script> Body"};
entry.Blog = new Blog() { Title = "MyTestBlog" };
Config.Settings.AllowScriptsInPosts = false;
//act, assert
UnitTestHelper.AssertThrows<IllegalPostCharactersException>(() =>
publisher.Publish(entry)
);
}
[Test]
public void Publish_WithScriptTagInTitle_ThrowsException()
{
//arrange
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null));
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var searchEngineService = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, null, null,searchEngineService.Object);
var entry = new Entry(PostType.BlogPost) {Title = "this is a test<script></script>", Body = "Some Body"};
entry.Blog = new Blog() { Title = "MyTestBlog" };
Config.Settings.AllowScriptsInPosts = false;
//act, assert
UnitTestHelper.AssertThrows<IllegalPostCharactersException>(() =>
publisher.Publish(entry)
);
}
[Test]
public void Publish_WithScriptTagInSlug_ThrowsException()
{
//arrange
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null));
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var searchEngineService = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, null, null, searchEngineService.Object);
var entry = new Entry(PostType.BlogPost)
{Title = "stuff", EntryName = "<script></script>", Body = "Some Body"};
entry.Blog = new Blog() { Title = "MyTestBlog" };
Config.Settings.AllowScriptsInPosts = false;
//act, assert
UnitTestHelper.AssertThrows<IllegalPostCharactersException>(() =>
publisher.Publish(entry)
);
}
[Test]
public void Publish_WithScriptTagInDescription_ThrowsException()
{
//arrange
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null));
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var searchEngineService = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, null, null, searchEngineService.Object);
var entry = new Entry(PostType.BlogPost)
{Title = "this is a test", Body = "Whatever", Description = "Some <script></script> Body"};
entry.Blog = new Blog() { Title = "MyTestBlog" };
Config.Settings.AllowScriptsInPosts = false;
//act, assert
UnitTestHelper.AssertThrows<IllegalPostCharactersException>(() =>
publisher.Publish(entry)
);
}
[Test]
public void Publish_WithEntryHavingValidEntryName_DoesNotChangeEntryName()
{
//arrange
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null));
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var transform = new Mock<ITextTransformation>();
transform.Setup(t => t.Transform(It.IsAny<string>())).Returns<string>(s => s);
var searchEngineService = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, transform.Object, null, searchEngineService.Object);
var entry = new Entry(PostType.BlogPost) {Title = "Test", Body = "test", EntryName = "original-entry-name"};
entry.Blog = new Blog() { Title = "MyTestBlog" };
//act
publisher.Publish(entry);
//assert
Assert.AreEqual("original-entry-name", entry.EntryName);
}
[Test]
public void Publish_WithEntryHavingNumericIntegerEntryName_PrependsNUnderscore()
{
//arrange
var repository = new Mock<ObjectProvider>();
repository.Setup(r => r.Create(It.IsAny<Entry>(), null));
var context = new Mock<ISubtextContext>();
context.Setup(c => c.Blog.TimeZone.Now).Returns(DateTime.Now);
context.Setup(c => c.Repository).Returns(repository.Object);
var transform = new Mock<ITextTransformation>();
transform.Setup(t => t.Transform(It.IsAny<string>())).Returns<string>(s => s);
var searchEngineService = new Mock<IIndexingService>();
var publisher = new EntryPublisher(context.Object, transform.Object, null, searchEngineService.Object);
var entry = new Entry(PostType.BlogPost) {Title = "Test", Body = "test", EntryName = "4321"};
entry.Blog = new Blog() { Title = "MyTestBlog" };
//act
publisher.Publish(entry);
//assert
Assert.AreEqual("n_4321", entry.EntryName);
}
}
}
| |
// NamespaceSummariesForm.cs - form for adding namespace summaries
// Copyright (C) 2001 Kral Ferch, Keith Hill
//
// Modified by: Keith Hill on Sep 28, 2001.
// Tweaked the layout, made the dialog not show up in the task bar.
//
// Modified by: Jason Diamond on Oct 19, 2001.
// Updated to work with the new NDoc.Core.Project interface.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace NDoc.Gui
{
using System;
using System.Drawing;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using NDoc.Core;
/// <summary>
/// Summary description for NamespaceSummariesForm.
/// </summary>
public class NamespaceSummariesForm : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.TextBox summaryTextBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ComboBox namespaceComboBox;
private string selectedText;
private System.Windows.Forms.StatusBar statusBar1;
private Project _Project;
private bool scanInitiated=false;
/// <summary>Allows the user to associate a summaries with the
/// namespaces found in the assemblies that are being
/// documented.</summary>
public NamespaceSummariesForm(Project project)
{
_Project = project;
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.okButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.summaryTextBox = new System.Windows.Forms.TextBox();
this.namespaceComboBox = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.statusBar1 = new System.Windows.Forms.StatusBar();
this.SuspendLayout();
//
// okButton
//
this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.okButton.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.okButton.Location = new System.Drawing.Point(216, 248);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(88, 24);
this.okButton.TabIndex = 4;
this.okButton.Text = "OK";
this.okButton.Click += new System.EventHandler(this.okButton_Click);
//
// cancelButton
//
this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.cancelButton.Location = new System.Drawing.Point(312, 248);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(88, 24);
this.cancelButton.TabIndex = 5;
this.cancelButton.Text = "Cancel";
//
// summaryTextBox
//
this.summaryTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.summaryTextBox.Location = new System.Drawing.Point(8, 80);
this.summaryTextBox.Multiline = true;
this.summaryTextBox.Name = "summaryTextBox";
this.summaryTextBox.Size = new System.Drawing.Size(392, 160);
this.summaryTextBox.TabIndex = 3;
this.summaryTextBox.Text = "";
//
// namespaceComboBox
//
this.namespaceComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.namespaceComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.namespaceComboBox.DropDownWidth = 192;
this.namespaceComboBox.Location = new System.Drawing.Point(8, 32);
this.namespaceComboBox.Name = "namespaceComboBox";
this.namespaceComboBox.Size = new System.Drawing.Size(392, 21);
this.namespaceComboBox.Sorted = true;
this.namespaceComboBox.TabIndex = 0;
this.namespaceComboBox.SelectedIndexChanged += new System.EventHandler(this.namespaceComboBox_SelectedIndexChanged);
//
// label1
//
this.label1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label1.Location = new System.Drawing.Point(8, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(104, 16);
this.label1.TabIndex = 1;
this.label1.Text = "Select Namespace:";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label2
//
this.label2.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label2.Location = new System.Drawing.Point(8, 64);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(64, 16);
this.label2.TabIndex = 2;
this.label2.Text = "Summary:";
//
// statusBar1
//
this.statusBar1.Location = new System.Drawing.Point(0, 280);
this.statusBar1.Name = "statusBar1";
this.statusBar1.Size = new System.Drawing.Size(408, 22);
this.statusBar1.TabIndex = 6;
//
// NamespaceSummariesForm
//
this.AcceptButton = this.okButton;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.AutoScroll = true;
this.CancelButton = this.cancelButton;
this.ClientSize = new System.Drawing.Size(408, 302);
this.Controls.Add(this.statusBar1);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.okButton);
this.Controls.Add(this.summaryTextBox);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.namespaceComboBox);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(416, 232);
this.Name = "NamespaceSummariesForm";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Edit Namespace Summaries";
this.Activated += new System.EventHandler(this.NamespaceSummariesForm_Activated);
this.ResumeLayout(false);
}
/// <summary>
/// Saves the summary text for the currently selected namespace
/// before exiting the form.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void okButton_Click (object sender, System.EventArgs e)
{
_Project.Namespaces[selectedText]= summaryTextBox.Text;
}
/// <summary>
/// Saves the currently entered text with the appropriate namespace
/// and then puts the newly selected namespace's summary in the edit box.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void namespaceComboBox_SelectedIndexChanged (object sender, System.EventArgs e)
{
if (selectedText != null)
{
_Project.Namespaces[selectedText]=summaryTextBox.Text;
}
summaryTextBox.Text = _Project.Namespaces[namespaceComboBox.Text];
summaryTextBox.Focus();
selectedText = namespaceComboBox.Text;
}
private void NamespaceSummariesForm_Activated(object sender, System.EventArgs e)
{
if (!scanInitiated)
{
scanInitiated=true;
try
{
statusBar1.Text="Scanning assemblies for namespace names...";
namespaceComboBox.Enabled=false;
summaryTextBox.Enabled=false;
okButton.Enabled=false;
cancelButton.Enabled=false;
Application.DoEvents();
namespaceComboBox.Items.Clear();
_Project.Namespaces.LoadNamespacesFromAssemblies(_Project);
foreach (string namespaceName in _Project.Namespaces.NamespaceNames)
namespaceComboBox.Items.Add(namespaceName);
if ( namespaceComboBox.Items.Count > 0 )
namespaceComboBox.SelectedIndex = 0;
namespaceComboBox.Enabled=true;
summaryTextBox.Enabled=true;
okButton.Enabled=true;
}
catch(Exception docEx)
{
ErrorForm.ShowError( "Unable to complete namspace scan...", docEx, this );
}
finally
{
statusBar1.Text="";
cancelButton.Enabled=true;
}
}
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using NLog.Common;
using NLog.Config;
using NLog.Targets;
using NLog.Targets.Wrappers;
using NLog.UnitTests.Common;
using NLog.UnitTests.Targets.Wrappers;
#if !SILVERLIGHT
namespace NLog.UnitTests.LayoutRenderers
{
using System.Security.Principal;
using System.Threading;
using Xunit;
public class IdentityTests : NLogTestBase
{
[Fact]
public void IdentityTest1()
{
var oldPrincipal = Thread.CurrentPrincipal;
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("SOMEDOMAIN\\SomeUser", "CustomAuth"), new[] { "Role1", "Role2" });
try
{
AssertLayoutRendererOutput("${identity}", "auth:CustomAuth:SOMEDOMAIN\\SomeUser");
AssertLayoutRendererOutput("${identity:authtype=false}", "auth:SOMEDOMAIN\\SomeUser");
AssertLayoutRendererOutput("${identity:authtype=false:isauthenticated=false}", "SOMEDOMAIN\\SomeUser");
AssertLayoutRendererOutput("${identity:fsnormalize=true}", "auth_CustomAuth_SOMEDOMAIN_SomeUser");
}
finally
{
Thread.CurrentPrincipal = oldPrincipal;
}
}
/// <summary>
/// Test writing ${identity} async
/// </summary>
[Fact]
public void IdentityTest1Async()
{
var oldPrincipal = Thread.CurrentPrincipal;
try
{
ConfigurationItemFactory.Default.Targets
.RegisterDefinition("CSharpEventTarget", typeof(CSharpEventTarget));
LogManager.Configuration = CreateConfigurationFromString(@"<?xml version='1.0' encoding='utf-8' ?>
<nlog xmlns='http://www.nlog-project.org/schemas/NLog.xsd'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
internalLogLevel='Debug'
throwExceptions='true' >
<targets async='true'>
<target name='target1' xsi:type='CSharpEventTarget' layout='${identity}' />
</targets>
<rules>
<logger name='*' writeTo='target1' />
</rules>
</nlog>
");
try
{
var continuationHit = new ManualResetEvent(false);
string rendered = null;
var threadId = Thread.CurrentThread.ManagedThreadId;
var asyncThreadId = threadId;
LogEventInfo lastLogEvent = null;
var asyncTarget = LogManager.Configuration.FindTargetByName<AsyncTargetWrapper>("target1");
Assert.NotNull(asyncTarget);
var target = asyncTarget.WrappedTarget as CSharpEventTarget;
Assert.NotNull(target);
target.BeforeWrite += (logevent, rendered1, asyncThreadId1) =>
{
//clear in current thread before write
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("ANOTHER user", "type"),null);
};
target.EventWritten += (logevent, rendered1, asyncThreadId1) =>
{
rendered = rendered1;
asyncThreadId = asyncThreadId1;
lastLogEvent = logevent;
continuationHit.Set();
};
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("SOMEDOMAIN\\SomeUser", "CustomAuth"), new[] { "Role1", "Role2" });
var logger = LogManager.GetCurrentClassLogger();
logger.Debug("test write");
Assert.True(continuationHit.WaitOne());
Assert.NotNull(lastLogEvent);
//should be written in another thread.
Assert.NotEqual(threadId, asyncThreadId);
Assert.Equal("auth:CustomAuth:SOMEDOMAIN\\SomeUser", rendered);
}
finally
{
LogManager.Configuration.Close();
}
}
finally
{
Thread.CurrentPrincipal = oldPrincipal;
}
}
[Fact]
public void IdentityTest2()
{
var oldPrincipal = Thread.CurrentPrincipal;
Thread.CurrentPrincipal = new GenericPrincipal(new NotAuthenticatedIdentity(), new[] { "role1" });
try
{
AssertLayoutRendererOutput("${identity}", "notauth::");
}
finally
{
Thread.CurrentPrincipal = oldPrincipal;
}
}
/// <summary>
/// Mock object for IsAuthenticated property.
/// </summary>
private class NotAuthenticatedIdentity : GenericIdentity
{
public NotAuthenticatedIdentity()
: base("")
{
}
#region Overrides of GenericIdentity
/// <summary>
/// Gets a value indicating whether the user has been authenticated.
/// </summary>
/// <returns>
/// true if the user was has been authenticated; otherwise, false.
/// </returns>
public override bool IsAuthenticated
{
get { return false; }
}
#endregion
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
// This class implements a text writer that writes to a string buffer and allows
// the resulting sequence of characters to be presented as a string.
public class StringWriter : TextWriter
{
private static volatile UnicodeEncoding s_encoding = null;
private StringBuilder _sb;
private bool _isOpen;
// Constructs a new StringWriter. A new StringBuilder is automatically
// created and associated with the new StringWriter.
public StringWriter()
: this(new StringBuilder(), CultureInfo.CurrentCulture)
{
}
public StringWriter(IFormatProvider formatProvider)
: this(new StringBuilder(), formatProvider)
{
}
// Constructs a new StringWriter that writes to the given StringBuilder.
//
public StringWriter(StringBuilder sb) : this(sb, CultureInfo.CurrentCulture)
{
}
public StringWriter(StringBuilder sb, IFormatProvider formatProvider) : base(formatProvider)
{
if (sb == null)
{
throw new ArgumentNullException(nameof(sb), SR.ArgumentNull_Buffer);
}
_sb = sb;
_isOpen = true;
}
public override void Close()
{
Dispose(true);
}
protected override void Dispose(bool disposing)
{
// Do not destroy _sb, so that we can extract this after we are
// done writing (similar to MemoryStream's GetBuffer & ToArray methods)
_isOpen = false;
base.Dispose(disposing);
}
public override Encoding Encoding
{
get
{
if (s_encoding == null)
{
s_encoding = new UnicodeEncoding(false, false);
}
return s_encoding;
}
}
// Returns the underlying StringBuilder. This is either the StringBuilder
// that was passed to the constructor, or the StringBuilder that was
// automatically created.
//
public virtual StringBuilder GetStringBuilder()
{
return _sb;
}
// Writes a character to the underlying string buffer.
//
public override void Write(char value)
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
_sb.Append(value);
}
// Writes a range of a character array to the underlying string buffer.
// This method will write count characters of data into this
// StringWriter from the buffer character array starting at position
// index.
//
public override void Write(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
_sb.Append(buffer, index, count);
}
public override void Write(ReadOnlySpan<char> buffer)
{
if (GetType() != typeof(StringWriter))
{
// This overload was added affter the Write(char[], ...) overload, and so in case
// a derived type may have overridden it, we need to delegate to it, which the base does.
base.Write(buffer);
return;
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
_sb.Append(buffer);
}
// Writes a string to the underlying string buffer. If the given string is
// null, nothing is written.
//
public override void Write(string value)
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
if (value != null)
{
_sb.Append(value);
}
}
public override void WriteLine(ReadOnlySpan<char> buffer)
{
if (GetType() != typeof(StringWriter))
{
// This overload was added affter the WriteLine(char[], ...) overload, and so in case
// a derived type may have overridden it, we need to delegate to it, which the base does.
base.WriteLine(buffer);
return;
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
_sb.Append(buffer);
WriteLine();
}
#region Task based Async APIs
public override Task WriteAsync(char value)
{
Write(value);
return Task.CompletedTask;
}
public override Task WriteAsync(string value)
{
Write(value);
return Task.CompletedTask;
}
public override Task WriteAsync(char[] buffer, int index, int count)
{
Write(buffer, index, count);
return Task.CompletedTask;
}
public override Task WriteAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
Write(buffer.Span);
return Task.CompletedTask;
}
public override Task WriteLineAsync(char value)
{
WriteLine(value);
return Task.CompletedTask;
}
public override Task WriteLineAsync(string value)
{
WriteLine(value);
return Task.CompletedTask;
}
public override Task WriteLineAsync(char[] buffer, int index, int count)
{
WriteLine(buffer, index, count);
return Task.CompletedTask;
}
public override Task WriteLineAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
WriteLine(buffer.Span);
return Task.CompletedTask;
}
public override Task FlushAsync()
{
return Task.CompletedTask;
}
#endregion
// Returns a string containing the characters written to this TextWriter
// so far.
//
public override string ToString()
{
return _sb.ToString();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UsePatternMatching;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UsePatternMatching
{
public partial class CSharpAsAndNullCheckTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, CodeFixProvider>(
new CSharpAsAndNullCheckDiagnosticAnalyzer(),
new CSharpAsAndNullCheckCodeFixProvider());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task InlineTypeCheck1()
{
await TestAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (x != null)
{
}
}
}",
@"class C
{
void M()
{
if (o is string x)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task InlineTypeCheckInvertedCheck1()
{
await TestAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (null != x)
{
}
}
}",
@"class C
{
void M()
{
if (o is string x)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestMissingInCSharp6()
{
await TestMissingAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (x != null)
{
}
}
}", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestMissingInWrongName()
{
await TestMissingAsync(
@"class C
{
void M()
{
[|var|] y = o as string;
if (x != null)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestMissingOnNonDeclaration()
{
await TestMissingAsync(
@"class C
{
void M()
{
[|y|] = o as string;
if (x != null)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestMissingOnIsExpression()
{
await TestMissingAsync(
@"class C
{
void M()
{
[|var|] x = o is string;
if (x != null)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task InlineTypeCheckComplexExpression1()
{
await TestAsync(
@"class C
{
void M()
{
[|var|] x = (o ? z : w) as string;
if (x != null)
{
}
}
}",
@"class C
{
void M()
{
if ((o ? z : w) is string x)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestMissingOnNullEquality()
{
await TestMissingAsync(
@"class C
{
void M()
{
[|var|] x = o is string;
if (x == null)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestInlineTypeCheckWithElse()
{
await TestAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (null != x)
{
}
else
{
}
}
}",
@"class C
{
void M()
{
if (o is string x)
{
}
else
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestComments1()
{
await TestAsync(
@"class C
{
void M()
{
// prefix comment
[|var|] x = o as string;
if (x != null)
{
}
}
}",
@"class C
{
void M()
{
// prefix comment
if (o is string x)
{
}
}
}", compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestComments2()
{
await TestAsync(
@"class C
{
void M()
{
[|var|] x = o as string; // suffix comment
if (x != null)
{
}
}
}",
@"class C
{
void M()
{
// suffix comment
if (o is string x)
{
}
}
}", compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestComments3()
{
await TestAsync(
@"class C
{
void M()
{
// prefix comment
[|var|] x = o as string; // suffix comment
if (x != null)
{
}
}
}",
@"class C
{
void M()
{
// prefix comment
// suffix comment
if (o is string x)
{
}
}
}", compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task InlineTypeCheckComplexCondition1()
{
await TestAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (x != null ? 0 : 1)
{
}
}
}",
@"class C
{
void M()
{
if (o is string x ? 0 : 1)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task InlineTypeCheckComplexCondition2()
{
await TestAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if ((x != null))
{
}
}
}",
@"class C
{
void M()
{
if ((o is string x))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task InlineTypeCheckComplexCondition3()
{
await TestAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (x != null && x.Length > 0)
{
}
}
}",
@"class C
{
void M()
{
if (o is string x && x.Length > 0)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestDefiniteAssignment1()
{
await TestMissingAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (x != null && x.Length > 0)
{
}
else if (x != null)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestDefiniteAssignment2()
{
await TestMissingAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (x != null && x.Length > 0)
{
}
Console.WriteLine(x);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestDefiniteAssignment3()
{
await TestAsync(
@"class C
{
void M()
{
[|var|] x = o as string;
if (x != null && x.Length > 0)
{
}
x = null;
Console.WriteLine(x);
}
}",
@"class C
{
void M()
{
if (o is string x && x.Length > 0)
{
}
x = null;
Console.WriteLine(x);
}
}");
}
[WorkItem(15957, "https://github.com/dotnet/roslyn/issues/15957")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTypeCheck)]
public async Task TestTrivia1()
{
await TestAsync(
@"class C
{
void M(object y)
{
if (y != null)
{
}
[|var|] x = o as string;
if (x != null)
{
}
}
}",
@"class C
{
void M(object y)
{
if (y != null)
{
}
if (o is string x)
{
}
}
}", compareTokens: false);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Tests
{
public class MutexTests : RemoteExecutorTestBase
{
private const int FailedWaitTimeout = 30000;
[Fact]
public void Ctor_ConstructWaitRelease()
{
using (Mutex m = new Mutex())
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
}
using (Mutex m = new Mutex(false))
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
}
using (Mutex m = new Mutex(true))
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
m.ReleaseMutex();
}
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public void Ctor_InvalidName()
{
Assert.Throws<ArgumentException>(() => new Mutex(false, new string('a', 1000)));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public void Ctor_ValidName_Windows()
{
string name = Guid.NewGuid().ToString("N");
bool createdNew;
using (Mutex m1 = new Mutex(false, name, out createdNew))
{
Assert.True(createdNew);
using (Mutex m2 = new Mutex(false, name, out createdNew))
{
Assert.False(createdNew);
}
}
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public void Ctor_NameUsedByOtherSynchronizationPrimitive_Windows()
{
string name = Guid.NewGuid().ToString("N");
using (Semaphore s = new Semaphore(1, 1, name))
{
Assert.Throws<WaitHandleCannotBeOpenedException>(() => new Mutex(false, name));
}
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public void OpenExisting_Windows()
{
string name = Guid.NewGuid().ToString("N");
Mutex resultHandle;
Assert.False(Mutex.TryOpenExisting(name, out resultHandle));
using (Mutex m1 = new Mutex(false, name))
{
using (Mutex m2 = Mutex.OpenExisting(name))
{
Assert.True(m1.WaitOne(FailedWaitTimeout));
Assert.False(Task.Factory.StartNew(() => m2.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
m1.ReleaseMutex();
Assert.True(m2.WaitOne(FailedWaitTimeout));
Assert.False(Task.Factory.StartNew(() => m1.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
m2.ReleaseMutex();
}
Assert.True(Mutex.TryOpenExisting(name, out resultHandle));
Assert.NotNull(resultHandle);
resultHandle.Dispose();
}
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public void OpenExisting_InvalidNames_Windows()
{
Assert.Throws<ArgumentNullException>("name", () => Mutex.OpenExisting(null));
Assert.Throws<ArgumentException>(() => Mutex.OpenExisting(string.Empty));
Assert.Throws<ArgumentException>(() => Mutex.OpenExisting(new string('a', 10000)));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public void OpenExisting_UnavailableName_Windows()
{
string name = Guid.NewGuid().ToString("N");
Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name));
Mutex ignored;
Assert.False(Mutex.TryOpenExisting(name, out ignored));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public void OpenExisting_NameUsedByOtherSynchronizationPrimitive_Windows()
{
string name = Guid.NewGuid().ToString("N");
using (Semaphore sema = new Semaphore(1, 1, name))
{
Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name));
Mutex ignored;
Assert.False(Mutex.TryOpenExisting(name, out ignored));
}
}
[Fact]
public void AbandonExisting()
{
using (Mutex m = new Mutex())
{
Task t = Task.Factory.StartNew(() =>
{
Assert.True(m.WaitOne(FailedWaitTimeout));
// don't release the mutex; abandon it on this thread
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
t.Wait();
Assert.Throws<AbandonedMutexException>(() => m.WaitOne(FailedWaitTimeout));
}
using (Mutex m = new Mutex())
{
Task t = Task.Factory.StartNew(() =>
{
Assert.True(m.WaitOne(FailedWaitTimeout));
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
t.Wait();
AbandonedMutexException ame = Assert.Throws<AbandonedMutexException>(() => WaitHandle.WaitAny(new[] { m }, FailedWaitTimeout));
Assert.Equal(0, ame.MutexIndex);
Assert.Equal(m, ame.Mutex);
}
}
[PlatformSpecific(PlatformID.Windows)] // names aren't supported on Unix
[Theory]
[InlineData("")]
[InlineData("Local\\")]
[InlineData("Global\\")]
public void CrossProcess_NamedMutex_ProtectedFileAccessAtomic(string prefix)
{
string mutexName = prefix + Guid.NewGuid().ToString("N");
string fileName = GetTestFilePath();
Func<string, string, int> otherProcess = (m, f) =>
{
using (var mutex = Mutex.OpenExisting(m))
{
mutex.WaitOne();
try { File.WriteAllText(f, "0"); }
finally { mutex.ReleaseMutex(); }
IncrementValueInFileNTimes(mutex, f, 10);
}
return SuccessExitCode;
};
using (var mutex = new Mutex(false, mutexName))
using (var remote = RemoteInvoke(otherProcess, mutexName, fileName))
{
SpinWait.SpinUntil(() => File.Exists(fileName));
IncrementValueInFileNTimes(mutex, fileName, 10);
}
Assert.Equal(20, int.Parse(File.ReadAllText(fileName)));
}
private static void IncrementValueInFileNTimes(Mutex mutex, string fileName, int n)
{
for (int i = 0; i < n; i++)
{
mutex.WaitOne();
try
{
int current = int.Parse(File.ReadAllText(fileName));
Thread.Sleep(10);
File.WriteAllText(fileName, (current + 1).ToString());
}
finally { mutex.ReleaseMutex(); }
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
namespace Microsoft.Azure.KeyVault
{
using System.Threading;
using System.Threading.Tasks;
using Models;
using System.Net.Http;
using Rest.Azure;
using System.Collections.Generic;
using Rest;
using System;
using System.Net;
using Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
using Microsoft.Azure.KeyVault.Customized.Authentication;
/// <summary>
/// Client class to perform cryptographic key operations and vault
/// operations against the Key Vault service.
/// </summary>
public partial class KeyVaultClient
{
/// <summary>
/// The authentication callback delegate which is to be implemented by the client code
/// </summary>
/// <param name="authority"> Identifier of the authority, a URL. </param>
/// <param name="resource"> Identifier of the target resource that is the recipient of the requested token, a URL. </param>
/// <param name="scope"> The scope of the authentication request. </param>
/// <returns> access token </returns>
public delegate Task<string> AuthenticationCallback(string authority, string resource, string scope);
/// <summary>
/// Constructor
/// </summary>
/// <param name="authenticationCallback">The authentication callback</param>
/// <param name='handlers'>Optional. The delegating handlers to add to the http client pipeline.</param>
public KeyVaultClient(AuthenticationCallback authenticationCallback, params DelegatingHandler[] handlers)
: this(new KeyVaultCredential(authenticationCallback), handlers)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="authenticationCallback">The authentication callback</param>
/// <param name="httpClient">Customized HTTP client </param>
public KeyVaultClient(AuthenticationCallback authenticationCallback, HttpClient httpClient)
: this(new KeyVaultCredential(authenticationCallback), httpClient)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="credential">Credential for key vault operations</param>
/// <param name="httpClient">Customized HTTP client </param>
public KeyVaultClient(KeyVaultCredential credential, HttpClient httpClient)
// clone the KeyVaultCredential to ensure the instance is only used by this client since it
// will use this client's HttpClient for unauthenticated calls to retrieve the auth challenge
: this(credential.Clone())
{
base.HttpClient = httpClient;
}
/// <summary>
/// Gets the pending certificate signing request response.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='certificateName'>
/// The name of the certificate
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<string>> GetPendingCertificateSigningRequestWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultBaseUrl == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultBaseUrl");
}
if (certificateName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "certificateName");
}
if (this.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("vaultBaseUrl", vaultBaseUrl);
tracingParameters.Add("certificateName", certificateName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetPendingCertificateSigningRequest", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "certificates/{certificate-name}/pending";
_url = _url.Replace("{vaultBaseUrl}", vaultBaseUrl);
_url = _url.Replace("{certificate-name}", Uri.EscapeDataString(certificateName));
List<string> _queryParameters = new List<string>();
if (this.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
_httpRequest.Headers.Add("Accept", "application/pkcs10");
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach (var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new KeyVaultErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
KeyVaultError _errorBody = SafeJsonConvert.DeserializeObject<KeyVaultError>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<string>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Overrides the base <see cref="CreateHttpHandlerPipeline"/> to add a <see cref="ChallengeCacheHandler"/> as the outermost <see cref="DelegatingHandler"/>.
/// </summary>
/// <param name="httpClientHandler">The base handler for the client</param>
/// <param name="handlers">The handler pipeline for the client</param>
/// <returns></returns>
protected override DelegatingHandler CreateHttpHandlerPipeline(HttpClientHandler httpClientHandler, params DelegatingHandler[] handlers)
{
var challengeCacheHandler = new ChallengeCacheHandler();
challengeCacheHandler.InnerHandler = base.CreateHttpHandlerPipeline(httpClientHandler, handlers);
return challengeCacheHandler;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
namespace CExtensions.Patch.Utils.Extensions
{
public enum StringManipulationMode
{
Inclusive,
Exclusive
}
public static class StringManipulationExtensions
{
/// <summary>
/// Extension Method:
/// This method returns a list of items that are contained in the string between the two separator.
/// example:
/// <code> "someValues : {{one}},{{two}},{{three}}".ExtractEntriesBetween("{{", "}}");</code>
/// will return a list containing these items in a list:
/// <code>
/// one,two,three
/// </code>
///
/// </summary>
/// <param name="str">the string to act on</param>
/// <param name="startSeparator">the left separator</param>
/// <param name="endSeparator">the right separator</param>
/// <returns>a list with the items</returns>
public static IList<string> ExtractValues(this String str, String startSeparator, String endSeparator)
{
if (str.IsNullOrEmpty())
{
return new List<string>();
}
int startIndex = str.IndexOf(startSeparator);
IList<string> result = new List<string>();
int maxLoop = 1;
if (startIndex < 0)
{
return result;
}
while (startIndex >= 0 && maxLoop < 100)
{
maxLoop++;
str = str.Remove(0, startIndex + startSeparator.Length);
int endIndex = str.IndexOf(endSeparator);
if (endIndex < 0)
{
return result;
}
String item = str.Substring(0, endIndex);
result.Add(item);
str = str.Remove(0, endIndex + endSeparator.Length);
startIndex = str.IndexOf(startSeparator);
}
return result;
}
/// <summary>
/// Extension Method:
/// This method returns a String that is contained in the string between the two separator.
/// example:
/// <code> "valueOut(valueIn)valueExt".BetweenFirst("(", ")",StringManipulationMode.Exclusive);</code>
/// will return a String with:
/// <code>
/// valueIn
/// </code>
///
/// </summary>
/// <param name="str">the string to act on</param>
/// <param name="startSeparator">the left separator</param>
/// <param name="endSeparator">the right separator</param>
/// <param name="mode">exclude or include the separators</param>
/// <returns>the extrated string</returns>
public static String BetweenFirst(this String str, String from, String to, StringManipulationMode mode)
{
String result = null;
int firstIndex = str.IndexOf(from);
int lastIndex = str.IndexOf(to);
if(lastIndex < 0 || firstIndex < 0 || lastIndex < firstIndex) {
return result;
}
if(mode == StringManipulationMode.Exclusive){
result = SubStringFrom(str, firstIndex + from.Length + 1, lastIndex);
}
else
result = SubStringFrom(str, firstIndex + 1 , lastIndex + to.Length);
return result;
}
public static String SubStringFrom(this String str, int from, int to)
{
return SubStringFrom(str, from, to, StringManipulationMode.Inclusive);
}
public static String SubStringFrom(this String str, int from, int to, StringManipulationMode mode)
{
if (str.Length < to || from > to)
{
throw new ArgumentException("from must be less or equal than to and string length must be greater or equal than to");
}
String result = str;
if (mode == StringManipulationMode.Inclusive)
{
result = str.Substring(from - 1, to + 1 - from);
}
else if (mode == StringManipulationMode.Exclusive)
{
result = str.Substring(from, to -1 - from);
}
else
{
throw new ArgumentException(mode + " is not yet supported");
}
return result;
}
public static Boolean IsNullOrEmpty(this string str)
{
if(string.IsNullOrEmpty(str))
{
return true;
}
return false;
}
public static Boolean IsNotNullOrEmpty(this string str)
{
return !IsNullOrEmpty(str);
}
/// <summary>
/// Extension Method:
/// This method delete a substring between two separators and returns a new String.
/// example:
/// <code> "(one)(two)(three)".EraseBetweenFirst('(', ')', StringManipulationMode.Exclusive);</code>
/// will return a String with:
/// <code>
/// ()(two)(three)
/// </code>
///
/// </summary>
/// <param name="str">the string to act on</param>
/// <param name="from">the left separator</param>
/// <param name="to">the right separator</param>
/// <param name="mode">exclude or include the separators</param>
/// <returns>the new string</returns>
public static string EraseBetweenFirst(this string str, char from, char to, StringManipulationMode mode)
{
if (str.IsNullOrEmpty())
{
return str;
}
int startindex = (str).IndexOf(from);
if (startindex < 0)
{
return str;
}
int endIndex = str.IndexOf(to);
string result = null;
if(mode == StringManipulationMode.Exclusive)
{
result = str.Remove(startindex + 1, (endIndex + 1) - (startindex + 2));
}
else
{
result = str.Remove(startindex, (endIndex + 1 ) - (startindex));
}
return result;
}
/// <summary>
/// Extension Method:
/// This method return the substring before a separator
/// example:
/// <code> "before.value".BeforeLast('.', StringManipulationMode.Exclusive);</code>
/// will return a String with:
/// <code>
/// before
/// </code>
///
/// </summary>
/// <param name="str">the string to act on</param>
/// <param name="from">the separator</param>
/// <param name="mode">exclude or include the separators</param>
/// <returns>the new string</returns>
public static string BeforeLast(this string str, char from, StringManipulationMode mode)
{
int startindex = str.LastIndexOf(from);
if (startindex < 0)
{
return str;
}
string result;
if(mode == StringManipulationMode.Exclusive){
result = str.Substring(0, startindex);
}
else
{
result = str.Substring(0, startindex+1);
}
return result;
}
/// <summary>
/// Extension Method:
/// This method return the substring after a separator
/// example:
/// <code> "before.value".BeforeLast('.', StringManipulationMode.Exclusive);</code>
/// will return a String with:
/// <code>
/// before
/// </code>
///
/// </summary>
/// <param name="str">the string to act on</param>
/// <param name="from">the separator</param>
/// <param name="mode">exclude or include the separators</param>
/// <returns>the new string</returns>
public static string AfterLast(this string str, char from, StringManipulationMode mode)
{
if (str == null)
{
return str;
}
int startindex = (str).LastIndexOf(from);
if (startindex < 0)
{
return str;
}
string result;
if (mode == StringManipulationMode.Exclusive)
{
result = str.Remove(0, startindex + 1);
}
else
{
result = str.Remove(0, startindex);
}
return result;
}
public static KeyValuePair<string, string> KeyValue(this string str, char splitter)
{
if (str.IsNullOrEmpty())
{
return new KeyValuePair<string,string>();
}
String[] keyValue = str.Split(splitter);
return new KeyValuePair<string, string>(keyValue[0], keyValue[1]);
}
public static KeyValuePair<string, string> KeyValue(this string str)
{
return KeyValue(str, '=');
}
/// <summary>
/// Extension Method:
/// This method return a new string after removing a given substring
/// <code> "value.after".RemoveLast("after");</code>
/// will return a String with:
/// <code>
/// value.
/// </code>
///
/// </summary>
/// <param name="str">the string to act on</param>
/// <param name="toBeRemoved">the substring to remove</param>
/// <returns>the new string</returns>
public static string RemoveLast(this string str, string toBeRemoved)
{
if(str == null) return null;
int startindex = (str).LastIndexOf(toBeRemoved);
if (startindex < 0)
{
return str;
}
string result = str.Remove(startindex, toBeRemoved.Length);
return result;
}
/// <summary>
/// Extension Method:
/// This method return a new string after removing after given substring
/// <code> "value.after".RemoveAfter("af");</code>
/// will return a String with:
/// <code>
/// value.
/// </code>
///
/// </summary>
/// <param name="str">the string to act on</param>
/// <param name="toBeRemoved">the substring to remove</param>
/// <returns>the new string</returns>
public static string RemoveAfter(this string str, string toBeRemoved)
{
if (str == null) return null;
int startindex = (str).LastIndexOf(toBeRemoved);
if (startindex < 0)
{
return str;
}
string result = str.Remove(startindex, str.Length - startindex);
return result;
}
/// <summary>
/// Extension Method:
/// This method return a new string after removing after given substring
/// <code> "value.after".RemoveBefore("af");</code>
/// will return a String with:
/// <code>
/// ter
/// </code>
///
/// </summary>
/// <param name="str">the string to act on</param>
/// <param name="toBeRemoved">the substring to remove</param>
/// <returns>the new string</returns>
public static string RemoveBefore(this string str, string toBeRemoved)
{
if (str == null) return null;
int startindex = (str).IndexOf(toBeRemoved);
if (startindex < 0)
{
return str;
}
string result = str.Remove(0, startindex + toBeRemoved.Length);
return result;
}
public static string[] Split(this string str, string splitter)
{
return str.Split(new string[] { splitter }, StringSplitOptions.RemoveEmptyEntries);
}
public static string ReplaceExpressions(this string str,string enclosingStart = "{{", string enclosingEnd = "}}", Boolean concat = false)
{
if (str == null) return null;
if(!str.Contains(enclosingStart))
{
return str;
}
string[] strEnclosure = str.SplitStringEnclosing();
string expression = "";
for (int i = 0; i < strEnclosure.Length; ++i)
{
if (concat)
{
if (i > 0) expression = expression + " + ";
if (strEnclosure[i].IndexOf('{') != -1)
{
string str2 = strEnclosure[i].RemoveEnclosure();
if (str2.Split(".").Length == 1) str2 = str2 + ".Target";
expression = expression + str2;
}
else expression = expression + "'" + strEnclosure[i] + "'";
}
else
{
if (strEnclosure[i].IndexOf('{') != -1)
{
string str2 = strEnclosure[i].RemoveEnclosure();
if (str2.Split(".").Length == 1) str2 = str2 + ".Target";
expression = expression + str2;
}
else expression = expression + strEnclosure[i];
}
}
return expression;
}
/// <summary>
/// Extension Method:
/// This method return a array of substrings of a string separated by values enclosed by a specific char
/// <code> "databases/{{config.General.DataBase}}/collections/{{resourceTemplate.Source}}".SplitString();</code>
/// will return a String with:
/// <code>
/// [databases/,{{config.General.DataBase}},/collections/,{{resourceTemplate.Source}}]
/// </code>
///
/// </summary>
/// <param name="str">the string to act on</param>
/// <param name="enclosingStart">the enclosing start</param>
/// <param name="enclosingStart">the enclosing start</param>
/// <returns>array of substrings</returns>
public static string[] SplitStringEnclosing(this string str, string enclosingStart = "{{", string enclosingEnd = "}}")
{
int[] startIndexs = str.IndexOfEnclosure(enclosingStart);
int[] endIndexs = str.IndexOfEnclosure(enclosingEnd);
IList<string> subString = new List<string>();
int currentIndex = 1;
int lastIndex = startIndexs[0];
int i = 0;
int j = 0;
if ((startIndexs[0] + 1) == currentIndex)
{
lastIndex = endIndexs[0] + 2;
i = 1;
}
while ((i <= startIndexs.Length * 2) && (currentIndex <= lastIndex))
{
subString.Add(str.SubStringFrom(currentIndex, lastIndex));
currentIndex = lastIndex + 1;
if (i % 2 == 0) lastIndex = endIndexs[j] + 2;
else
{
if (j < startIndexs.Length - 1)
{
++j;
lastIndex = startIndexs[j];
}
else lastIndex = str.Length;
}
++i;
}
return subString.ToArray();
}
public static int[] IndexOfEnclosure(this string str, string enclosing)
{
IList<int> index = new List<int>();
int i = 0;
while ((i = str.IndexOf(enclosing, i)) != -1)
{
index.Add(i);
++i;
}
int[] array = index.ToArray();
return array;
}
//TODO this method needs to be more general. right now only works with {{}}
public static string RemoveEnclosure(this string str)
{
return str.SubStringFrom(3,str.Length-2);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
namespace System.Numerics
{
// This file contains the definitions for all of the JIT intrinsic methods and properties that are recognized by the current x64 JIT compiler.
// The implementation defined here is used in any circumstance where the JIT fails to recognize these members as intrinsic.
// The JIT recognizes these methods and properties by name and signature: if either is changed, the JIT will no longer recognize the member.
// Some methods declared here are not strictly intrinsic, but delegate to an intrinsic method. For example, only one overload of CopyTo()
// is actually recognized by the JIT, but both are here for simplicity.
public partial struct Vector3
{
/// <summary>
/// The X component of the vector.
/// </summary>
public Single X;
/// <summary>
/// The Y component of the vector.
/// </summary>
public Single Y;
/// <summary>
/// The Z component of the vector.
/// </summary>
public Single Z;
#region Constructors
/// <summary>
/// Constructs a vector whose elements are all the single specified value.
/// </summary>
/// <param name="value">The element to fill the vector with.</param>
[JitIntrinsic]
public Vector3(Single value) : this(value, value, value) { }
/// <summary>
/// Constructs a Vector3 from the given Vector2 and a third value.
/// </summary>
/// <param name="value">The Vector to extract X and Y components from.</param>
/// <param name="z">The Z component.</param>
public Vector3(Vector2 value, float z) : this(value.X, value.Y, z) { }
/// <summary>
/// Constructs a vector with the given individual elements.
/// </summary>
/// <param name="x">The X component.</param>
/// <param name="y">The Y component.</param>
/// <param name="z">The Z component.</param>
[JitIntrinsic]
public Vector3(Single x, Single y, Single z)
{
X = x;
Y = y;
Z = z;
}
#endregion Constructors
#region Public Instance Methods
/// <summary>
/// Copies the contents of the vector into the given array.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(Single[] array)
{
CopyTo(array, 0);
}
/// <summary>
/// Copies the contents of the vector into the given array, starting from index.
/// </summary>
/// <exception cref="ArgumentNullException">If array is null.</exception>
/// <exception cref="RankException">If array is multidimensional.</exception>
/// <exception cref="ArgumentOutOfRangeException">If index is greater than end of the array or index is less than zero.</exception>
/// <exception cref="ArgumentException">If number of elements in source vector is greater than those available in destination array.</exception>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(Single[] array, int index)
{
if (array == null)
{
// Match the JIT's exception type here. For perf, a NullReference is thrown instead of an ArgumentNull.
throw new NullReferenceException(SR.Arg_NullArgumentNullRef);
}
if (index < 0 || index >= array.Length)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.Arg_ArgumentOutOfRangeException, index));
}
if ((array.Length - index) < 3)
{
throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, index));
}
array[index] = X;
array[index + 1] = Y;
array[index + 2] = Z;
}
/// <summary>
/// Returns a boolean indicating whether the given Vector3 is equal to this Vector3 instance.
/// </summary>
/// <param name="other">The Vector3 to compare this instance to.</param>
/// <returns>True if the other Vector3 is equal to this instance; False otherwise.</returns>
[JitIntrinsic]
public bool Equals(Vector3 other)
{
return X == other.X &&
Y == other.Y &&
Z == other.Z;
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the dot product of two vectors.
/// </summary>
/// <param name="vector1">The first vector.</param>
/// <param name="vector2">The second vector.</param>
/// <returns>The dot product.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Dot(Vector3 vector1, Vector3 vector2)
{
return vector1.X * vector2.X +
vector1.Y * vector2.Y +
vector1.Z * vector2.Z;
}
/// <summary>
/// Returns a vector whose elements are the minimum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The minimized vector.</returns>
[JitIntrinsic]
public static Vector3 Min(Vector3 value1, Vector3 value2)
{
return new Vector3(
(value1.X < value2.X) ? value1.X : value2.X,
(value1.Y < value2.Y) ? value1.Y : value2.Y,
(value1.Z < value2.Z) ? value1.Z : value2.Z);
}
/// <summary>
/// Returns a vector whose elements are the maximum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The maximized vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Max(Vector3 value1, Vector3 value2)
{
return new Vector3(
(value1.X > value2.X) ? value1.X : value2.X,
(value1.Y > value2.Y) ? value1.Y : value2.Y,
(value1.Z > value2.Z) ? value1.Z : value2.Z);
}
/// <summary>
/// Returns a vector whose elements are the absolute values of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The absolute value vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Abs(Vector3 value)
{
return new Vector3(Math.Abs(value.X), Math.Abs(value.Y), Math.Abs(value.Z));
}
/// <summary>
/// Returns a vector whose elements are the square root of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The square root vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 SquareRoot(Vector3 value)
{
return new Vector3((Single)Math.Sqrt(value.X), (Single)Math.Sqrt(value.Y), (Single)Math.Sqrt(value.Z));
}
#endregion Public Static Methods
#region Public Static Operators
/// <summary>
/// Adds two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator +(Vector3 left, Vector3 right)
{
return new Vector3(left.X + right.X, left.Y + right.Y, left.Z + right.Z);
}
/// <summary>
/// Subtracts the second vector from the first.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator -(Vector3 left, Vector3 right)
{
return new Vector3(left.X - right.X, left.Y - right.Y, left.Z - right.Z);
}
/// <summary>
/// Multiplies two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The product vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Vector3 left, Vector3 right)
{
return new Vector3(left.X * right.X, left.Y * right.Y, left.Z * right.Z);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Vector3 left, Single right)
{
return left * new Vector3(right);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The scalar value.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Single left, Vector3 right)
{
return new Vector3(left) * right;
}
/// <summary>
/// Divides the first vector by the second.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The vector resulting from the division.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator /(Vector3 left, Vector3 right)
{
return new Vector3(left.X / right.X, left.Y / right.Y, left.Z / right.Z);
}
/// <summary>
/// Divides the vector by the given scalar.
/// </summary>
/// <param name="value1">The source vector.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the division.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator /(Vector3 value1, float value2)
{
float invDiv = 1.0f / value2;
return new Vector3(
value1.X * invDiv,
value1.Y * invDiv,
value1.Z * invDiv);
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator -(Vector3 value)
{
return Zero - value;
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are equal; False otherwise.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Vector3 left, Vector3 right)
{
return (left.X == right.X &&
left.Y == right.Y &&
left.Z == right.Z);
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are not equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are not equal; False if they are equal.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Vector3 left, Vector3 right)
{
return (left.X != right.X ||
left.Y != right.Y ||
left.Z != right.Z);
}
#endregion Public Static Operators
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
namespace Internal.Cryptography.Pal
{
internal sealed class OpenSslCertificateFinder : IFindPal
{
private readonly X509Certificate2Collection _findFrom;
private readonly X509Certificate2Collection _copyTo;
private readonly bool _validOnly;
internal OpenSslCertificateFinder(X509Certificate2Collection findFrom, X509Certificate2Collection copyTo, bool validOnly)
{
_findFrom = findFrom;
_copyTo = copyTo;
_validOnly = validOnly;
}
public string NormalizeOid(string maybeOid, OidGroup expectedGroup)
{
Oid oid = new Oid(maybeOid);
// If maybeOid is interpreted to be a FriendlyName, return the OID.
if (!StringComparer.OrdinalIgnoreCase.Equals(oid.Value, maybeOid))
{
return oid.Value;
}
FindPal.ValidateOidValue(maybeOid);
return maybeOid;
}
public void FindByThumbprint(byte[] thumbprint)
{
FindCore(cert => cert.GetCertHash().ContentsEqual(thumbprint));
}
public void FindBySubjectName(string subjectName)
{
FindCore(
cert =>
{
string formedSubject = X500NameEncoder.X500DistinguishedNameDecode(cert.SubjectName.RawData, false, X500DistinguishedNameFlags.None);
return formedSubject.IndexOf(subjectName, StringComparison.OrdinalIgnoreCase) >= 0;
});
}
public void FindBySubjectDistinguishedName(string subjectDistinguishedName)
{
FindCore(cert => StringComparer.OrdinalIgnoreCase.Equals(subjectDistinguishedName, cert.Subject));
}
public void FindByIssuerName(string issuerName)
{
FindCore(
cert =>
{
string formedIssuer = X500NameEncoder.X500DistinguishedNameDecode(cert.IssuerName.RawData, false, X500DistinguishedNameFlags.None);
return formedIssuer.IndexOf(issuerName, StringComparison.OrdinalIgnoreCase) >= 0;
});
}
public void FindByIssuerDistinguishedName(string issuerDistinguishedName)
{
FindCore(cert => StringComparer.OrdinalIgnoreCase.Equals(issuerDistinguishedName, cert.Issuer));
}
public void FindBySerialNumber(BigInteger hexValue, BigInteger decimalValue)
{
FindCore(
cert =>
{
byte[] serialBytes = cert.GetSerialNumber();
BigInteger serialNumber = FindPal.PositiveBigIntegerFromByteArray(serialBytes);
bool match = hexValue.Equals(serialNumber) || decimalValue.Equals(serialNumber);
return match;
});
}
private static DateTime NormalizeDateTime(DateTime dateTime)
{
// If it's explicitly UTC, convert it to local before a comparison, since the
// NotBefore and NotAfter are in Local time.
//
// If it was Unknown, assume it was Local.
if (dateTime.Kind == DateTimeKind.Utc)
{
return dateTime.ToLocalTime();
}
return dateTime;
}
public void FindByTimeValid(DateTime dateTime)
{
DateTime normalized = NormalizeDateTime(dateTime);
FindCore(cert => cert.NotBefore <= normalized && normalized <= cert.NotAfter);
}
public void FindByTimeNotYetValid(DateTime dateTime)
{
DateTime normalized = NormalizeDateTime(dateTime);
FindCore(cert => cert.NotBefore > normalized);
}
public void FindByTimeExpired(DateTime dateTime)
{
DateTime normalized = NormalizeDateTime(dateTime);
FindCore(cert => cert.NotAfter < normalized);
}
public void FindByTemplateName(string templateName)
{
FindCore(
cert =>
{
X509Extension ext = FindExtension(cert, Oids.EnrollCertTypeExtension);
if (ext != null)
{
// Try a V1 template structure, just a string:
string decodedName = Interop.Crypto.DerStringToManagedString(ext.RawData);
// If this doesn't match, maybe a V2 template will
if (StringComparer.OrdinalIgnoreCase.Equals(templateName, decodedName))
{
return true;
}
}
ext = FindExtension(cert, Oids.CertificateTemplate);
if (ext != null)
{
DerSequenceReader reader = new DerSequenceReader(ext.RawData);
// SEQUENCE (
// OID oid,
// INTEGER major,
// INTEGER minor OPTIONAL
// )
if (reader.PeekTag() == (byte)DerSequenceReader.DerTag.ObjectIdentifier)
{
Oid oid = reader.ReadOid();
if (StringComparer.Ordinal.Equals(templateName, oid.Value))
{
return true;
}
}
}
return false;
});
}
public void FindByApplicationPolicy(string oidValue)
{
FindCore(
cert =>
{
X509Extension ext = FindExtension(cert, Oids.EnhancedKeyUsage);
if (ext == null)
{
// A certificate with no EKU is valid for all extended purposes.
return true;
}
var ekuExt = (X509EnhancedKeyUsageExtension)ext;
foreach (Oid usageOid in ekuExt.EnhancedKeyUsages)
{
if (StringComparer.Ordinal.Equals(oidValue, usageOid.Value))
{
return true;
}
}
// If the certificate had an EKU extension, and the value we wanted was
// not present, then it is not valid for that usage.
return false;
});
}
public void FindByCertificatePolicy(string oidValue)
{
FindCore(
cert =>
{
X509Extension ext = FindExtension(cert, Oids.CertPolicies);
if (ext == null)
{
// Unlike Application Policy, Certificate Policy is "assume false".
return false;
}
ISet<string> policyOids = CertificatePolicyChain.ReadCertPolicyExtension(ext);
return policyOids.Contains(oidValue);
});
}
public void FindByExtension(string oidValue)
{
FindCore(cert => FindExtension(cert, oidValue) != null);
}
public void FindByKeyUsage(X509KeyUsageFlags keyUsage)
{
FindCore(
cert =>
{
X509Extension ext = FindExtension(cert, Oids.KeyUsage);
if (ext == null)
{
// A certificate with no key usage extension is considered valid for all key usages.
return true;
}
var kuExt = (X509KeyUsageExtension)ext;
return (kuExt.KeyUsages & keyUsage) == keyUsage;
});
}
public void FindBySubjectKeyIdentifier(byte[] keyIdentifier)
{
FindCore(
cert =>
{
X509Extension ext = FindExtension(cert, Oids.SubjectKeyIdentifier);
byte[] certKeyId;
if (ext != null)
{
// The extension exposes the value as a hexadecimal string, or we can decode here.
// Enough parsing has gone on, let's decode.
certKeyId = OpenSslX509Encoder.DecodeX509SubjectKeyIdentifierExtension(ext.RawData);
}
else
{
// The Desktop/Windows version of this method use CertGetCertificateContextProperty
// with a property ID of CERT_KEY_IDENTIFIER_PROP_ID.
//
// MSDN says that when there's no extension, this method takes the SHA-1 of the
// SubjectPublicKeyInfo block, and returns that.
//
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa376079%28v=vs.85%29.aspx
OpenSslX509CertificateReader certPal = (OpenSslX509CertificateReader)cert.Pal;
using (HashAlgorithm hash = SHA1.Create())
{
byte[] publicKeyInfoBytes = Interop.Crypto.OpenSslEncode(
Interop.Crypto.GetX509SubjectPublicKeyInfoDerSize,
Interop.Crypto.EncodeX509SubjectPublicKeyInfo,
certPal.SafeHandle);
certKeyId = hash.ComputeHash(publicKeyInfoBytes);
}
}
return keyIdentifier.ContentsEqual(certKeyId);
});
}
public void Dispose()
{
// No resources to release, but required by the interface.
}
private static X509Extension FindExtension(X509Certificate2 cert, string extensionOid)
{
if (cert.Extensions == null || cert.Extensions.Count == 0)
{
return null;
}
foreach (X509Extension ext in cert.Extensions)
{
if (ext != null &&
ext.Oid != null &&
StringComparer.Ordinal.Equals(extensionOid, ext.Oid.Value))
{
return ext;
}
}
return null;
}
private void FindCore(Predicate<X509Certificate2> predicate)
{
foreach (X509Certificate2 cert in _findFrom)
{
if (predicate(cert))
{
if (!_validOnly || IsCertValid(cert))
{
OpenSslX509CertificateReader certPal = (OpenSslX509CertificateReader)cert.Pal;
_copyTo.Add(new X509Certificate2(certPal.DuplicateHandles()));
}
}
}
}
private static bool IsCertValid(X509Certificate2 cert)
{
try
{
// This needs to be kept in sync with VerifyCertificateIgnoringErrors in the
// Windows PAL version (and potentially any other PALs that come about)
using (X509Chain chain = new X509Chain
{
ChainPolicy =
{
RevocationMode = X509RevocationMode.NoCheck,
RevocationFlag = X509RevocationFlag.ExcludeRoot
}
})
{
bool valid = chain.Build(cert);
int elementCount = chain.ChainElements.Count;
for (int i = 0; i < elementCount; i++)
{
chain.ChainElements[i].Certificate.Dispose();
}
return valid;
}
}
catch (CryptographicException)
{
return false;
}
}
}
}
| |
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using FileStaging;
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// An Azure Batch task. A task is a piece of work that is associated with a job and runs on a compute node.
/// </summary>
public partial class CloudTask : ITransportObjectProvider<Models.TaskAddParameter>, IInheritedBehaviors, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<AffinityInformation> AffinityInformationProperty;
public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty;
public readonly PropertyAccessor<string> CommandLineProperty;
public readonly PropertyAccessor<ComputeNodeInformation> ComputeNodeInformationProperty;
public readonly PropertyAccessor<TaskConstraints> ConstraintsProperty;
public readonly PropertyAccessor<DateTime?> CreationTimeProperty;
public readonly PropertyAccessor<TaskDependencies> DependsOnProperty;
public readonly PropertyAccessor<string> DisplayNameProperty;
public readonly PropertyAccessor<IList<EnvironmentSetting>> EnvironmentSettingsProperty;
public readonly PropertyAccessor<string> ETagProperty;
public readonly PropertyAccessor<TaskExecutionInformation> ExecutionInformationProperty;
public readonly PropertyAccessor<ExitConditions> ExitConditionsProperty;
public readonly PropertyAccessor<IList<IFileStagingProvider>> FilesToStageProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<DateTime?> LastModifiedProperty;
public readonly PropertyAccessor<MultiInstanceSettings> MultiInstanceSettingsProperty;
public readonly PropertyAccessor<Common.TaskState?> PreviousStateProperty;
public readonly PropertyAccessor<DateTime?> PreviousStateTransitionTimeProperty;
public readonly PropertyAccessor<IList<ResourceFile>> ResourceFilesProperty;
public readonly PropertyAccessor<bool?> RunElevatedProperty;
public readonly PropertyAccessor<Common.TaskState?> StateProperty;
public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty;
public readonly PropertyAccessor<TaskStatistics> StatisticsProperty;
public readonly PropertyAccessor<string> UrlProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.AffinityInformationProperty = this.CreatePropertyAccessor<AffinityInformation>("AffinityInformation", BindingAccess.Read | BindingAccess.Write);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>("ApplicationPackageReferences", BindingAccess.Read | BindingAccess.Write);
this.CommandLineProperty = this.CreatePropertyAccessor<string>("CommandLine", BindingAccess.Read | BindingAccess.Write);
this.ComputeNodeInformationProperty = this.CreatePropertyAccessor<ComputeNodeInformation>("ComputeNodeInformation", BindingAccess.None);
this.ConstraintsProperty = this.CreatePropertyAccessor<TaskConstraints>("Constraints", BindingAccess.Read | BindingAccess.Write);
this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>("CreationTime", BindingAccess.None);
this.DependsOnProperty = this.CreatePropertyAccessor<TaskDependencies>("DependsOn", BindingAccess.Read | BindingAccess.Write);
this.DisplayNameProperty = this.CreatePropertyAccessor<string>("DisplayName", BindingAccess.Read | BindingAccess.Write);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>("EnvironmentSettings", BindingAccess.Read | BindingAccess.Write);
this.ETagProperty = this.CreatePropertyAccessor<string>("ETag", BindingAccess.None);
this.ExecutionInformationProperty = this.CreatePropertyAccessor<TaskExecutionInformation>("ExecutionInformation", BindingAccess.None);
this.ExitConditionsProperty = this.CreatePropertyAccessor<ExitConditions>("ExitConditions", BindingAccess.Read | BindingAccess.Write);
this.FilesToStageProperty = this.CreatePropertyAccessor<IList<IFileStagingProvider>>("FilesToStage", BindingAccess.Read | BindingAccess.Write);
this.IdProperty = this.CreatePropertyAccessor<string>("Id", BindingAccess.Read | BindingAccess.Write);
this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>("LastModified", BindingAccess.None);
this.MultiInstanceSettingsProperty = this.CreatePropertyAccessor<MultiInstanceSettings>("MultiInstanceSettings", BindingAccess.Read | BindingAccess.Write);
this.PreviousStateProperty = this.CreatePropertyAccessor<Common.TaskState?>("PreviousState", BindingAccess.None);
this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>("PreviousStateTransitionTime", BindingAccess.None);
this.ResourceFilesProperty = this.CreatePropertyAccessor<IList<ResourceFile>>("ResourceFiles", BindingAccess.Read | BindingAccess.Write);
this.RunElevatedProperty = this.CreatePropertyAccessor<bool?>("RunElevated", BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor<Common.TaskState?>("State", BindingAccess.None);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>("StateTransitionTime", BindingAccess.None);
this.StatisticsProperty = this.CreatePropertyAccessor<TaskStatistics>("Statistics", BindingAccess.None);
this.UrlProperty = this.CreatePropertyAccessor<string>("Url", BindingAccess.None);
}
public PropertyContainer(Models.CloudTask protocolObject) : base(BindingState.Bound)
{
this.AffinityInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AffinityInfo, o => new AffinityInformation(o).Freeze()),
"AffinityInformation",
BindingAccess.Read);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor(
ApplicationPackageReference.ConvertFromProtocolCollectionAndFreeze(protocolObject.ApplicationPackageReferences),
"ApplicationPackageReferences",
BindingAccess.Read);
this.CommandLineProperty = this.CreatePropertyAccessor(
protocolObject.CommandLine,
"CommandLine",
BindingAccess.Read);
this.ComputeNodeInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NodeInfo, o => new ComputeNodeInformation(o).Freeze()),
"ComputeNodeInformation",
BindingAccess.Read);
this.ConstraintsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new TaskConstraints(o)),
"Constraints",
BindingAccess.Read | BindingAccess.Write);
this.CreationTimeProperty = this.CreatePropertyAccessor(
protocolObject.CreationTime,
"CreationTime",
BindingAccess.Read);
this.DependsOnProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.DependsOn, o => new TaskDependencies(o).Freeze()),
"DependsOn",
BindingAccess.Read);
this.DisplayNameProperty = this.CreatePropertyAccessor(
protocolObject.DisplayName,
"DisplayName",
BindingAccess.Read);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor(
EnvironmentSetting.ConvertFromProtocolCollectionAndFreeze(protocolObject.EnvironmentSettings),
"EnvironmentSettings",
BindingAccess.Read);
this.ETagProperty = this.CreatePropertyAccessor(
protocolObject.ETag,
"ETag",
BindingAccess.Read);
this.ExecutionInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExecutionInfo, o => new TaskExecutionInformation(o).Freeze()),
"ExecutionInformation",
BindingAccess.Read);
this.ExitConditionsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExitConditions, o => new ExitConditions(o).Freeze()),
"ExitConditions",
BindingAccess.Read);
this.FilesToStageProperty = this.CreatePropertyAccessor<IList<IFileStagingProvider>>(
"FilesToStage",
BindingAccess.None);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
"Id",
BindingAccess.Read);
this.LastModifiedProperty = this.CreatePropertyAccessor(
protocolObject.LastModified,
"LastModified",
BindingAccess.Read);
this.MultiInstanceSettingsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.MultiInstanceSettings, o => new MultiInstanceSettings(o).Freeze()),
"MultiInstanceSettings",
BindingAccess.Read);
this.PreviousStateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.TaskState, Common.TaskState>(protocolObject.PreviousState),
"PreviousState",
BindingAccess.Read);
this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.PreviousStateTransitionTime,
"PreviousStateTransitionTime",
BindingAccess.Read);
this.ResourceFilesProperty = this.CreatePropertyAccessor(
ResourceFile.ConvertFromProtocolCollectionAndFreeze(protocolObject.ResourceFiles),
"ResourceFiles",
BindingAccess.Read);
this.RunElevatedProperty = this.CreatePropertyAccessor(
protocolObject.RunElevated,
"RunElevated",
BindingAccess.Read);
this.StateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.TaskState, Common.TaskState>(protocolObject.State),
"State",
BindingAccess.Read);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.StateTransitionTime,
"StateTransitionTime",
BindingAccess.Read);
this.StatisticsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new TaskStatistics(o).Freeze()),
"Statistics",
BindingAccess.Read);
this.UrlProperty = this.CreatePropertyAccessor(
protocolObject.Url,
"Url",
BindingAccess.Read);
}
}
private PropertyContainer propertyContainer;
private readonly BatchClient parentBatchClient;
private readonly string parentJobId;
internal string ParentJobId
{
get
{
return this.parentJobId;
}
}
#region Constructors
internal CloudTask(
BatchClient parentBatchClient,
string parentJobId,
Models.CloudTask protocolObject,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.parentJobId = parentJobId;
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region IInheritedBehaviors
/// <summary>
/// Gets or sets a list of behaviors that modify or customize requests to the Batch service
/// made via this <see cref="CloudTask"/>.
/// </summary>
/// <remarks>
/// <para>These behaviors are inherited by child objects.</para>
/// <para>Modifications are applied in the order of the collection. The last write wins.</para>
/// </remarks>
public IList<BatchClientBehavior> CustomBehaviors { get; set; }
#endregion IInheritedBehaviors
#region CloudTask
/// <summary>
/// Gets or sets a locality hint that can be used by the Batch service to select a node on which to start the task.
/// </summary>
public AffinityInformation AffinityInformation
{
get { return this.propertyContainer.AffinityInformationProperty.Value; }
set { this.propertyContainer.AffinityInformationProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of application packages that the Batch service will deploy to the compute node before running
/// the command line.
/// </summary>
public IList<ApplicationPackageReference> ApplicationPackageReferences
{
get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; }
set
{
this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the command line of the task.
/// </summary>
/// <remarks>
/// The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment
/// variable expansion. If you want to take advantage of such features, you should invoke the shell in the command
/// line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux.
/// </remarks>
public string CommandLine
{
get { return this.propertyContainer.CommandLineProperty.Value; }
set { this.propertyContainer.CommandLineProperty.Value = value; }
}
/// <summary>
/// Gets information about the compute node on which the task ran.
/// </summary>
public ComputeNodeInformation ComputeNodeInformation
{
get { return this.propertyContainer.ComputeNodeInformationProperty.Value; }
}
/// <summary>
/// Gets or sets the execution constraints that apply to this task.
/// </summary>
public TaskConstraints Constraints
{
get { return this.propertyContainer.ConstraintsProperty.Value; }
set { this.propertyContainer.ConstraintsProperty.Value = value; }
}
/// <summary>
/// Gets the creation time of the task.
/// </summary>
public DateTime? CreationTime
{
get { return this.propertyContainer.CreationTimeProperty.Value; }
}
/// <summary>
/// Gets or sets any other tasks that this <see cref="CloudTask"/> depends on. The task will not be scheduled until
/// all depended-on tasks have completed successfully.
/// </summary>
/// <remarks>
/// The job must set <see cref="CloudJob.UsesTaskDependencies"/> to true in order to use task dependencies. If UsesTaskDependencies
/// is false (the default), adding a task with dependencies will fail with an error.
/// </remarks>
public TaskDependencies DependsOn
{
get { return this.propertyContainer.DependsOnProperty.Value; }
set { this.propertyContainer.DependsOnProperty.Value = value; }
}
/// <summary>
/// Gets or sets the display name of the task.
/// </summary>
public string DisplayName
{
get { return this.propertyContainer.DisplayNameProperty.Value; }
set { this.propertyContainer.DisplayNameProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of environment variable settings for the task.
/// </summary>
public IList<EnvironmentSetting> EnvironmentSettings
{
get { return this.propertyContainer.EnvironmentSettingsProperty.Value; }
set
{
this.propertyContainer.EnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets the ETag for the task.
/// </summary>
public string ETag
{
get { return this.propertyContainer.ETagProperty.Value; }
}
/// <summary>
/// Gets the execution information for the task.
/// </summary>
public TaskExecutionInformation ExecutionInformation
{
get { return this.propertyContainer.ExecutionInformationProperty.Value; }
}
/// <summary>
/// Gets or sets how the Batch service should respond when the task completes.
/// </summary>
public ExitConditions ExitConditions
{
get { return this.propertyContainer.ExitConditionsProperty.Value; }
set { this.propertyContainer.ExitConditionsProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of files to be staged for the task.
/// </summary>
public IList<IFileStagingProvider> FilesToStage
{
get { return this.propertyContainer.FilesToStageProperty.Value; }
set
{
this.propertyContainer.FilesToStageProperty.Value = ConcurrentChangeTrackedList<IFileStagingProvider>.TransformEnumerableToConcurrentList(value);
}
}
/// <summary>
/// Gets or sets the id of the task.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
set { this.propertyContainer.IdProperty.Value = value; }
}
/// <summary>
/// Gets the last modified time of the task.
/// </summary>
public DateTime? LastModified
{
get { return this.propertyContainer.LastModifiedProperty.Value; }
}
/// <summary>
/// Gets or sets information about how to run the multi-instance task.
/// </summary>
public MultiInstanceSettings MultiInstanceSettings
{
get { return this.propertyContainer.MultiInstanceSettingsProperty.Value; }
set { this.propertyContainer.MultiInstanceSettingsProperty.Value = value; }
}
/// <summary>
/// Gets the previous state of the task.
/// </summary>
/// <remarks>
/// If the task is in its initial <see cref="Common.TaskState.Active"/> state, the PreviousState property is not
/// defined.
/// </remarks>
public Common.TaskState? PreviousState
{
get { return this.propertyContainer.PreviousStateProperty.Value; }
}
/// <summary>
/// Gets the time at which the task entered its previous state.
/// </summary>
/// <remarks>
/// If the task is in its initial <see cref="Common.TaskState.Active"/> state, the PreviousStateTransitionTime property
/// is not defined.
/// </remarks>
public DateTime? PreviousStateTransitionTime
{
get { return this.propertyContainer.PreviousStateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets or sets a list of files that the Batch service will download to the compute node before running the command
/// line.
/// </summary>
public IList<ResourceFile> ResourceFiles
{
get { return this.propertyContainer.ResourceFilesProperty.Value; }
set
{
this.propertyContainer.ResourceFilesProperty.Value = ConcurrentChangeTrackedModifiableList<ResourceFile>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets whether to run the task in elevated mode.
/// </summary>
public bool? RunElevated
{
get { return this.propertyContainer.RunElevatedProperty.Value; }
set { this.propertyContainer.RunElevatedProperty.Value = value; }
}
/// <summary>
/// Gets the current state of the task.
/// </summary>
public Common.TaskState? State
{
get { return this.propertyContainer.StateProperty.Value; }
}
/// <summary>
/// Gets the time at which the task entered its current state.
/// </summary>
public DateTime? StateTransitionTime
{
get { return this.propertyContainer.StateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets resource usage statistics for the task.
/// </summary>
/// <remarks>
/// This property is populated only if the <see cref="CloudTask"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/>
/// including the 'stats' attribute; otherwise it is null.
/// </remarks>
public TaskStatistics Statistics
{
get { return this.propertyContainer.StatisticsProperty.Value; }
}
/// <summary>
/// Gets the URL of the task.
/// </summary>
public string Url
{
get { return this.propertyContainer.UrlProperty.Value; }
}
#endregion // CloudTask
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.TaskAddParameter ITransportObjectProvider<Models.TaskAddParameter>.GetTransportObject()
{
Models.TaskAddParameter result = new Models.TaskAddParameter()
{
AffinityInfo = UtilitiesInternal.CreateObjectWithNullCheck(this.AffinityInformation, (o) => o.GetTransportObject()),
ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences),
CommandLine = this.CommandLine,
Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()),
DependsOn = UtilitiesInternal.CreateObjectWithNullCheck(this.DependsOn, (o) => o.GetTransportObject()),
DisplayName = this.DisplayName,
EnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.EnvironmentSettings),
ExitConditions = UtilitiesInternal.CreateObjectWithNullCheck(this.ExitConditions, (o) => o.GetTransportObject()),
Id = this.Id,
MultiInstanceSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.MultiInstanceSettings, (o) => o.GetTransportObject()),
ResourceFiles = UtilitiesInternal.ConvertToProtocolCollection(this.ResourceFiles),
RunElevated = this.RunElevated,
};
return result;
}
#endregion // Internal/private methods
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Core.Data;
using ArcGIS.Core.Data.PluginDatastore;
using ArcGIS.Core.Geometry;
using ProSqlExpressDb;
namespace ProSqlExpressPluginDatasource
{
/// <summary>
/// (Custom) interface the sample uses to extract row information from the
/// plugin table
/// </summary>
internal interface IPluginRowProvider
{
PluginRow FindRow(int oid, IEnumerable<string> columnFilter, SpatialReference sr);
}
/// <summary>
/// Acts as a conduit between a data structure in a third-party data source (Microsoft Access DB)
/// and a ArcGIS.Core.Data.Table (or ArcGIS.Core.Data.FeatureClass) in ArcGIS Pro.
/// </summary>
public class ProSqlPluginTableTemplate : PluginTableTemplate, IDisposable, IPluginRowProvider
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[DllImport("kernel32.dll")]
internal static extern uint GetCurrentThreadId();
private readonly ProSqlExpressDb.ProSqlExpressDb _sqlDb;
private readonly string _tableName;
private readonly DataTable _dataTable = new DataTable();
private Envelope _gisExtent;
private readonly SpatialReference _spatialReference;
private readonly ProSqlExpressTableInfo _tableInfo;
private List<PluginField> _pluginFields = null;
/// <summary>
/// Ctor using ProSqlExpressDb from datasource as parameter
/// </summary>
/// <param name="ProSqlExpressDb">ProSqlExpressDb from datasource</param>
/// <param name="tableInfo">ProSqlExpressTableInfo of table/feature class that has been opened</param>
public ProSqlPluginTableTemplate(ProSqlExpressDb.ProSqlExpressDb ProSqlExpressDb, ProSqlExpressTableInfo tableInfo)
{
_sqlDb = ProSqlExpressDb;
_tableName = tableInfo.TableName;
if (!string.IsNullOrEmpty(tableInfo.SpatialRefString))
{
_spatialReference = SpatialReferenceBuilder.CreateSpatialReference(tableInfo.SpatialRefString);
}
_tableInfo = tableInfo;
}
/// <summary>
/// Returns a list of PluginFields - in essence the attribute columns of the sql database table
/// </summary>
/// <returns>list of PluginFields</returns>
public override IReadOnlyList<PluginField> GetFields()
{
if (_pluginFields == null)
{
_pluginFields = new List<PluginField>();
foreach (var col in _tableInfo.FieldInfo.Columns)
{
// TODO: process all field types here ... this list is not complete
var fieldType = FieldType.String;
//System.Diagnostics.Debug.WriteLine($@"{col.ColumnName} {col.ColumnDataType}");
if (col.ColumnName == _tableInfo.FieldInfo.ObjectIdField)
{
fieldType = FieldType.OID;
}
else
{
if (col.ColumnName.Equals(_tableInfo.GeometryFieldName, StringComparison.CurrentCultureIgnoreCase))
{
fieldType = FieldType.Geometry;
}
else
{
switch (col.ColumnDataType.Name)
{
case nameof(DateTime):
fieldType = FieldType.Date;
break;
case nameof(Double):
fieldType = FieldType.Double;
break;
case nameof(Int16):
fieldType = FieldType.Integer;
break;
case nameof(Int32):
fieldType = FieldType.Integer;
break;
case nameof(Guid):
fieldType = FieldType.GUID;
break;
case nameof(String):
fieldType = FieldType.String;
break;
case nameof(Single):
fieldType = FieldType.Single;
break;
default:
System.Diagnostics.Debug.WriteLine($@"Unsupported datatype: {col.ColumnDataType.Name} not mapped");
break;
}
}
}
_pluginFields.Add(new PluginField()
{
Name = col.ColumnName,
AliasName = col.Alias,
FieldType = fieldType,
Length = col.ColumnLength
});
}
}
return _pluginFields;
}
/// <summary>
/// Get the name of the table
/// </summary>
/// <returns>Table name</returns>
public override string GetName() => _tableName;
/// <summary>
/// Gets whether native row count is supported
/// </summary>
/// <remarks>Return true if your table can get the row count without having
/// to enumerate through all the rows (and count them)....which will be
/// the default behavior if you return false</remarks>
/// <returns>True or false</returns>
public override bool IsNativeRowCountSupported() => true;
/// <summary>
/// Search data in this table (feature class) using a given QueryFilter
/// </summary>
/// <param name="queryFilter">QueryFilter to perform selection on table</param>
/// <returns>returns a PluginCursorTemplate</returns>
public override PluginCursorTemplate Search(QueryFilter queryFilter) =>
this.SearchInternal(queryFilter);
/// <summary>
/// Search data in this table (feature class) using a given SpatialQueryFilter
/// </summary>
/// <param name="spatialQueryFilter">SpatialQueryFilter to perform selection on table</param>
/// <returns>returns a PluginCursorTemplate</returns>
public override PluginCursorTemplate Search(SpatialQueryFilter spatialQueryFilter) =>
this.SearchInternal(spatialQueryFilter);
/// <summary>
/// Get the extent for the dataset (if it has one)
/// </summary>
/// <remarks>Ideally, your plugin table should return an extent even if it is
/// empty</remarks>
/// <returns><see cref="Envelope"/></returns>
public override Envelope GetExtent()
{
if (_gisExtent == null)
{
var builder = new EnvelopeBuilder(EnvelopeBuilder.CreateEnvelope(
_tableInfo.ExtentLeft,
_tableInfo.ExtentBottom,
_tableInfo.ExtentRight,
_tableInfo.ExtentTop,
_spatialReference));
//Assume 0 for Z
{
builder.ZMin = 0;
builder.ZMax = 0;
}
builder.HasZ = false;
builder.HasM = false;
return builder.ToGeometry();
}
return _gisExtent;
}
/// <summary>
/// Returns geometry type supported by this feature class
/// </summary>
/// <returns>GeometryType of the feature class</returns>
public override GeometryType GetShapeType()
{
var geomType = GeometryType.Unknown;
switch (_tableInfo.GeometryType)
{
case 1:
geomType = GeometryType.Point;
break;
case 3:
geomType = GeometryType.Polyline;
break;
case 4:
geomType = GeometryType.Polygon;
break;
}
return geomType;
}
#region Internal Processing
private PluginCursorTemplate SearchInternal(QueryFilter qf)
{
var oids = this.ExecuteQuery(qf);
var columns = this.GetQuerySubFields(qf);
return new ProSqlPluginCursorTemplate(this,
oids,
columns,
qf.OutputSpatialReference);
}
/// <summary>
/// Implement querying with a query filter
/// </summary>
/// <param name="qf"></param>
/// <returns></returns>
private List<int> ExecuteQuery(QueryFilter qf)
{
List<int> result = new List<int>();
SpatialQueryFilter sqf = null;
if (qf is SpatialQueryFilter)
{
sqf = qf as SpatialQueryFilter;
}
var whereClause = string.Empty;
if (!string.IsNullOrEmpty(qf.WhereClause))
{
whereClause = qf.WhereClause;
}
else
{
if (qf.ObjectIDs.Count() > 0)
{
whereClause = $@"{_tableInfo.FieldInfo.ObjectIdField} in ({string.Join (",", qf.ObjectIDs)})";
}
}
var subFields = string.IsNullOrEmpty (qf.SubFields) ? "*" : qf.SubFields;
_dataTable.Clear();
int recCount = _sqlDb.QueryTable(_tableName, subFields, whereClause, qf.PostfixClause, _dataTable);
_dataTable.PrimaryKey = new DataColumn[] { _dataTable.Columns[_tableInfo.FieldInfo.ObjectIdField] };
if (recCount == 0) return result;
if (sqf == null)
{
result = _dataTable.AsEnumerable().Select(row => (int)row[_tableInfo.FieldInfo.ObjectIdField]).ToList();
}
else
{
result = _dataTable.AsEnumerable().Where(Row => CheckSpatialQuery (sqf, Row[_tableInfo.GeometryFieldName])).Select(row => (int)row[_tableInfo.FieldInfo.ObjectIdField]).ToList();
}
return result;
}
private bool CheckSpatialQuery (SpatialQueryFilter sqf, object geomFromDb)
{
var geom = GetGeometryFromBuffer ((byte [])geomFromDb, _spatialReference);
if (geom == null)
{
return false;
}
return HasRelationship(GeometryEngine.Instance,
sqf.FilterGeometry, geom, sqf.SpatialRelationship);
}
private static Geometry GetGeometryFromBuffer (byte[] geomBuffer, SpatialReference sr)
{
var geomType = GetGeometryType(geomBuffer);
switch (geomType)
{
case GeometryType.Point:
{
int offset = 4;
double x = DoubleWithNaN(BitConverter.ToDouble(geomBuffer, offset));
offset += 8;
double y = DoubleWithNaN(BitConverter.ToDouble(geomBuffer, offset));
var mp = MapPointBuilder.FromEsriShape(geomBuffer, sr);
//System.Diagnostics.Debug.WriteLine($@"x: {x} = {mp.X} y: {y} = {mp.Y}");
return mp;
}
case GeometryType.Polyline:
{
var line = PolylineBuilder.FromEsriShape(geomBuffer, sr);
return line;
}
case GeometryType.Polygon:
{
var poly = PolygonBuilder.FromEsriShape(geomBuffer, sr);
return poly;
}
}
return null;
}
private static double DoubleWithNaN(double d)
{
return (d < -1.0e38) ? double.NaN : d;
}
private static GeometryType GetGeometryType(byte[] buffer, int offset = 0)
{
// read the shape type
int typeInt = BitConverter.ToInt32(buffer, offset);
int type = (int)(typeInt & (int)0x000000FF);
switch (type)
{
case 0:
return GeometryType.Unknown;
case 1:
// A point consists of a pair of double-precision coordinates.
case 21:
// A PointM consists of a pair of double-precision coordinates in the order X, Y, plus a measure M.
case 11:
// A PointZM consists of a triplet of double-precision coordinates plus a measure.
case 9:
// A PointZ consists of a triplet of double-precision coordinates in the order X, Y, Z where Z usually represents height.
return GeometryType.Point;
case 3:
// PolyLine is an ordered set of vertices that consists of one or more parts. A part is a
// connected sequence of two or more points. Parts may or may not be connected to one
// another. Parts may or may not intersect one another.
case 23:
// A shapefile PolyLineM consists of one or more parts. A part is a connected sequence of
// two or more points. Parts may or may not be connected to one another. Parts may or may
// not intersect one another.
case 13:
// A shapefile PolyLineZM consists of one or more parts. A part is a connected sequence of
// two or more points. Parts may or may not be connected to one another. Parts may or may
// not intersect one another.
case 10:
// A PolyLineZ consists of one or more parts. A part is a connected sequence of two or
// more points. Parts may or may not be connected to one another. Parts may or may not
// intersect one another.
return GeometryType.Polyline;
case 5:
// A polygon consists of one or more rings. A ring is a connected sequence of four or more
// points that form a closed, non-self-intersecting loop. A polygon may contain multiple
// outer rings. The order of vertices or orientation for a ring indicates which side of the ring
// is the interior of the polygon. The neighborhood to the right of an observer walking along
// the ring in vertex order is the neighborhood inside the polygon. Vertices of rings defining
// holes in polygons are in a counterclockwise direction. Vertices for a single, ringed
// polygon are, therefore, always in clockwise order. The rings of a polygon are referred to
// as its parts.
case 25:
// A PolygonM consists of a number of rings. A ring is a closed, non-self-intersecting loop.
case 15:
// A PolygonZM consists of a number of rings. A ring is a closed, non-self-intersecting loop.
case 19:
// A PolygonZ consists of a number of rings. A ring is a closed, non-self-intersecting loop.
// A PolygonZ may contain multiple outer rings. The rings of a PolygonZ are referred to as
// its parts.
return GeometryType.Polygon;
case 50:
// GeneralPolyline
return GeometryType.Polyline;
case 51:
// GeneralPolygon
return GeometryType.Polygon;
case 52:
// GeneralPoint
return GeometryType.Point;
// not supported: 31: MultiPatchM
// not supported: 32: MultiPatch
// not supported: 53: GeneralMultiPoint
// not supported: 54: GeneralMultiPatch
default:
throw new Exception($@"Unknown shape type {type}");
}
}
internal static bool HasRelationship(IGeometryEngine engine,
Geometry geom1,
Geometry geom2,
SpatialRelationship relationship)
{
switch (relationship)
{
case SpatialRelationship.Intersects:
return engine.Intersects(geom1, geom2);
case SpatialRelationship.IndexIntersects:
return engine.Intersects(geom1, geom2);
case SpatialRelationship.EnvelopeIntersects:
return engine.Intersects(geom1.Extent, geom2.Extent);
case SpatialRelationship.Contains:
return engine.Contains(geom1, geom2);
case SpatialRelationship.Crosses:
return engine.Crosses(geom1, geom2);
case SpatialRelationship.Overlaps:
return engine.Overlaps(geom1, geom2);
case SpatialRelationship.Touches:
return engine.Touches(geom1, geom2);
case SpatialRelationship.Within:
return engine.Within(geom1, geom2);
}
return false;//unknown relationship
}
private List<string> GetQuerySubFields(QueryFilter qf)
{
//Honor Subfields in Query Filter
string columns = qf.SubFields ?? "*";
List<string> subFields;
if (columns == "*")
{
subFields = this.GetFields().Select(col => col.Name.ToUpper()).ToList();
}
else
{
var names = columns.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
subFields = names.Select(n => n.ToUpper()).ToList();
}
return subFields;
}
#endregion Internal Processing
#region IPluginRowProvider
/// <summary>
/// Find a given row (using Object ID) and retrieve attributes using columnFilter and output spatial reference
/// </summary>
/// <param name="oid">Search for this record using this Object ID</param>
/// <param name="columnFilter">List of Column Names to be returned</param>
/// <param name="srout">project spatial data using this output spatial reference</param>
/// <returns>PlugInRow</returns>
public PluginRow FindRow(int oid, IEnumerable<string> columnFilter, SpatialReference srout)
{
Geometry shape = null;
List<object> values = new List<object>();
// oid happens to be the primary key as well
var row = _dataTable.Rows.Find (oid);
//The order of the columns in the returned rows ~must~ match
//GetFields. If a column is filtered out, an empty placeholder must
//still be provided even though the actual value is skipped
var columnNames = this.GetFields().Select(col => col.Name.ToUpper()).ToList();
foreach (var colName in columnNames)
{
if (columnFilter.Contains(colName))
{
//special handling for shape
if (colName.Equals (_tableInfo.GeometryFieldName, StringComparison.CurrentCultureIgnoreCase))
{
var geomBuffer = (byte [])row[_tableInfo.GeometryFieldName];
shape = GetGeometryFromBuffer(geomBuffer, _spatialReference);
if (srout != null)
{
if (!srout.Equals(_spatialReference))
shape = GeometryEngine.Instance.Project(shape, srout);
}
values.Add(shape);
}
else
{
values.Add(row[colName]);
}
}
else
{
values.Add(DBNull.Value);//place holder
}
}
return new PluginRow() { Values = values };
}
#endregion IPluginRowProvider
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
/// <summary>
/// Clean up resources
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (_dataTable == null)
return;
if (disposing)
{
_dataTable?.Clear();
_gisExtent = null;
}
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~ProPluginTableTemplate()
// {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
/// <summary>
/// This code added to correctly implement the disposable pattern.
/// </summary>
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using Markdig.Helpers;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
namespace Markdig.Renderers
{
/// <summary>
/// A text based <see cref="IMarkdownRenderer"/>.
/// </summary>
/// <seealso cref="RendererBase" />
public abstract class TextRendererBase : RendererBase
{
private TextWriter writer;
/// <summary>
/// Initializes a new instance of the <see cref="TextRendererBase"/> class.
/// </summary>
/// <param name="writer">The writer.</param>
/// <exception cref="ArgumentNullException"></exception>
protected TextRendererBase(TextWriter writer)
{
if (writer == null) ThrowHelper.ArgumentNullException_writer();
this.Writer = writer;
// By default we output a newline with '\n' only even on Windows platforms
Writer.NewLine = "\n";
}
/// <summary>
/// Gets or sets the writer.
/// </summary>
/// <exception cref="ArgumentNullException">if the value is null</exception>
public TextWriter Writer
{
get { return writer; }
set
{
if (value == null)
{
ThrowHelper.ArgumentNullException(nameof(value));
}
writer = value;
}
}
/// <summary>
/// Renders the specified markdown object (returns the <see cref="Writer"/> as a render object).
/// </summary>
/// <param name="markdownObject">The markdown object.</param>
/// <returns></returns>
public override object Render(MarkdownObject markdownObject)
{
Write(markdownObject);
return Writer;
}
}
/// <summary>
/// Typed <see cref="TextRendererBase"/>.
/// </summary>
/// <typeparam name="T">Type of the renderer</typeparam>
/// <seealso cref="RendererBase" />
public abstract class TextRendererBase<T> : TextRendererBase where T : TextRendererBase<T>
{
private bool previousWasLine;
#if !NETCORE
private char[] buffer;
#endif
private readonly List<string> indents;
/// <summary>
/// Initializes a new instance of the <see cref="TextRendererBase{T}"/> class.
/// </summary>
/// <param name="writer">The writer.</param>
protected TextRendererBase(TextWriter writer) : base(writer)
{
#if !NETCORE
buffer = new char[1024];
#endif
// We assume that we are starting as if we had previously a newline
previousWasLine = true;
indents = new List<string>();
}
internal void Reset()
{
if (Writer is StringWriter stringWriter)
{
stringWriter.GetStringBuilder().Length = 0;
}
else
{
ThrowHelper.InvalidOperationException("Cannot reset this TextWriter instance");
}
previousWasLine = true;
indents.Clear();
}
/// <summary>
/// Ensures a newline.
/// </summary>
/// <returns>This instance</returns>
public T EnsureLine()
{
if (!previousWasLine)
{
WriteLine();
}
return (T)this;
}
public void PushIndent(string indent)
{
if (indent == null) ThrowHelper.ArgumentNullException(nameof(indent));
indents.Add(indent);
}
public void PopIndent()
{
// TODO: Check
indents.RemoveAt(indents.Count - 1);
}
private void WriteIndent()
{
if (previousWasLine)
{
previousWasLine = false;
for (int i = 0; i < indents.Count; i++)
{
Writer.Write(indents[i]);
}
}
}
/// <summary>
/// Writes the specified content.
/// </summary>
/// <param name="content">The content.</param>
/// <returns>This instance</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Write(string content)
{
WriteIndent();
previousWasLine = false;
Writer.Write(content);
return (T) this;
}
/// <summary>
/// Writes the specified slice.
/// </summary>
/// <param name="slice">The slice.</param>
/// <returns>This instance</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Write(ref StringSlice slice)
{
if (slice.Start > slice.End)
{
return (T) this;
}
return Write(slice.Text, slice.Start, slice.Length);
}
/// <summary>
/// Writes the specified slice.
/// </summary>
/// <param name="slice">The slice.</param>
/// <returns>This instance</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Write(StringSlice slice)
{
return Write(ref slice);
}
/// <summary>
/// Writes the specified character.
/// </summary>
/// <param name="content">The content.</param>
/// <returns>This instance</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Write(char content)
{
WriteIndent();
previousWasLine = content == '\n';
Writer.Write(content);
return (T) this;
}
/// <summary>
/// Writes the specified content.
/// </summary>
/// <param name="content">The content.</param>
/// <param name="offset">The offset.</param>
/// <param name="length">The length.</param>
/// <returns>This instance</returns>
public T Write(string content, int offset, int length)
{
if (content == null)
{
return (T) this;
}
WriteIndent();
previousWasLine = false;
#if NETCORE
Writer.Write(content.AsSpan(offset, length));
#else
if (offset == 0 && content.Length == length)
{
Writer.Write(content);
}
else
{
if (length > buffer.Length)
{
buffer = content.ToCharArray();
Writer.Write(buffer, offset, length);
}
else
{
content.CopyTo(offset, buffer, 0, length);
Writer.Write(buffer, 0, length);
}
}
#endif
return (T) this;
}
/// <summary>
/// Writes a newline.
/// </summary>
/// <returns>This instance</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T WriteLine()
{
WriteIndent();
Writer.WriteLine();
previousWasLine = true;
return (T) this;
}
/// <summary>
/// Writes a content followed by a newline.
/// </summary>
/// <param name="content">The content.</param>
/// <returns>This instance</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T WriteLine(string content)
{
WriteIndent();
previousWasLine = true;
Writer.WriteLine(content);
return (T) this;
}
/// <summary>
/// Writes the inlines of a leaf inline.
/// </summary>
/// <param name="leafBlock">The leaf block.</param>
/// <returns>This instance</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T WriteLeafInline(LeafBlock leafBlock)
{
if (leafBlock == null) ThrowHelper.ArgumentNullException_leafBlock();
var inline = (Inline) leafBlock.Inline;
if (inline != null)
{
while (inline != null)
{
Write(inline);
inline = inline.NextSibling;
}
}
return (T) this;
}
}
}
| |
using System;
using System.Text;
namespace OpenSteerDotNet
{
public class LocalSpace
{
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2003, Sony Computer Entertainment America
// Original author: Craig Reynolds <[email protected]>
//
// 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.
//
//
// ----------------------------------------------------------------------------
//
//
// LocalSpace: a local coordinate system for 3d space
//
// Provide functionality such as transforming from local space to global
// space and vice versa. Also regenerates a valid space from a perturbed
// "forward vector" which is the basis of abnstract vehicle turning.
//
// These are comparable to a 4x4 homogeneous transformation matrix where the
// 3x3 (R) portion is constrained to be a pure rotation (no shear or scale).
// The rows of the 3x3 R matrix are the basis vectors of the space. They are
// all constrained to be mutually perpendicular and of unit length. The top
// ("x") row is called "side", the middle ("y") row is called "up" and the
// bottom ("z") row is called forward. The translation vector is called
// "position". Finally the "homogeneous column" is always [0 0 0 1].
//
// [ R R R 0 ] [ Sx Sy Sz 0 ]
// [ R R R 0 ] [ Ux Uy Uz 0 ]
// [ R R R 0 ] -> [ Fx Fy Fz 0 ]
// [ ] [ ]
// [ T T T 1 ] [ Tx Ty Tz 1 ]
//
// This file defines three classes:
// AbstractLocalSpace: pure virtual interface
// LocalSpaceMixin: mixin to layer LocalSpace functionality on any base
// LocalSpace: a concrete object (can be instantiated)
//
// 10-04-04 bk: put everything into the OpenSteer namespace
// 06-05-02 cwr: created
//
//
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
Vector3 _side; // side-pointing unit basis vector
Vector3 _up; // upward-pointing unit basis vector
Vector3 _forward; // forward-pointing unit basis vector
Vector3 _position; // origin of local space
public Vector3 side () {return _side;}
public Vector3 up() { return _up; }
public Vector3 forward() { return _forward; }
public Vector3 Position {
get
{
return _position;
}
}
public Vector3 setSide(Vector3 s) { return _side = s; }
public Vector3 setUp(Vector3 u) { return _up = u; }
public Vector3 setForward(Vector3 f) { return _forward = f; }
public Vector3 setPosition(Vector3 p) { return _position = p; }
public Vector3 setSide(float x, float y, float z) { return _side = new Vector3(x, y, z); }
public Vector3 setUp(float x, float y, float z) { return _up = new Vector3(x, y, z); }
public Vector3 setForward(float x, float y, float z) { return _forward = new Vector3(x, y, z); }
public Vector3 setPosition(float x, float y, float z) { return _position = new Vector3(x, y, z); }
// use right-(or left-)handed coordinate space
public bool rightHanded() { return true; }
// ------------------------------------------------------------------------
// reset transform: set local space to its identity state, equivalent to a
// 4x4 homogeneous transform like this:
//
// [ X 0 0 0 ]
// [ 0 1 0 0 ]
// [ 0 0 1 0 ]
// [ 0 0 0 1 ]
//
// where X is 1 for a left-handed system and -1 for a right-handed system.
public void resetLocalSpace()
{
_forward = new Vector3(0, 0, 1);
_side = localRotateForwardToSide (_forward);
_up = new Vector3(0, 1, 0);
_position = new Vector3(0, 0, 0);
}
// ------------------------------------------------------------------------
// transform a direction in global space to its equivalent in local space
public Vector3 localizeDirection(Vector3 globalDirection)
{
// dot offset with local basis vectors to obtain local coordiantes
return new Vector3 (globalDirection.DotProduct (_side),
globalDirection.DotProduct (_up),
globalDirection.DotProduct (_forward));
}
// ------------------------------------------------------------------------
// transform a point in global space to its equivalent in local space
public Vector3 localizePosition(Vector3 globalPosition)
{
// global offset from local origin
Vector3 globalOffset = globalPosition - _position;
// dot offset with local basis vectors to obtain local coordiantes
return localizeDirection (globalOffset);
}
// ------------------------------------------------------------------------
// transform a point in local space to its equivalent in global space
public Vector3 globalizePosition(Vector3 localPosition)
{
return _position + globalizeDirection (localPosition);
}
// ------------------------------------------------------------------------
// transform a direction in local space to its equivalent in global space
public Vector3 globalizeDirection(Vector3 localDirection)
{
return ((_side * localDirection.x) +
(_up * localDirection.y) +
(_forward * localDirection.z));
}
// ------------------------------------------------------------------------
// set "side" basis vector to normalized cross product of forward and up
public void setUnitSideFromForwardAndUp()
{
// derive new unit side basis vector from forward and up
if (rightHanded())
//_side.cross (_forward, _up);
_side = _forward.CrossProduct(_up);
else
//_side.cross(_up, _forward);
_side = _up.CrossProduct(_forward);
_side.Normalise ();
}
// ------------------------------------------------------------------------
// regenerate the orthonormal basis vectors given a new forward
// (which is expected to have unit length)
public void regenerateOrthonormalBasisUF(Vector3 newUnitForward)
{
_forward = newUnitForward;
// derive new side basis vector from NEW forward and OLD up
setUnitSideFromForwardAndUp ();
// derive new Up basis vector from new Side and new Forward
// (should have unit length since Side and Forward are
// perpendicular and unit length)
if (rightHanded())
//_up.cross (_side, _forward);
_up=_side.CrossProduct( _forward);
else
//_up.cross (_forward, _side);
_up = _forward.CrossProduct(_side);
}
// for when the new forward is NOT know to have unit length
public void regenerateOrthonormalBasis(Vector3 newForward)
{
newForward.Normalise();
regenerateOrthonormalBasisUF (newForward);
}
// for supplying both a new forward and and new up
public void regenerateOrthonormalBasis (Vector3 newForward,
Vector3 newUp)
{
_up = newUp;
newForward.Normalise();
regenerateOrthonormalBasis(newForward);
}
// ------------------------------------------------------------------------
// rotate, in the canonical direction, a vector pointing in the
// "forward" (+Z) direction to the "side" (+/-X) direction
public Vector3 localRotateForwardToSide (Vector3 v)
{
return new Vector3 (rightHanded () ? -v.z : +v.z,
v.y,
v.x);
}
// not currently used, just added for completeness
public Vector3 globalRotateForwardToSide(Vector3 globalForward)
{
Vector3 localForward = localizeDirection (globalForward);
Vector3 localSide = localRotateForwardToSide (localForward);
return globalizeDirection (localSide);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
namespace System.Security.Claims
{
/// <summary>
/// Concrete IPrincipal supporting multiple claims-based identities
/// </summary>
public class ClaimsPrincipal : IPrincipal
{
private enum SerializationMask
{
None = 0,
HasIdentities = 1,
UserData = 2
}
private List<ClaimsIdentity> _identities = new List<ClaimsIdentity>();
private byte[] _userSerializationData;
private static Func<IEnumerable<ClaimsIdentity>, ClaimsIdentity> s_identitySelector = SelectPrimaryIdentity;
private static Func<ClaimsPrincipal> s_principalSelector = ClaimsPrincipalSelector;
/// <summary>
/// This method iterates through the collection of ClaimsIdentities and chooses an identity as the primary.
/// </summary>
static ClaimsIdentity SelectPrimaryIdentity(IEnumerable<ClaimsIdentity> identities)
{
if (identities == null)
{
throw new ArgumentNullException("identities");
}
foreach (ClaimsIdentity identity in identities)
{
if (identity != null)
{
return identity;
}
}
return null;
}
public static Func<IEnumerable<ClaimsIdentity>, ClaimsIdentity> PrimaryIdentitySelector
{
get
{
return s_identitySelector;
}
set
{
s_identitySelector = value;
}
}
public static Func<ClaimsPrincipal> ClaimsPrincipalSelector
{
get
{
return s_principalSelector;
}
set
{
s_principalSelector = value;
}
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsPrincipal"/>.
/// </summary>
public ClaimsPrincipal()
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsPrincipal"/>.
/// </summary>
/// <param name="identities"> <see cref="IEnumerable{ClaimsIdentity}"/> the subjects in the principal.</param>
/// <exception cref="ArgumentNullException">if 'identities' is null.</exception>
public ClaimsPrincipal(IEnumerable<ClaimsIdentity> identities)
{
if (identities == null)
{
throw new ArgumentNullException("identities");
}
Contract.EndContractBlock();
_identities.AddRange(identities);
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsPrincipal"/>
/// </summary>
/// <param name="identity"> <see cref="IIdentity"/> representing the subject in the principal. </param>
/// <exception cref="ArgumentNullException">if 'identity' is null.</exception>
public ClaimsPrincipal(IIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
Contract.EndContractBlock();
ClaimsIdentity ci = identity as ClaimsIdentity;
if (ci != null)
{
_identities.Add(ci);
}
else
{
_identities.Add(new ClaimsIdentity(identity));
}
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsPrincipal"/>
/// </summary>
/// <param name="principal"><see cref="IPrincipal"/> used to form this instance.</param>
/// <exception cref="ArgumentNullException">if 'principal' is null.</exception>
public ClaimsPrincipal(IPrincipal principal)
{
if (null == principal)
{
throw new ArgumentNullException("principal");
}
Contract.EndContractBlock();
//
// If IPrincipal is a ClaimsPrincipal add all of the identities
// If IPrincipal is not a ClaimsPrincipal, create a new identity from IPrincipal.Identity
//
ClaimsPrincipal cp = principal as ClaimsPrincipal;
if (null == cp)
{
_identities.Add(new ClaimsIdentity(principal.Identity));
}
else
{
if (null != cp.Identities)
{
_identities.AddRange(cp.Identities);
}
}
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsPrincipal"/> using a <see cref="BinaryReader"/>.
/// Normally the <see cref="BinaryReader"/> is constructed using the bytes from <see cref="WriteTo(BinaryWriter)"/> and initialized in the same way as the <see cref="BinaryWriter"/>.
/// </summary>
/// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsPrincipal"/>.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
public ClaimsPrincipal(BinaryReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
Initialize(reader);
}
/// <summary>
/// Adds a single <see cref="ClaimsIdentity"/> to an internal list.
/// </summary>
/// <param name="identity">the <see cref="ClaimsIdentity"/>add.</param>
/// <exception cref="ArgumentNullException">if 'identity' is null.</exception>
public virtual void AddIdentity(ClaimsIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
Contract.EndContractBlock();
_identities.Add(identity);
}
/// <summary>
/// Adds a <see cref="IEnumerable{ClaimsIdentity}"/> to the internal list.
/// </summary>
/// <param name="identities">Enumeration of ClaimsIdentities to add.</param>
/// <exception cref="ArgumentNullException">if 'identities' is null.</exception>
public virtual void AddIdentities(IEnumerable<ClaimsIdentity> identities)
{
if (identities == null)
{
throw new ArgumentNullException("identities");
}
Contract.EndContractBlock();
_identities.AddRange(identities);
}
/// <summary>
/// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="ClaimsPrincipal"/> by enumerating all <see cref="ClaimsIdentities"/>.
/// </summary>
public virtual IEnumerable<Claim> Claims
{
get
{
foreach (ClaimsIdentity identity in Identities)
{
foreach (Claim claim in identity.Claims)
{
yield return claim;
}
}
}
}
/// <summary>
/// Contains any additional data provided by derived type, typically set when calling <see cref="WriteTo(BinaryWriter, byte[])"/>.</param>
/// </summary>
protected virtual byte[] CustomSerializationData
{
get
{
return _userSerializationData;
}
}
/// <summary>
/// Creates a new instance of <see cref="ClaimsPrincipal"/> with values copied from this object.
/// </summary>
public virtual ClaimsPrincipal Clone()
{
return new ClaimsPrincipal(this);
}
/// <summary>
/// Provides and extensibility point for derived types to create a custom <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="reader">the <see cref="BinaryReader"/>that points at the claim.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
/// <returns>a new <see cref="ClaimsIdentity"/>.</returns>
protected virtual ClaimsIdentity CreateClaimsIdentity(BinaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
return new ClaimsIdentity(reader);
}
/// <summary>
/// Returns the Current Principal by calling a delegate. Users may specify the delegate.
/// </summary>
public static ClaimsPrincipal Current
{
// just accesses the current selected principal selector, doesn't set
get
{
if (s_principalSelector != null)
{
return s_principalSelector();
}
return null;
}
}
/// <summary>
/// Retrieves a <see cref="IEnumerable{Claim}"/> where each claim is matched by <param name="match"/>.
/// </summary>
/// <param name="match">The predicate that performs the matching logic.</param>
/// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.FindAll"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual IEnumerable<Claim> FindAll(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException("match");
}
Contract.EndContractBlock();
foreach (ClaimsIdentity identity in Identities)
{
if (identity != null)
{
foreach (Claim claim in identity.FindAll(match))
{
yield return claim;
}
}
}
}
/// <summary>
/// Retrieves a <see cref="IEnumerable{Claim}"/> where each Claim.Type equals <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.FindAll"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
public virtual IEnumerable<Claim> FindAll(string type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
foreach (ClaimsIdentity identity in Identities)
{
if (identity != null)
{
foreach (Claim claim in identity.FindAll(type))
{
yield return claim;
}
}
}
}
/// <summary>
/// Retrieves the first <see cref="Claim"/> that is matched by <param name="match"/>.
/// </summary>
/// <param name="match">The predicate that performs the matching logic.</param>
/// <returns>A <see cref="Claim"/>, null if nothing matches.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.FindFirst"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual Claim FindFirst(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException("match");
}
Contract.EndContractBlock();
Claim claim = null;
foreach (ClaimsIdentity identity in Identities)
{
if (identity != null)
{
claim = identity.FindFirst(match);
if (claim != null)
{
return claim;
}
}
}
return claim;
}
/// <summary>
/// Retrieves the first <see cref="Claim"/> where the Claim.Type equals <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <returns>A <see cref="Claim"/>, null if nothing matches.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.FindFirst"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
public virtual Claim FindFirst(string type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
Claim claim = null;
for (int i = 0; i < _identities.Count; i++)
{
if (_identities[i] != null)
{
claim = _identities[i].FindFirst(type);
if (claim != null)
{
return claim;
}
}
}
return claim;
}
/// <summary>
/// Determines if a claim is contained within all the ClaimsIdentities in this ClaimPrincipal.
/// </summary>
/// <param name="match">The predicate that performs the matching logic.</param>
/// <returns>true if a claim is found, false otherwise.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.HasClaim"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual bool HasClaim(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException("match");
}
Contract.EndContractBlock();
for (int i = 0; i < _identities.Count; i++)
{
if (_identities[i] != null)
{
if (_identities[i].HasClaim(match))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Determines if a claim of claimType AND claimValue exists in any of the identities.
/// </summary>
/// <param name="type"> the type of the claim to match.</param>
/// <param name="value"> the value of the claim to match.</param>
/// <returns>true if a claim is matched, false otherwise.</returns>
/// <remarks>Each <see cref="ClaimsIdentity"/> is called. <seealso cref="ClaimsIdentity.HasClaim"/>.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
/// <exception cref="ArgumentNullException">if 'value' is null.</exception>
public virtual bool HasClaim(string type, string value)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (value == null)
{
throw new ArgumentNullException("value");
}
Contract.EndContractBlock();
for (int i = 0; i < _identities.Count; i++)
{
if (_identities[i] != null)
{
if (_identities[i].HasClaim(type, value))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Collection of <see cref="ClaimsIdentity" />
/// </summary>
public virtual IEnumerable<ClaimsIdentity> Identities
{
get
{
return _identities;
}
}
/// <summary>
/// Gets the identity of the current principal.
/// </summary>
public virtual System.Security.Principal.IIdentity Identity
{
get
{
if (s_identitySelector != null)
{
return s_identitySelector(_identities);
}
else
{
return SelectPrimaryIdentity(_identities);
}
}
}
/// <summary>
/// IsInRole answers the question: does an identity this principal possesses
/// contain a claim of type RoleClaimType where the value is '==' to the role.
/// </summary>
/// <param name="role">The role to check for.</param>
/// <returns>'True' if a claim is found. Otherwise 'False'.</returns>
/// <remarks>Each Identity has its own definition of the ClaimType that represents a role.</remarks>
public virtual bool IsInRole(string role)
{
for (int i = 0; i < _identities.Count; i++)
{
if (_identities[i] != null)
{
if (_identities[i].HasClaim(_identities[i].RoleClaimType, role))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Initializes from a <see cref="BinaryReader"/>. Normally the reader is initialized with the results from <see cref="WriteTo(BinaryWriter)"/>
/// Normally the <see cref="BinaryReader"/> is initialized in the same way as the <see cref="BinaryWriter"/> passed to <see cref="WriteTo(BinaryWriter)"/>.
/// </summary>
/// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsPrincipal"/>.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
private void Initialize(BinaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
SerializationMask mask = (SerializationMask)reader.ReadInt32();
int numPropertiesToRead = reader.ReadInt32();
int numPropertiesRead = 0;
if ((mask & SerializationMask.HasIdentities) == SerializationMask.HasIdentities)
{
numPropertiesRead++;
int numberOfIdentities = reader.ReadInt32();
for (int index = 0; index < numberOfIdentities; ++index)
{
// directly add to _identities as that is what we serialized from
_identities.Add(CreateClaimsIdentity(reader));
}
}
if ((mask & SerializationMask.UserData) == SerializationMask.UserData)
{
// TODO - brentschmaltz - maximum size ??
int cb = reader.ReadInt32();
_userSerializationData = reader.ReadBytes(cb);
numPropertiesRead++;
}
for (int i = numPropertiesRead; i < numPropertiesToRead; i++)
{
reader.ReadString();
}
}
/// <summary>
/// Serializes using a <see cref="BinaryWriter"/>
/// </summary>
/// <exception cref="ArgumentNullException">if 'writer' is null.</exception>
public virtual void WriteTo(BinaryWriter writer)
{
WriteTo(writer, null);
}
/// <summary>
/// Serializes using a <see cref="BinaryWriter"/>
/// </summary>
/// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param>
/// <param name="userData">additional data provided by derived type.</param>
/// <exception cref="ArgumentNullException">if 'writer' is null.</exception>
protected virtual void WriteTo(BinaryWriter writer, byte[] userData)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
int numberOfPropertiesWritten = 0;
var mask = SerializationMask.None;
if (_identities.Count > 0)
{
mask |= SerializationMask.HasIdentities;
numberOfPropertiesWritten++;
}
if (userData != null && userData.Length > 0)
{
numberOfPropertiesWritten++;
mask |= SerializationMask.UserData;
}
writer.Write((Int32)mask);
writer.Write((Int32)numberOfPropertiesWritten);
if ((mask & SerializationMask.HasIdentities) == SerializationMask.HasIdentities)
{
writer.Write(_identities.Count);
foreach (var identity in _identities)
{
identity.WriteTo(writer);
}
}
if ((mask & SerializationMask.UserData) == SerializationMask.UserData)
{
writer.Write((Int32)userData.Length);
writer.Write(userData);
}
writer.Flush();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using TextMatch;
using TextMatch.Models;
namespace TextMatch.Controllers
{
[Authorize]
public class AccountController : Controller
{
public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
UserManager = userManager;
SignInManager = signInManager;
}
public UserManager<ApplicationUser> UserManager { get; private set; }
public SignInManager<ApplicationUser> SignInManager { get; private set; }
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewBag.ReturnUrl = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
if (result.Succeeded)
{
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/Register
[AllowAnonymous]
[HttpGet]
public IActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await UserManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Context.Request.Scheme);
//await MessageServices.SendEmailAsync(model.Email, "Confirm your account",
// "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
await SignInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LogOff()
{
SignInManager.SignOut();
return RedirectToAction("Index", "Home");
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = SignInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
}
//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null)
{
var info = await SignInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login.
var result = await SignInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = info.LoginProvider;
var email = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
if (User.IsSignedIn())
{
return RedirectToAction("Index", "Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await SignInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await UserManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await UserManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
// var code = await UserManager.GeneratePasswordResetTokenAsync(user);
// var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Context.Request.Scheme);
// await MessageServices.SendEmailAsync(model.Email, "Reset Password",
// "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");
// return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
var result = await UserManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
//
// GET: /Account/SendCode
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await SignInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var user = await SignInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
// Generate the token and send it
var code = await UserManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return View("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await MessageServices.SendEmailAsync(await UserManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await MessageServices.SendSmsAsync(await UserManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/VerifyCode
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await SignInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
ModelState.AddModelError("", "Invalid code.");
return View(model);
}
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await UserManager.FindByIdAsync(Context.User.GetUserId());
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using bv.common.Configuration;
using bv.common.Core;
using bv.winclient.Core;
using bv.winclient.Localization;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid;
using DevExpress.XtraNavBar;
using DevExpress.XtraPivotGrid;
using DevExpress.XtraTab;
using DevExpress.XtraTreeList;
namespace bv.winclient.Layout
{
public class MandatoryStyleController : StyleController
{
}
public static class StyleControllerExtension
{
public static bool IsMandatory(this IStyleController style)
{
return style is MandatoryStyleController;
}
}
public class LayoutCorrector
{
private static readonly object m_ButtonStyleControllerSyncLock = new object();
private static readonly object m_MandatoryStyleControllerSyncLock = new object();
private static readonly object m_ReadOnlyStyleControllerSyncLock = new object();
private static readonly object m_EditorStyleControllerSyncLock = new object();
private static readonly object m_DropDownStyleControllerSyncLock = new object();
private static StyleController m_ButtonStyleController;
private static MandatoryStyleController m_MandatoryStyleController;
private static StyleController m_ReadOnlyStyleController;
private static StyleController m_EditorStyleController;
private static StyleController m_DropDownStyleController;
public static StyleController ButtonStyleController
{
get
{
lock (m_ButtonStyleControllerSyncLock)
{
if (m_ButtonStyleController == null)
{
m_ButtonStyleController = new StyleController();
m_ButtonStyleController.InitStyleController();
}
return m_ButtonStyleController;
}
}
}
public static StyleController MandatoryStyleController
{
get
{
lock (m_MandatoryStyleControllerSyncLock)
{
if (m_MandatoryStyleController == null)
{
m_MandatoryStyleController = new MandatoryStyleController();
m_MandatoryStyleController.InitStyleController();
m_MandatoryStyleController.Appearance.BackColor = Color.LemonChiffon;
m_MandatoryStyleController.Appearance.BorderColor = Color.Red;
//m_MandatoryStyleController.Appearance.Font = new Font("Arial", 8.25F, FontStyle.Regular,
// GraphicsUnit.Point, ((204)));
m_MandatoryStyleController.Appearance.Options.UseBackColor = true;
m_MandatoryStyleController.Appearance.Options.UseBorderColor = true;
m_MandatoryStyleController.Appearance.Options.UseFont = true;
m_MandatoryStyleController.AppearanceDisabled.BorderColor = Color.Red;
m_MandatoryStyleController.AppearanceDisabled.Options.UseBorderColor = true;
m_MandatoryStyleController.AppearanceDropDown.BorderColor = Color.Red;
m_MandatoryStyleController.AppearanceDropDown.Options.UseBorderColor = true;
m_MandatoryStyleController.AppearanceDropDownHeader.BorderColor = Color.Red;
m_MandatoryStyleController.AppearanceDropDownHeader.Options.UseBorderColor = true;
m_MandatoryStyleController.BorderStyle = BorderStyles.Simple;
m_MandatoryStyleController.InitStyleController();
}
return m_MandatoryStyleController;
}
}
}
public static StyleController ReadOnlyStyleController
{
get
{
lock (m_ReadOnlyStyleControllerSyncLock)
{
if (m_ReadOnlyStyleController == null)
{
m_ReadOnlyStyleController = new StyleController();
m_ReadOnlyStyleController.InitStyleController();
}
return m_ReadOnlyStyleController;
}
}
}
public static StyleController EditorStyleController
{
get
{
lock (m_EditorStyleControllerSyncLock)
{
if (m_EditorStyleController == null)
{
m_EditorStyleController = new StyleController();
m_EditorStyleController.InitStyleController();
}
return m_EditorStyleController;
}
}
}
public static StyleController DropDownStyleController
{
get
{
lock (m_DropDownStyleControllerSyncLock)
{
if (m_DropDownStyleController == null)
{
m_DropDownStyleController = new StyleController();
m_DropDownStyleController.InitStyleController();
m_DropDownStyleController.Appearance.BackColor = Color.White;
//m_DropDownStyleController.Appearance.Font = new Font("Arial", 8.25F, FontStyle.Regular,
// GraphicsUnit.Point, ((204)));
m_DropDownStyleController.Appearance.Options.UseBackColor = true;
m_DropDownStyleController.Appearance.Options.UseFont = true;
m_DropDownStyleController.InitStyleController();
}
return m_DropDownStyleController;
}
}
}
/// <summary>
/// </summary>
/// <param name="ctl"></param>
public static void ApplySystemFont(Control ctl)
{
SetControlFont(ctl);
foreach (Control c in ctl.Controls)
{
ApplySystemFont(c);
}
}
/// <summary>
/// </summary>
/// <param name="form"></param>
public static void InitFormLayout(XtraForm form)
{
form.LookAndFeel.SkinName = "Money Twins"; //BaseSettings.SkinName;
}
/// <summary>
/// </summary>
public static void Init()
{
EditorStyleController.InitStyleController();
MandatoryStyleController.InitStyleController();
ReadOnlyStyleController.InitStyleController();
DropDownStyleController.InitStyleController();
ButtonStyleController.InitStyleController();
}
public static void Reset()
{
lock (m_EditorStyleControllerSyncLock)
{
m_EditorStyleController = null;
}
lock (m_MandatoryStyleControllerSyncLock)
{
m_MandatoryStyleController = null;
}
lock (m_ReadOnlyStyleControllerSyncLock)
{
m_ReadOnlyStyleController = null;
}
lock (m_DropDownStyleControllerSyncLock)
{
m_DropDownStyleController = null;
}
lock (m_ButtonStyleControllerSyncLock)
{
m_ButtonStyleController = null;
}
}
/// <summary>
/// </summary>
/// <param name="c"></param>
/// <param name="source"></param>
public static void SetStyleController(BaseControl c, IStyleController source)
{
c.StyleController = source;
var be = c as BaseEdit;
if (be == null)
{
return;
}
SetClearButtonVisibility(c, !(source is MandatoryStyleController));
if (!be.Properties.Appearance.Font.Equals(source.Appearance.Font))
{
be.Properties.Appearance.Font = source.Appearance.Font;
}
if (!be.Properties.AppearanceDisabled.Font.Equals(source.AppearanceDisabled.Font))
{
be.Properties.AppearanceDisabled.Font = source.AppearanceDisabled.Font;
}
if (!be.Properties.AppearanceFocused.Font.Equals(source.AppearanceFocused.Font))
{
be.Properties.AppearanceFocused.Font = source.AppearanceFocused.Font;
}
if (!be.Properties.AppearanceReadOnly.Font.Equals(source.AppearanceReadOnly.Font))
{
be.Properties.AppearanceReadOnly.Font = source.AppearanceReadOnly.Font;
}
var pe = c as PopupBaseEdit;
if (pe == null)
{
return;
}
if (!pe.Properties.AppearanceDropDown.Font.Equals(source.AppearanceDropDown.Font))
{
pe.Properties.AppearanceDropDown.Font = source.AppearanceDropDown.Font;
}
var cb = c as LookUpEdit;
if (cb == null)
{
return;
}
if (!cb.Properties.AppearanceDropDownHeader.Font.Equals(source.AppearanceDropDownHeader.Font))
{
cb.Properties.AppearanceDropDownHeader.Font = source.AppearanceDropDownHeader.Font;
}
}
private static void SetClearButtonVisibility(BaseControl ctl, bool visible)
{
var btnEdit = ctl as ButtonEdit;
if (btnEdit != null)
{
foreach (EditorButton btn in btnEdit.Properties.Buttons)
{
if (!visible &&
Utils.Str(btn.Tag).ToLowerInvariant().IndexOf("{alwayseditable}", StringComparison.Ordinal) >= 0)
{
continue;
}
if (btn.Kind == ButtonPredefines.Delete)
{
btn.Visible = visible;
}
}
}
}
/// <summary>
/// </summary>
/// <param name="c"></param>
public static void SetControlFont(object c)
{
if ((c is Control) && TagEquals((Control) c, "FixFont"))
{
return;
}
//TODO: uncomment conditions below if PopUpButton or BarcodeButton will be implemented
if (c is Label || c is LabelControl || c is TabControl || /*c is PopUpButton|| c is BarcodeButton||*/
c is Button || c is XtraForm)
{
var ctl = (Control) c;
if (ctl.Font.Size != 8.25F || TagEquals(ctl, "FixFontSize"))
{
ctl.Font = new Font(WinClientContext.CurrentFont.FontFamily.Name, ctl.Font.Size, ctl.Font.Style);
}
else if (ctl.Font.Bold)
{
ctl.Font = WinClientContext.CurrentBoldFont;
}
else
{
ctl.Font = WinClientContext.CurrentFont;
}
}
else if (c is GridControl)
{
((GridControl) c).InitXtraGridAppearance(BaseSettings.ShowDateTimeFormatAsNullText);
}
else if (c is PivotGridControl)
{
((PivotGridControl) c).InitPivotGridAppearance();
}
else if (c is NavBarControl)
{
((NavBarControl) c).InitNavAppearance();
}
else if (c is TreeList)
{
((TreeList) c).InitXtraTreeAppearance(BaseSettings.ShowDateTimeFormatAsNullText);
}
else if (c is XtraTabPage)
{
((XtraTabPage) c).InitXtraTabAppearance();
}
else if (c is XtraTabControl)
{
((XtraTabControl) c).InitXtraTabControlAppearance();
}
else if (c is GroupControl)
{
((GroupControl) c).InitGroupControlAppearance();
}
else if (c is RadioGroup)
{
((RadioGroup) c).InitRadioGroupAppearance();
}
else if (c is CheckEdit)
{
((CheckEdit) c).InitCheckEditAppearance();
}
else if (c is CheckedListBoxControl)
{
((CheckedListBoxControl) c).Appearance.InitAppearance();
}
else if (c is BaseEdit && ((BaseEdit) c).StyleController == null)
{
if (c is PopupBaseEdit)
{
SetStyleController((BaseControl) c, DropDownStyleController);
}
else
{
SetStyleController((BaseControl) c, EditorStyleController);
}
}
}
/// <summary>
/// </summary>
/// <param name="ctl"></param>
/// <param name="text"></param>
/// <returns></returns>
private static bool TagEquals(Control ctl, string text)
{
if (ctl.Tag == null)
{
return false;
}
//if ((ctl.Tag) is TagHelper)
//{
// return Utils.Str(((TagHelper)ctl.Tag).StringTag) == text;
//}
return Utils.Str(ctl.Tag) == text;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
#if !(NET20 || NET35 || NET40 || PORTABLE40)
using System.Collections.Generic;
using Newtonsoft.Json.Tests.TestObjects;
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Linq;
using System.IO;
using System.Threading.Tasks;
namespace Newtonsoft.Json.Tests.Linq
{
[TestFixture]
public class JObjectAsyncTests : TestFixtureBase
{
[Test]
public async Task ReadWithSupportMultipleContentAsync()
{
string json = @"{ 'name': 'Admin' }{ 'name': 'Publisher' }";
IList<JObject> roles = new List<JObject>();
JsonTextReader reader = new JsonTextReader(new StringReader(json));
reader.SupportMultipleContent = true;
while (true)
{
JObject role = (JObject)await JToken.ReadFromAsync(reader);
roles.Add(role);
if (!await reader.ReadAsync())
{
break;
}
}
Assert.AreEqual(2, roles.Count);
Assert.AreEqual("Admin", (string)roles[0]["name"]);
Assert.AreEqual("Publisher", (string)roles[1]["name"]);
}
[Test]
public async Task JTokenReaderAsync()
{
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JRaw("[1,2,3,4,5]"),
LastName = "LastNameValue"
};
JObject o = JObject.FromObject(raw);
JsonReader reader = new JTokenReader(o);
Assert.IsTrue(await reader.ReadAsync());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(await reader.ReadAsync());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(await reader.ReadAsync());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.IsTrue(await reader.ReadAsync());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(await reader.ReadAsync());
Assert.AreEqual(JsonToken.Raw, reader.TokenType);
Assert.IsTrue(await reader.ReadAsync());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(await reader.ReadAsync());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.IsTrue(await reader.ReadAsync());
Assert.AreEqual(JsonToken.EndObject, reader.TokenType);
Assert.IsFalse(await reader.ReadAsync());
}
[Test]
public async Task LoadFromNestedObjectAsync()
{
string jsonText = @"{
""short"":
{
""error"":
{
""code"":0,
""msg"":""No action taken""
}
}
}";
JsonReader reader = new JsonTextReader(new StringReader(jsonText));
await reader.ReadAsync();
await reader.ReadAsync();
await reader.ReadAsync();
await reader.ReadAsync();
await reader.ReadAsync();
JObject o = (JObject)await JToken.ReadFromAsync(reader);
Assert.IsNotNull(o);
StringAssert.AreEqual(@"{
""code"": 0,
""msg"": ""No action taken""
}", o.ToString(Formatting.Indented));
}
[Test]
public async Task LoadFromNestedObjectIncompleteAsync()
{
await ExceptionAssert.ThrowsAsync<JsonReaderException>(async () =>
{
string jsonText = @"{
""short"":
{
""error"":
{
""code"":0";
JsonReader reader = new JsonTextReader(new StringReader(jsonText));
await reader.ReadAsync();
await reader.ReadAsync();
await reader.ReadAsync();
await reader.ReadAsync();
await reader.ReadAsync();
await JToken.ReadFromAsync(reader);
}, "Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 14.");
}
[Test]
public async Task ParseMultipleProperties_EmptySettingsAsync()
{
string json = @"{
""Name"": ""Name1"",
""Name"": ""Name2""
}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
JObject o = (JObject)await JToken.ReadFromAsync(reader, new JsonLoadSettings());
string value = (string)o["Name"];
Assert.AreEqual("Name2", value);
}
[Test]
public async Task ParseMultipleProperties_IgnoreDuplicateSettingAsync()
{
string json = @"{
""Name"": ""Name1"",
""Name"": ""Name2""
}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
JObject o = (JObject)await JToken.ReadFromAsync(reader, new JsonLoadSettings
{
DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Ignore
});
string value = (string)o["Name"];
Assert.AreEqual("Name1", value);
}
}
}
#endif
| |
using System;
using System.Threading.Tasks;
using Orleans.Runtime;
namespace Orleans
{
using System.Runtime.ExceptionServices;
/// <summary>
/// This class a convinent utiliity class to execute a certain asyncronous function with retires,
/// allowing to specify custom retry filters and policies.
/// </summary>
internal static class AsyncExecutorWithRetries
{
public static readonly int INFINITE_RETRIES = -1;
private static readonly Func<Exception, int, bool> retryAllExceptionsFilter = (Exception exc, int i) => true;
/// <summary>
/// Execute a given function a number of times, based on retry configuration parameters.
/// </summary>
public static Task ExecuteWithRetries(
Func<int, Task> action,
int maxNumErrorTries,
Func<Exception, int, bool> retryExceptionFilter,
TimeSpan maxExecutionTime,
IBackoffProvider onErrorBackOff)
{
Func<int, Task<bool>> function = async (int i) => { await action(i); return true; };
return ExecuteWithRetriesHelper<bool>(
function,
0,
0,
maxNumErrorTries,
maxExecutionTime,
DateTime.UtcNow,
null,
retryExceptionFilter,
null,
onErrorBackOff);
}
/// <summary>
/// Execute a given function a number of times, based on retry configuration parameters.
/// </summary>
public static Task<T> ExecuteWithRetries<T>(
Func<int, Task<T>> function,
int maxNumErrorTries,
Func<Exception, int, bool> retryExceptionFilter,
TimeSpan maxExecutionTime,
IBackoffProvider onErrorBackOff)
{
return ExecuteWithRetries<T>(
function,
0,
maxNumErrorTries,
null,
retryExceptionFilter,
maxExecutionTime,
null,
onErrorBackOff);
}
/// <summary>
/// Execute a given function a number of times, based on retry configuration parameters.
/// </summary>
/// <param name="function">Function to execute</param>
/// <param name="maxNumSuccessTries">Maximal number of successful execution attempts.
/// ExecuteWithRetries will try to re-execute the given function again if directed so by retryValueFilter.
/// Set to -1 for unlimited number of success retries, until retryValueFilter is satisfied.
/// Set to 0 for only one success attempt, which will cause retryValueFilter to be ignored and the given function executed only once until first success.</param>
/// <param name="maxNumErrorTries">Maximal number of execution attempts due to errors.
/// Set to -1 for unlimited number of error retries, until retryExceptionFilter is satisfied.</param>
/// <param name="retryValueFilter">Filter function to indicate if successful execution should be retied.
/// Set to null to disable successful retries.</param>
/// <param name="retryExceptionFilter">Filter function to indicate if error execution should be retied.
/// Set to null to disable error retries.</param>
/// <param name="maxExecutionTime">The maximal execution time of the ExecuteWithRetries function.</param>
/// <param name="onSuccessBackOff">The backoff provider object, which determines how much to wait between success retries.</param>
/// <param name="onErrorBackOff">The backoff provider object, which determines how much to wait between error retries</param>
/// <returns></returns>
public static Task<T> ExecuteWithRetries<T>(
Func<int, Task<T>> function,
int maxNumSuccessTries,
int maxNumErrorTries,
Func<T, int, bool> retryValueFilter,
Func<Exception, int, bool> retryExceptionFilter,
TimeSpan maxExecutionTime = default(TimeSpan),
IBackoffProvider onSuccessBackOff = null,
IBackoffProvider onErrorBackOff = null)
{
return ExecuteWithRetriesHelper<T>(
function,
0,
maxNumSuccessTries,
maxNumErrorTries,
maxExecutionTime,
DateTime.UtcNow,
retryValueFilter,
retryExceptionFilter,
onSuccessBackOff,
onErrorBackOff);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static async Task<T> ExecuteWithRetriesHelper<T>(
Func<int, Task<T>> function,
int callCounter,
int maxNumSuccessTries,
int maxNumErrorTries,
TimeSpan maxExecutionTime,
DateTime startExecutionTime,
Func<T, int, bool> retryValueFilter = null,
Func<Exception, int, bool> retryExceptionFilter = null,
IBackoffProvider onSuccessBackOff = null,
IBackoffProvider onErrorBackOff = null)
{
if (maxExecutionTime != Constants.INFINITE_TIMESPAN && maxExecutionTime != default(TimeSpan))
{
DateTime now = DateTime.UtcNow;
if (now - startExecutionTime > maxExecutionTime)
{
Exception timeoutException = new TimeoutException(String.Format("ExecuteWithRetries has exceeded its max execution time of {0}. Now is {1}, started at {2}, passed {3}",
maxExecutionTime, LogFormatter.PrintDate(now), LogFormatter.PrintDate(startExecutionTime), now - startExecutionTime));
throw timeoutException;
}
}
T result = default(T);
int counter = callCounter;
Exception exception = null;
try
{
callCounter++;
result = await function(counter);
bool retry = false;
if (callCounter < maxNumSuccessTries || maxNumSuccessTries == INFINITE_RETRIES) // -1 for infinite retries
{
if (retryValueFilter != null)
retry = retryValueFilter(result, counter);
}
if (retry)
{
if (onSuccessBackOff == null)
{
return await ExecuteWithRetriesHelper(function, callCounter, maxNumSuccessTries, maxNumErrorTries, maxExecutionTime, startExecutionTime, retryValueFilter, retryExceptionFilter, onSuccessBackOff, onErrorBackOff);
}
else
{
TimeSpan delay = onSuccessBackOff.Next(counter);
await Task.Delay(delay);
return await ExecuteWithRetriesHelper(function, callCounter, maxNumSuccessTries, maxNumErrorTries, maxExecutionTime, startExecutionTime, retryValueFilter, retryExceptionFilter, onSuccessBackOff, onErrorBackOff);
}
}
return result;
}
catch (Exception exc)
{
exception = exc;
}
if (exception != null)
{
bool retry = false;
if (callCounter < maxNumErrorTries || maxNumErrorTries == INFINITE_RETRIES)
{
if (retryExceptionFilter != null)
retry = retryExceptionFilter(exception, counter);
}
if (retry)
{
if (onErrorBackOff == null)
{
return await ExecuteWithRetriesHelper(function, callCounter, maxNumSuccessTries, maxNumErrorTries, maxExecutionTime, startExecutionTime, retryValueFilter, retryExceptionFilter, onSuccessBackOff, onErrorBackOff);
}
else
{
TimeSpan delay = onErrorBackOff.Next(counter);
await Task.Delay(delay);
return await ExecuteWithRetriesHelper(function, callCounter, maxNumSuccessTries, maxNumErrorTries, maxExecutionTime, startExecutionTime, retryValueFilter, retryExceptionFilter, onSuccessBackOff, onErrorBackOff);
}
}
ExceptionDispatchInfo.Capture(exception).Throw();
}
return result; // this return value is just for the compiler to supress "not all control paths return a value".
}
}
// Allow multiple implementations of the backoff algorithm.
// For instance, ConstantBackoff variation that always waits for a fixed timespan,
// or a RateLimitingBackoff that keeps makes sure that some minimum time period occurs between calls to some API
// (especially useful if you use the same instance for multiple potentially simultaneous calls to ExecuteWithRetries).
// Implementations should be imutable.
// If mutable state is needed, extend the next function to pass the state from the caller.
// example: TimeSpan Next(int attempt, object state, out object newState);
internal interface IBackoffProvider
{
TimeSpan Next(int attempt);
}
internal class FixedBackoff : IBackoffProvider
{
private readonly TimeSpan fixedDelay;
public FixedBackoff(TimeSpan delay)
{
fixedDelay = delay;
}
public TimeSpan Next(int attempt)
{
return fixedDelay;
}
}
internal class ExponentialBackoff : IBackoffProvider
{
private readonly TimeSpan minDelay;
private readonly TimeSpan maxDelay;
private readonly TimeSpan step;
private readonly SafeRandom random;
public ExponentialBackoff(TimeSpan minDelay, TimeSpan maxDelay, TimeSpan step)
{
if (minDelay <= TimeSpan.Zero) throw new ArgumentOutOfRangeException("minDelay", minDelay, "ExponentialBackoff min delay must be a positive number.");
if (maxDelay <= TimeSpan.Zero) throw new ArgumentOutOfRangeException("maxDelay", maxDelay, "ExponentialBackoff max delay must be a positive number.");
if (step <= TimeSpan.Zero) throw new ArgumentOutOfRangeException("step", step, "ExponentialBackoff step must be a positive number.");
if (minDelay >= maxDelay) throw new ArgumentOutOfRangeException("minDelay", minDelay, "ExponentialBackoff min delay must be greater than max delay.");
this.minDelay = minDelay;
this.maxDelay = maxDelay;
this.step = step;
this.random = new SafeRandom();
}
public TimeSpan Next(int attempt)
{
TimeSpan currMax;
try
{
long multiple = checked(1 << attempt);
currMax = minDelay + step.Multiply(multiple); // may throw OverflowException
if (currMax <= TimeSpan.Zero)
throw new OverflowException();
}
catch (OverflowException)
{
currMax = maxDelay;
}
currMax = StandardExtensions.Min(currMax, maxDelay);
if (minDelay >= currMax) throw new ArgumentOutOfRangeException(String.Format("minDelay {0}, currMax = {1}", minDelay, currMax));
return random.NextTimeSpan(minDelay, currMax);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using JetBrains.Annotations;
using osu.Game.Audio;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Legacy;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Skinning;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Beatmaps.Formats
{
public class LegacyBeatmapEncoder
{
public const int LATEST_VERSION = 128;
private readonly IBeatmap beatmap;
[CanBeNull]
private readonly ISkin skin;
/// <summary>
/// Creates a new <see cref="LegacyBeatmapEncoder"/>.
/// </summary>
/// <param name="beatmap">The beatmap to encode.</param>
/// <param name="skin">The beatmap's skin, used for encoding combo colours.</param>
public LegacyBeatmapEncoder(IBeatmap beatmap, [CanBeNull] ISkin skin)
{
this.beatmap = beatmap;
this.skin = skin;
if (beatmap.BeatmapInfo.RulesetID < 0 || beatmap.BeatmapInfo.RulesetID > 3)
throw new ArgumentException("Only beatmaps in the osu, taiko, catch, or mania rulesets can be encoded to the legacy beatmap format.", nameof(beatmap));
}
public void Encode(TextWriter writer)
{
writer.WriteLine($"osu file format v{LATEST_VERSION}");
writer.WriteLine();
handleGeneral(writer);
writer.WriteLine();
handleEditor(writer);
writer.WriteLine();
handleMetadata(writer);
writer.WriteLine();
handleDifficulty(writer);
writer.WriteLine();
handleEvents(writer);
writer.WriteLine();
handleControlPoints(writer);
writer.WriteLine();
handleColours(writer);
writer.WriteLine();
handleHitObjects(writer);
}
private void handleGeneral(TextWriter writer)
{
writer.WriteLine("[General]");
if (beatmap.Metadata.AudioFile != null) writer.WriteLine(FormattableString.Invariant($"AudioFilename: {Path.GetFileName(beatmap.Metadata.AudioFile)}"));
writer.WriteLine(FormattableString.Invariant($"AudioLeadIn: {beatmap.BeatmapInfo.AudioLeadIn}"));
writer.WriteLine(FormattableString.Invariant($"PreviewTime: {beatmap.Metadata.PreviewTime}"));
// Todo: Not all countdown types are supported by lazer yet
writer.WriteLine(FormattableString.Invariant($"Countdown: {(beatmap.BeatmapInfo.Countdown ? '1' : '0')}"));
writer.WriteLine(FormattableString.Invariant($"SampleSet: {toLegacySampleBank(beatmap.ControlPointInfo.SamplePointAt(double.MinValue).SampleBank)}"));
writer.WriteLine(FormattableString.Invariant($"StackLeniency: {beatmap.BeatmapInfo.StackLeniency}"));
writer.WriteLine(FormattableString.Invariant($"Mode: {beatmap.BeatmapInfo.RulesetID}"));
writer.WriteLine(FormattableString.Invariant($"LetterboxInBreaks: {(beatmap.BeatmapInfo.LetterboxInBreaks ? '1' : '0')}"));
// if (beatmap.BeatmapInfo.UseSkinSprites)
// writer.WriteLine(@"UseSkinSprites: 1");
// if (b.AlwaysShowPlayfield)
// writer.WriteLine(@"AlwaysShowPlayfield: 1");
// if (b.OverlayPosition != OverlayPosition.NoChange)
// writer.WriteLine(@"OverlayPosition: " + b.OverlayPosition);
// if (!string.IsNullOrEmpty(b.SkinPreference))
// writer.WriteLine(@"SkinPreference:" + b.SkinPreference);
// if (b.EpilepsyWarning)
// writer.WriteLine(@"EpilepsyWarning: 1");
// if (b.CountdownOffset > 0)
// writer.WriteLine(@"CountdownOffset: " + b.CountdownOffset.ToString());
if (beatmap.BeatmapInfo.RulesetID == 3)
writer.WriteLine(FormattableString.Invariant($"SpecialStyle: {(beatmap.BeatmapInfo.SpecialStyle ? '1' : '0')}"));
writer.WriteLine(FormattableString.Invariant($"WidescreenStoryboard: {(beatmap.BeatmapInfo.WidescreenStoryboard ? '1' : '0')}"));
// if (b.SamplesMatchPlaybackRate)
// writer.WriteLine(@"SamplesMatchPlaybackRate: 1");
}
private void handleEditor(TextWriter writer)
{
writer.WriteLine("[Editor]");
if (beatmap.BeatmapInfo.Bookmarks.Length > 0)
writer.WriteLine(FormattableString.Invariant($"Bookmarks: {string.Join(',', beatmap.BeatmapInfo.Bookmarks)}"));
writer.WriteLine(FormattableString.Invariant($"DistanceSpacing: {beatmap.BeatmapInfo.DistanceSpacing}"));
writer.WriteLine(FormattableString.Invariant($"BeatDivisor: {beatmap.BeatmapInfo.BeatDivisor}"));
writer.WriteLine(FormattableString.Invariant($"GridSize: {beatmap.BeatmapInfo.GridSize}"));
writer.WriteLine(FormattableString.Invariant($"TimelineZoom: {beatmap.BeatmapInfo.TimelineZoom}"));
}
private void handleMetadata(TextWriter writer)
{
writer.WriteLine("[Metadata]");
writer.WriteLine(FormattableString.Invariant($"Title: {beatmap.Metadata.Title}"));
if (beatmap.Metadata.TitleUnicode != null) writer.WriteLine(FormattableString.Invariant($"TitleUnicode: {beatmap.Metadata.TitleUnicode}"));
writer.WriteLine(FormattableString.Invariant($"Artist: {beatmap.Metadata.Artist}"));
if (beatmap.Metadata.ArtistUnicode != null) writer.WriteLine(FormattableString.Invariant($"ArtistUnicode: {beatmap.Metadata.ArtistUnicode}"));
writer.WriteLine(FormattableString.Invariant($"Creator: {beatmap.Metadata.AuthorString}"));
writer.WriteLine(FormattableString.Invariant($"Version: {beatmap.BeatmapInfo.Version}"));
if (beatmap.Metadata.Source != null) writer.WriteLine(FormattableString.Invariant($"Source: {beatmap.Metadata.Source}"));
if (beatmap.Metadata.Tags != null) writer.WriteLine(FormattableString.Invariant($"Tags: {beatmap.Metadata.Tags}"));
if (beatmap.BeatmapInfo.OnlineBeatmapID != null) writer.WriteLine(FormattableString.Invariant($"BeatmapID: {beatmap.BeatmapInfo.OnlineBeatmapID}"));
if (beatmap.BeatmapInfo.BeatmapSet?.OnlineBeatmapSetID != null) writer.WriteLine(FormattableString.Invariant($"BeatmapSetID: {beatmap.BeatmapInfo.BeatmapSet.OnlineBeatmapSetID}"));
}
private void handleDifficulty(TextWriter writer)
{
writer.WriteLine("[Difficulty]");
writer.WriteLine(FormattableString.Invariant($"HPDrainRate: {beatmap.BeatmapInfo.BaseDifficulty.DrainRate}"));
writer.WriteLine(FormattableString.Invariant($"CircleSize: {beatmap.BeatmapInfo.BaseDifficulty.CircleSize}"));
writer.WriteLine(FormattableString.Invariant($"OverallDifficulty: {beatmap.BeatmapInfo.BaseDifficulty.OverallDifficulty}"));
writer.WriteLine(FormattableString.Invariant($"ApproachRate: {beatmap.BeatmapInfo.BaseDifficulty.ApproachRate}"));
// Taiko adjusts the slider multiplier (see: TaikoBeatmapConverter.LEGACY_VELOCITY_MULTIPLIER)
writer.WriteLine(beatmap.BeatmapInfo.RulesetID == 1
? FormattableString.Invariant($"SliderMultiplier: {beatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier / 1.4f}")
: FormattableString.Invariant($"SliderMultiplier: {beatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier}"));
writer.WriteLine(FormattableString.Invariant($"SliderTickRate: {beatmap.BeatmapInfo.BaseDifficulty.SliderTickRate}"));
}
private void handleEvents(TextWriter writer)
{
writer.WriteLine("[Events]");
if (!string.IsNullOrEmpty(beatmap.BeatmapInfo.Metadata.BackgroundFile))
writer.WriteLine(FormattableString.Invariant($"{(int)LegacyEventType.Background},0,\"{beatmap.BeatmapInfo.Metadata.BackgroundFile}\",0,0"));
foreach (var b in beatmap.Breaks)
writer.WriteLine(FormattableString.Invariant($"{(int)LegacyEventType.Break},{b.StartTime},{b.EndTime}"));
}
private void handleControlPoints(TextWriter writer)
{
if (beatmap.ControlPointInfo.Groups.Count == 0)
return;
writer.WriteLine("[TimingPoints]");
foreach (var group in beatmap.ControlPointInfo.Groups)
{
var groupTimingPoint = group.ControlPoints.OfType<TimingControlPoint>().FirstOrDefault();
// If the group contains a timing control point, it needs to be output separately.
if (groupTimingPoint != null)
{
writer.Write(FormattableString.Invariant($"{groupTimingPoint.Time},"));
writer.Write(FormattableString.Invariant($"{groupTimingPoint.BeatLength},"));
outputControlPointEffectsAt(groupTimingPoint.Time, true);
}
// Output any remaining effects as secondary non-timing control point.
var difficultyPoint = beatmap.ControlPointInfo.DifficultyPointAt(group.Time);
writer.Write(FormattableString.Invariant($"{group.Time},"));
writer.Write(FormattableString.Invariant($"{-100 / difficultyPoint.SpeedMultiplier},"));
outputControlPointEffectsAt(group.Time, false);
}
void outputControlPointEffectsAt(double time, bool isTimingPoint)
{
var samplePoint = beatmap.ControlPointInfo.SamplePointAt(time);
var effectPoint = beatmap.ControlPointInfo.EffectPointAt(time);
// Apply the control point to a hit sample to uncover legacy properties (e.g. suffix)
HitSampleInfo tempHitSample = samplePoint.ApplyTo(new ConvertHitObjectParser.LegacyHitSampleInfo(string.Empty));
// Convert effect flags to the legacy format
LegacyEffectFlags effectFlags = LegacyEffectFlags.None;
if (effectPoint.KiaiMode)
effectFlags |= LegacyEffectFlags.Kiai;
if (effectPoint.OmitFirstBarLine)
effectFlags |= LegacyEffectFlags.OmitFirstBarLine;
writer.Write(FormattableString.Invariant($"{(int)beatmap.ControlPointInfo.TimingPointAt(time).TimeSignature},"));
writer.Write(FormattableString.Invariant($"{(int)toLegacySampleBank(tempHitSample.Bank)},"));
writer.Write(FormattableString.Invariant($"{toLegacyCustomSampleBank(tempHitSample)},"));
writer.Write(FormattableString.Invariant($"{tempHitSample.Volume},"));
writer.Write(FormattableString.Invariant($"{(isTimingPoint ? '1' : '0')},"));
writer.Write(FormattableString.Invariant($"{(int)effectFlags}"));
writer.WriteLine();
}
}
private void handleColours(TextWriter writer)
{
var colours = skin?.GetConfig<GlobalSkinColours, IReadOnlyList<Color4>>(GlobalSkinColours.ComboColours)?.Value;
if (colours == null || colours.Count == 0)
return;
writer.WriteLine("[Colours]");
for (var i = 0; i < colours.Count; i++)
{
var comboColour = colours[i];
writer.Write(FormattableString.Invariant($"Combo{i}: "));
writer.Write(FormattableString.Invariant($"{(byte)(comboColour.R * byte.MaxValue)},"));
writer.Write(FormattableString.Invariant($"{(byte)(comboColour.G * byte.MaxValue)},"));
writer.Write(FormattableString.Invariant($"{(byte)(comboColour.B * byte.MaxValue)},"));
writer.Write(FormattableString.Invariant($"{(byte)(comboColour.A * byte.MaxValue)}"));
writer.WriteLine();
}
}
private void handleHitObjects(TextWriter writer)
{
writer.WriteLine("[HitObjects]");
if (beatmap.HitObjects.Count == 0)
return;
foreach (var h in beatmap.HitObjects)
handleHitObject(writer, h);
}
private void handleHitObject(TextWriter writer, HitObject hitObject)
{
Vector2 position = new Vector2(256, 192);
switch (beatmap.BeatmapInfo.RulesetID)
{
case 0:
position = ((IHasPosition)hitObject).Position;
break;
case 2:
position.X = ((IHasXPosition)hitObject).X;
break;
case 3:
int totalColumns = (int)Math.Max(1, beatmap.BeatmapInfo.BaseDifficulty.CircleSize);
position.X = (int)Math.Ceiling(((IHasXPosition)hitObject).X * (512f / totalColumns));
break;
}
writer.Write(FormattableString.Invariant($"{position.X},"));
writer.Write(FormattableString.Invariant($"{position.Y},"));
writer.Write(FormattableString.Invariant($"{hitObject.StartTime},"));
writer.Write(FormattableString.Invariant($"{(int)getObjectType(hitObject)},"));
writer.Write(FormattableString.Invariant($"{(int)toLegacyHitSoundType(hitObject.Samples)},"));
if (hitObject is IHasPath path)
{
addPathData(writer, path, position);
writer.Write(getSampleBank(hitObject.Samples));
}
else
{
if (hitObject is IHasDuration)
addEndTimeData(writer, hitObject);
writer.Write(getSampleBank(hitObject.Samples));
}
writer.WriteLine();
}
private LegacyHitObjectType getObjectType(HitObject hitObject)
{
LegacyHitObjectType type = 0;
if (hitObject is IHasCombo combo)
{
type = (LegacyHitObjectType)(combo.ComboOffset << 4);
if (combo.NewCombo)
type |= LegacyHitObjectType.NewCombo;
}
switch (hitObject)
{
case IHasPath _:
type |= LegacyHitObjectType.Slider;
break;
case IHasDuration _:
if (beatmap.BeatmapInfo.RulesetID == 3)
type |= LegacyHitObjectType.Hold;
else
type |= LegacyHitObjectType.Spinner;
break;
default:
type |= LegacyHitObjectType.Circle;
break;
}
return type;
}
private void addPathData(TextWriter writer, IHasPath pathData, Vector2 position)
{
PathType? lastType = null;
for (int i = 0; i < pathData.Path.ControlPoints.Count; i++)
{
PathControlPoint point = pathData.Path.ControlPoints[i];
if (point.Type.Value != null)
{
// We've reached a new (explicit) segment!
// Explicit segments have a new format in which the type is injected into the middle of the control point string.
// To preserve compatibility with osu-stable as much as possible, explicit segments with the same type are converted to use implicit segments by duplicating the control point.
// One exception are consecutive perfect curves, which aren't supported in osu!stable and can lead to decoding issues if encoded as implicit segments
bool needsExplicitSegment = point.Type.Value != lastType || point.Type.Value == PathType.PerfectCurve;
// Another exception to this is when the last two control points of the last segment were duplicated. This is not a scenario supported by osu!stable.
// Lazer does not add implicit segments for the last two control points of _any_ explicit segment, so an explicit segment is forced in order to maintain consistency with the decoder.
if (i > 1)
{
// We need to use the absolute control point position to determine equality, otherwise floating point issues may arise.
Vector2 p1 = position + pathData.Path.ControlPoints[i - 1].Position.Value;
Vector2 p2 = position + pathData.Path.ControlPoints[i - 2].Position.Value;
if ((int)p1.X == (int)p2.X && (int)p1.Y == (int)p2.Y)
needsExplicitSegment = true;
}
if (needsExplicitSegment)
{
switch (point.Type.Value)
{
case PathType.Bezier:
writer.Write("B|");
break;
case PathType.Catmull:
writer.Write("C|");
break;
case PathType.PerfectCurve:
writer.Write("P|");
break;
case PathType.Linear:
writer.Write("L|");
break;
}
lastType = point.Type.Value;
}
else
{
// New segment with the same type - duplicate the control point
writer.Write(FormattableString.Invariant($"{position.X + point.Position.Value.X}:{position.Y + point.Position.Value.Y}|"));
}
}
if (i != 0)
{
writer.Write(FormattableString.Invariant($"{position.X + point.Position.Value.X}:{position.Y + point.Position.Value.Y}"));
writer.Write(i != pathData.Path.ControlPoints.Count - 1 ? "|" : ",");
}
}
var curveData = pathData as IHasPathWithRepeats;
writer.Write(FormattableString.Invariant($"{(curveData?.RepeatCount ?? 0) + 1},"));
writer.Write(FormattableString.Invariant($"{pathData.Path.Distance},"));
if (curveData != null)
{
for (int i = 0; i < curveData.NodeSamples.Count; i++)
{
writer.Write(FormattableString.Invariant($"{(int)toLegacyHitSoundType(curveData.NodeSamples[i])}"));
writer.Write(i != curveData.NodeSamples.Count - 1 ? "|" : ",");
}
for (int i = 0; i < curveData.NodeSamples.Count; i++)
{
writer.Write(getSampleBank(curveData.NodeSamples[i], true));
writer.Write(i != curveData.NodeSamples.Count - 1 ? "|" : ",");
}
}
}
private void addEndTimeData(TextWriter writer, HitObject hitObject)
{
var endTimeData = (IHasDuration)hitObject;
var type = getObjectType(hitObject);
char suffix = ',';
// Holds write the end time as if it's part of sample data.
if (type == LegacyHitObjectType.Hold)
suffix = ':';
writer.Write(FormattableString.Invariant($"{endTimeData.EndTime}{suffix}"));
}
private string getSampleBank(IList<HitSampleInfo> samples, bool banksOnly = false)
{
LegacySampleBank normalBank = toLegacySampleBank(samples.SingleOrDefault(s => s.Name == HitSampleInfo.HIT_NORMAL)?.Bank);
LegacySampleBank addBank = toLegacySampleBank(samples.FirstOrDefault(s => !string.IsNullOrEmpty(s.Name) && s.Name != HitSampleInfo.HIT_NORMAL)?.Bank);
StringBuilder sb = new StringBuilder();
sb.Append(FormattableString.Invariant($"{(int)normalBank}:"));
sb.Append(FormattableString.Invariant($"{(int)addBank}"));
if (!banksOnly)
{
string customSampleBank = toLegacyCustomSampleBank(samples.FirstOrDefault(s => !string.IsNullOrEmpty(s.Name)));
string sampleFilename = samples.FirstOrDefault(s => string.IsNullOrEmpty(s.Name))?.LookupNames.First() ?? string.Empty;
int volume = samples.FirstOrDefault()?.Volume ?? 100;
sb.Append(':');
sb.Append(FormattableString.Invariant($"{customSampleBank}:"));
sb.Append(FormattableString.Invariant($"{volume}:"));
sb.Append(FormattableString.Invariant($"{sampleFilename}"));
}
return sb.ToString();
}
private LegacyHitSoundType toLegacyHitSoundType(IList<HitSampleInfo> samples)
{
LegacyHitSoundType type = LegacyHitSoundType.None;
foreach (var sample in samples)
{
switch (sample.Name)
{
case HitSampleInfo.HIT_WHISTLE:
type |= LegacyHitSoundType.Whistle;
break;
case HitSampleInfo.HIT_FINISH:
type |= LegacyHitSoundType.Finish;
break;
case HitSampleInfo.HIT_CLAP:
type |= LegacyHitSoundType.Clap;
break;
}
}
return type;
}
private LegacySampleBank toLegacySampleBank(string sampleBank)
{
switch (sampleBank?.ToLowerInvariant())
{
case "normal":
return LegacySampleBank.Normal;
case "soft":
return LegacySampleBank.Soft;
case "drum":
return LegacySampleBank.Drum;
default:
return LegacySampleBank.None;
}
}
private string toLegacyCustomSampleBank(HitSampleInfo hitSampleInfo)
{
if (hitSampleInfo is ConvertHitObjectParser.LegacyHitSampleInfo legacy)
return legacy.CustomSampleBank.ToString(CultureInfo.InvariantCulture);
return "0";
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using Roslyn.Utilities;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.CodeAnalysis.CommandLine;
using System.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// This class defines all of the common stuff that is shared between the Vbc and Csc tasks.
/// This class is not instantiatable as a Task just by itself.
/// </summary>
public abstract class ManagedCompiler : ToolTask
{
private CancellationTokenSource _sharedCompileCts;
internal readonly PropertyDictionary _store = new PropertyDictionary();
public ManagedCompiler()
{
TaskResources = ErrorString.ResourceManager;
}
#region Properties
// Please keep these alphabetized.
public string[] AdditionalLibPaths
{
set { _store[nameof(AdditionalLibPaths)] = value; }
get { return (string[])_store[nameof(AdditionalLibPaths)]; }
}
public string[] AddModules
{
set { _store[nameof(AddModules)] = value; }
get { return (string[])_store[nameof(AddModules)]; }
}
public ITaskItem[] AdditionalFiles
{
set { _store[nameof(AdditionalFiles)] = value; }
get { return (ITaskItem[])_store[nameof(AdditionalFiles)]; }
}
public ITaskItem[] Analyzers
{
set { _store[nameof(Analyzers)] = value; }
get { return (ITaskItem[])_store[nameof(Analyzers)]; }
}
// We do not support BugReport because it always requires user interaction,
// which will cause a hang.
public string CodeAnalysisRuleSet
{
set { _store[nameof(CodeAnalysisRuleSet)] = value; }
get { return (string)_store[nameof(CodeAnalysisRuleSet)]; }
}
public int CodePage
{
set { _store[nameof(CodePage)] = value; }
get { return _store.GetOrDefault(nameof(CodePage), 0); }
}
[Output]
public ITaskItem[] CommandLineArgs
{
set { _store[nameof(CommandLineArgs)] = value; }
get { return (ITaskItem[])_store[nameof(CommandLineArgs)]; }
}
public string DebugType
{
set { _store[nameof(DebugType)] = value; }
get { return (string)_store[nameof(DebugType)]; }
}
public string DefineConstants
{
set { _store[nameof(DefineConstants)] = value; }
get { return (string)_store[nameof(DefineConstants)]; }
}
public bool DelaySign
{
set { _store[nameof(DelaySign)] = value; }
get { return _store.GetOrDefault(nameof(DelaySign), false); }
}
public bool Deterministic
{
set { _store[nameof(Deterministic)] = value; }
get { return _store.GetOrDefault(nameof(Deterministic), false); }
}
public bool PublicSign
{
set { _store[nameof(PublicSign)] = value; }
get { return _store.GetOrDefault(nameof(PublicSign), false); }
}
public bool EmitDebugInformation
{
set { _store[nameof(EmitDebugInformation)] = value; }
get { return _store.GetOrDefault(nameof(EmitDebugInformation), false); }
}
public string ErrorLog
{
set { _store[nameof(ErrorLog)] = value; }
get { return (string)_store[nameof(ErrorLog)]; }
}
public string Features
{
set { _store[nameof(Features)] = value; }
get { return (string)_store[nameof(Features)]; }
}
public int FileAlignment
{
set { _store[nameof(FileAlignment)] = value; }
get { return _store.GetOrDefault(nameof(FileAlignment), 0); }
}
public bool HighEntropyVA
{
set { _store[nameof(HighEntropyVA)] = value; }
get { return _store.GetOrDefault(nameof(HighEntropyVA), false); }
}
public string KeyContainer
{
set { _store[nameof(KeyContainer)] = value; }
get { return (string)_store[nameof(KeyContainer)]; }
}
public string KeyFile
{
set { _store[nameof(KeyFile)] = value; }
get { return (string)_store[nameof(KeyFile)]; }
}
public ITaskItem[] LinkResources
{
set { _store[nameof(LinkResources)] = value; }
get { return (ITaskItem[])_store[nameof(LinkResources)]; }
}
public string MainEntryPoint
{
set { _store[nameof(MainEntryPoint)] = value; }
get { return (string)_store[nameof(MainEntryPoint)]; }
}
public bool NoConfig
{
set { _store[nameof(NoConfig)] = value; }
get { return _store.GetOrDefault(nameof(NoConfig), false); }
}
public bool NoLogo
{
set { _store[nameof(NoLogo)] = value; }
get { return _store.GetOrDefault(nameof(NoLogo), false); }
}
public bool NoWin32Manifest
{
set { _store[nameof(NoWin32Manifest)] = value; }
get { return _store.GetOrDefault(nameof(NoWin32Manifest), false); }
}
public bool Optimize
{
set { _store[nameof(Optimize)] = value; }
get { return _store.GetOrDefault(nameof(Optimize), false); }
}
[Output]
public ITaskItem OutputAssembly
{
set { _store[nameof(OutputAssembly)] = value; }
get { return (ITaskItem)_store[nameof(OutputAssembly)]; }
}
public string Platform
{
set { _store[nameof(Platform)] = value; }
get { return (string)_store[nameof(Platform)]; }
}
public bool Prefer32Bit
{
set { _store[nameof(Prefer32Bit)] = value; }
get { return _store.GetOrDefault(nameof(Prefer32Bit), false); }
}
public bool ProvideCommandLineArgs
{
set { _store[nameof(ProvideCommandLineArgs)] = value; }
get { return _store.GetOrDefault(nameof(ProvideCommandLineArgs), false); }
}
public ITaskItem[] References
{
set { _store[nameof(References)] = value; }
get { return (ITaskItem[])_store[nameof(References)]; }
}
public bool ReportAnalyzer
{
set { _store[nameof(ReportAnalyzer)] = value; }
get { return _store.GetOrDefault(nameof(ReportAnalyzer), false); }
}
public ITaskItem[] Resources
{
set { _store[nameof(Resources)] = value; }
get { return (ITaskItem[])_store[nameof(Resources)]; }
}
public ITaskItem[] ResponseFiles
{
set { _store[nameof(ResponseFiles)] = value; }
get { return (ITaskItem[])_store[nameof(ResponseFiles)]; }
}
public bool SkipCompilerExecution
{
set { _store[nameof(SkipCompilerExecution)] = value; }
get { return _store.GetOrDefault(nameof(SkipCompilerExecution), false); }
}
public ITaskItem[] Sources
{
set
{
if (UsedCommandLineTool)
{
NormalizePaths(value);
}
_store[nameof(Sources)] = value;
}
get { return (ITaskItem[])_store[nameof(Sources)]; }
}
public string SubsystemVersion
{
set { _store[nameof(SubsystemVersion)] = value; }
get { return (string)_store[nameof(SubsystemVersion)]; }
}
public string TargetType
{
set { _store[nameof(TargetType)] = CultureInfo.InvariantCulture.TextInfo.ToLower(value); }
get { return (string)_store[nameof(TargetType)]; }
}
public bool TreatWarningsAsErrors
{
set { _store[nameof(TreatWarningsAsErrors)] = value; }
get { return _store.GetOrDefault(nameof(TreatWarningsAsErrors), false); }
}
public bool Utf8Output
{
set { _store[nameof(Utf8Output)] = value; }
get { return _store.GetOrDefault(nameof(Utf8Output), false); }
}
public string Win32Icon
{
set { _store[nameof(Win32Icon)] = value; }
get { return (string)_store[nameof(Win32Icon)]; }
}
public string Win32Manifest
{
set { _store[nameof(Win32Manifest)] = value; }
get { return (string)_store[nameof(Win32Manifest)]; }
}
public string Win32Resource
{
set { _store[nameof(Win32Resource)] = value; }
get { return (string)_store[nameof(Win32Resource)]; }
}
public string PathMap
{
set { _store[nameof(PathMap)] = value; }
get { return (string)_store[nameof(PathMap)]; }
}
/// <summary>
/// If this property is true then the task will take every C# or VB
/// compilation which is queued by MSBuild and send it to the
/// VBCSCompiler server instance, starting a new instance if necessary.
/// If false, we will use the values from ToolPath/Exe.
/// </summary>
public bool UseSharedCompilation
{
set { _store[nameof(UseSharedCompilation)] = value; }
get { return _store.GetOrDefault(nameof(UseSharedCompilation), false); }
}
// Map explicit platform of "AnyCPU" or the default platform (null or ""), since it is commonly understood in the
// managed build process to be equivalent to "AnyCPU", to platform "AnyCPU32BitPreferred" if the Prefer32Bit
// property is set.
internal string PlatformWith32BitPreference
{
get
{
string platform = Platform;
if ((string.IsNullOrEmpty(platform) || platform.Equals("anycpu", StringComparison.OrdinalIgnoreCase)) && Prefer32Bit)
{
platform = "anycpu32bitpreferred";
}
return platform;
}
}
/// <summary>
/// Overridable property specifying the encoding of the captured task standard output stream
/// </summary>
protected override Encoding StandardOutputEncoding
{
get
{
return (Utf8Output) ? Encoding.UTF8 : base.StandardOutputEncoding;
}
}
#endregion
internal abstract RequestLanguage Language { get; }
protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands)
{
if (ProvideCommandLineArgs)
{
CommandLineArgs = GetArguments(commandLineCommands, responseFileCommands)
.Select(arg => new TaskItem(arg)).ToArray();
}
if (SkipCompilerExecution)
{
return 0;
}
if (!UseSharedCompilation || !string.IsNullOrEmpty(ToolPath))
{
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
using (_sharedCompileCts = new CancellationTokenSource())
{
try
{
CompilerServerLogger.Log($"CommandLine = '{commandLineCommands}'");
CompilerServerLogger.Log($"BuildResponseFile = '{responseFileCommands}'");
// Try to get the location of the user-provided build client and server,
// which should be located next to the build task. If not, fall back to
// "pathToTool", which is the compiler in the MSBuild default bin directory.
var clientDir = TryGetClientDir() ?? Path.GetDirectoryName(pathToTool);
pathToTool = Path.Combine(clientDir, ToolExe);
// Note: we can't change the "tool path" printed to the console when we run
// the Csc/Vbc task since MSBuild logs it for us before we get here. Instead,
// we'll just print our own message that contains the real client location
Log.LogMessage(ErrorString.UsingSharedCompilation, clientDir);
var buildPaths = new BuildPaths(
clientDir: clientDir,
// MSBuild doesn't need the .NET SDK directory
sdkDir: null,
workingDir: CurrentDirectoryToUse());
var responseTask = BuildClientShim.RunServerCompilation(
Language,
GetArguments(commandLineCommands, responseFileCommands).ToList(),
buildPaths,
keepAlive: null,
libEnvVariable: LibDirectoryToUse(),
cancellationToken: _sharedCompileCts.Token);
responseTask.Wait(_sharedCompileCts.Token);
var response = responseTask.Result;
if (response != null)
{
ExitCode = HandleResponse(response, pathToTool, responseFileCommands, commandLineCommands);
}
else
{
Log.LogMessage(ErrorString.SharedCompilationFallback, pathToTool);
ExitCode = base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
}
catch (OperationCanceledException)
{
ExitCode = 0;
}
catch (Exception e)
{
Log.LogErrorWithCodeFromResources("Compiler_UnexpectedException");
LogErrorOutput(e.ToString());
ExitCode = -1;
}
}
return ExitCode;
}
/// <summary>
/// Try to get the directory this assembly is in. Returns null if assembly
/// was in the GAC or DLL location can not be retrieved.
/// </summary>
private static string TryGetClientDir()
{
#if PORTABLE50
return null;
#else
var buildTask = typeof(ManagedCompiler).GetTypeInfo().Assembly;
if (buildTask.GlobalAssemblyCache)
return null;
var uri = new Uri(buildTask.CodeBase);
string assemblyPath = uri.IsFile
? uri.LocalPath
: Assembly.GetCallingAssembly().Location;
return Path.GetDirectoryName(assemblyPath);
#endif
}
/// <summary>
/// Cancel the in-process build task.
/// </summary>
public override void Cancel()
{
base.Cancel();
_sharedCompileCts?.Cancel();
}
/// <summary>
/// Get the current directory that the compiler should run in.
/// </summary>
private string CurrentDirectoryToUse()
{
// ToolTask has a method for this. But it may return null. Use the process directory
// if ToolTask didn't override. MSBuild uses the process directory.
string workingDirectory = GetWorkingDirectory();
if (string.IsNullOrEmpty(workingDirectory))
workingDirectory = Directory.GetCurrentDirectory();
return workingDirectory;
}
/// <summary>
/// Get the "LIB" environment variable, or NULL if none.
/// </summary>
private string LibDirectoryToUse()
{
// First check the real environment.
string libDirectory = Environment.GetEnvironmentVariable("LIB");
// Now go through additional environment variables.
string[] additionalVariables = EnvironmentVariables;
if (additionalVariables != null)
{
foreach (string var in EnvironmentVariables)
{
if (var.StartsWith("LIB=", StringComparison.OrdinalIgnoreCase))
{
libDirectory = var.Substring(4);
}
}
}
return libDirectory;
}
/// <summary>
/// The return code of the compilation. Strangely, this isn't overridable from ToolTask, so we need
/// to create our own.
/// </summary>
[Output]
public new int ExitCode { get; private set; }
/// <summary>
/// Handle a response from the server, reporting messages and returning
/// the appropriate exit code.
/// </summary>
private int HandleResponse(BuildResponse response, string pathToTool, string responseFileCommands, string commandLineCommands)
{
switch (response.Type)
{
case BuildResponse.ResponseType.MismatchedVersion:
LogErrorOutput(CommandLineParser.MismatchedVersionErrorText);
return -1;
case BuildResponse.ResponseType.Completed:
var completedResponse = (CompletedBuildResponse)response;
LogMessages(completedResponse.Output, StandardOutputImportanceToUse);
if (LogStandardErrorAsError)
{
LogErrorOutput(completedResponse.ErrorOutput);
}
else
{
LogMessages(completedResponse.ErrorOutput, StandardErrorImportanceToUse);
}
return completedResponse.ReturnCode;
case BuildResponse.ResponseType.Rejected:
case BuildResponse.ResponseType.AnalyzerInconsistency:
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
default:
throw new InvalidOperationException("Encountered unknown response type");
}
}
private void LogErrorOutput(string output)
{
string[] lines = output.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
string trimmedMessage = line.Trim();
if (trimmedMessage != "")
{
Log.LogError(trimmedMessage);
}
}
}
/// <summary>
/// Log each of the messages in the given output with the given importance.
/// We assume each line is a message to log.
/// </summary>
/// <remarks>
/// Should be "private protected" visibility once it is introduced into C#.
/// </remarks>
internal abstract void LogMessages(string output, MessageImportance messageImportance);
public string GenerateResponseFileContents()
{
return GenerateResponseFileCommands();
}
/// <summary>
/// Get the command line arguments to pass to the compiler.
/// </summary>
private string[] GetArguments(string commandLineCommands, string responseFileCommands)
{
var commandLineArguments =
CommandLineParser.SplitCommandLineIntoArguments(commandLineCommands, removeHashComments: true);
var responseFileArguments =
CommandLineParser.SplitCommandLineIntoArguments(responseFileCommands, removeHashComments: true);
return commandLineArguments.Concat(responseFileArguments).ToArray();
}
/// <summary>
/// Returns the command line switch used by the tool executable to specify the response file
/// Will only be called if the task returned a non empty string from GetResponseFileCommands
/// Called after ValidateParameters, SkipTaskExecution and GetResponseFileCommands
/// </summary>
protected override string GenerateResponseFileCommands()
{
CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension();
AddResponseFileCommands(commandLineBuilder);
return commandLineBuilder.ToString();
}
protected override string GenerateCommandLineCommands()
{
CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension();
AddCommandLineCommands(commandLineBuilder);
return commandLineBuilder.ToString();
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can't go into a response file and
/// must go directly onto the command line.
/// </summary>
protected internal virtual void AddCommandLineCommands(CommandLineBuilderExtension commandLine)
{
commandLine.AppendWhenTrue("/noconfig", _store, nameof(NoConfig));
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file.
/// </summary>
protected internal virtual void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
{
// If outputAssembly is not specified, then an "/out: <name>" option won't be added to
// overwrite the one resulting from the OutputAssembly member of the CompilerParameters class.
// In that case, we should set the outputAssembly member based on the first source file.
if (
(OutputAssembly == null) &&
(Sources != null) &&
(Sources.Length > 0) &&
(ResponseFiles == null) // The response file may already have a /out: switch in it, so don't try to be smart here.
)
{
try
{
OutputAssembly = new TaskItem(Path.GetFileNameWithoutExtension(Sources[0].ItemSpec));
}
catch (ArgumentException e)
{
throw new ArgumentException(e.Message, "Sources");
}
if (string.Compare(TargetType, "library", StringComparison.OrdinalIgnoreCase) == 0)
{
OutputAssembly.ItemSpec += ".dll";
}
else if (string.Compare(TargetType, "module", StringComparison.OrdinalIgnoreCase) == 0)
{
OutputAssembly.ItemSpec += ".netmodule";
}
else
{
OutputAssembly.ItemSpec += ".exe";
}
}
commandLine.AppendSwitchIfNotNull("/addmodule:", AddModules, ",");
commandLine.AppendSwitchWithInteger("/codepage:", _store, nameof(CodePage));
ConfigureDebugProperties();
// The "DebugType" parameter should be processed after the "EmitDebugInformation" parameter
// because it's more specific. Order matters on the command-line, and the last one wins.
// /debug+ is just a shorthand for /debug:full. And /debug- is just a shorthand for /debug:none.
commandLine.AppendPlusOrMinusSwitch("/debug", _store, nameof(EmitDebugInformation));
commandLine.AppendSwitchIfNotNull("/debug:", DebugType);
commandLine.AppendPlusOrMinusSwitch("/delaysign", _store, nameof(DelaySign));
commandLine.AppendSwitchWithInteger("/filealign:", _store, nameof(FileAlignment));
commandLine.AppendSwitchIfNotNull("/keycontainer:", KeyContainer);
commandLine.AppendSwitchIfNotNull("/keyfile:", KeyFile);
// If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject.
commandLine.AppendSwitchIfNotNull("/linkresource:", LinkResources, new string[] { "LogicalName", "Access" });
commandLine.AppendWhenTrue("/nologo", _store, nameof(NoLogo));
commandLine.AppendWhenTrue("/nowin32manifest", _store, nameof(NoWin32Manifest));
commandLine.AppendPlusOrMinusSwitch("/optimize", _store, nameof(Optimize));
commandLine.AppendSwitchIfNotNull("/pathmap:", PathMap);
commandLine.AppendSwitchIfNotNull("/out:", OutputAssembly);
commandLine.AppendSwitchIfNotNull("/ruleset:", CodeAnalysisRuleSet);
commandLine.AppendSwitchIfNotNull("/errorlog:", ErrorLog);
commandLine.AppendSwitchIfNotNull("/subsystemversion:", SubsystemVersion);
commandLine.AppendWhenTrue("/reportanalyzer", _store, nameof(ReportAnalyzer));
// If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject.
commandLine.AppendSwitchIfNotNull("/resource:", Resources, new string[] { "LogicalName", "Access" });
commandLine.AppendSwitchIfNotNull("/target:", TargetType);
commandLine.AppendPlusOrMinusSwitch("/warnaserror", _store, nameof(TreatWarningsAsErrors));
commandLine.AppendWhenTrue("/utf8output", _store, nameof(Utf8Output));
commandLine.AppendSwitchIfNotNull("/win32icon:", Win32Icon);
commandLine.AppendSwitchIfNotNull("/win32manifest:", Win32Manifest);
AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(commandLine);
AddAnalyzersToCommandLine(commandLine, Analyzers);
AddAdditionalFilesToCommandLine(commandLine);
// Append the sources.
commandLine.AppendFileNamesIfNotNull(Sources, " ");
}
internal void AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(CommandLineBuilderExtension commandLine)
{
commandLine.AppendPlusOrMinusSwitch("/deterministic", _store, nameof(Deterministic));
commandLine.AppendPlusOrMinusSwitch("/publicsign", _store, nameof(PublicSign));
AddFeatures(commandLine, Features);
}
/// <summary>
/// Adds a "/features:" switch to the command line for each provided feature.
/// </summary>
internal static void AddFeatures(CommandLineBuilderExtension commandLine, string features)
{
if (string.IsNullOrEmpty(features))
{
return;
}
foreach (var feature in CompilerOptionParseUtilities.ParseFeatureFromMSBuild(features))
{
commandLine.AppendSwitchIfNotNull("/features:", feature.Trim());
}
}
/// <summary>
/// Adds a "/analyzer:" switch to the command line for each provided analyzer.
/// </summary>
internal static void AddAnalyzersToCommandLine(CommandLineBuilderExtension commandLine, ITaskItem[] analyzers)
{
// If there were no analyzers passed in, don't add any /analyzer: switches
// on the command-line.
if (analyzers == null)
{
return;
}
foreach (ITaskItem analyzer in analyzers)
{
commandLine.AppendSwitchIfNotNull("/analyzer:", analyzer.ItemSpec);
}
}
/// <summary>
/// Adds a "/additionalfile:" switch to the command line for each additional file.
/// </summary>
private void AddAdditionalFilesToCommandLine(CommandLineBuilderExtension commandLine)
{
// If there were no additional files passed in, don't add any /additionalfile: switches
// on the command-line.
if (AdditionalFiles == null)
{
return;
}
foreach (ITaskItem additionalFile in AdditionalFiles)
{
commandLine.AppendSwitchIfNotNull("/additionalfile:", additionalFile.ItemSpec);
}
}
/// <summary>
/// Configure the debug switches which will be placed on the compiler command-line.
/// The matrix of debug type and symbol inputs and the desired results is as follows:
///
/// Debug Symbols DebugType Desired Results
/// True Full /debug+ /debug:full
/// True PdbOnly /debug+ /debug:PdbOnly
/// True None /debug-
/// True Blank /debug+
/// False Full /debug- /debug:full
/// False PdbOnly /debug- /debug:PdbOnly
/// False None /debug-
/// False Blank /debug-
/// Blank Full /debug:full
/// Blank PdbOnly /debug:PdbOnly
/// Blank None /debug-
/// Debug: Blank Blank /debug+ //Microsoft.common.targets will set this
/// Release: Blank Blank "Nothing for either switch"
///
/// The logic is as follows:
/// If debugtype is none set debugtype to empty and debugSymbols to false
/// If debugType is blank use the debugsymbols "as is"
/// If debug type is set, use its value and the debugsymbols value "as is"
/// </summary>
private void ConfigureDebugProperties()
{
// If debug type is set we need to take some action depending on the value. If debugtype is not set
// We don't need to modify the EmitDebugInformation switch as its value will be used as is.
if (_store[nameof(DebugType)] != null)
{
// If debugtype is none then only show debug- else use the debug type and the debugsymbols as is.
if (string.Compare((string)_store[nameof(DebugType)], "none", StringComparison.OrdinalIgnoreCase) == 0)
{
_store[nameof(DebugType)] = null;
_store[nameof(EmitDebugInformation)] = false;
}
}
}
/// <summary>
/// Validate parameters, log errors and warnings and return true if
/// Execute should proceed.
/// </summary>
protected override bool ValidateParameters()
{
return ListHasNoDuplicateItems(Resources, nameof(Resources), "LogicalName", Log) && ListHasNoDuplicateItems(Sources, nameof(Sources), Log);
}
/// <summary>
/// Returns true if the provided item list contains duplicate items, false otherwise.
/// </summary>
internal static bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName, TaskLoggingHelper log)
{
return ListHasNoDuplicateItems(itemList, parameterName, null, log);
}
/// <summary>
/// Returns true if the provided item list contains duplicate items, false otherwise.
/// </summary>
/// <param name="itemList"></param>
/// <param name="disambiguatingMetadataName">Optional name of metadata that may legitimately disambiguate items. May be null.</param>
/// <param name="parameterName"></param>
/// <param name="log"></param>
private static bool ListHasNoDuplicateItems(ITaskItem[] itemList, string parameterName, string disambiguatingMetadataName, TaskLoggingHelper log)
{
if (itemList == null || itemList.Length == 0)
{
return true;
}
Hashtable alreadySeen = new Hashtable(StringComparer.OrdinalIgnoreCase);
foreach (ITaskItem item in itemList)
{
string key;
string disambiguatingMetadataValue = null;
if (disambiguatingMetadataName != null)
{
disambiguatingMetadataValue = item.GetMetadata(disambiguatingMetadataName);
}
if (disambiguatingMetadataName == null || string.IsNullOrEmpty(disambiguatingMetadataValue))
{
key = item.ItemSpec;
}
else
{
key = item.ItemSpec + ":" + disambiguatingMetadataValue;
}
if (alreadySeen.ContainsKey(key))
{
if (disambiguatingMetadataName == null || string.IsNullOrEmpty(disambiguatingMetadataValue))
{
log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupported", item.ItemSpec, parameterName);
}
else
{
log.LogErrorWithCodeFromResources("General_DuplicateItemsNotSupportedWithMetadata", item.ItemSpec, parameterName, disambiguatingMetadataValue, disambiguatingMetadataName);
}
return false;
}
else
{
alreadySeen[key] = string.Empty;
}
}
return true;
}
/// <summary>
/// Allows tool to handle the return code.
/// This method will only be called with non-zero exitCode.
/// </summary>
protected override bool HandleTaskExecutionErrors()
{
// For managed compilers, the compiler should emit the appropriate
// error messages before returning a non-zero exit code, so we don't
// normally need to emit any additional messages now.
//
// If somehow the compiler DID return a non-zero exit code and didn't log an error, we'd like to log that exit code.
// We can only do this for the command line compiler: if the inproc compiler was used,
// we can't tell what if anything it logged as it logs directly to Visual Studio's output window.
//
if (!Log.HasLoggedErrors && UsedCommandLineTool)
{
// This will log a message "MSB3093: The command exited with code {0}."
base.HandleTaskExecutionErrors();
}
return false;
}
/// <summary>
/// Takes a list of files and returns the normalized locations of these files
/// </summary>
private void NormalizePaths(ITaskItem[] taskItems)
{
foreach (var item in taskItems)
{
item.ItemSpec = Utilities.GetFullPathNoThrow(item.ItemSpec);
}
}
/// <summary>
/// Whether the command line compiler was invoked, instead
/// of the host object compiler.
/// </summary>
protected bool UsedCommandLineTool
{
get;
set;
}
private bool _hostCompilerSupportsAllParameters;
protected bool HostCompilerSupportsAllParameters
{
get { return _hostCompilerSupportsAllParameters; }
set { _hostCompilerSupportsAllParameters = value; }
}
/// <summary>
/// Checks the bool result from calling one of the methods on the host compiler object to
/// set one of the parameters. If it returned false, that means the host object doesn't
/// support a particular parameter or variation on a parameter. So we log a comment,
/// and set our state so we know not to call the host object to do the actual compilation.
/// </summary>
/// <owner>RGoel</owner>
protected void CheckHostObjectSupport
(
string parameterName,
bool resultFromHostObjectSetOperation
)
{
if (!resultFromHostObjectSetOperation)
{
Log.LogMessageFromResources(MessageImportance.Normal, "General_ParameterUnsupportedOnHostCompiler", parameterName);
_hostCompilerSupportsAllParameters = false;
}
}
internal void InitializeHostObjectSupportForNewSwitches(ITaskHost hostObject, ref string param)
{
var compilerOptionsHostObject = hostObject as ICompilerOptionsHostObject;
if (compilerOptionsHostObject != null)
{
var commandLineBuilder = new CommandLineBuilderExtension();
AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(commandLineBuilder);
param = "CompilerOptions";
CheckHostObjectSupport(param, compilerOptionsHostObject.SetCompilerOptions(commandLineBuilder.ToString()));
}
}
/// <summary>
/// Checks to see whether all of the passed-in references exist on disk before we launch the compiler.
/// </summary>
/// <owner>RGoel</owner>
protected bool CheckAllReferencesExistOnDisk()
{
if (null == References)
{
// No references
return true;
}
bool success = true;
foreach (ITaskItem reference in References)
{
if (!File.Exists(reference.ItemSpec))
{
success = false;
Log.LogErrorWithCodeFromResources("General_ReferenceDoesNotExist", reference.ItemSpec);
}
}
return success;
}
/// <summary>
/// The IDE and command line compilers unfortunately differ in how win32
/// manifests are specified. In particular, the command line compiler offers a
/// "/nowin32manifest" switch, while the IDE compiler does not offer analogous
/// functionality. If this switch is omitted from the command line and no win32
/// manifest is specified, the compiler will include a default win32 manifest
/// named "default.win32manifest" found in the same directory as the compiler
/// executable. Again, the IDE compiler does not offer analogous support.
///
/// We'd like to imitate the command line compiler's behavior in the IDE, but
/// it isn't aware of the default file, so we must compute the path to it if
/// noDefaultWin32Manifest is false and no win32Manifest was provided by the
/// project.
///
/// This method will only be called during the initialization of the host object,
/// which is only used during IDE builds.
/// </summary>
/// <returns>the path to the win32 manifest to provide to the host object</returns>
internal string GetWin32ManifestSwitch
(
bool noDefaultWin32Manifest,
string win32Manifest
)
{
if (!noDefaultWin32Manifest)
{
if (string.IsNullOrEmpty(win32Manifest) && string.IsNullOrEmpty(Win32Resource))
{
// We only want to consider the default.win32manifest if this is an executable
if (!string.Equals(TargetType, "library", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(TargetType, "module", StringComparison.OrdinalIgnoreCase))
{
// We need to compute the path to the default win32 manifest
string pathToDefaultManifest = ToolLocationHelper.GetPathToDotNetFrameworkFile
(
"default.win32manifest",
// We are choosing to pass Version46 instead of VersionLatest. TargetDotNetFrameworkVersion
// is an enum, and VersionLatest is not some sentinel value but rather a constant that is
// equal to the highest version defined in the enum. Enum values, being constants, are baked
// into consuming assembly, so specifying VersionLatest means not the latest version wherever
// this code is running, but rather the latest version of the framework according to the
// reference assembly with which this assembly was built. As of this writing, we are building
// our bits on machines with Visual Studio 2015 that know about 4.6.1, so specifying
// VersionLatest would bake in the enum value for 4.6.1. But we need to run on machines with
// MSBuild that only know about Version46 (and no higher), so VersionLatest will fail there.
// Explicitly passing Version46 prevents this problem.
TargetDotNetFrameworkVersion.Version46
);
if (null == pathToDefaultManifest)
{
// This is rather unlikely, and the inproc compiler seems to log an error anyway.
// So just a message is fine.
Log.LogMessageFromResources
(
"General_ExpectedFileMissing",
"default.win32manifest"
);
}
return pathToDefaultManifest;
}
}
}
return win32Manifest;
}
}
}
| |
using Microsoft.PowerShell.Activities;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
namespace Microsoft.PowerShell.Activities
{
/// <summary>
/// Activity to invoke the CimCmdlets\New-CimSessionOption command in a Workflow.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")]
public sealed class NewCimSessionOption : GenericCimCmdletActivity
{
/// <summary>
/// Gets the display name of the command invoked by this activity.
/// </summary>
public NewCimSessionOption()
{
this.DisplayName = "New-CimSessionOption";
}
/// <summary>
/// Gets the fully qualified name of the command invoked by this activity.
/// </summary>
public override string PSCommandName { get { return "CimCmdlets\\New-CimSessionOption"; } }
/// <summary>
/// The .NET type implementing the cmdlet to invoke.
/// </summary>
public override System.Type TypeImplementingCmdlet { get { return typeof(Microsoft.Management.Infrastructure.CimCmdlets.NewCimSessionOptionCommand); } }
// Arguments
/// <summary>
/// Provides access to the NoEncryption parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> NoEncryption { get; set; }
/// <summary>
/// Provides access to the CertificateCACheck parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> CertificateCACheck { get; set; }
/// <summary>
/// Provides access to the CertificateCNCheck parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> CertificateCNCheck { get; set; }
/// <summary>
/// Provides access to the CertRevocationCheck parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> CertRevocationCheck { get; set; }
/// <summary>
/// Provides access to the EncodePortInServicePrincipalName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> EncodePortInServicePrincipalName { get; set; }
/// <summary>
/// Provides access to the Encoding parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.Management.Infrastructure.Options.PacketEncoding> Encoding { get; set; }
/// <summary>
/// Provides access to the HttpPrefix parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Uri> HttpPrefix { get; set; }
/// <summary>
/// Provides access to the MaxEnvelopeSizeKB parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.UInt32> MaxEnvelopeSizeKB { get; set; }
/// <summary>
/// Provides access to the ProxyAuthentication parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.Management.Infrastructure.Options.PasswordAuthenticationMechanism> ProxyAuthentication { get; set; }
/// <summary>
/// Provides access to the ProxyCertificateThumbprint parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> ProxyCertificateThumbprint { get; set; }
/// <summary>
/// Provides access to the ProxyCredential parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSCredential> ProxyCredential { get; set; }
/// <summary>
/// Provides access to the ProxyType parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.Management.Infrastructure.Options.ProxyType> ProxyType { get; set; }
/// <summary>
/// Provides access to the UseSsl parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> UseSsl { get; set; }
/// <summary>
/// Provides access to the Impersonation parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.Management.Infrastructure.Options.ImpersonationType> Impersonation { get; set; }
/// <summary>
/// Provides access to the PacketIntegrity parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> PacketIntegrity { get; set; }
/// <summary>
/// Provides access to the PacketPrivacy parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> PacketPrivacy { get; set; }
/// <summary>
/// Provides access to the Protocol parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.Management.Infrastructure.CimCmdlets.ProtocolType> Protocol { get; set; }
/// <summary>
/// Provides access to the UICulture parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Globalization.CultureInfo> UICulture { get; set; }
/// <summary>
/// Provides access to the Culture parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Globalization.CultureInfo> Culture { get; set; }
/// <summary>
/// Script module contents for this activity`n/// </summary>
protected override string PSDefiningModule { get { return null; } }
/// <summary>
/// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
/// </summary>
/// <param name="context">The NativeActivityContext for the currently running activity.</param>
/// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
/// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
{
System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create();
System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);
// Initialize the arguments
if(NoEncryption.Expression != null)
{
targetCommand.AddParameter("NoEncryption", NoEncryption.Get(context));
}
if(CertificateCACheck.Expression != null)
{
targetCommand.AddParameter("CertificateCACheck", CertificateCACheck.Get(context));
}
if(CertificateCNCheck.Expression != null)
{
targetCommand.AddParameter("CertificateCNCheck", CertificateCNCheck.Get(context));
}
if(CertRevocationCheck.Expression != null)
{
targetCommand.AddParameter("CertRevocationCheck", CertRevocationCheck.Get(context));
}
if(EncodePortInServicePrincipalName.Expression != null)
{
targetCommand.AddParameter("EncodePortInServicePrincipalName", EncodePortInServicePrincipalName.Get(context));
}
if(Encoding.Expression != null)
{
targetCommand.AddParameter("Encoding", Encoding.Get(context));
}
if(HttpPrefix.Expression != null)
{
targetCommand.AddParameter("HttpPrefix", HttpPrefix.Get(context));
}
if(MaxEnvelopeSizeKB.Expression != null)
{
targetCommand.AddParameter("MaxEnvelopeSizeKB", MaxEnvelopeSizeKB.Get(context));
}
if(ProxyAuthentication.Expression != null)
{
targetCommand.AddParameter("ProxyAuthentication", ProxyAuthentication.Get(context));
}
if(ProxyCertificateThumbprint.Expression != null)
{
targetCommand.AddParameter("ProxyCertificateThumbprint", ProxyCertificateThumbprint.Get(context));
}
if(ProxyCredential.Expression != null)
{
targetCommand.AddParameter("ProxyCredential", ProxyCredential.Get(context));
}
if(ProxyType.Expression != null)
{
targetCommand.AddParameter("ProxyType", ProxyType.Get(context));
}
if(UseSsl.Expression != null)
{
targetCommand.AddParameter("UseSsl", UseSsl.Get(context));
}
if(Impersonation.Expression != null)
{
targetCommand.AddParameter("Impersonation", Impersonation.Get(context));
}
if(PacketIntegrity.Expression != null)
{
targetCommand.AddParameter("PacketIntegrity", PacketIntegrity.Get(context));
}
if(PacketPrivacy.Expression != null)
{
targetCommand.AddParameter("PacketPrivacy", PacketPrivacy.Get(context));
}
if(Protocol.Expression != null)
{
targetCommand.AddParameter("Protocol", Protocol.Get(context));
}
if(UICulture.Expression != null)
{
targetCommand.AddParameter("UICulture", UICulture.Get(context));
}
if(Culture.Expression != null)
{
targetCommand.AddParameter("Culture", Culture.Get(context));
}
return new ActivityImplementationContext() { PowerShellInstance = invoker };
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
using TestUtilities.Python;
using TestUtilities.UI;
using TestUtilities.UI.Python;
namespace PythonToolsUITests {
public class TestExplorerTests {
private const string resultStackTraceSection = "Result StackTrace:";
private const string resultMessageSection = "Result Message:";
private static TestInfo[] AllPytests = new TestInfo[] {
// test_pt.py
new TestInfo("test__pt_fail", "test_pt", "test_pt", "test_pt.py", 4, "Failed", "assert False"),
new TestInfo("test__pt_pass", "test_pt", "test_pt", "test_pt.py", 1, "Passed"),
new TestInfo("test_method_pass", "test_pt", "TestClassPT", "test_pt.py", 8, "Passed"),
// test_ut.py
new TestInfo("test__ut_fail", "test_ut", "TestClassUT", "test_ut.py", 4, "Failed", "AssertionError: Not implemented"),
new TestInfo("test__ut_pass", "test_ut", "TestClassUT", "test_ut.py", 7, "Passed"),
// test_mark.py
new TestInfo("test_webtest", "test_mark", "test_mark", "test_mark.py", 5, "Passed"),
new TestInfo("test_skip", "test_mark", "test_mark", "test_mark.py", 9, "Skipped", "skip unconditionally"),
new TestInfo("test_skipif_not_skipped", "test_mark", "test_mark", "test_mark.py", 17, "Passed"),
new TestInfo("test_skipif_skipped", "test_mark", "test_mark", "test_mark.py", 13, "Skipped", "skip VAL == 1"),
// test_fixture.py
new TestInfo("test_data[0]", "test_fixture", "test_fixture", "test_fixture.py", 7, "Passed"),
new TestInfo("test_data[1]", "test_fixture", "test_fixture", "test_fixture.py", 7, "Passed"),
new TestInfo("test_data[3]", "test_fixture", "test_fixture", "test_fixture.py", 7, "Failed", "assert 3 != 3"),
};
private static TestInfo[] AllUnittests = new TestInfo[] {
new TestInfo("test_failure", "test1", "Test_test1", "test1.py", 4, "Failed", "Not implemented", new[] {
"", // skip the python version - see https://github.com/microsoft/PTVS/issues/5463
"test1.py\", line 11, in helper",
"self.fail('Not implemented')",
"test1.py\", line 5, in test_failure",
"self.helper()",
}),
new TestInfo("test_success", "test1", "Test_test1", "test1.py", 7, "Passed"),
};
public void RunAllUnittestProject(PythonVisualStudioApp app) {
var sln = app.CopyProjectForTest(@"TestData\TestExplorerUnittest.sln");
app.OpenProject(sln);
RunAllTests(app, AllUnittests);
}
public void RunAllUnittestWorkspace(PythonVisualStudioApp app) {
var workspaceFolderPath = PrepareWorkspace(
"unittest",
"TestExplorerUnittest",
TestData.GetPath("TestData", "TestExplorerUnittest")
);
app.OpenFolder(workspaceFolderPath);
RunAllTests(app, AllUnittests);
}
public void RunAllPytestProject(PythonVisualStudioApp app) {
var defaultSetter = new InterpreterWithPackageSetter(app.ServiceProvider, "pytest");
using (defaultSetter) {
var sln = app.CopyProjectForTest(@"TestData\TestExplorerPytest.sln");
app.OpenProject(sln);
RunAllTests(app, AllPytests);
}
}
public void DebugPytestProject(PythonVisualStudioApp app) {
var defaultSetter = new InterpreterWithPackageSetter(app.ServiceProvider, "pytest");
using (defaultSetter) {
var sln = app.CopyProjectForTest(@"TestData\TestExplorerPytest.sln");
var project = app.OpenProject(sln);
var test = AllPytests.First();
DebugTest(app, test, AllPytests);
}
}
public void DebugPytestWorkspace(PythonVisualStudioApp app) {
var defaultSetter = new InterpreterWithPackageSetter(app.ServiceProvider, "pytest");
using (defaultSetter) {
var workspaceFolderPath = PrepareWorkspace(
"pytest",
"TestExplorerPytest",
TestData.GetPath("TestData", "TestExplorerPytest")
);
app.OpenFolder(workspaceFolderPath);
var test = AllPytests.First();
DebugTest(app, test, AllPytests);
}
}
public void DebugUnittestWorkspace(PythonVisualStudioApp app) {
var workspaceFolderPath = PrepareWorkspace(
"unittest",
"TestExplorerUnittest",
TestData.GetPath("TestData", "TestExplorerUnittest")
);
app.OpenFolder(workspaceFolderPath);
var test = AllUnittests.First();
DebugTest(app, test, AllUnittests);
}
public void DebugUnittestProject(PythonVisualStudioApp app) {
var sln = app.CopyProjectForTest(@"TestData\TestExplorerUnittest.sln");
app.OpenProject(sln);
var test = AllUnittests.First();
DebugTest(app, test, AllUnittests);
}
public void RunAllPytestWorkspace(PythonVisualStudioApp app) {
var defaultSetter = new InterpreterWithPackageSetter(app.ServiceProvider, "pytest");
using (defaultSetter) {
var workspaceFolderPath = PrepareWorkspace(
"pytest",
"TestExplorerPytest",
TestData.GetPath("TestData", "TestExplorerPytest")
);
app.OpenFolder(workspaceFolderPath);
RunAllTests(app, AllPytests);
}
}
private static string PrepareWorkspace(string framework, string workspaceName, string sourceProjectFolderPath) {
// Create a workspace folder with test framework enabled and with the
// set of files from the source project folder
var workspaceFolderPath = Path.Combine(TestData.GetTempPath(), workspaceName);
Directory.CreateDirectory(workspaceFolderPath);
var pythonSettingsJson = "{\"TestFramework\": \"" + framework + " \"}";
File.WriteAllText(Path.Combine(workspaceFolderPath, "PythonSettings.json"), pythonSettingsJson);
foreach (var filePath in Directory.GetFiles(sourceProjectFolderPath, "*.py")) {
var destFilePath = Path.Combine(workspaceFolderPath, Path.GetFileName(filePath));
File.Copy(filePath, destFilePath, true);
}
return workspaceFolderPath;
}
private static void DebugTest(PythonVisualStudioApp app, TestInfo test, TestInfo[] tests) {
var testExplorer = app.OpenTestExplorer();
Assert.IsNotNull(testExplorer, "Could not open test explorer");
Console.WriteLine("Waiting for tests discovery");
app.WaitForOutputWindowText("Tests", $"discovery finished: {tests.Length} Tests found", 15_000);
testExplorer.GroupByProjectNamespaceClass();
var item = testExplorer.WaitForItem(test.Path);
Assert.IsNotNull(item, $"Coult not find {string.Join(":", test.Path)}");
var breakLineno = test.SourceLine + 1;
app.Dte.Debugger.Breakpoints.Add(File: test.SourceFile, Line: breakLineno);
Console.WriteLine($"Debugging test {test.Name}");
testExplorer.DebugAll();
app.WaitForMode(EnvDTE.dbgDebugMode.dbgBreakMode);
Assert.IsNotNull(app.Dte.Debugger.BreakpointLastHit);
Assert.AreEqual(breakLineno, app.Dte.Debugger.BreakpointLastHit.FileLine);
app.Dte.Debugger.Stop(WaitForDesignMode: true);
}
private static void RunAllTests(PythonVisualStudioApp app, TestInfo[] tests) {
var testExplorer = app.OpenTestExplorer();
Assert.IsNotNull(testExplorer, "Could not open test explorer");
Console.WriteLine("Waiting for tests discovery");
app.WaitForOutputWindowText("Tests", $"discovery finished: {tests.Length} Tests found", 15_000);
testExplorer.GroupByProjectNamespaceClass();
foreach (var test in tests) {
var item = testExplorer.WaitForItem(test.Path);
Assert.IsNotNull(item, $"Coult not find {string.Join(":", test.Path)}");
}
Console.WriteLine("Running all tests");
testExplorer.RunAll(TimeSpan.FromSeconds(10));
app.WaitForOutputWindowText("Tests", $"Run finished: {tests.Length} tests run", 10_000);
foreach (var test in tests) {
var item = testExplorer.WaitForItem(test.Path);
Assert.IsNotNull(item, $"Coult not find {string.Join(":", test.Path)}");
item.Select();
item.SetFocus();
var actualDetails = testExplorer.GetDetailsWithRetry();
AssertUtil.Contains(actualDetails, $"Test Name: {test.Name}");
AssertUtil.Contains(actualDetails, $"Test Outcome: {test.Outcome}");
AssertUtil.Contains(actualDetails, $"{test.SourceFile} : line {test.SourceLine}");
if (test.ResultMessage != null) {
AssertUtil.Contains(actualDetails, $"{resultMessageSection} {test.ResultMessage}");
}
if (test.CallStack != null) {
var actualStack = ParseCallStackFromResultDetails(actualDetails);
Assert.AreEqual(test.CallStack.Length, actualStack.Length, "Unexpected stack depth.");
for (int i = 0; i < test.CallStack.Length; i++) {
AssertUtil.Contains(actualStack[i], test.CallStack[i]);
}
}
}
}
private static string[] ParseCallStackFromResultDetails(string details) {
int startIndex = details.IndexOf(resultStackTraceSection);
if (startIndex < 0) {
Assert.Fail("Stack trace was expected but not found in test result details");
}
// There's always a message section when there's an error,
// and that marks the end of the stack trace section.
startIndex += resultStackTraceSection.Length;
int endIndex = details.IndexOf(resultMessageSection, startIndex);
if (endIndex < 0) {
Assert.Fail("Message section was expected but not found in test result details");
}
return details
.Substring(startIndex, endIndex - startIndex)
.Trim()
.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
}
class TestInfo {
public TestInfo(string name, string project, string classOrModule, string sourceFile, int sourceLine, string outcome, string resultMessage = null, string[] callStack = null) {
Name = name;
Project = project;
ClassOrModule = classOrModule;
SourceFile = sourceFile;
SourceLine = sourceLine;
Outcome = outcome;
ResultMessage = resultMessage;
CallStack = callStack;
Path = new string[] { Project, SourceFile, ClassOrModule, Name };
}
public string Name { get; }
public string Project { get; }
public string ClassOrModule { get; }
public string SourceFile { get; }
public int SourceLine { get; }
public string Outcome { get; }
public string ResultMessage { get; }
public string[] Path { get; }
public string[] CallStack { get; }
}
}
}
| |
//Copyright 2014 Spin Services Limited
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Policy;
using SS.Integration.Common.Extensions;
namespace SS.Integration.Adapter.Model
{
/// <summary>
/// This class represents a market as it comes within
/// a (delta/full)-snasphot.
///
/// As delta snapshots don't have the tag section,
/// some properties don't have a valid value when
/// the object is created from a delta snapshot.
/// </summary>
[Serializable]
public class Market
{
private readonly Dictionary<string, string> _tags;
protected List<Selection> _selections;
public Market(string Id)
: this()
{
this.Id = Id;
}
public Market()
{
_tags = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
_selections = new List<Selection> ();
}
/// <summary>
/// Market's name. Not present if
/// the snapshot is a delta snapshot
/// </summary>
[IgnoreDataMember]
public string Name
{
get
{
return GetTagValue("name");
}
}
/// <summary>
/// Market's type. This information
/// is not present if this object
/// is coming from a delta-snapshot.
/// </summary>
[IgnoreDataMember]
public string Type
{
get
{
return GetTagValue("type");
}
}
/// <summary>
/// Market's Id
/// </summary>
public string Id { get; set; }
public Rule4[] Rule4s { get; set; }
/// <summary>
/// Determines if the market is an
/// over-under market by looking a the tags.
///
/// Information not available on a delta snapshot
/// </summary>
[IgnoreDataMember]
public bool IsOverUnder
{
get
{
return Selections.Any(s => s.HasTag("identifier") && string.Equals(s.GetTagValue("identifier"), "over", StringComparison.OrdinalIgnoreCase));
}
}
/// <summary>
/// Determines if the market can be traded in play.
///
/// The information is always available
/// </summary>
public bool IsTradedInPlay { get; set; }
/// <summary>
/// Returns true if the market is active.
///
/// This information is always available and it is computed
/// by looking a the selections' states and
/// theirs tradability values.
/// </summary>
public bool IsActive { get; set; }
/// <summary>
/// Returns true if the market is suspended.
///
/// Please note that this value only make sense
/// when IsActive is true.
///
/// This value is always present.
/// </summary>
public bool IsSuspended { get; set; }
/// <summary>
/// Determines if the market has been
/// resulted on the Connect platform.
///
/// The value is always present and it
/// is computed by looking at the selections'
/// states and theirs tradability values
/// </summary>
public bool IsResulted { get; set; }
/// <summary>
/// Determines if the market has at least
/// one voided selection.
///
/// The value is always present and it is
/// computed by looking at all the selections'
/// states (included selections that are
/// not currently contained within this
/// object)
/// </summary>
public bool IsVoided { get; set; }
/// <summary>
/// Determines if the market is in a pending state.
///
/// This information is always present and it is
/// computed by looking at the selections's states.
/// </summary>
public bool IsPending { get; set; }
/// <summary>
/// Returns the selections's for this market
/// as they are contained within the snapshot.
/// </summary>
public virtual List<Selection> Selections
{
get { return _selections; }
protected set { _selections = value; }
}
#region Tags
/// <summary>
/// Determines if the market has the given tag.
///
/// If this object has been created from a delta snapshot,
/// this method always returns false.
/// </summary>
/// <param name="tagKey"></param>
/// <param name="keyCaseSensitive"></param>
/// <returns></returns>
public bool HasTag(string tagKey) => HasTag(tagKey, true);
public bool HasTag(string tagKey, bool keyCaseSensitive) => !string.IsNullOrEmpty(tagKey) && _tags.FindKey(tagKey, keyCaseSensitive) != null;
/// <summary>
/// Returns the value of the given tag.
/// Null if the tag doesn't exist.
/// </summary>
/// <param name="tagKey"></param>
/// <param name="keyCaseSensitive"></param>
/// <returns></returns>
public string GetTagValue(string tagKey) => GetTagValue(tagKey, true);
public string GetTagValue(string tagKey, bool keyCaseSensitive) => _tags.GetValue(tagKey, keyCaseSensitive);
public bool IsTagValueMatch(string tagKey, string value, bool valueCaseSensitive = false, bool keyCaseSensitive = true)
=> _tags.IsValueMatch(tagKey, value, valueCaseSensitive, keyCaseSensitive);
/// <summary>
/// Allows to add/update a tag
/// </summary>
/// <param name="tagKey">Must not be empty or null</param>
/// <param name="tagValue"></param>
/// <param name="keyCaseSensitive"></param>
public void AddOrUpdateTagValue(string tagKey, string tagValue) => AddOrUpdateTagValue(tagKey, tagValue, true);
public void AddOrUpdateTagValue(string tagKey, string tagValue, bool keyCaseSensitive) => _tags.AddOrUpdateValue(tagKey, tagValue, keyCaseSensitive);
/// <summary>
/// Returns the list of all tags
/// </summary>
[IgnoreDataMember]
public IEnumerable<string> TagKeys
{
get
{
return _tags.Keys;
}
}
/// <summary>
/// Returns the number of tags contained
/// within this object.
/// </summary>
[IgnoreDataMember]
public int TagsCount
{
get
{
return _tags.Count;
}
}
/// <summary>
/// Deprecated, use the API interface to deal with tags
/// </summary>
[Obsolete("Use Tag interface to deal with tags", false)]
public Dictionary<string, string> Tags
{
get
{
return _tags;
}
}
#endregion
public override string ToString()
{
string format = "Market marketId={0}";
if (!string.IsNullOrEmpty(this.Name))
{
format += " marketName=\"{1}\"";
return string.Format(format, this.Id, this.Name);
}
return string.Format(format, this.Id);
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using Microsoft.Win32;
using Dullware.Library;
public class Houston : DullForm
{
static System.Diagnostics.FileVersionInfo info = System.Diagnostics.FileVersionInfo.GetVersionInfo(Application.ExecutablePath);
public static string regKeyString = string.Format(@"Software\DullWare\{0}", Application.ProductName);
public static string HoustonVersion = string.Format("{0}.{1} (Build {2})", info.ProductMajorPart, info.ProductMinorPart, info.ProductBuildPart);
public System.Windows.Forms.StatusBar SB;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.Splitter splitter1;
public System.Windows.Forms.ListView jobslistview;
private System.Windows.Forms.TabPage tabInput;
private System.Windows.Forms.TabPage tabLog;
private System.Windows.Forms.MenuStrip mMenu;
private System.Windows.Forms.ToolStripMenuItem mFile;
private System.Windows.Forms.ToolStripMenuItem mFileNew;
private System.Windows.Forms.ToolStripMenuItem mFileOpen;
private System.Windows.Forms.ToolStripMenuItem mFileClose;
private System.Windows.Forms.ToolStripMenuItem mFileSave;
private System.Windows.Forms.ToolStripMenuItem mFileSaveAs;
private System.Windows.Forms.ToolStripMenuItem mControl;
private System.Windows.Forms.ToolStripMenuItem mControlAbort;
private System.Windows.Forms.ToolStripMenuItem mFileExit;
private System.Windows.Forms.ToolStripMenuItem mEdit;
private System.Windows.Forms.ToolStripMenuItem mControlSchedule;
private System.Windows.Forms.ToolStripMenuItem mControlQueue;
private System.Windows.Forms.ToolStripMenuItem mControlDequeue;
private System.Windows.Forms.ToolStripMenuItem mControlUnschedule;
private System.Windows.Forms.ToolStripMenuItem mFileRevert;
public System.Windows.Forms.TextBox logBox;
private System.Windows.Forms.Splitter splitter2;
private System.Windows.Forms.ToolStripMenuItem mEditCut;
private System.Windows.Forms.ToolStripMenuItem mEditCopy;
private System.Windows.Forms.ToolStripMenuItem mEditPaste;
private System.Windows.Forms.ToolStripMenuItem mEditUndo;
private System.Windows.Forms.ToolStripMenuItem mControlCheckInputFile;
private System.Windows.Forms.ToolStripMenuItem menuItem9;
private System.Windows.Forms.ToolStripMenuItem mEditSelectAll;
private System.Windows.Forms.ContextMenuStrip CMJob;
private System.Windows.Forms.ToolStripMenuItem cmControlQueue;
private System.Windows.Forms.ToolStripMenuItem cmControlDequeue;
private System.Windows.Forms.ToolStripMenuItem cmControlAbort;
private System.Windows.Forms.ToolStripMenuItem cmControlSchedule;
private System.Windows.Forms.ToolStripMenuItem cmControlUnschedule;
private System.Windows.Forms.ToolStripMenuItem cmControlCheckInput;
private System.Windows.Forms.ToolBar tBar;
private System.Windows.Forms.ToolStripMenuItem mControlPrefetch;
private System.Windows.Forms.ToolStripMenuItem cmControlPrefetch;
private Scheduler sched, netsched;
private System.Windows.Forms.ToolStripMenuItem mHelp;
private System.Windows.Forms.ToolStripMenuItem mHelpRemoteJobs;
private System.Windows.Forms.ToolStripMenuItem cmControlRemoveEntry;
private System.Windows.Forms.ToolStripMenuItem mControlQueueNetwork;
private System.Windows.Forms.ToolStripMenuItem cmControlQueueNetwork;
private System.Windows.Forms.ToolStripMenuItem mControlNetworkSchedule;
private System.Windows.Forms.ToolStripMenuItem cmControlNetworkSchedule;
[STAThread]
static void Main()
{
//Application.EnableVisualStyles();
//Application.Run(new Houston());
NewFormRequest += new NewFormEventHandler(Houston_NewFormRequest);
Run(null, new StartupCheck(Verify), true);
}
static void Houston_NewFormRequest(NewFormEventArgs frea)
{
frea.form = new Houston();
}
public Houston()
{
Icon = new Icon(GetType(), "Houston.Houston.ico");
Init();
}
static bool Verify()
{ // the first `true' disables `phone home'
bool ok = true || System.Net.Dns.GetHostName() == "huiskamerq" || System.Net.Dns.GetHostName() == "qatv-pcc-03006" || System.Net.Dns.GetHostName() == "qkleinepc" || (new StartupScreen()).ShowDialog() == DialogResult.OK;
return ok;
}
void Init()
{
this.SB = new System.Windows.Forms.StatusBar();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabInput = new System.Windows.Forms.TabPage();
this.tabLog = new System.Windows.Forms.TabPage();
this.splitter1 = new System.Windows.Forms.Splitter();
this.jobslistview = new System.Windows.Forms.ListView();
this.CMJob = new System.Windows.Forms.ContextMenuStrip();
this.cmControlQueue = new System.Windows.Forms.ToolStripMenuItem();
this.cmControlQueueNetwork = new System.Windows.Forms.ToolStripMenuItem();
this.cmControlDequeue = new System.Windows.Forms.ToolStripMenuItem();
this.cmControlPrefetch = new System.Windows.Forms.ToolStripMenuItem();
this.cmControlAbort = new System.Windows.Forms.ToolStripMenuItem();
this.cmControlRemoveEntry = new System.Windows.Forms.ToolStripMenuItem();
this.cmControlSchedule = new System.Windows.Forms.ToolStripMenuItem();
this.cmControlNetworkSchedule = new System.Windows.Forms.ToolStripMenuItem();
this.cmControlUnschedule = new System.Windows.Forms.ToolStripMenuItem();
this.cmControlCheckInput = new System.Windows.Forms.ToolStripMenuItem();
this.mMenu = new System.Windows.Forms.MenuStrip();
this.mFile = new System.Windows.Forms.ToolStripMenuItem();
this.mFileNew = new System.Windows.Forms.ToolStripMenuItem();
this.mFileOpen = new System.Windows.Forms.ToolStripMenuItem();
this.mFileClose = new System.Windows.Forms.ToolStripMenuItem();
this.mFileSave = new System.Windows.Forms.ToolStripMenuItem();
this.mFileSaveAs = new System.Windows.Forms.ToolStripMenuItem();
this.mFileRevert = new System.Windows.Forms.ToolStripMenuItem();
this.mFileExit = new System.Windows.Forms.ToolStripMenuItem();
this.mEdit = new System.Windows.Forms.ToolStripMenuItem();
this.mEditUndo = new System.Windows.Forms.ToolStripMenuItem();
this.mEditCut = new System.Windows.Forms.ToolStripMenuItem();
this.mEditCopy = new System.Windows.Forms.ToolStripMenuItem();
this.mEditPaste = new System.Windows.Forms.ToolStripMenuItem();
this.mEditSelectAll = new System.Windows.Forms.ToolStripMenuItem();
this.mControl = new ToolStripMenuItem();
this.mControlQueue = new System.Windows.Forms.ToolStripMenuItem();
this.mControlQueueNetwork = new System.Windows.Forms.ToolStripMenuItem();
this.mControlDequeue = new System.Windows.Forms.ToolStripMenuItem();
this.mControlPrefetch = new System.Windows.Forms.ToolStripMenuItem();
this.mControlAbort = new System.Windows.Forms.ToolStripMenuItem();
this.mControlSchedule = new System.Windows.Forms.ToolStripMenuItem();
this.mControlNetworkSchedule = new System.Windows.Forms.ToolStripMenuItem();
this.mControlUnschedule = new System.Windows.Forms.ToolStripMenuItem();
this.mControlCheckInputFile = new System.Windows.Forms.ToolStripMenuItem();
this.mHelp = new System.Windows.Forms.ToolStripMenuItem();
this.menuItem9 = new System.Windows.Forms.ToolStripMenuItem();
this.mHelpRemoteJobs = new System.Windows.Forms.ToolStripMenuItem();
this.logBox = new System.Windows.Forms.TextBox();
this.splitter2 = new System.Windows.Forms.Splitter();
this.tBar = new System.Windows.Forms.ToolBar();
this.tabControl1.SuspendLayout();
this.SuspendLayout();
//
// SB
//
this.SB.Location = new System.Drawing.Point(0, 594);
this.SB.Name = "SB";
this.SB.Size = new System.Drawing.Size(840, 22);
this.SB.TabIndex = 0;
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabInput);
this.tabControl1.Controls.Add(this.tabLog);
this.tabControl1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.tabControl1.Location = new System.Drawing.Point(0, 199);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(840, 272);
this.tabControl1.TabIndex = 1;
//
// tabInput
//
this.tabInput.BackColor = System.Drawing.SystemColors.Window;
this.tabInput.Location = new System.Drawing.Point(4, 22);
this.tabInput.Name = "tabInput";
this.tabInput.Size = new System.Drawing.Size(832, 246);
this.tabInput.TabIndex = 0;
this.tabInput.Text = "Input File";
//
// tabLog
//
this.tabLog.BackColor = System.Drawing.SystemColors.Window;
this.tabLog.Location = new System.Drawing.Point(4, 22);
this.tabLog.Name = "tabLog";
this.tabLog.Size = new System.Drawing.Size(832, 246);
this.tabLog.TabIndex = 1;
this.tabLog.Text = "Log File";
//
// splitter1
//
this.splitter1.BackColor = System.Drawing.SystemColors.Control;
this.splitter1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.splitter1.Location = new System.Drawing.Point(0, 196);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(840, 3);
this.splitter1.TabIndex = 2;
this.splitter1.TabStop = false;
//
// jobs
//
this.jobslistview.BackColor = System.Drawing.SystemColors.Window;
this.jobslistview.ContextMenuStrip = this.CMJob;
this.jobslistview.Dock = System.Windows.Forms.DockStyle.Fill;
this.jobslistview.FullRowSelect = true;
this.jobslistview.GridLines = true;
this.jobslistview.HideSelection = false;
this.jobslistview.Location = new System.Drawing.Point(0, 28);
this.jobslistview.MultiSelect = false;
this.jobslistview.Name = "jobs";
this.jobslistview.Size = new System.Drawing.Size(840, 168);
this.jobslistview.TabIndex = 3;
this.jobslistview.View = System.Windows.Forms.View.Details;
this.jobslistview.DoubleClick += new System.EventHandler(this.jobs_DoubleClick);
this.jobslistview.SelectedIndexChanged += new System.EventHandler(this.jobs_SelectedIndexChanged);
//
// CMJob
//
if (Application.ProductName == "Houston")
{
this.CMJob.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.cmControlQueue,
this.cmControlQueueNetwork,
this.cmControlDequeue,
new ToolStripSeparator(),
this.cmControlPrefetch,
this.cmControlAbort,
this.cmControlRemoveEntry,
new ToolStripSeparator(),
this.cmControlSchedule,
this.cmControlNetworkSchedule,
this.cmControlUnschedule,
new ToolStripSeparator(),
this.cmControlCheckInput});
}
else
{
this.CMJob.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.cmControlQueueNetwork,
this.cmControlDequeue,
new ToolStripSeparator(),
this.cmControlPrefetch,
this.cmControlAbort,
this.cmControlRemoveEntry,
new ToolStripSeparator(),
this.cmControlNetworkSchedule,
this.cmControlUnschedule,
new ToolStripSeparator(),
this.cmControlCheckInput});
}
this.CMJob.Opened += new System.EventHandler(this.mControl_Popup);
//
// cmControlQueue
//
this.cmControlQueue.Text = "&Queue";
this.cmControlQueue.Click += new System.EventHandler(this.mControlQueue_Click);
//
// cmControlQueueNetwork
//
this.cmControlQueueNetwork.Text = "Queue on Network";
this.cmControlQueueNetwork.Click += new System.EventHandler(this.mControlQueueNetwork_Click);
//
// cmControlDequeue
//
this.cmControlDequeue.Text = "&Dequeue";
this.cmControlDequeue.Click += new System.EventHandler(this.mControlDequeue_Click);
//
// cmControlPrefetch
//
this.cmControlPrefetch.Text = "&Prefetch Output";
this.cmControlPrefetch.Click += new System.EventHandler(this.mControlPrefetch_Click);
//
// cmControlAbort
//
this.cmControlAbort.Text = "&Abort";
this.cmControlAbort.Click += new System.EventHandler(this.mControlAbort_Click);
//
// cmControlRemoveEntry
//
this.cmControlRemoveEntry.Text = "&Remove entry";
this.cmControlRemoveEntry.Click += new System.EventHandler(this.mFileClose_Click);
//
// cmControlSchedule
//
this.cmControlSchedule.Text = "&Schedule";
this.cmControlSchedule.Click += new System.EventHandler(this.mControlSchedule_Click);
//
// cmControlNetworkSchedule
//
this.cmControlNetworkSchedule.Text = "Sc&hedule on Network";
this.cmControlNetworkSchedule.Click += new System.EventHandler(this.mControlScheduleNetwork_Click);
//
// cmControlUnschedule
//
this.cmControlUnschedule.Text = "&Unschedule";
this.cmControlUnschedule.Click += new System.EventHandler(this.mControlUnschedule_Click);
//
// cmControlCheckInput
//
this.cmControlCheckInput.Text = "&Check Input";
this.cmControlCheckInput.Click += new System.EventHandler(this.mControlCheckInputFile_Click);
//
// mMenu
//
this.mMenu.Items.AddRange(new System.Windows.Forms.ToolStripMenuItem[] {
this.mFile,
this.mEdit,
this.mControl,
HelpMenu});
//
// mFile
//
this.mFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mFileNew,
this.mFileOpen,
this.mFileClose,
new ToolStripSeparator(),
this.mFileSave,
this.mFileSaveAs,
this.mFileRevert,
new ToolStripSeparator(),
this.mFileExit});
this.mFile.Text = "&File";
this.mFile.DropDownOpening += new System.EventHandler(this.mFile_Popup);
this.mFile.DropDownClosed += new EventHandler(mDropDownClosed);
//
// mFileNew
//
this.mFileNew.ShortcutKeys = Keys.Control | Keys.N;
this.mFileNew.Text = "&New";
this.mFileNew.Click += new System.EventHandler(this.mFileNew_Click);
//
// mFileOpen
//
this.mFileOpen.ShortcutKeys = Keys.Control | Keys.O;
this.mFileOpen.Text = "&Open...";
this.mFileOpen.Click += new System.EventHandler(this.mFileOpen_Click);
//
// mFileClose
//
this.mFileClose.ShortcutKeys = Keys.Control | Keys.W; ;
this.mFileClose.Text = "&Close";
this.mFileClose.Click += new System.EventHandler(this.mFileClose_Click);
//
// mFileSave
//
this.mFileSave.ShortcutKeys = Keys.Control | Keys.S;
this.mFileSave.Text = "&Save";
this.mFileSave.Click += new System.EventHandler(this.mFileSave_Click);
//
// mFileSaveAs
//
this.mFileSaveAs.Text = "Save &As...";
this.mFileSaveAs.Click += new System.EventHandler(this.mFileSaveAs_Click);
//
// mFileRevert
//
this.mFileRevert.Text = "&Revert";
this.mFileRevert.Click += new System.EventHandler(this.mFileRevert_Click);
//
// mFileExit
//
this.mFileExit.ShortcutKeys = Keys.Control | Keys.Q;
this.mFileExit.Text = "E&xit";
this.mFileExit.Click += new System.EventHandler(this.mFileExit_Click);
//
// mEdit
//
this.mEdit.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mEditUndo,
new ToolStripSeparator(),
this.mEditCut,
this.mEditCopy,
this.mEditPaste,
new ToolStripSeparator(),
this.mEditSelectAll});
this.mEdit.Text = "&Edit";
this.mEdit.DropDownOpening += new System.EventHandler(this.mEdit_Popup);
this.mEdit.DropDownClosed += new EventHandler(mDropDownClosed);
//
// mEditUndo
//
this.mEditUndo.ShortcutKeys = Keys.Control | Keys.Z;
this.mEditUndo.Text = "&Undo";
this.mEditUndo.Click += new System.EventHandler(this.mEditUndo_Click);
//
// mEditCut
//
this.mEditCut.ShortcutKeys = Keys.Control | Keys.X;
this.mEditCut.Text = "Cu&t";
this.mEditCut.Click += new System.EventHandler(this.mEditCut_Click);
//
// mEditCopy
//
this.mEditCopy.ShortcutKeys = Keys.Control | Keys.C;
this.mEditCopy.Text = "&Copy";
this.mEditCopy.Click += new System.EventHandler(this.mEditCopy_Click);
//
// mEditPaste
//
this.mEditPaste.ShortcutKeys = Keys.Control | Keys.V;
this.mEditPaste.Text = "&Paste";
this.mEditPaste.Click += new System.EventHandler(this.mEditPaste_Click);
//
// mEditSelectAll
//
this.mEditSelectAll.ShortcutKeys = Keys.Control | Keys.A;
this.mEditSelectAll.Text = "Select &All";
this.mEditSelectAll.Click += new System.EventHandler(this.mEditSelectAll_Click);
//
// mControl
//
if (Application.ProductName == "Houston")
{
this.mControl.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mControlQueue,
this.mControlQueueNetwork,
this.mControlDequeue,
new ToolStripSeparator(),
this.mControlPrefetch,
this.mControlAbort,
new ToolStripSeparator(),
this.mControlSchedule,
this.mControlNetworkSchedule,
this.mControlUnschedule,
new ToolStripSeparator(),
this.mControlCheckInputFile});
}
else
{
this.mControl.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mControlQueueNetwork,
this.mControlDequeue,
new ToolStripSeparator(),
this.mControlPrefetch,
this.mControlAbort,
new ToolStripSeparator(),
this.mControlNetworkSchedule,
this.mControlUnschedule,
new ToolStripSeparator(),
this.mControlCheckInputFile});
}
this.mControl.Text = "&Control";
this.mControl.DropDownOpening += new System.EventHandler(this.mControl_Popup);
this.mControl.DropDownClosed += new EventHandler(mDropDownClosed);
//
// mControlQueue
//
this.mControlQueue.ShortcutKeys = Keys.F5;
this.mControlQueue.Text = "&Queue for Immediate Start";
this.mControlQueue.Click += new System.EventHandler(this.mControlQueue_Click);
//
// mControlQueueNetwork
//
this.mControlQueueNetwork.ShortcutKeys = Keys.F6;
this.mControlQueueNetwork.Text = "Queue for Immediate &Network Start";
this.mControlQueueNetwork.Click += new System.EventHandler(this.mControlQueueNetwork_Click);
//
// mControlDequeue
//
this.mControlDequeue.ShortcutKeys = Keys.F4;
this.mControlDequeue.Text = "&Dequeue";
this.mControlDequeue.Click += new System.EventHandler(this.mControlDequeue_Click);
//
// mControlPrefetch
//
this.mControlPrefetch.Text = "&Prefetch Output";
this.mControlPrefetch.Click += new System.EventHandler(this.mControlPrefetch_Click);
//
// mControlAbort
//
this.mControlAbort.ShortcutKeys = Keys.Control | Keys.Shift | Keys.F5;
this.mControlAbort.Text = "&Abort";
this.mControlAbort.Click += new System.EventHandler(this.mControlAbort_Click);
//
// mControlSchedule
//
this.mControlSchedule.ShortcutKeys = Keys.Control | Keys.F5;
this.mControlSchedule.Text = "&Schedule Queuing...";
this.mControlSchedule.Click += new System.EventHandler(this.mControlSchedule_Click);
//
// mControlNetworkSchedule
//
this.mControlNetworkSchedule.ShortcutKeys = Keys.Control | Keys.F6;
this.mControlNetworkSchedule.Text = "Sc&hedule Network Queuing...";
this.mControlNetworkSchedule.Click += new System.EventHandler(this.mControlScheduleNetwork_Click);
//
// mControlUnschedule
//
this.mControlUnschedule.ShortcutKeys = Keys.Control | Keys.F4;
this.mControlUnschedule.Text = "&Unschedule";
this.mControlUnschedule.Click += new System.EventHandler(this.mControlUnschedule_Click);
//
// mControlCheckInputFile
//
this.mControlCheckInputFile.ShortcutKeys = Keys.Control | Keys.K;
this.mControlCheckInputFile.Text = "&Check Input File";
this.mControlCheckInputFile.Click += new System.EventHandler(this.mControlCheckInputFile_Click);
//
// mHelp
//
this.mHelp.DropDownItems.AddRange(new System.Windows.Forms.ToolStripMenuItem[] {
this.menuItem9});
this.mHelp.DropDownClosed += new EventHandler(mDropDownClosed);
this.mHelp.Text = "&Help";
//
// menuItem9
//
this.menuItem9.Text = "A&bout...";
this.menuItem9.Click += new System.EventHandler(this.menuItem9_Click);
//
// logBox
//
this.logBox.AcceptsReturn = true;
this.logBox.AcceptsTab = true;
this.logBox.Dock = System.Windows.Forms.DockStyle.Bottom;
this.logBox.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.logBox.Location = new System.Drawing.Point(0, 474);
this.logBox.Multiline = true;
this.logBox.Name = "logBox";
this.logBox.ReadOnly = true;
this.logBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.logBox.Size = new System.Drawing.Size(840, 120);
this.logBox.TabIndex = 4;
this.logBox.Text = "";
//
// splitter2
//
this.splitter2.Dock = System.Windows.Forms.DockStyle.Bottom;
this.splitter2.Location = new System.Drawing.Point(0, 471);
this.splitter2.Name = "splitter2";
this.splitter2.Size = new System.Drawing.Size(840, 3);
this.splitter2.TabIndex = 5;
this.splitter2.TabStop = false;
//
// tBar
//
this.tBar.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
this.tBar.ButtonSize = new System.Drawing.Size(23, 22);
this.tBar.DropDownArrows = true;
this.tBar.Location = new System.Drawing.Point(0, 0);
this.tBar.Name = "tBar";
this.tBar.ShowToolTips = true;
this.tBar.Size = new System.Drawing.Size(840, 28);
this.tBar.TabIndex = 6;
//
// Houston
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.SystemColors.Window;
this.ClientSize = new System.Drawing.Size(840, 616);
this.Controls.Add(this.jobslistview);
this.Controls.Add(this.splitter1);
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.splitter2);
this.Controls.Add(this.logBox);
this.Controls.Add(this.SB);
this.Controls.Add(this.tBar);
this.Controls.Add(this.mMenu);
this.ForeColor = System.Drawing.SystemColors.WindowText;
this.Name = Application.ProductName;
this.Text = Application.ProductName;
this.tabControl1.ResumeLayout(false);
this.ResumeLayout(false);
}
void mDropDownClosed(object sender, EventArgs e)
{
ToolStripMenuItem menu = sender as ToolStripMenuItem;
foreach (ToolStripItem it in menu.DropDownItems)
{
if (it is ToolStripMenuItem) it.Enabled = true;
}
}
protected override void OnLoad(EventArgs ea)
{
base.OnLoad(ea);
//if (!Verify())
//{
// Close();
// return;
//}
SetupJobView();
sched = new Scheduler(this.jobslistview);
netsched = new Scheduler(this.jobslistview);
logBox.SelectionStart = 0;
logBox.AppendText(string.Format("{0} this is {1} {2}\r\n", DateTime.Now, Application.ProductName, HoustonVersion));
if (!System.Environment.OSVersion.ToString().StartsWith("Microsoft Windows NT"))
{
logBox.AppendText(DateTime.Now + " this program only runs on Windows NT, 2k or XP\r\n");
mControl.Enabled = false;
}
DocumentName = "Control Center";
}
private void SetupJobView()
{
string[] disp = Enum.GetNames(typeof(Display));
for (int i = 0; i < disp.Length; i++)
{
switch (disp[i])
{
case "name":
jobslistview.Columns.Add("Job", 150, HorizontalAlignment.Left);
break;
case "start":
jobslistview.Columns.Add("Start", 80, HorizontalAlignment.Left);
break;
case "stop":
jobslistview.Columns.Add("Stop", 80, HorizontalAlignment.Left);
break;
case "stat":
jobslistview.Columns.Add("Status", 80, HorizontalAlignment.Left);
break;
case "cpu":
jobslistview.Columns.Add("CPU", 80, HorizontalAlignment.Left);
break;
case "mem":
jobslistview.Columns.Add("Memory", 80, HorizontalAlignment.Left);
break;
case "prio":
jobslistview.Columns.Add("Priority", 80, HorizontalAlignment.Left);
break;
case "dir":
jobslistview.Columns.Add("Folder", 200, HorizontalAlignment.Left);
break;
case "where":
jobslistview.Columns.Add("Where", 80, HorizontalAlignment.Left);
break;
default:
MessageBox.Show("Display enum item not found: " + disp[i]);
break;
}
}
}
private bool EnabledFileItem(ToolStripMenuItem toolStripMenuItem)
{
mFile_Popup(toolStripMenuItem, EventArgs.Empty);
bool enabled = toolStripMenuItem.Enabled;
mDropDownClosed(mFile, EventArgs.Empty);
return enabled;
}
private bool EnabledEditItem(ToolStripMenuItem toolStripMenuItem)
{
mEdit_Popup(toolStripMenuItem, EventArgs.Empty);
bool enabled = toolStripMenuItem.Enabled;
mDropDownClosed(mEdit, EventArgs.Empty);
return enabled;
}
private bool EnabledControlItem(ToolStripMenuItem toolStripMenuItem)
{
mControl_Popup(toolStripMenuItem, EventArgs.Empty);
bool enabled = toolStripMenuItem.Enabled;
mDropDownClosed(mControl, EventArgs.Empty);
return enabled;
}
private void mFile_Popup(object sender, System.EventArgs e)
{
mFileNew.Enabled = true;
mFileOpen.Enabled = true;
mFileClose.Enabled = false;
mFileSave.Enabled = false;
mFileSaveAs.Enabled = false;
mFileRevert.Enabled = false;
mFileExit.Enabled = true;
if (jobslistview.SelectedIndices.Count == 1)
{
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
mFileClose.Enabled = true;
if (je.InputChanged() || je._inputFile.Untitled)
mFileSave.Enabled = true;
mFileSaveAs.Enabled = true;
mFileRevert.Enabled = je.InputChanged() && !je._inputFile.Untitled;
}
}
private void mFileNew_Click(object sender, System.EventArgs e)
{
if (!EnabledFileItem(sender as ToolStripMenuItem)) return;
JobEntry je = new JobEntry(this, tabControl1, tabInput, tabLog);
jobslistview.BeginUpdate();
jobslistview.Items.Add(je);
if (je.AddNewJob())
{
je.SetStatus(Status.idle);
this.tabControl1.SelectedTab = tabInput;
je.Selected = true;
}
else
{
jobslistview.Items.Remove(je);
}
jobslistview.EndUpdate();
}
//private void mFileOpen_Click(object sender, System.EventArgs e)
//{
// JobEntry je = new JobEntry(this, tabControl1, tabInput, tabLog);
// jobs.BeginUpdate();
// jobs.Items.Add(je);
// if (je.OpenInputFile())
// {
// je.SetStatus(Status.idle);
// this.tabControl1.SelectedTab = tabInput;
// je.Selected = true;
// }
// else
// {
// jobs.Items.Remove(je);
// }
// jobs.EndUpdate();
//}
private void mFileOpen_Click(object sender, System.EventArgs e)
{
if (!EnabledFileItem(sender as ToolStripMenuItem)) return;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Input Files (*.in,*.txt)|*.in;*.txt|All Files (*.*)|*.*";
ofd.Multiselect = true;
if (ofd.ShowDialog(this) == DialogResult.OK)
{
foreach (string fn in ofd.FileNames)
{
JobEntry je = new JobEntry(this, tabControl1, tabInput, tabLog);
jobslistview.BeginUpdate();
jobslistview.Items.Add(je);
if (je.OpenInputFile(fn))
{
je.SetStatus(Status.idle);
this.tabControl1.SelectedTab = tabInput;
je.Selected = true;
}
else
{
jobslistview.Items.Remove(je);
}
jobslistview.EndUpdate();
}
}
ofd.Dispose();
}
private void mFileClose_Click(object sender, System.EventArgs e)
{
if (!EnabledFileItem(sender as ToolStripMenuItem)) return;
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
int idx = jobslistview.Items.IndexOf(je);
if (je.stat == Status.running)
{
MessageBox.Show("Cannot close a running job.", "Job Running", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
if (je._inputFile.CloseWindow(je.InputChanged()))
{
je.WriteToLog("removed from the job list");
tabInput.Text = tabInput.Text.TrimEnd(new char[] { ' ', '*' });
jobslistview.Items.Remove(je);
//je._fileWatch -= FileChanged_Handler;
je._fileWatch.Dispose();
je.Dispose();
if (jobslistview.Items.Count > 0)
{
if (jobslistview.Items.Count >= idx) idx = jobslistview.Items.Count - 1;
jobslistview.Items[idx].Selected = true;
}
}
}
private void mFileSave_Click(object sender, System.EventArgs e)
{
if (!EnabledFileItem(sender as ToolStripMenuItem)) return;
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
je.SaveInputFile();
if (je.stat == Status.running)
{
MessageBox.Show("Your changes are saved.\n\nHowever, the changes won't affect the running job.", "Job Running", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
private void mFileRevert_Click(object sender, System.EventArgs e)
{
if (!EnabledFileItem(sender as ToolStripMenuItem)) return;
((JobEntry)jobslistview.SelectedItems[0])._inputFile.Revert(true);
}
private void mFileExit_Click(object sender, System.EventArgs e)
{
if (!EnabledFileItem(sender as ToolStripMenuItem)) return;
Close();
}
private void mFileSaveAs_Click(object sender, System.EventArgs e)
{
if (!EnabledFileItem(sender as ToolStripMenuItem)) return;
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
je._inputFile.SaveFileAs("Save As");
if (je.stat == Status.running)
{
MessageBox.Show("The operation is completed.\n\nHowever, your changes won't affect the running job.", "Job Running", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
private void mEdit_Popup(object sender, System.EventArgs e)
{
mEditCut.Enabled = mEditCopy.Enabled = mEditPaste.Enabled = mEditSelectAll.Enabled = mEditUndo.Enabled = false;
if (jobslistview.SelectedIndices.Count == 1)
{
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
mEditUndo.Enabled = je._input.Focused && je._input.CanUndo;
mEditPaste.Enabled = je._input.Focused && Clipboard.GetDataObject().GetDataPresent(DataFormats.Text);
if (je.selectedText_input())
mEditCut.Enabled = mEditCopy.Enabled = true;
else if (je.selectedText_log())
mEditCopy.Enabled = true;
if (!jobslistview.Focused) mEditSelectAll.Enabled = true;
}
if (logBox.Focused)
{
if (logBox.SelectionLength > 0)
mEditCopy.Enabled = true;
mEditSelectAll.Enabled = true;
}
}
private void mEditUndo_Click(object sender, System.EventArgs e)
{
if (!EnabledEditItem(sender as ToolStripMenuItem)) return;
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
je._input.Undo();
}
private void mEditCut_Click(object sender, System.EventArgs e)
{
if (!EnabledEditItem(sender as ToolStripMenuItem)) return;
if (jobslistview.SelectedIndices.Count == 1)
{
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
if (je.selectedText_input())
je._input.Cut();
}
}
private void mEditCopy_Click(object sender, System.EventArgs e)
{
if (!EnabledEditItem(sender as ToolStripMenuItem)) return;
if (jobslistview.SelectedIndices.Count == 1)
{
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
if (je.selectedText_input())
je._input.Copy();
else if (je.selectedText_log())
je._log.Copy();
}
if (logBox.Focused && logBox.SelectionLength > 0)
logBox.Copy();
}
private void mEditPaste_Click(object sender, System.EventArgs e)
{
if (!EnabledEditItem(sender as ToolStripMenuItem)) return;
if (jobslistview.SelectedIndices.Count == 1)
{
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
if (je._input.Focused) je._input.Paste();
else if (je._log.Focused) je._log.Paste();
}
if (logBox.Focused) logBox.Paste();
}
private void mEditSelectAll_Click(object sender, System.EventArgs e)
{
if (!EnabledEditItem(sender as ToolStripMenuItem)) return;
if (jobslistview.SelectedIndices.Count == 1)
{
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
if (je._input.Focused)
je._input.SelectAll();
else if (je._log.Focused)
je._log.SelectAll();
}
if (logBox.Focused)
logBox.SelectAll();
}
private void mControl_Popup(object sender, EventArgs e)
{
mControlQueue.Enabled = cmControlQueue.Enabled = false;
mControlQueueNetwork.Enabled = cmControlQueueNetwork.Enabled = false;
mControlPrefetch.Enabled = cmControlPrefetch.Enabled = false;
mControlAbort.Enabled = cmControlAbort.Enabled = false;
mControlSchedule.Enabled = cmControlSchedule.Enabled = false;
mControlNetworkSchedule.Enabled = cmControlNetworkSchedule.Enabled = false;
mControlCheckInputFile.Enabled = cmControlCheckInput.Enabled = false;
mControlDequeue.Enabled = cmControlDequeue.Enabled = false;
mControlUnschedule.Enabled = cmControlUnschedule.Enabled = false;
this.cmControlRemoveEntry.Enabled = false;
//if (DateTime.Compare(DateTime.Now, new DateTime(2006, 12, 15)) > 0)
//{
// logBox.AppendText(DateTime.Now + " this version will expired soon\r\n" + DateTime.Now + " please apply for an update\r\n");
// //mFile.Enabled = false;
//}
//if (DateTime.Compare(DateTime.Now, new DateTime(2007, 1, 15)) > 0)
//{
// logBox.AppendText(DateTime.Now + " this version has expired\r\n" + DateTime.Now + " please apply for an update\r\n");
// //mFile.Enabled = false;
//}
//else
if (jobslistview.SelectedIndices.Count == 1)
{
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
mControlQueue.Enabled = cmControlQueue.Enabled = je.stat == Status.idle || je.stat == Status.aborted || je.stat == Status.completed;
mControlQueueNetwork.Enabled = cmControlQueueNetwork.Enabled = je.stat == Status.idle || je.stat == Status.aborted || je.stat == Status.completed;
mControlDequeue.Enabled = cmControlDequeue.Enabled = je.stat == Status.queued || je.stat == Status.rqueued;
mControlPrefetch.Enabled = cmControlPrefetch.Enabled = je.stat == Status.running && je._job == null;
mControlAbort.Enabled = cmControlAbort.Enabled = je.stat == Status.running;
mControlSchedule.Enabled = cmControlSchedule.Enabled = je.stat == Status.idle || je.stat == Status.aborted || je.stat == Status.completed;
mControlUnschedule.Enabled = cmControlUnschedule.Enabled = je.stat == Status.scheduled || je.stat == Status.rscheduled;
mControlCheckInputFile.Enabled = cmControlCheckInput.Enabled = je.stat != Status.running;
cmControlRemoveEntry.Enabled = je.stat != Status.running;
}
}
private void mControlQueue_Click(object sender, System.EventArgs e)
{
if (!EnabledControlItem(sender as ToolStripMenuItem)) return;
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
if (je._inputFile.SaveFile(je.InputChanged()))
{
je.SetStatus(Status.queued);
je.SubItems[(int)Display.where].Text = "Locally";
}
}
private void mControlQueueNetwork_Click(object sender, System.EventArgs e)
{
if (!EnabledControlItem(sender as ToolStripMenuItem)) return;
JobDestinationDlg jobdestination = null;
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
if (je._inputFile.SaveFile(je.InputChanged()))
{
if (jobdestination == null)
{
jobdestination = new JobDestinationDlg();
}
if (jobdestination.ShowDialog(this) == DialogResult.OK)
{
if (jobdestination.lvHosts.SelectedItems.Count > 0)
{ //dit zou ook weg kunnen en de info alleen uit cbxHosts.text halen.
je.remotehost = jobdestination.lvHosts.SelectedItems[0].Text;
}
else
{
je.remotehost = jobdestination.cbxHosts.Text;
jobdestination.UpdateList();
}
je.remoteport = (int)jobdestination.nudPortnr.Value;
je.SetStatus(Status.rqueued);
je.SubItems[(int)Display.where].Text = je.remotehost;
}
jobdestination.Close();
}
}
private void mControlDequeue_Click(object sender, System.EventArgs e)
{
if (!EnabledControlItem(sender as ToolStripMenuItem)) return;
((JobEntry)jobslistview.SelectedItems[0]).SetStatus(Status.idle);
}
private void mControlPrefetch_Click(object sender, System.EventArgs e)
{
if (!EnabledControlItem(sender as ToolStripMenuItem)) return;
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
je.WriteToLog("prefetching");
je._net.Download(je.DirectoryName);
je.WriteToLog("prefetching finished");
}
private void mControlAbort_Click(object sender, System.EventArgs e)
{
if (!EnabledControlItem(sender as ToolStripMenuItem)) return;
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
if (MessageBox.Show("Are you sure to abort `" + je.FileName + "'?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.tabControl1.SelectedTab = tabLog;
je.AbortJob();
}
}
private void mControlSchedule_Click(object sender, System.EventArgs e)
{
if (!EnabledControlItem(sender as ToolStripMenuItem)) return;
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
if (je._inputFile.SaveFile(je.InputChanged()))
{
PickTime pt = new PickTime();
if (pt.ShowDialog() == DialogResult.OK)
{
je.Schedule(pt.dateTimePicker1.Value, false);
je.SubItems[(int)Display.where].Text = "Locally";
}
pt.Dispose();
}
}
private void mControlScheduleNetwork_Click(object sender, System.EventArgs e)
{
if (!EnabledControlItem(sender as ToolStripMenuItem)) return;
JobDestinationDlg jobdestination = null;
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
if (je._inputFile.SaveFile(je.InputChanged()))
{
PickTime pt = new PickTime();
if (pt.ShowDialog() == DialogResult.OK)
{
if (jobdestination == null)
{
jobdestination = new JobDestinationDlg();
}
if (jobdestination.ShowDialog(this) == DialogResult.OK)
{
if (jobdestination.lvHosts.SelectedItems.Count > 0)
{
je.remotehost = jobdestination.lvHosts.SelectedItems[0].Text;
}
else
{
je.remotehost = jobdestination.cbxHosts.Text;
jobdestination.UpdateList();
}
je.remoteport = (int)jobdestination.nudPortnr.Value;
je.Schedule(pt.dateTimePicker1.Value, true);
je.SubItems[(int)Display.where].Text = je.remotehost;
}
}
pt.Dispose();
}
}
private void mControlUnschedule_Click(object sender, System.EventArgs e)
{
if (!EnabledControlItem(sender as ToolStripMenuItem)) return;
((JobEntry)jobslistview.SelectedItems[0]).Unschedule();
}
private void mControlCheckInputFile_Click(object sender, System.EventArgs e)
{
if (!EnabledControlItem(sender as ToolStripMenuItem)) return;
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
if ((je.stat == Status.scheduled || je.stat == Status.rscheduled) && je._schedTime.Subtract(DateTime.Now).TotalSeconds < 200)
{
MessageBox.Show("It is not possible to check the input file at this moment because the job is scheduled to start real soon.", "Already scheduled", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (je._inputFile.SaveFile(je.InputChanged()))
je.StartJob(true);
}
private void jobs_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (jobslistview.SelectedIndices.Count == 1)
{
//jobslistview.BeginUpdate();
JobEntry je = (JobEntry)jobslistview.SelectedItems[0];
je.Select();
jobslistview.Select();
//jobslistview.EndUpdate();
}
else // cannot occur
{
tabInput.Controls.Clear();
tabLog.Controls.Clear();
}
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
//base.OnClosing(e);
foreach (JobEntry je in jobslistview.Items)
{
if (!je.CloseWindow())
{
e.Cancel = true;
break;
}
}
if (!e.Cancel)
{
foreach (JobEntry je in jobslistview.Items)
{
if (je.stat == Status.queued || je.stat == Status.scheduled || je.stat == Status.rqueued || je.stat == Status.rscheduled)
{
if (MessageBox.Show("You have queued or scheduled jobs.\n\nDo you really want to quit?", "Queued jobs", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
e.Cancel = true;
break;
}
}
}
if (!e.Cancel)
{
foreach (JobEntry je in jobslistview.Items)
{
if (je.stat == Status.running || je.stat == Status.waiting)
{
if (MessageBox.Show("You have running jobs.\n\nDo you really want to quit?", "Running jobs", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
e.Cancel = true;
break;
}
}
}
if (!e.Cancel)
{
ExitSplash splash = new ExitSplash();
splash.StartPosition = FormStartPosition.CenterScreen;
splash.Show(this);
Application.DoEvents();
foreach (JobEntry je in jobslistview.Items)
{ // eerst alle gequeue-de jobs cancelen
switch (je.stat)
{
case Status.running:
case Status.waiting:
break;
default:
je.SetStatus(Status.idle);
break;
}
}
foreach (JobEntry je in jobslistview.Items)
{ // dan de draaiende jobs stoppen
switch (je.stat)
{
case Status.running:
case Status.waiting:
je.AbortJob();
break;
default:
break;
}
}
foreach (JobEntry je in jobslistview.Items)
{ // wachten totdat alle netwerkjobs klaar zijn (alles gedownload etc)
while (je.RunAndDownloadIsActive)
{
Application.DoEvents(); //nodig om dead-locks te voorkomen (vanwegen invoked calls als SetSubItem)
System.Threading.Thread.Sleep(10);
}
je.Dispose();
}
if (sched != null) sched.Dispose();
System.Threading.Thread.Sleep(500);
splash.Hide();
splash.Dispose();
}
}
private void menuItem9_Click(object sender, System.EventArgs e)
{
if (!(sender as ToolStripMenuItem).Enabled) return;
MessageBox.Show("Houston\n\n\n(c) 2003-2015 Dullware\n\nhttps://github.com/dullware\n\n", "About", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void jobs_DoubleClick(object sender, System.EventArgs e)
{
this.tabControl1.SelectedTab = tabInput;
}
public void AddtoRegistry(string remotehost, int remoteport)
{
int maxsavedhosts = 6;
int alreadypresentat = -1;
RegistryKey reghouston11 = Registry.CurrentUser.OpenSubKey(regKeyString, true);
if (reghouston11 == null) reghouston11 = Registry.CurrentUser.CreateSubKey(regKeyString);
RegistryKey reghosts = reghouston11.OpenSubKey("Hosts", true);
if (reghosts == null) reghosts = reghouston11.CreateSubKey("Hosts");
string[] hosts = reghosts.GetValueNames();
for (int i = 0; i < maxsavedhosts && i < hosts.Length; i++)
{
if (string.Compare(remotehost, reghosts.GetValue(hosts[i]).ToString(), true) == 0)
{
alreadypresentat = i;
break;
}
}
if (alreadypresentat == -1)
{
if (hosts.Length < maxsavedhosts)
{
for (int i = hosts.Length; i > 0; i--)
{
reghosts.SetValue("host" + i.ToString(), reghosts.GetValue(hosts[i - 1]).ToString());
}
}
else
{
for (int i = maxsavedhosts - 1; i > 0; i--)
{
reghosts.SetValue(hosts[i], reghosts.GetValue(hosts[i - 1]).ToString());
}
}
}
else
{
for (int i = alreadypresentat; i > 0; i--)
{
reghosts.SetValue(hosts[i], reghosts.GetValue(hosts[i - 1]).ToString());
}
}
reghosts.SetValue("host0", remotehost);
for (int i = maxsavedhosts; i < hosts.Length; i++) reghosts.DeleteValue(hosts[i]);
reghosts.Close();
reghouston11.SetValue("lastport", remoteport);
reghouston11.Close();
}
delegate void SetStatusBarTextDelegate(string s);
public void SetStatusBarText(string s)
{
if (InvokeRequired) Invoke(new SetStatusBarTextDelegate(SetStatusBarText), new object[] { s });
else SB.Text = s;
}
}
| |
#pragma warning disable 1591
using System;
using System.Collections.Generic;
using System.Text;
namespace Braintree
{
public class TransactionSearchRequest : SearchRequest
{
public RangeNode<TransactionSearchRequest> Amount
{
get
{
return new RangeNode<TransactionSearchRequest>("amount", this);
}
}
public DateRangeNode<TransactionSearchRequest> AuthorizationExpiredAt
{
get
{
return new DateRangeNode<TransactionSearchRequest>("authorization-expired-at", this);
}
}
public DateRangeNode<TransactionSearchRequest> AuthorizedAt
{
get
{
return new DateRangeNode<TransactionSearchRequest>("authorized-at", this);
}
}
public TextNode<TransactionSearchRequest> BillingCompany
{
get
{
return new TextNode<TransactionSearchRequest>("billing-company", this);
}
}
public TextNode<TransactionSearchRequest> BillingCountryName
{
get
{
return new TextNode<TransactionSearchRequest>("billing-country-name", this);
}
}
public TextNode<TransactionSearchRequest> BillingExtendedAddress
{
get
{
return new TextNode<TransactionSearchRequest>("billing-extended-address", this);
}
}
public TextNode<TransactionSearchRequest> BillingFirstName
{
get
{
return new TextNode<TransactionSearchRequest>("billing-first-name", this);
}
}
public TextNode<TransactionSearchRequest> BillingLastName
{
get
{
return new TextNode<TransactionSearchRequest>("billing-last-name", this);
}
}
public TextNode<TransactionSearchRequest> BillingLocality
{
get
{
return new TextNode<TransactionSearchRequest>("billing-locality", this);
}
}
public TextNode<TransactionSearchRequest> BillingPostalCode
{
get
{
return new TextNode<TransactionSearchRequest>("billing-postal-code", this);
}
}
public TextNode<TransactionSearchRequest> BillingRegion
{
get
{
return new TextNode<TransactionSearchRequest>("billing-region", this);
}
}
public TextNode<TransactionSearchRequest> BillingStreetAddress
{
get
{
return new TextNode<TransactionSearchRequest>("billing-street-address", this);
}
}
public DateRangeNode<TransactionSearchRequest> CreatedAt
{
get
{
return new DateRangeNode<TransactionSearchRequest>("created-at", this);
}
}
public MultipleValueNode<TransactionSearchRequest, TransactionCreatedUsing> CreatedUsing
{
get
{
return new MultipleValueNode<TransactionSearchRequest, TransactionCreatedUsing>("created-using", this);
}
}
public TextNode<TransactionSearchRequest> CreditCardCardholderName
{
get
{
return new TextNode<TransactionSearchRequest>("credit-card-cardholder-name", this);
}
}
public EqualityNode<TransactionSearchRequest> CreditCardExpirationDate
{
get
{
return new EqualityNode<TransactionSearchRequest>("credit-card-expiration-date", this);
}
}
public PartialMatchNode<TransactionSearchRequest> CreditCardNumber
{
get
{
return new PartialMatchNode<TransactionSearchRequest>("credit-card-number", this);
}
}
public MultipleValueNode<TransactionSearchRequest, Braintree.CreditCardCardType> CreditCardCardType
{
get
{
return new MultipleValueNode<TransactionSearchRequest, Braintree.CreditCardCardType>("credit-card-card-type", this);
}
}
public MultipleValueNode<TransactionSearchRequest, Braintree.CreditCardCustomerLocation> CreditCardCustomerLocation
{
get
{
return new MultipleValueNode<TransactionSearchRequest, Braintree.CreditCardCustomerLocation>("credit-card-customer-location", this);
}
}
public TextNode<TransactionSearchRequest> Currency
{
get
{
return new TextNode<TransactionSearchRequest>("currency", this);
}
}
public TextNode<TransactionSearchRequest> CustomerCompany
{
get
{
return new TextNode<TransactionSearchRequest>("customer-company", this);
}
}
public TextNode<TransactionSearchRequest> CustomerEmail
{
get
{
return new TextNode<TransactionSearchRequest>("customer-email", this);
}
}
public TextNode<TransactionSearchRequest> CustomerFax
{
get
{
return new TextNode<TransactionSearchRequest>("customer-fax", this);
}
}
public TextNode<TransactionSearchRequest> CustomerFirstName
{
get
{
return new TextNode<TransactionSearchRequest>("customer-first-name", this);
}
}
public TextNode<TransactionSearchRequest> CustomerId
{
get
{
return new TextNode<TransactionSearchRequest>("customer-id", this);
}
}
public TextNode<TransactionSearchRequest> CustomerLastName
{
get
{
return new TextNode<TransactionSearchRequest>("customer-last-name", this);
}
}
public TextNode<TransactionSearchRequest> CustomerPhone
{
get
{
return new TextNode<TransactionSearchRequest>("customer-phone", this);
}
}
public TextNode<TransactionSearchRequest> CustomerWebsite
{
get
{
return new TextNode<TransactionSearchRequest>("customer-website", this);
}
}
public DateRangeNode<TransactionSearchRequest> FailedAt
{
get
{
return new DateRangeNode<TransactionSearchRequest>("failed-at", this);
}
}
public DateRangeNode<TransactionSearchRequest> GatewayRejectedAt
{
get
{
return new DateRangeNode<TransactionSearchRequest>("gateway-rejected-at", this);
}
}
public TextNode<TransactionSearchRequest> Id
{
get
{
return new TextNode<TransactionSearchRequest>("id", this);
}
}
public MultipleValueNode<TransactionSearchRequest, string> Ids
{
get
{
return new MultipleValueNode<TransactionSearchRequest, string>("ids", this);
}
}
public MultipleValueNode<TransactionSearchRequest, string> MerchantAccountId
{
get
{
return new MultipleValueNode<TransactionSearchRequest, string>("merchant-account-id", this);
}
}
public TextNode<TransactionSearchRequest> OrderId
{
get
{
return new TextNode<TransactionSearchRequest>("order-id", this);
}
}
public TextNode<TransactionSearchRequest> PaymentMethodToken
{
get
{
return new TextNode<TransactionSearchRequest>("payment-method-token", this);
}
}
public TextNode<TransactionSearchRequest> ProcessorAuthorizationCode
{
get
{
return new TextNode<TransactionSearchRequest>("processor-authorization-code", this);
}
}
public DateRangeNode<TransactionSearchRequest> ProcessorDeclinedAt
{
get
{
return new DateRangeNode<TransactionSearchRequest>("processor-declined-at", this);
}
}
public KeyValueNode<TransactionSearchRequest> Refund
{
get
{
return new KeyValueNode<TransactionSearchRequest>("refund", this);
}
}
public DateRangeNode<TransactionSearchRequest> SettledAt
{
get
{
return new DateRangeNode<TransactionSearchRequest>("settled-at", this);
}
}
public TextNode<TransactionSearchRequest> SettlementBatchId
{
get
{
return new TextNode<TransactionSearchRequest>("settlement-batch-id", this);
}
}
public TextNode<TransactionSearchRequest> ShippingCompany
{
get
{
return new TextNode<TransactionSearchRequest>("shipping-company", this);
}
}
public TextNode<TransactionSearchRequest> ShippingCountryName
{
get
{
return new TextNode<TransactionSearchRequest>("shipping-country-name", this);
}
}
public TextNode<TransactionSearchRequest> ShippingExtendedAddress
{
get
{
return new TextNode<TransactionSearchRequest>("shipping-extended-address", this);
}
}
public TextNode<TransactionSearchRequest> ShippingFirstName
{
get
{
return new TextNode<TransactionSearchRequest>("shipping-first-name", this);
}
}
public TextNode<TransactionSearchRequest> ShippingLastName
{
get
{
return new TextNode<TransactionSearchRequest>("shipping-last-name", this);
}
}
public TextNode<TransactionSearchRequest> ShippingLocality
{
get
{
return new TextNode<TransactionSearchRequest>("shipping-locality", this);
}
}
public TextNode<TransactionSearchRequest> ShippingPostalCode
{
get
{
return new TextNode<TransactionSearchRequest>("shipping-postal-code", this);
}
}
public TextNode<TransactionSearchRequest> ShippingRegion
{
get
{
return new TextNode<TransactionSearchRequest>("shipping-region", this);
}
}
public TextNode<TransactionSearchRequest> ShippingStreetAddress
{
get
{
return new TextNode<TransactionSearchRequest>("shipping-street-address", this);
}
}
public MultipleValueNode<TransactionSearchRequest, TransactionStatus> Status
{
get
{
return new MultipleValueNode<TransactionSearchRequest, TransactionStatus>("status", this);
}
}
public DateRangeNode<TransactionSearchRequest> SubmittedForSettlementAt
{
get
{
return new DateRangeNode<TransactionSearchRequest>("submitted-for-settlement-at", this);
}
}
public MultipleValueNode<TransactionSearchRequest, TransactionSource> Source
{
get
{
return new MultipleValueNode<TransactionSearchRequest, TransactionSource>("source", this);
}
}
public MultipleValueNode<TransactionSearchRequest, TransactionType> Type
{
get
{
return new MultipleValueNode<TransactionSearchRequest, TransactionType>("type", this);
}
}
public DateRangeNode<TransactionSearchRequest> VoidedAt
{
get
{
return new DateRangeNode<TransactionSearchRequest>("voided-at", this);
}
}
public TransactionSearchRequest() : base()
{
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Encog.Engine.Network.Activation;
using Encog.MathUtil;
using Encog.ML.Data;
using Encog.ML.Data.Basic;
using Encog.ML.Data.Temporal;
using Encog.Util.Arrayutil;
namespace Encog.Util.NetworkUtil
{
/// <summary>
/// Use this helper class to build training inputs for neural networks (only memory based datasets).
/// Mostly this class is used in financial neural networks when receiving multiple inputs (indicators, prices, etc) and
/// having to put them in neural datasets.
///
/// </summary>
public static class TrainerHelper
{
/// <summary>
/// Makes the double [][] from single array.
/// this is a very important method used in financial markets when you have multiple inputs (Close price, 1 indicator, 1 ATR, 1 moving average for example) , and each is already formated in an array of doubles.
/// You just provide the number of inputs (4 here) , and it will create the resulting double [][]
/// </summary>
/// <param name="array">The array.</param>
/// <param name="numberofinputs">The numberofinputs.</param>
/// <returns></returns>
public static double [][] MakeDoubleJaggedInputFromArray(double [] array , int numberofinputs)
{
//we must be able to fit all our numbers in the same double array..no spill over.
if (array.Length % numberofinputs != 0)
return null;
int dimension = array.Length / numberofinputs;
int currentindex = 0;
double[][] result = EngineArray.AllocateDouble2D(dimension, numberofinputs);
//now we loop through the index.
int index = 0;
for (index = 0; index < result.Length; index++)
{
for (int j = 0; j < numberofinputs; j++)
{
result[index][j] = array[currentindex++];
}
}
return (result);
}
/// <summary>
/// Doubles the List of doubles into a jagged array.
/// This is exactly similar as the MakeDoubleJaggedInputFromArray just it takes a List of double as parameter.
/// It quite easier to Add doubles to a list than into a double [] Array (so this method is used more).
/// </summary>
/// <param name="inputs">The inputs.</param>
/// <param name="lenght">The lenght.</param>
/// <returns></returns>
public static double[][] DoubleInputsToArraySimple(List<double> inputs, int lenght)
{
//we must be able to fit all our numbers in the same double array..no spill over.
if (inputs.Count % lenght != 0)
return null;
int dimension = inputs.Count / lenght;
double[][] result = EngineArray.AllocateDouble2D(dimension, lenght);
foreach (double doubles in inputs)
{
for (int index = 0; index < result.Length; index++)
{
for (int j = 0; j < lenght; j++)
{
result[index][j] = doubles;
}
}
}
return (result);
}
/// <summary>
/// Processes the specified double serie into an IMLDataset.
/// To use this method, you must provide a formated double array.
/// The number of points in the input window makes the input array , and the predict window will create the array used in ideal.
/// Example you have an array with 1, 2, 3 , 4 , 5.
/// You can use this method to make an IMLDataset 4 inputs and 1 ideal (5).
/// </summary>
/// <param name="data">The data.</param>
/// <param name="_inputWindow">The _input window.</param>
/// <param name="_predictWindow">The _predict window.</param>
/// <returns></returns>
public static IMLDataSet ProcessDoubleSerieIntoIMLDataset(double[] data, int _inputWindow, int _predictWindow)
{
var result = new BasicMLDataSet();
int totalWindowSize = _inputWindow + _predictWindow;
int stopPoint = data.Length - totalWindowSize;
for (int i = 0; i < stopPoint; i++)
{
var inputData = new BasicMLData(_inputWindow);
var idealData = new BasicMLData(_predictWindow);
int index = i;
// handle input window
for (int j = 0; j < _inputWindow; j++)
{
inputData[j] = data[index++];
}
// handle predict window
for (int j = 0; j < _predictWindow; j++)
{
idealData[j] = data[index++];
}
var pair = new BasicMLDataPair(inputData, idealData);
result.Add(pair);
}
return result;
}
/// <summary>
/// Processes the specified double serie into an IMLDataset.
/// To use this method, you must provide a formated double array with the input data and the ideal data in another double array.
/// The number of points in the input window makes the input array , and the predict window will create the array used in ideal.
/// This method will use ALL the data inputs and ideals you have provided.
/// </summary>
/// <param name="datainput">The datainput.</param>
/// <param name="ideals">The ideals.</param>
/// <param name="_inputWindow">The _input window.</param>
/// <param name="_predictWindow">The _predict window.</param>
/// <returns></returns>
public static IMLDataSet ProcessDoubleSerieIntoIMLDataset(List<double> datainput,List<double>ideals, int _inputWindow, int _predictWindow)
{
var result = new BasicMLDataSet();
//int count = 0;
////lets check if there is a modulo , if so we move forward in the List of doubles in inputs.This is just a check
////as the data of inputs should be able to fill without having .
//while (datainput.Count % _inputWindow !=0)
//{
// count++;
//}
var inputData = new BasicMLData(_inputWindow);
var idealData = new BasicMLData(_predictWindow);
foreach (double d in datainput)
{
// handle input window
for (int j = 0; j < _inputWindow; j++)
{
inputData[j] = d;
}
}
foreach (double ideal in ideals)
{
// handle predict window
for (int j = 0; j < _predictWindow; j++)
{
idealData[j] =ideal;
}
}
var pair = new BasicMLDataPair(inputData, idealData);
result.Add(pair);
return result;
}
static bool IsNoModulo(double first,int second)
{
return first % second == 0;
}
/// <summary>
/// Grabs every Predict point in a double serie.
/// This is useful if you have a double series and you need to grab every 5 points for examples and make an ourput serie (like in elmhan networks).
/// E.G , 1, 2, 1, 2,5 ...and you just need the 5..
/// </summary>
/// <param name="inputs">The inputs.</param>
/// <param name="PredictSize">Size of the predict.</param>
/// <returns></returns>
public static List<double> CreateIdealFromSerie(List<double> inputs, int PredictSize)
{
//we need to copy into a new list only the doubles on each point of predict..
List<int> Indexes = new List<int>();
for (int i =0 ; i < inputs.Count;i++)
{
if (i % PredictSize == 0)
Indexes.Add(i);
}
List<double> Results = Indexes.Select(index => inputs[index]).ToList();
return Results;
}
/// <summary>
/// Generates the Temporal MLDataset with a given data array.
/// You must input the "predict" size (inputs) and the windowsize (outputs).
/// This is oftenly used with Ehlman networks.
/// The temporal dataset will be in RAW format (no normalization used..Most of the times it means you already have normalized your inputs /ouputs.
///
/// </summary>
/// <param name="inputserie">The inputserie.</param>
/// <param name="windowsize">The windowsize.</param>
/// <param name="predictsize">The predictsize.</param>
/// <returns>A temporalMLDataset</returns>
public static TemporalMLDataSet GenerateTrainingWithRawSerie(double[] inputserie, int windowsize, int predictsize)
{
TemporalMLDataSet result = new TemporalMLDataSet(windowsize, predictsize);
TemporalDataDescription desc = new TemporalDataDescription(
TemporalDataDescription.Type.Raw, true, true);
result.AddDescription(desc);
for (int index = 0; index < inputserie.Length - 1; index++)
{
TemporalPoint point = new TemporalPoint(1);
point.Sequence = index;
point.Data[0] = inputserie[index];
result.Points.Add(point);
}
result.Generate();
return result;
}
/// <summary>
/// Generates the training with delta change on serie.
/// </summary>
/// <param name="inputserie">The inputserie.</param>
/// <param name="windowsize">The windowsize.</param>
/// <param name="predictsize">The predictsize.</param>
/// <returns></returns>
public static TemporalMLDataSet GenerateTrainingWithDeltaChangeOnSerie(double[] inputserie, int windowsize, int predictsize)
{
TemporalMLDataSet result = new TemporalMLDataSet(windowsize, predictsize);
TemporalDataDescription desc = new TemporalDataDescription(
TemporalDataDescription.Type.DeltaChange, true, true);
result.AddDescription(desc);
for (int index = 0; index < inputserie.Length - 1; index++)
{
TemporalPoint point = new TemporalPoint(1);
point.Sequence = index;
point.Data[0] = inputserie[index];
result.Points.Add(point);
}
result.Generate();
return result;
}
/// <summary>
/// Generates a temporal data set with a given double serie or a any number of double series , making your inputs.
/// uses Type percent change.
/// </summary>
/// <param name="windowsize">The windowsize.</param>
/// <param name="predictsize">The predictsize.</param>
/// <param name="inputserie">The inputserie.</param>
/// <returns></returns>
public static TemporalMLDataSet GenerateTrainingWithPercentChangeOnSerie(int windowsize, int predictsize, params double[][] inputserie)
{
TemporalMLDataSet result = new TemporalMLDataSet(windowsize, predictsize);
TemporalDataDescription desc = new TemporalDataDescription(TemporalDataDescription.Type.PercentChange, true,
true);
result.AddDescription(desc);
foreach (double[] t in inputserie)
{
for (int j = 0; j < t.Length; j++)
{
TemporalPoint point = new TemporalPoint(1);
point.Sequence = j;
point.Data[0] = t[j];
result.Points.Add(point);
}
result.Generate();
return result;
}
return null;
}
/// <summary>
/// This method takes ARRAYS of arrays (parametrable arrays) and places them in double [][]
/// You can use this method if you have already formatted arrays and you want to create a double [][] ready for network.
/// Example you could use this method to input the XOR example:
/// A[0,0] B[0,1] C[1, 0] D[1,1] would format them directly in the double [][] in one method call.
/// This could also be used in unsupervised learning.
/// </summary>
/// <param name="Inputs">The inputs.</param>
/// <returns></returns>
public static double[][] NetworkbuilArrayByParams(params double[][] Inputs)
{
double[][] Resulting = new double[Inputs.Length][];
int i = Inputs.Length;
foreach (double[] doubles in Resulting)
{
for (int k = 0; k < Inputs.Length; k++)
Resulting[k] = doubles;
}
return Resulting;
}
/// <summary>
/// Prints the content of an array to the console.(Mostly used in debugging).
/// </summary>
/// <param name="num">The num.</param>
public static void PrinteJaggedArray(int[][] num)
{
foreach (int t1 in num.SelectMany(t => t))
{
Console.WriteLine(@"Values : {0}", t1);//displaying values of Jagged Array
}
}
/// <summary>
/// Processes a double array of data of input and a second array of data for ideals
/// you must input the input and output size.
/// this typically builds a supervised IMLDatapair, which you must add to a IMLDataset.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="ideal">The ideal.</param>
/// <param name="_inputWindow">The _input window.</param>
/// <param name="_predictWindow">The _predict window.</param>
/// <returns></returns>
public static IMLDataPair ProcessPairs(double[] data, double[] ideal, int _inputWindow, int _predictWindow)
{
var result = new BasicMLDataSet();
for (int i = 0; i < data.Length; i++)
{
var inputData = new BasicMLData(_inputWindow);
var idealData = new BasicMLData(_predictWindow);
int index = i;
// handle input window
for (int j = 0; j < _inputWindow; j++)
{
inputData[j] = data[index++];
}
index = 0;
// handle predict window
for (int j = 0; j < _predictWindow; j++)
{
idealData[j] = ideal[index++];
}
IMLDataPair pair = new BasicMLDataPair(inputData, idealData);
return pair;
}
return null;
}
/// <summary>
/// Takes 2 inputs arrays and makes a jagged array.
/// this just copies the second array after the first array in a double [][]
/// </summary>
/// <param name="firstArray">The first array.</param>
/// <param name="SecondArray">The second array.</param>
/// <returns></returns>
public static double[][] FromDualToJagged(double[] firstArray, double[] SecondArray)
{
return new[] { firstArray, SecondArray };
}
///// <summary>
///// Generates the Temporal Training based on an array of doubles.
///// You need to have 2 array of doubles [] for this method to work!
///// </summary>
///// <param name="inputsize">The inputsize.</param>
///// <param name="outputsize">The outputsize.</param>
///// <param name="Arraydouble">The arraydouble.</param>
///// <returns></returns>
//public static TemporalMLDataSet GenerateTraining(int inputsize, int outputsize, params double[][] Arraydouble)
//{
// if (Arraydouble.Length < 2)
// return null;
// if (Arraydouble.Length > 2)
// return null;
// TemporalMLDataSet result = new TemporalMLDataSet(inputsize, outputsize);
// TemporalDataDescription desc = new TemporalDataDescription(new ActivationTANH(), TemporalDataDescription.Type.PercentChange, true, true);
// result.AddDescription(desc);
// TemporalPoint point = new TemporalPoint(Arraydouble.Length);
// int currentindex;
// for (int w = 0; w < Arraydouble[0].Length; w++)
// {
// //We have filled in one dimension now lets put them in our temporal dataset.
// for (int year = 0; year < Arraydouble.Length - 1; year++)
// {
// //We have as many points as we passed the array of doubles.
// point = new TemporalPoint(Arraydouble.Length);
// //our first sequence (0).
// point.Sequence = w;
// //point 0 is double[0] array.
// point.Data[0] = Arraydouble[0][w];
// point.Data[1] = Arraydouble[1][w++];
// //we add the point..
// }
// result.Points.Add(point);
// }
// result.Generate();
// return result;
//}
/// <summary>
/// Calculates and returns the copied array.
/// This is used in live data , when you want have a full array of doubles but you want to cut from a starting position
/// and return only from that point to the end.
/// example you have 1000 doubles , but you want only the last 100.
/// input size is the input you must set to 100.
/// I use this method next to every day when calculating on an array of doubles which has just received a new price (A quote for example).
/// As the array of quotes as all the quotes since a few days, i just need the last 100 for example , so this method is used when not training but using the neural network.
/// </summary>
/// <param name="inputted">The inputted.</param>
/// <param name="inputsize">The input neuron size (window size).</param>
/// <returns></returns>
public static double[] ReturnArrayOnSize(double[] inputted, int inputsize)
{
//lets say we receive an array of 105 doubles ...input size is 100.(or window size)
//we need to just copy the last 100.
//so if inputted.Lenght > inputsize :
// start index = inputtedLenght - inputsize.
//if inputtedlenght is equal to input size , well our index will be 0..
//if inputted lenght is smaller than input...We return null.
double[] arr = new double[inputsize];
int howBig = 0;
if (inputted.Length >= inputsize)
{
howBig = inputted.Length - inputsize;
}
EngineArray.ArrayCopy(inputted, howBig, arr, 0, inputsize);
return arr;
}
/// <summary>
/// Quickly an IMLDataset from a double array using the TemporalWindow array.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="inputsize">The inputsize.</param>
/// <param name="outputsize">The outputsize.</param>
/// <returns></returns>
public static IMLDataSet QuickTrainingFromDoubleArray(double[] array, int inputsize, int outputsize)
{
TemporalWindowArray temp = new TemporalWindowArray(inputsize, outputsize);
temp.Analyze(array);
return temp.Process(array);
}
/// <summary>
/// Generates an array with as many double array inputs as wanted.
/// This is useful for neural networks when you have already formated your data arrays and need to create a double []
/// with all the inputs following each others.(Elman type format)
/// </summary>
/// <param name="inputs">The inputs.</param>
/// <returns>
/// the double [] array with all inputs.
/// </returns>
public static double[] GenerateInputz(params double[][] inputs)
{
ArrayList al = new ArrayList();
foreach (double[] doublear in inputs)
{
al.Add((double[])doublear);
}
return (double[])al.ToArray(typeof(double));
}
/// <summary>
/// Prepare realtime inputs, and place them in an understandable one jagged input neuron array.
/// This method uses linq.
/// you can use this method if you have many inputs and need to format them as inputs with a specified "window"/input size.
/// You can add as many inputs as wanted to this input layer (parametrable inputs).
/// </summary>
/// <param name="inputsize">The inputsize.</param>
/// <param name="firstinputt">The firstinputt.</param>
/// <returns>a ready to use jagged array with all the inputs setup.</returns>
public static double[][] AddInputsViaLinq(int inputsize, params double[][] firstinputt)
{
ArrayList arlist = new ArrayList(4);
ArrayList FirstList = new ArrayList();
List<double> listused = new List<double>();
int lenghtofArrays = firstinputt[0].Length;
//There must be NO modulo...or the arrays would not be divisible by this input size.
if (lenghtofArrays % inputsize != 0)
return null;
//we add each input one , after the other in a list of doubles till we reach the input size
for (int i = 0; i < lenghtofArrays; i++)
{
foreach (double[] t in firstinputt.Where(t => listused.Count < inputsize*firstinputt.Length))
{
listused.Add(t[i]);
if (listused.Count != inputsize*firstinputt.Length) continue;
FirstList.Add(listused.ToArray());
listused.Clear();
}
}
return (double[][])FirstList.ToArray(typeof(double[]));
}
/// <summary>
/// Prepare realtime inputs, and place them in an understandable one jagged input neuron array.
/// you can use this method if you have many inputs and need to format them as inputs with a specified "window"/input size.
/// You can add as many inputs as wanted to this input layer (parametrable inputs).
/// </summary>
/// <param name="inputsize">The inputsize.</param>
/// <param name="firstinputt">The firstinputt.</param>
/// <returns>a ready to use jagged array with all the inputs setup.</returns>
public static double[][] AddInputs(int inputsize, params double[][] firstinputt)
{
ArrayList arlist = new ArrayList(4);
ArrayList FirstList = new ArrayList();
List<double> listused = new List<double>();
int lenghtofArrays = firstinputt[0].Length;
//There must be NO modulo...or the arrays would not be divisile by this input size.
if (lenghtofArrays % inputsize != 0)
return null;
//we add each input one , after the other in a list of doubles till we reach the input size
for (int i = 0; i < lenghtofArrays; i++)
{
for (int k = 0; k < firstinputt.Length; k++)
{
if (listused.Count < inputsize * firstinputt.Length)
{
listused.Add(firstinputt[k][i]);
if (listused.Count == inputsize * firstinputt.Length)
{
FirstList.Add(listused.ToArray());
listused.Clear();
}
}
}
}
return (double[][])FirstList.ToArray(typeof(double[]));
}
/// <summary>
/// Makes a data set with parametrable inputs and one output double array.
/// you can provide as many inputs as needed and the timelapse size (input size).
/// for more information on this method read the AddInputs Method.
/// </summary>
/// <param name="outputs">The outputs.</param>
/// <param name="inputsize">The inputsize.</param>
/// <param name="firstinputt">The firstinputt.</param>
/// <returns></returns>
public static IMLDataSet MakeDataSet(double[] outputs, int inputsize, params double[][] firstinputt)
{
IMLDataSet set = new BasicMLDataSet();
ArrayList outputsar = new ArrayList();
ArrayList FirstList = new ArrayList();
List<double> listused = new List<double>();
int lenghtofArrays = firstinputt[0].Length;
//There must be NO modulo...or the arrays would not be divisible by this input size.
if (lenghtofArrays % inputsize != 0)
return null;
//we add each input one , after the other in a list of doubles till we reach the input size
for (int i = 0; i < lenghtofArrays; i++)
{
for (int k = 0; k < firstinputt.Length; k++)
{
if (listused.Count < inputsize * firstinputt.Length)
{
listused.Add(firstinputt[k][i]);
if (listused.Count == inputsize * firstinputt.Length)
{
FirstList.Add(listused.ToArray());
listused.Clear();
}
}
}
}
foreach (double d in outputs)
{
listused.Add(d);
outputsar.Add(listused.ToArray());
listused.Clear();
}
set = new BasicMLDataSet((double[][])FirstList.ToArray(typeof(double[])), (double[][])outputsar.ToArray(typeof(double[])));
return set;
}
public static double[] MakeInputs(int number)
{
Random rdn = new Random();
Encog.MathUtil.Randomize.RangeRandomizer encogRnd = new Encog.MathUtil.Randomize.RangeRandomizer(-1, 1);
double[] x = new double[number];
for (int i = 0; i < number; i++)
{
x[i] = encogRnd.Randomize((rdn.NextDouble()));
}
return x;
}
/// <summary>
/// Makes a random dataset with the number of IMLDatapairs.
/// Quite useful to test networks (benchmarks).
/// </summary>
/// <param name="inputs">The inputs.</param>
/// <param name="predictWindow">The predict window.</param>
/// <param name="numberofPairs">The numberof pairs.</param>
/// <returns></returns>
public static BasicMLDataSet MakeRandomIMLDataset(int inputs, int predictWindow, int numberofPairs)
{
BasicMLDataSet SuperSet = new BasicMLDataSet();
for (int i = 0; i < numberofPairs;i++ )
{
double[] firstinput = MakeInputs(inputs);
double[] secondideal = MakeInputs(inputs);
IMLDataPair pair = ProcessPairs(firstinput, secondideal, inputs, predictWindow);
SuperSet.Add(pair);
}
return SuperSet;
}
/// <summary>
/// This is the most used method in finance.
/// You send directly your double arrays and get an IMLData set ready for network training.
/// You must place your ideal data as the last double data array.
/// IF you have 1 data of closing prices, 1 moving average, 1 data series of interest rates , and the data you want to predict
/// This method will look the lenght of the first Data input to calculate how many points to take from each array.
/// this is the method you will use to make your Dataset.
/// </summary>
/// <param name="number">The number.</param>
/// <param name="inputs">The inputs.</param>
/// <returns></returns>
public static IMLDataSet MakeSetFromInputsSources(int predwindow, params double[][] inputs)
{
ArrayList list = new ArrayList(inputs.Length);
IMLDataSet set = new BasicMLDataSet();
//we know now how many items we have in each data series (all series should be of equal lenght).
int dimension = inputs[0].Length;
//we will take predictwindow of each serie and make new series.
List<double> InputList = new List<double>();
int index = 0;
int currentArrayObserved = 0;
//foreach (double[] doubles in inputs)
//{
// for (int k = 0; k < dimension; k++)
// {
// //We will take predict window number from each of our array and add them up.
// for (int i = 0; i < predwindow; i++)
// {
// InputList.Add(doubles[index]);
// }
// }
// index++;
//}
foreach (double[] doublear in inputs)
{
list.Add((double[])doublear);
}
// return (double[][])list.ToArray(typeof(double[]));
return set;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Shared;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
using Xunit;
namespace Microsoft.Build.UnitTests.OM.Construction
{
/// <summary>
/// Tests for the ProjectOnErrorElement class
/// </summary>
public class ProjectOnErrorElement_Tests
{
/// <summary>
/// Read a target containing only OnError
/// </summary>
[Fact]
public void ReadTargetOnlyContainingOnError()
{
ProjectOnErrorElement onError = GetOnError();
Assert.Equal("t", onError.ExecuteTargetsAttribute);
Assert.Equal("c", onError.Condition);
}
/// <summary>
/// Read a target with two onerrors, and some tasks
/// </summary>
[Fact]
public void ReadTargetTwoOnErrors()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1/>
<t2/>
<OnError ExecuteTargets='1'/>
<OnError ExecuteTargets='2'/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children);
var onErrors = Helpers.MakeList(target.OnErrors);
ProjectOnErrorElement onError1 = onErrors[0];
ProjectOnErrorElement onError2 = onErrors[1];
Assert.Equal("1", onError1.ExecuteTargetsAttribute);
Assert.Equal("2", onError2.ExecuteTargetsAttribute);
}
/// <summary>
/// Read onerror with no executetargets attribute
/// </summary>
/// <remarks>
/// This was accidentally allowed in 2.0/3.5 but it should be an error now.
/// </remarks>
[Fact]
public void ReadMissingExecuteTargets()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<OnError/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children);
ProjectOnErrorElement onError = (ProjectOnErrorElement)Helpers.GetFirst(target.Children);
Assert.Equal(String.Empty, onError.ExecuteTargetsAttribute);
}
);
}
/// <summary>
/// Read onerror with empty executetargets attribute
/// </summary>
/// <remarks>
/// This was accidentally allowed in 2.0/3.5 but it should be an error now.
/// </remarks>
[Fact]
public void ReadEmptyExecuteTargets()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<OnError ExecuteTargets=''/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children);
ProjectOnErrorElement onError = (ProjectOnErrorElement)Helpers.GetFirst(target.Children);
Assert.Equal(String.Empty, onError.ExecuteTargetsAttribute);
}
);
}
/// <summary>
/// Read onerror with invalid attribute
/// </summary>
[Fact]
public void ReadInvalidUnexpectedAttribute()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<OnError ExecuteTargets='t' XX='YY'/>
</Target>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Read onerror with invalid child element
/// </summary>
[Fact]
public void ReadInvalidUnexpectedChild()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<OnError ExecuteTargets='t'>
<X/>
</OnError>
</Target>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Read onerror before task
/// </summary>
[Fact]
public void ReadInvalidBeforeTask()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<OnError ExecuteTargets='t'/>
<t/>
</Target>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Read onerror before task
/// </summary>
[Fact]
public void ReadInvalidBeforePropertyGroup()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<OnError ExecuteTargets='t'/>
<PropertyGroup/>
</Target>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Read onerror before task
/// </summary>
[Fact]
public void ReadInvalidBeforeItemGroup()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<OnError ExecuteTargets='t'/>
<ItemGroup/>
</Target>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Set ExecuteTargets
/// </summary>
[Fact]
public void SetExecuteTargetsValid()
{
ProjectOnErrorElement onError = GetOnError();
onError.ExecuteTargetsAttribute = "t2";
Assert.Equal("t2", onError.ExecuteTargetsAttribute);
}
/// <summary>
/// Set ExecuteTargets to null
/// </summary>
[Fact]
public void SetInvalidExecuteTargetsNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
ProjectOnErrorElement onError = GetOnError();
onError.ExecuteTargetsAttribute = null;
}
);
}
/// <summary>
/// Set ExecuteTargets to empty string
/// </summary>
[Fact]
public void SetInvalidExecuteTargetsEmpty()
{
Assert.Throws<ArgumentException>(() =>
{
ProjectOnErrorElement onError = GetOnError();
onError.ExecuteTargetsAttribute = String.Empty;
}
);
}
/// <summary>
/// Set on error condition
/// </summary>
[Fact]
public void SetCondition()
{
ProjectRootElement project = ProjectRootElement.Create();
ProjectTargetElement target = project.AddTarget("t");
ProjectOnErrorElement onError = project.CreateOnErrorElement("et");
target.AppendChild(onError);
Helpers.ClearDirtyFlag(project);
onError.Condition = "c";
Assert.Equal("c", onError.Condition);
Assert.True(project.HasUnsavedChanges);
}
/// <summary>
/// Set on error executetargets value
/// </summary>
[Fact]
public void SetExecuteTargets()
{
ProjectRootElement project = ProjectRootElement.Create();
ProjectTargetElement target = project.AddTarget("t");
ProjectOnErrorElement onError = project.CreateOnErrorElement("et");
target.AppendChild(onError);
Helpers.ClearDirtyFlag(project);
onError.ExecuteTargetsAttribute = "et2";
Assert.Equal("et2", onError.ExecuteTargetsAttribute);
Assert.True(project.HasUnsavedChanges);
}
/// <summary>
/// Get a basic ProjectOnErrorElement
/// </summary>
private static ProjectOnErrorElement GetOnError()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<OnError ExecuteTargets='t' Condition='c'/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children);
ProjectOnErrorElement onError = (ProjectOnErrorElement)Helpers.GetFirst(target.Children);
return onError;
}
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData {
using System;
using System.Resources;
/// <summary>
/// Strongly-typed and parameterized string resources.
/// </summary>
internal static class Strings {
/// <summary>
/// A string like "A service operation with name '{0}' could not be found in the provided model."
/// </summary>
internal static string ODataQueryUtils_DidNotFindServiceOperation(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.ODataQueryUtils_DidNotFindServiceOperation,p0);
}
/// <summary>
/// A string like "Found multiple service operations with name '{0}' in a single entity container. Service operation overloads are not supported."
/// </summary>
internal static string ODataQueryUtils_FoundMultipleServiceOperations(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.ODataQueryUtils_FoundMultipleServiceOperations,p0);
}
/// <summary>
/// A string like "Setting a metadata annotation on a primitive type is not supported."
/// </summary>
internal static string ODataQueryUtils_CannotSetMetadataAnnotationOnPrimitiveType {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.ODataQueryUtils_CannotSetMetadataAnnotationOnPrimitiveType);
}
}
/// <summary>
/// A string like "An entity set with name '{0}' could not be found in the provided model."
/// </summary>
internal static string ODataQueryUtils_DidNotFindEntitySet(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.ODataQueryUtils_DidNotFindEntitySet,p0);
}
/// <summary>
/// A string like "Only operands with primitive types are allowed in binary operators. Found operand types '{0}' and '{1}'."
/// </summary>
internal static string BinaryOperatorQueryNode_InvalidOperandType(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.BinaryOperatorQueryNode_InvalidOperandType,p0,p1);
}
/// <summary>
/// A string like "Both operands of a binary operators must have the same type. Found different operand types '{0}' and '{1}'."
/// </summary>
internal static string BinaryOperatorQueryNode_OperandsMustHaveSameTypes(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.BinaryOperatorQueryNode_OperandsMustHaveSameTypes,p0,p1);
}
/// <summary>
/// A string like "An unsupported query node kind '{0}' was found."
/// </summary>
internal static string QueryExpressionTranslator_UnsupportedQueryNodeKind(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_UnsupportedQueryNodeKind,p0);
}
/// <summary>
/// A string like "An unsupported extension query node was found."
/// </summary>
internal static string QueryExpressionTranslator_UnsupportedExtensionNode {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_UnsupportedExtensionNode);
}
}
/// <summary>
/// A string like "A query node of kind '{0}' was translated to a null expression. Translation of any query node must return a non-null expression."
/// </summary>
internal static string QueryExpressionTranslator_NodeTranslatedToNull(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_NodeTranslatedToNull,p0);
}
/// <summary>
/// A string like "A query node of kind '{0}' was translated to an expression of type '{1}' but an expression of type '{2}' was expected."
/// </summary>
internal static string QueryExpressionTranslator_NodeTranslatedToWrongType(object p0, object p1, object p2) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_NodeTranslatedToWrongType,p0,p1,p2);
}
/// <summary>
/// A string like "A CollectionQueryNode of kind '{0}' with null ItemType was found. Only a CollectionQueryNode with non-null ItemType can be translated into an expression."
/// </summary>
internal static string QueryExpressionTranslator_CollectionQueryNodeWithoutItemType(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_CollectionQueryNodeWithoutItemType,p0);
}
/// <summary>
/// A string like "A SingleValueQueryNode of kind '{0}' with null TypeReference was found. A SingleValueQueryNode can only be translated into an expression if it has a non-null type or statically represents the null value."
/// </summary>
internal static string QueryExpressionTranslator_SingleValueQueryNodeWithoutTypeReference(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_SingleValueQueryNodeWithoutTypeReference,p0);
}
/// <summary>
/// A string like "A ConstantQueryNode of type '{0}' was found. Only a ConstantQueryNode of a primitive type can be translated to an expression."
/// </summary>
internal static string QueryExpressionTranslator_ConstantNonPrimitive(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_ConstantNonPrimitive,p0);
}
/// <summary>
/// A string like "A KeyLookupQueryNode is being applied to a collection of type '{0}' which is of kind '{1}'. KeyLookupQueryNode can only be applied to a collection of entity types."
/// </summary>
internal static string QueryExpressionTranslator_KeyLookupOnlyOnEntities(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_KeyLookupOnlyOnEntities,p0,p1);
}
/// <summary>
/// A string like "A KeyLookupQueryNode is being applied to an expression of incompatible type '{0}'. This KeyLookupQueryNode can only be applied to a collection which translates to an expression of type '{1}'."
/// </summary>
internal static string QueryExpressionTranslator_KeyLookupOnlyOnQueryable(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_KeyLookupOnlyOnQueryable,p0,p1);
}
/// <summary>
/// A string like "A KeyLookupQueryNode is either missing or has more than one value for a key property '{0}' on type '{1}'. There must be exactly one value for the key property."
/// </summary>
internal static string QueryExpressionTranslator_KeyLookupWithoutKeyProperty(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_KeyLookupWithoutKeyProperty,p0,p1);
}
/// <summary>
/// A string like "A KeyLookupQueryNode with no key property values was found. Only a KeyLookupQueryNode with at least one key property value can be translated into an expression."
/// </summary>
internal static string QueryExpressionTranslator_KeyLookupWithNoKeyValues {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_KeyLookupWithNoKeyValues);
}
}
/// <summary>
/// A string like "A KeyPropertyValue instance without a valid key property was found. The KeyPropertyValue.KeyProperty must specify a key property."
/// </summary>
internal static string QueryExpressionTranslator_KeyPropertyValueWithoutProperty {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_KeyPropertyValueWithoutProperty);
}
}
/// <summary>
/// A string like "A KeyPropertyValue instance for key property '{0}' has a value of a wrong type. The KeyPropertyValue.KeyValue must be of the same type as the key property."
/// </summary>
internal static string QueryExpressionTranslator_KeyPropertyValueWithWrongValue(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_KeyPropertyValueWithWrongValue,p0);
}
/// <summary>
/// A string like "A FilterQueryNode input collection was translated to an expression of type '{0}', but type '{1}' is expected."
/// </summary>
internal static string QueryExpressionTranslator_FilterCollectionOfWrongType(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_FilterCollectionOfWrongType,p0,p1);
}
/// <summary>
/// A string like "A FilterQueryNode.Expression was translated to an expression of type '{0}', but the expression must evaluate to a boolean value."
/// </summary>
internal static string QueryExpressionTranslator_FilterExpressionOfWrongType(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_FilterExpressionOfWrongType,p0);
}
/// <summary>
/// A string like "The operand for the unary not operator is being applied to an expression of type '{0}'. A unary not operator can only be applied to an operand of type bool or bool?."
/// </summary>
internal static string QueryExpressionTranslator_UnaryNotOperandNotBoolean(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_UnaryNotOperandNotBoolean,p0);
}
/// <summary>
/// A string like "The source of a PropertyAccessQueryNode was translated to an expression of type '{0}', but type '{1}' is required in order to translate the property access."
/// </summary>
internal static string QueryExpressionTranslator_PropertyAccessSourceWrongType(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_PropertyAccessSourceWrongType,p0,p1);
}
/// <summary>
/// A string like "The source of a PropertyAccessQueryNode is of kind '{0}'. Properties are only supported for type kinds 'Complex' and 'Entity'."
/// </summary>
internal static string QueryExpressionTranslator_PropertyAccessSourceNotStructured(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_PropertyAccessSourceNotStructured,p0);
}
/// <summary>
/// A string like "A ParameterQueryNode which is not defined in the current scope was found."
/// </summary>
internal static string QueryExpressionTranslator_ParameterNotDefinedInScope {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_ParameterNotDefinedInScope);
}
}
/// <summary>
/// A string like "An OrderByQueryNode input collection was translated to an expression of type '{0}', but type '{1}' is expected."
/// </summary>
internal static string QueryExpressionTranslator_OrderByCollectionOfWrongType(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_OrderByCollectionOfWrongType,p0,p1);
}
/// <summary>
/// A string like "An unknown function with name '{0}' was found."
/// </summary>
internal static string QueryExpressionTranslator_UnknownFunction(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_UnknownFunction,p0);
}
/// <summary>
/// A string like "The argument for an invocation of a function with name '{0}' is not a single value. All arguments for this function must be single values."
/// </summary>
internal static string QueryExpressionTranslator_FunctionArgumentNotSingleValue(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_FunctionArgumentNotSingleValue,p0);
}
/// <summary>
/// A string like "No function signature for the function with name '{0}' matches the specified arguments. The function signatures considered are: {1}."
/// </summary>
internal static string QueryExpressionTranslator_NoApplicableFunctionFound(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryExpressionTranslator_NoApplicableFunctionFound,p0,p1);
}
/// <summary>
/// A string like "The specified URI '{0}' must be absolute."
/// </summary>
internal static string QueryDescriptorQueryToken_UriMustBeAbsolute(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryDescriptorQueryToken_UriMustBeAbsolute,p0);
}
/// <summary>
/// A string like "The maximum depth setting must be a number greater than zero."
/// </summary>
internal static string QueryDescriptorQueryToken_MaxDepthInvalid {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryDescriptorQueryToken_MaxDepthInvalid);
}
}
/// <summary>
/// A string like "Invalid value '{0}' for $skip query option found. The $skip query option requires a non-negative integer value."
/// </summary>
internal static string QueryDescriptorQueryToken_InvalidSkipQueryOptionValue(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryDescriptorQueryToken_InvalidSkipQueryOptionValue,p0);
}
/// <summary>
/// A string like "Invalid value '{0}' for $top query option found. The $top query option requires a non-negative integer value."
/// </summary>
internal static string QueryDescriptorQueryToken_InvalidTopQueryOptionValue(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryDescriptorQueryToken_InvalidTopQueryOptionValue,p0);
}
/// <summary>
/// A string like "Invalid value '{0}' for $inlinecount query option found. Valid values are '{1}'."
/// </summary>
internal static string QueryDescriptorQueryToken_InvalidInlineCountQueryOptionValue(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryDescriptorQueryToken_InvalidInlineCountQueryOptionValue,p0,p1);
}
/// <summary>
/// A string like "Query option '{0}' was specified more than once, but it must be specified at most once."
/// </summary>
internal static string QueryOptionUtils_QueryParameterMustBeSpecifiedOnce(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.QueryOptionUtils_QueryParameterMustBeSpecifiedOnce,p0);
}
/// <summary>
/// A string like "The CLR literal of type '{0}' is not supported to be written as a Uri part."
/// </summary>
internal static string UriBuilder_NotSupportedClrLiteral(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.UriBuilder_NotSupportedClrLiteral,p0);
}
/// <summary>
/// A string like "QueryToken '{0}' is not supported to be written as a Uri part."
/// </summary>
internal static string UriBuilder_NotSupportedQueryToken(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.UriBuilder_NotSupportedQueryToken,p0);
}
/// <summary>
/// A string like "Recursion depth exceeded allowed limit."
/// </summary>
internal static string UriQueryExpressionParser_TooDeep {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.UriQueryExpressionParser_TooDeep);
}
}
/// <summary>
/// A string like "Expression expected at position {0} in '{1}'."
/// </summary>
internal static string UriQueryExpressionParser_ExpressionExpected(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.UriQueryExpressionParser_ExpressionExpected,p0,p1);
}
/// <summary>
/// A string like "'(' expected at position {0} in '{1}'."
/// </summary>
internal static string UriQueryExpressionParser_OpenParenExpected(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.UriQueryExpressionParser_OpenParenExpected,p0,p1);
}
/// <summary>
/// A string like "')' or ',' expected at position {0} in '{1}'."
/// </summary>
internal static string UriQueryExpressionParser_CloseParenOrCommaExpected(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.UriQueryExpressionParser_CloseParenOrCommaExpected,p0,p1);
}
/// <summary>
/// A string like "')' or operator expected at position {0} in '{1}'."
/// </summary>
internal static string UriQueryExpressionParser_CloseParenOrOperatorExpected(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.UriQueryExpressionParser_CloseParenOrOperatorExpected,p0,p1);
}
/// <summary>
/// A string like "The URI '{0}' is not valid because it is not based on '{1}'."
/// </summary>
internal static string UriQueryPathParser_RequestUriDoesNotHaveTheCorrectBaseUri(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.UriQueryPathParser_RequestUriDoesNotHaveTheCorrectBaseUri,p0,p1);
}
/// <summary>
/// A string like "Bad Request: there was an error in the query syntax."
/// </summary>
internal static string UriQueryPathParser_SyntaxError {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.UriQueryPathParser_SyntaxError);
}
}
/// <summary>
/// A string like "Too many segments in URI."
/// </summary>
internal static string UriQueryPathParser_TooManySegments {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.UriQueryPathParser_TooManySegments);
}
}
/// <summary>
/// A string like "The key value '{0}' was not recognized as a valid literal."
/// </summary>
internal static string UriQueryPathParser_InvalidKeyValueLiteral(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.UriQueryPathParser_InvalidKeyValueLiteral,p0);
}
/// <summary>
/// A string like "Unable to find property '{2}' on the instance type '{1}' of the structured type '{0}'."
/// </summary>
internal static string PropertyInfoTypeAnnotation_CannotFindProperty(object p0, object p1, object p2) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.PropertyInfoTypeAnnotation_CannotFindProperty,p0,p1,p2);
}
/// <summary>
/// A string like "An unsupported query token kind '{0}' was found."
/// </summary>
internal static string MetadataBinder_UnsupportedQueryTokenKind(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_UnsupportedQueryTokenKind,p0);
}
/// <summary>
/// A string like "An unsupported extension query token was found."
/// </summary>
internal static string MetadataBinder_UnsupportedExtensionToken {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_UnsupportedExtensionToken);
}
}
/// <summary>
/// A string like "Could not find an entity set for root segment '{0}'."
/// </summary>
internal static string MetadataBinder_RootSegmentResourceNotFound(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_RootSegmentResourceNotFound,p0);
}
/// <summary>
/// A string like "Type '{0}' is not an entity type. Key value can only be applied to an entity type."
/// </summary>
internal static string MetadataBinder_KeyValueApplicableOnlyToEntityType(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_KeyValueApplicableOnlyToEntityType,p0);
}
/// <summary>
/// A string like "Type '{0}' does not have a property '{1}'."
/// </summary>
internal static string MetadataBinder_PropertyNotDeclared(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_PropertyNotDeclared,p0,p1);
}
/// <summary>
/// A string like "Property '{0}' is not declared on type '{1}' or is not a key property. Only key properties can be used in key lookups."
/// </summary>
internal static string MetadataBinder_PropertyNotDeclaredOrNotKeyInKeyValue(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_PropertyNotDeclaredOrNotKeyInKeyValue,p0,p1);
}
/// <summary>
/// A string like "An unnamed key value was used in a key lookup on a type '{0}' which has more than one key property. Unnamed key value can only be used on a type with one key property."
/// </summary>
internal static string MetadataBinder_UnnamedKeyValueOnTypeWithMultipleKeyProperties(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_UnnamedKeyValueOnTypeWithMultipleKeyProperties,p0);
}
/// <summary>
/// A string like "A key property '{0}' was found twice in a key lookup. Each key property can be specified just once in a key lookup."
/// </summary>
internal static string MetadataBinder_DuplicitKeyPropertyInKeyValues(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_DuplicitKeyPropertyInKeyValues,p0);
}
/// <summary>
/// A string like "A key lookup on type '{0}' didn't specify values for all key properties. All key properties must be specified in a key lookup."
/// </summary>
internal static string MetadataBinder_NotAllKeyPropertiesSpecifiedInKeyValues(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_NotAllKeyPropertiesSpecifiedInKeyValues,p0);
}
/// <summary>
/// A string like "Expression of type '{0}' cannot be converted to type '{1}'."
/// </summary>
internal static string MetadataBinder_CannotConvertToType(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_CannotConvertToType,p0,p1);
}
/// <summary>
/// A string like "Segment '{0}' which is a service operation returning non-queryable result has a key lookup. Only service operations returning queryable results can have a key lookup applied to them."
/// </summary>
internal static string MetadataBinder_NonQueryableServiceOperationWithKeyLookup(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_NonQueryableServiceOperationWithKeyLookup,p0);
}
/// <summary>
/// A string like "Service operation '{0}' of kind '{1}' returns type '{2}' which is not an entity type. Service operations of kind QueryWithMultipleResults or QueryWithSingleResult can only return entity types."
/// </summary>
internal static string MetadataBinder_QueryServiceOperationOfNonEntityType(object p0, object p1, object p2) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_QueryServiceOperationOfNonEntityType,p0,p1,p2);
}
/// <summary>
/// A string like "Service operation '{0}' is missing the required parameter '{1}'."
/// </summary>
internal static string MetadataBinder_ServiceOperationParameterMissing(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_ServiceOperationParameterMissing,p0,p1);
}
/// <summary>
/// A string like "The parameter '{0}' with value '{1}' for the service operation '{2}' is not a valid literal of type '{3}'."
/// </summary>
internal static string MetadataBinder_ServiceOperationParameterInvalidType(object p0, object p1, object p2, object p3) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_ServiceOperationParameterInvalidType,p0,p1,p2,p3);
}
/// <summary>
/// A string like "The $filter query option cannot be applied to the query path. Filter can only be applied to a collection of entities."
/// </summary>
internal static string MetadataBinder_FilterNotApplicable {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_FilterNotApplicable);
}
}
/// <summary>
/// A string like "The $filter expression must evaluate to a single boolean value."
/// </summary>
internal static string MetadataBinder_FilterExpressionNotSingleValue {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_FilterExpressionNotSingleValue);
}
}
/// <summary>
/// A string like "The $orderby query option cannot be applied to the query path. Ordering can only be applied to a collection of entities."
/// </summary>
internal static string MetadataBinder_OrderByNotApplicable {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_OrderByNotApplicable);
}
}
/// <summary>
/// A string like "The $orderby expression must evaluate to a single value of primitive type."
/// </summary>
internal static string MetadataBinder_OrderByExpressionNotSingleValue {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_OrderByExpressionNotSingleValue);
}
}
/// <summary>
/// A string like "The $skip query option cannot be applied to the query path. Skip can only be applied to a collection of entities."
/// </summary>
internal static string MetadataBinder_SkipNotApplicable {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_SkipNotApplicable);
}
}
/// <summary>
/// A string like "The $top query option cannot be applied to the query path. Top can only be applied to a collection of entities."
/// </summary>
internal static string MetadataBinder_TopNotApplicable {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_TopNotApplicable);
}
}
/// <summary>
/// A string like "A PropertyAccessQueryToken without a parent was encountered outside of $filter or $orderby expression. The PropertyAccessQueryToken without a parent token is only allowed inside $filter or $orderby expressions."
/// </summary>
internal static string MetadataBinder_PropertyAccessWithoutParentParameter {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_PropertyAccessWithoutParentParameter);
}
}
/// <summary>
/// A string like "The MultiValue property '{0}' cannot be used in $filter or $orderby query expression. MultiValue properties are not supported with these query options."
/// </summary>
internal static string MetadataBinder_MultiValuePropertyNotSupportedInExpression(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_MultiValuePropertyNotSupportedInExpression,p0);
}
/// <summary>
/// A string like "The operand for a binary operator '{0}' is not a single value. Binary operators require both operands to be single values."
/// </summary>
internal static string MetadataBinder_BinaryOperatorOperandNotSingleValue(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_BinaryOperatorOperandNotSingleValue,p0);
}
/// <summary>
/// A string like "The operand for a unary operator '{0}' is not a single value. Unary operators require the operand to be a single value."
/// </summary>
internal static string MetadataBinder_UnaryOperatorOperandNotSingleValue(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_UnaryOperatorOperandNotSingleValue,p0);
}
/// <summary>
/// A string like "The parent value for a property access of a property '{0}' is not a single value. Property access can only be applied to a single value."
/// </summary>
internal static string MetadataBinder_PropertyAccessSourceNotSingleValue(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_PropertyAccessSourceNotSingleValue,p0);
}
/// <summary>
/// A string like "A binary operator with incompatible types was detected. Found operand types '{0}' and '{1}' for operator kind '{2}'."
/// </summary>
internal static string MetadataBinder_IncompatibleOperandsError(object p0, object p1, object p2) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_IncompatibleOperandsError,p0,p1,p2);
}
/// <summary>
/// A string like "A unary operator with an incompatible type was detected. Found operand type '{0}' for operator kind '{1}'."
/// </summary>
internal static string MetadataBinder_IncompatibleOperandError(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_IncompatibleOperandError,p0,p1);
}
/// <summary>
/// A string like "An unknown function with name '{0}' was found."
/// </summary>
internal static string MetadataBinder_UnknownFunction(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_UnknownFunction,p0);
}
/// <summary>
/// A string like "The argument for an invocation of a function with name '{0}' is not a single value. All arguments for this function must be single values."
/// </summary>
internal static string MetadataBinder_FunctionArgumentNotSingleValue(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_FunctionArgumentNotSingleValue,p0);
}
/// <summary>
/// A string like "No function signature for the function with name '{0}' matches the specified arguments. The function signatures considered are: {1}."
/// </summary>
internal static string MetadataBinder_NoApplicableFunctionFound(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_NoApplicableFunctionFound,p0,p1);
}
/// <summary>
/// A string like "The system query option '{0}' is not supported."
/// </summary>
internal static string MetadataBinder_UnsupportedSystemQueryOption(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_UnsupportedSystemQueryOption,p0);
}
/// <summary>
/// A string like "A token of kind '{0}' was bound to the value null; this is invalid. A query token must always be bound to a non-null query node."
/// </summary>
internal static string MetadataBinder_BoundNodeCannotBeNull(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_BoundNodeCannotBeNull,p0);
}
/// <summary>
/// A string like "The value '{0}' is not a non-negative integer value. In OData, the $top query option must specify a non-negative integer value."
/// </summary>
internal static string MetadataBinder_TopRequiresNonNegativeInteger(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_TopRequiresNonNegativeInteger,p0);
}
/// <summary>
/// A string like "The value '{0}' is not a non-negative integer value. In OData, the $skip query option must specify a non-negative integer value."
/// </summary>
internal static string MetadataBinder_SkipRequiresNonNegativeInteger(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_SkipRequiresNonNegativeInteger,p0);
}
/// <summary>
/// A string like " The service operation '{0}' does not have an associated result kind. Without a result kind, a service operation cannot be bound."
/// </summary>
internal static string MetadataBinder_ServiceOperationWithoutResultKind(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_ServiceOperationWithoutResultKind,p0);
}
/// <summary>
/// A string like "Encountered invalid type cast. '{0}' is not assignable from '{1}'."
/// </summary>
internal static string MetadataBinder_HierarchyNotFollowed(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_HierarchyNotFollowed,p0,p1);
}
/// <summary>
/// A string like "Encountered Root segment in non-root location."
/// </summary>
internal static string MetadataBinder_MustBeCalledOnRoot {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_MustBeCalledOnRoot);
}
}
/// <summary>
/// A string like "A segment without an associated type was given as input."
/// </summary>
internal static string MetadataBinder_NoTypeSupported {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_NoTypeSupported);
}
}
/// <summary>
/// A string like "Only collection navigation properties may head Any/All queries."
/// </summary>
internal static string MetadataBinder_InvalidAnyAllHead {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.MetadataBinder_InvalidAnyAllHead);
}
}
/// <summary>
/// A string like "An internal error '{0}' occurred."
/// </summary>
internal static string General_InternalError(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.General_InternalError,p0);
}
/// <summary>
/// A string like "A non-negative integer value was expected, but the value '{0}' is not a valid non-negative integer."
/// </summary>
internal static string ExceptionUtils_CheckIntegerNotNegative(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.ExceptionUtils_CheckIntegerNotNegative,p0);
}
/// <summary>
/// A string like "A positive integer value was expected, but the value '{0}' is not a valid positive integer."
/// </summary>
internal static string ExceptionUtils_CheckIntegerPositive(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.ExceptionUtils_CheckIntegerPositive,p0);
}
/// <summary>
/// A string like "A positive long value was expected; however, the value '{0}' is not a valid positive long value."
/// </summary>
internal static string ExceptionUtils_CheckLongPositive(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.ExceptionUtils_CheckLongPositive,p0);
}
/// <summary>
/// A string like "Value cannot be null or empty."
/// </summary>
internal static string ExceptionUtils_ArgumentStringNullOrEmpty {
get {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.ExceptionUtils_ArgumentStringNullOrEmpty);
}
}
/// <summary>
/// A string like "An identifier was expected at position {0}."
/// </summary>
internal static string ExpressionToken_IdentifierExpected(object p0) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.ExpressionToken_IdentifierExpected,p0);
}
/// <summary>
/// A string like "There is an unterminated string literal at position {0} in '{1}'."
/// </summary>
internal static string ExpressionLexer_UnterminatedStringLiteral(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.ExpressionLexer_UnterminatedStringLiteral,p0,p1);
}
/// <summary>
/// A string like "Syntax error: character '{0}' is not valid at position {1} in '{2}'."
/// </summary>
internal static string ExpressionLexer_InvalidCharacter(object p0, object p1, object p2) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.ExpressionLexer_InvalidCharacter,p0,p1,p2);
}
/// <summary>
/// A string like "Syntax error at position {0} in '{1}'."
/// </summary>
internal static string ExpressionLexer_SyntaxError(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.ExpressionLexer_SyntaxError,p0,p1);
}
/// <summary>
/// A string like "There is an unterminated literal at position {0} in '{1}'."
/// </summary>
internal static string ExpressionLexer_UnterminatedLiteral(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.ExpressionLexer_UnterminatedLiteral,p0,p1);
}
/// <summary>
/// A string like "A digit was expected at position {0} in '{1}'."
/// </summary>
internal static string ExpressionLexer_DigitExpected(object p0, object p1) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.ExpressionLexer_DigitExpected,p0,p1);
}
/// <summary>
/// A string like "Unrecognized '{0}' literal '{1}' at '{2}' in '{3}'."
/// </summary>
internal static string UriQueryExpressionParser_UnrecognizedLiteral(object p0, object p1, object p2, object p3) {
return Microsoft.Data.OData.TextRes.GetString(Microsoft.Data.OData.TextRes.UriQueryExpressionParser_UnrecognizedLiteral,p0,p1,p2,p3);
}
}
/// <summary>
/// Strongly-typed and parameterized exception factory.
/// </summary>
internal static partial class Error {
/// <summary>
/// The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.
/// </summary>
internal static Exception ArgumentNull(string paramName) {
return new ArgumentNullException(paramName);
}
/// <summary>
/// The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.
/// </summary>
internal static Exception ArgumentOutOfRange(string paramName) {
return new ArgumentOutOfRangeException(paramName);
}
/// <summary>
/// The exception that is thrown when the author has yet to implement the logic at this point in the program. This can act as an exception based TODO tag.
/// </summary>
internal static Exception NotImplemented() {
return new NotImplementedException();
}
/// <summary>
/// The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.
/// </summary>
internal static Exception NotSupported() {
return new NotSupportedException();
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace SiteCollectionCreationWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
using Microsoft.VisualBasic.PowerPacks;
namespace _4PosBackOffice.NET
{
internal partial class frmPromotion : System.Windows.Forms.Form
{
private ADODB.Recordset withEventsField_adoPrimaryRS;
public ADODB.Recordset adoPrimaryRS {
get { return withEventsField_adoPrimaryRS; }
set {
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete -= adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord -= adoPrimaryRS_WillChangeRecord;
}
withEventsField_adoPrimaryRS = value;
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete += adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord += adoPrimaryRS_WillChangeRecord;
}
}
}
bool mbChangedByCode;
int mvBookMark;
bool mbEditFlag;
bool mbAddNewFlag;
bool mbDataChanged;
int gID;
int p_Prom;
bool p_Prom1;
List<CheckBox> chkFields = new List<CheckBox>();
List<TextBox> txtFields = new List<TextBox>();
List<DateTimePicker> DTFields = new List<DateTimePicker>();
private void loadLanguage()
{
//frmPromotion = No Code [Edit Promotion Details]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmPromotion.Caption = rsLang("LanguageLayoutLnk_Description"): frmPromotion.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1074;
//Undo|Checked
if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1085;
//Print|Checked
if (modRecordSet.rsLang.RecordCount){cmdPrint.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdPrint.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1010;
//General|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_5.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_5.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1139;
//Promotion Name|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_38.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_38.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1140;
//Start Date|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1141;
//End Date|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1142;
//From Time|Checked
if (modRecordSet.rsLang.RecordCount){Label1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1143;
//To Time|Checked
if (modRecordSet.rsLang.RecordCount){Label2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2463;
//Disabled|Checked
if (modRecordSet.rsLang.RecordCount){_chkFields_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_chkFields_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1145;
//Apply only to POS channel|Checked
if (modRecordSet.rsLang.RecordCount){_chkFields_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_chkFields_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1146;
//Only for Specific Time|Checked
if (modRecordSet.rsLang.RecordCount){_chkFields_2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_chkFields_2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1147;
//Add|Checked
if (modRecordSet.rsLang.RecordCount){cmdAdd.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdAdd.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1148;
//Delete|Checked
if (modRecordSet.rsLang.RecordCount){cmdDelete.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdDelete.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmPromotion.HelpContextID was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
private void buildDataControls()
{
// doDataControl Me.cmbChannel, "SELECT ChannelID, Channel_Name FROM Channel ORDER BY ChannelID", "Customer_ChannelID", "ChannelID", "Channel_Name"
}
private void doDataControl(ref myDataGridView dataControl, ref string sql, ref string DataField, ref string boundColumn, ref string listField)
{
//Dim rs As ADODB.Recordset
//rs = getRS(sql)
//UPGRADE_WARNING: Couldn't resolve default property of object dataControl.RowSource. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//dataControl.DataBindings.Add(rs)
//UPGRADE_ISSUE: Control method dataControl.DataSource was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
//dataControl.DataSource = adoPrimaryRS
//UPGRADE_ISSUE: Control method dataControl.DataField was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
//dataControl.DataField = DataField
//UPGRADE_WARNING: Couldn't resolve default property of object dataControl.boundColumn. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//dataControl.boundColumn = boundColumn
//UPGRADE_WARNING: Couldn't resolve default property of object dataControl.listField. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//dataControl.listField = listField
}
public void loadItem(ref int id)
{
System.Windows.Forms.TextBox oText = null;
DateTimePicker oDate = new DateTimePicker();
System.Windows.Forms.CheckBox oCheck = null;
// ERROR: Not supported in C#: OnErrorStatement
if (id) {
p_Prom = id;
adoPrimaryRS = modRecordSet.getRS(ref "select Promotion.* from Promotion WHERE PromotionID = " + id);
} else {
adoPrimaryRS = modRecordSet.getRS(ref "select * from Promotion");
adoPrimaryRS.AddNew();
this.Text = this.Text + " [New record]";
mbAddNewFlag = true;
}
setup();
foreach (TextBox oText_loopVariable in this.txtFields) {
oText = oText_loopVariable;
oText.DataBindings.Add(adoPrimaryRS);
oText.MaxLength = adoPrimaryRS.Fields(oText.DataBindings).DefinedSize;
}
foreach (DateTimePicker oDate_loopVariable in this.DTFields) {
oDate = oDate_loopVariable;
oDate.DataBindings.Add(adoPrimaryRS);
}
//adoPrimaryRS("Promotion_SpeTime")
//Bind the check boxes to the data provider
foreach (CheckBox oCheck_loopVariable in this.chkFields) {
oCheck = oCheck_loopVariable;
oCheck.DataBindings.Add(adoPrimaryRS);
}
buildDataControls();
mbDataChanged = false;
loadItems();
loadLanguage();
ShowDialog();
}
private void setup()
{
}
private void cmdAdd_Click(System.Object eventSender, System.EventArgs eventArgs)
{
int lID = 0;
ADODB.Recordset rs = default(ADODB.Recordset);
lID = My.MyProject.Forms.frmStockList.getItem();
if (lID != 0) {
// ERROR: Not supported in C#: OnErrorStatement
//cnnDB.Execute "INSERT INTO PromotionItem ( PromotionItem_PromotionID, PromotionItem_StockItemID, PromotionItem_Quantity, PromotionItem_Price ) SELECT " & adoPrimaryRS("PromotionID") & " AS [Set], CatalogueChannelLnk.CatalogueChannelLnk_StockItemID, 1,CatalogueChannelLnk.CatalogueChannelLnk_Price From CatalogueChannelLnk WHERE (((CatalogueChannelLnk.CatalogueChannelLnk_StockItemID)=" & lID & ") AND ((CatalogueChannelLnk.CatalogueChannelLnk_Quantity)=1) AND ((CatalogueChannelLnk.CatalogueChannelLnk_ChannelID)=1));"
My.MyProject.Forms.frmPromotionItem.loadItem(adoPrimaryRS.Fields("PromotionID").Value, lID);
loadItems(lID);
}
}
private void cmdDelete_Click(System.Object eventSender, System.EventArgs eventArgs)
{
int lID = 0;
if (lvPromotion.FocusedItem == null) {
} else {
if (Interaction.MsgBox("Are you sure you wish to remove " + lvPromotion.FocusedItem.Text + " from this Promotion?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "DELETE") == MsgBoxResult.Yes) {
lID = Convert.ToInt32(Strings.Split(lvPromotion.FocusedItem.Name, "_")[0]);
modRecordSet.cnnDB.Execute("DELETE PromotionItem.* From PromotionItem WHERE PromotionItem.PromotionItem_PromotionID=" + adoPrimaryRS.Fields("PromotionID").Value + " AND PromotionItem.PromotionItem_StockItemID=" + lID + " AND PromotionItem.PromotionItem_Quantity=" + Strings.Split(lvPromotion.FocusedItem.Name, "_")[1] + ";");
loadItems();
}
}
}
private void cmdPrint_Click(System.Object eventSender, System.EventArgs eventArgs)
{
update_Renamed();
modApplication.report_Promotion();
}
private void frmPromotion_Load(System.Object eventSender, System.EventArgs eventArgs)
{
chkFields.AddRange(new CheckBox[] {
_chkFields_0,
_chkFields_1,
_chkFields_2
});
txtFields.AddRange(new TextBox[] { _txtFields_0 });
DTFields.AddRange(new DateTimePicker[] {
_DTFields_0,
_DTFields_1,
_DTFields_2,
_DTFields_3
});
lvPromotion.Columns.Clear();
lvPromotion.Columns.Add("", "Stock Item", Convert.ToInt32(sizeConvertors.twipsToPixels(4050, true)));
lvPromotion.Columns.Add("QTY", Convert.ToInt32(sizeConvertors.twipsToPixels(800, true)), System.Windows.Forms.HorizontalAlignment.Right);
lvPromotion.Columns.Add("Price", Convert.ToInt32(sizeConvertors.twipsToPixels(1440, true)), System.Windows.Forms.HorizontalAlignment.Right);
}
private void loadItems(ref int lID = 0, ref short quantity = 0)
{
System.Windows.Forms.ListViewItem listItem = null;
ADODB.Recordset rs = default(ADODB.Recordset);
lvPromotion.Items.Clear();
rs = modRecordSet.getRS(ref "SELECT StockItem.StockItem_Name, PromotionItem.* FROM PromotionItem INNER JOIN StockItem ON PromotionItem.PromotionItem_StockItemID = StockItem.StockItemID Where (((PromotionItem.PromotionItem_PromotionID) = " + adoPrimaryRS.Fields("PromotionID").Value + ")) ORDER BY StockItem.StockItem_Name, PromotionItem.PromotionItem_Quantity;");
while (!(rs.EOF)) {
listItem = lvPromotion.Items.Add(rs.Fields("PromotionItem_StockItemID").Value + "_" + rs.Fields("PromotionItem_Quantity").Value, rs.Fields("Stockitem_Name").Value, "");
//UPGRADE_WARNING: Lower bound of collection listItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"'
if (listItem.SubItems.Count > 1) {
listItem.SubItems[1].Text = rs.Fields("PromotionItem_Quantity").Value;
} else {
listItem.SubItems.Insert(1, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, rs.Fields("PromotionItem_Quantity").Value));
}
//UPGRADE_WARNING: Lower bound of collection listItem has changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A3B628A0-A810-4AE2-BFA2-9E7A29EB9AD0"'
if (listItem.SubItems.Count > 2) {
listItem.SubItems[2].Text = Strings.FormatNumber(rs.Fields("PromotionItem_Price").Value, 2);
} else {
listItem.SubItems.Insert(2, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, Strings.FormatNumber(rs.Fields("PromotionItem_Price").Value, 2)));
}
if (rs.Fields("PromotionItem_StockItemID").Value == lID & rs.Fields("PromotionItem_Quantity").Value == quantity)
listItem.Selected = true;
rs.moveNext();
}
}
//UPGRADE_WARNING: Event frmPromotion.Resize may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
private void frmPromotion_Resize(System.Object eventSender, System.EventArgs eventArgs)
{
Button cmdLast = new Button();
Button cmdnext = new Button();
Label lblStatus = new Label();
// ERROR: Not supported in C#: OnErrorStatement
lblStatus.Width = sizeConvertors.pixelToTwips(this.Width, true) - 1500;
cmdnext.Left = lblStatus.Width + 700;
cmdLast.Left = cmdnext.Left + 340;
}
private void frmPromotion_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (mbEditFlag | mbAddNewFlag)
goto EventExitSub;
switch (KeyAscii) {
case System.Windows.Forms.Keys.Escape:
KeyAscii = 0;
adoPrimaryRS.Move(0);
cmdClose.Focus();
System.Windows.Forms.Application.DoEvents();
cmdClose_Click(cmdClose, new System.EventArgs());
break;
}
EventExitSub:
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void frmPromotion_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
{
//UPGRADE_WARNING: Screen property Screen.MousePointer has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6BA9B8D2-2A32-4B6E-8D36-44949974A5B4"'
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
}
private void adoPrimaryRS_MoveComplete(ADODB.EventReasonEnum adReason, ADODB.Error pError, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This will display the current record position for this recordset
}
private void adoPrimaryRS_WillChangeRecord(ADODB.EventReasonEnum adReason, int cRecords, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This is where you put validation code
//This event gets called when the following actions occur
bool bCancel = false;
switch (adReason) {
case ADODB.EventReasonEnum.adRsnAddNew:
break;
case ADODB.EventReasonEnum.adRsnClose:
break;
case ADODB.EventReasonEnum.adRsnDelete:
break;
case ADODB.EventReasonEnum.adRsnFirstChange:
break;
case ADODB.EventReasonEnum.adRsnMove:
break;
case ADODB.EventReasonEnum.adRsnRequery:
break;
case ADODB.EventReasonEnum.adRsnResynch:
break;
case ADODB.EventReasonEnum.adRsnUndoAddNew:
break;
case ADODB.EventReasonEnum.adRsnUndoDelete:
break;
case ADODB.EventReasonEnum.adRsnUndoUpdate:
break;
case ADODB.EventReasonEnum.adRsnUpdate:
break;
}
if (bCancel)
adStatus = ADODB.EventStatusEnum.adStatusCancel;
}
private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs)
{
// ERROR: Not supported in C#: OnErrorStatement
if (mbAddNewFlag) {
this.Close();
} else {
mbEditFlag = false;
mbAddNewFlag = false;
adoPrimaryRS.CancelUpdate();
if (mvBookMark > 0) {
adoPrimaryRS.Bookmark = mvBookMark;
} else {
adoPrimaryRS.MoveFirst();
}
mbDataChanged = false;
}
}
//UPGRADE_NOTE: update was upgraded to update_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"'
private bool update_Renamed()
{
bool functionReturnValue = false;
// ERROR: Not supported in C#: OnErrorStatement
functionReturnValue = true;
adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll);
if (mbAddNewFlag) {
adoPrimaryRS.MoveLast();
//move to the new record
}
mbEditFlag = false;
mbAddNewFlag = false;
mbDataChanged = false;
return functionReturnValue;
UpdateErr:
Interaction.MsgBox(Err().Description);
functionReturnValue = false;
return functionReturnValue;
}
private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs)
{
cmdClose.Focus();
System.Windows.Forms.Application.DoEvents();
if (update_Renamed()) {
if (chkFields[1].CheckState == 0) {
modRecordSet.cnnDB.Execute("UPDATE Promotion SET Promotion_StartDate = #" + DTFields[0].Value + "#, Promotion_EndDate = #" + DTFields[1].Value + "#, Promotion_StartTime = #" + DTFields[2].Value + "# ,Promotion_EndTime =#" + DTFields[3].Value + "# WHERE PromotionID = " + p_Prom + ";");
}
this.Close();
}
}
private void lvPromotion_DoubleClick(System.Object eventSender, System.EventArgs eventArgs)
{
int lID = 0;
short lQty = 0;
if (lvPromotion.FocusedItem == null) {
} else {
lID = Convert.ToInt32(Strings.Split(lvPromotion.FocusedItem.Name, "_")[0]);
lQty = Convert.ToInt16(Strings.Split(lvPromotion.FocusedItem.Name, "_")[1]);
My.MyProject.Forms.frmPromotionItem.loadItem(ref adoPrimaryRS.Fields("PromotionID").Value, ref lID, ref Convert.ToInt16(lQty));
loadItems(ref lID, ref lQty);
}
}
private void lvPromotion_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (KeyAscii == 13) {
lvPromotion_DoubleClick(lvPromotion, new System.EventArgs());
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void txtFields_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
int Index = 0;
TextBox txtBox = new TextBox();
txtBox = (TextBox)eventSender;
Index = GetIndex.GetIndexer(ref txtBox, ref txtFields);
modUtilities.MyGotFocus(ref txtFields[Index]);
}
private void txtInteger_MyGotFocus(ref short Index)
{
// MyGotFocusNumeric txtInteger(Index)
}
private void txtInteger_KeyPress(ref short Index, ref short KeyAscii)
{
// KeyPress KeyAscii
}
private void txtInteger_MyLostFocus(ref short Index)
{
// LostFocus txtInteger(Index), 0
}
private void txtFloat_MyGotFocus(ref short Index)
{
// MyGotFocusNumeric txtFloat(Index)
}
private void txtFloat_KeyPress(ref short Index, ref short KeyAscii)
{
// KeyPress KeyAscii
}
private void txtFloat_MyLostFocus(ref short Index)
{
// MyGotFocusNumeric txtFloat(Index), 2
}
private void txtFloatNegative_MyGotFocus(ref short Index)
{
// MyGotFocusNumeric txtFloatNegative(Index)
}
private void txtFloatNegative_KeyPress(ref short Index, ref short KeyAscii)
{
// KeyPressNegative txtFloatNegative(Index), KeyAscii
}
private void txtFloatNegative_MyLostFocus(ref short Index)
{
// LostFocus txtFloatNegative(Index), 2
}
}
}
| |
//
// ImageWriter.cs
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
#if !READ_ONLY
using Mono.Cecil.Cil;
using Mono.Cecil.Metadata;
using RVA = System.UInt32;
namespace Mono.Cecil.PE {
sealed class ImageWriter : BinaryStreamWriter {
readonly ModuleDefinition module;
readonly MetadataBuilder metadata;
readonly TextMap text_map;
ImageDebugDirectory debug_directory;
byte [] debug_data;
ByteBuffer win32_resources;
const uint pe_header_size = 0x178u;
const uint section_header_size = 0x28u;
const uint file_alignment = 0x200;
const uint section_alignment = 0x2000;
const ulong image_base = 0x00400000;
internal const RVA text_rva = 0x2000;
readonly bool pe64;
readonly bool has_reloc;
readonly uint time_stamp;
internal Section text;
internal Section rsrc;
internal Section reloc;
ushort sections;
ImageWriter (ModuleDefinition module, MetadataBuilder metadata, Stream stream)
: base (stream)
{
this.module = module;
this.metadata = metadata;
this.pe64 = module.Architecture == TargetArchitecture.AMD64 || module.Architecture == TargetArchitecture.IA64;
this.has_reloc = module.Architecture == TargetArchitecture.I386;
this.GetDebugHeader ();
this.GetWin32Resources ();
this.text_map = BuildTextMap ();
this.sections = (ushort) (has_reloc ? 2 : 1); // text + reloc?
this.time_stamp = (uint) DateTime.UtcNow.Subtract (new DateTime (1970, 1, 1)).TotalSeconds;
}
void GetDebugHeader ()
{
var symbol_writer = metadata.symbol_writer;
if (symbol_writer == null)
return;
if (!symbol_writer.GetDebugHeader (out debug_directory, out debug_data))
debug_data = Empty<byte>.Array;
}
void GetWin32Resources ()
{
var rsrc = GetImageResourceSection ();
if (rsrc == null)
return;
var raw_resources = new byte [rsrc.Data.Length];
Buffer.BlockCopy (rsrc.Data, 0, raw_resources, 0, rsrc.Data.Length);
win32_resources = new ByteBuffer (raw_resources);
}
Section GetImageResourceSection ()
{
if (!module.HasImage)
return null;
const string rsrc_section = ".rsrc";
return module.Image.GetSection (rsrc_section);
}
public static ImageWriter CreateWriter (ModuleDefinition module, MetadataBuilder metadata, Stream stream)
{
var writer = new ImageWriter (module, metadata, stream);
writer.BuildSections ();
return writer;
}
void BuildSections ()
{
var has_win32_resources = win32_resources != null;
if (has_win32_resources)
sections++;
text = CreateSection (".text", text_map.GetLength (), null);
var previous = text;
if (has_win32_resources) {
rsrc = CreateSection (".rsrc", (uint) win32_resources.length, previous);
PatchWin32Resources (win32_resources);
previous = rsrc;
}
if (has_reloc)
reloc = CreateSection (".reloc", 12u, previous);
}
Section CreateSection (string name, uint size, Section previous)
{
return new Section {
Name = name,
VirtualAddress = previous != null
? previous.VirtualAddress + Align (previous.VirtualSize, section_alignment)
: text_rva,
VirtualSize = size,
PointerToRawData = previous != null
? previous.PointerToRawData + previous.SizeOfRawData
: Align (GetHeaderSize (), file_alignment),
SizeOfRawData = Align (size, file_alignment)
};
}
static uint Align (uint value, uint align)
{
align--;
return (value + align) & ~align;
}
void WriteDOSHeader ()
{
Write (new byte [] {
// dos header start
0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00,
0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff,
0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
// lfanew
0x80, 0x00, 0x00, 0x00,
// dos header end
0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09,
0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21,
0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72,
0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63,
0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62,
0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69,
0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20, 0x6d,
0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a,
0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00
});
}
void WritePEFileHeader ()
{
WriteUInt32 (0x00004550); // Magic
WriteUInt16 (GetMachine ()); // Machine
WriteUInt16 (sections); // NumberOfSections
WriteUInt32 (time_stamp);
WriteUInt32 (0); // PointerToSymbolTable
WriteUInt32 (0); // NumberOfSymbols
WriteUInt16 ((ushort) (!pe64 ? 0xe0 : 0xf0)); // SizeOfOptionalHeader
// ExecutableImage | (pe64 ? 32BitsMachine : LargeAddressAware)
var characteristics = (ushort) (0x0002 | (!pe64 ? 0x0100 : 0x0020));
if (module.Kind == ModuleKind.Dll || module.Kind == ModuleKind.NetModule)
characteristics |= 0x2000;
WriteUInt16 (characteristics); // Characteristics
}
ushort GetMachine ()
{
switch (module.Architecture) {
case TargetArchitecture.I386:
return 0x014c;
case TargetArchitecture.AMD64:
return 0x8664;
case TargetArchitecture.IA64:
return 0x0200;
case TargetArchitecture.ARMv7:
return 0x01c4;
}
throw new NotSupportedException ();
}
Section LastSection ()
{
if (reloc != null)
return reloc;
if (rsrc != null)
return rsrc;
return text;
}
void WriteOptionalHeaders ()
{
WriteUInt16 ((ushort) (!pe64 ? 0x10b : 0x20b)); // Magic
WriteByte (8); // LMajor
WriteByte (0); // LMinor
WriteUInt32 (text.SizeOfRawData); // CodeSize
WriteUInt32 ((reloc != null ? reloc.SizeOfRawData : 0)
+ (rsrc != null ? rsrc.SizeOfRawData : 0)); // InitializedDataSize
WriteUInt32 (0); // UninitializedDataSize
var startub_stub = text_map.GetRange (TextSegment.StartupStub);
WriteUInt32 (startub_stub.Length > 0 ? startub_stub.Start : 0); // EntryPointRVA
WriteUInt32 (text_rva); // BaseOfCode
if (!pe64) {
WriteUInt32 (0); // BaseOfData
WriteUInt32 ((uint) image_base); // ImageBase
} else {
WriteUInt64 (image_base); // ImageBase
}
WriteUInt32 (section_alignment); // SectionAlignment
WriteUInt32 (file_alignment); // FileAlignment
WriteUInt16 (4); // OSMajor
WriteUInt16 (0); // OSMinor
WriteUInt16 (0); // UserMajor
WriteUInt16 (0); // UserMinor
WriteUInt16 (4); // SubSysMajor
WriteUInt16 (0); // SubSysMinor
WriteUInt32 (0); // Reserved
var last_section = LastSection();
WriteUInt32 (last_section.VirtualAddress + Align (last_section.VirtualSize, section_alignment)); // ImageSize
WriteUInt32 (text.PointerToRawData); // HeaderSize
WriteUInt32 (0); // Checksum
WriteUInt16 (GetSubSystem ()); // SubSystem
WriteUInt16 ((ushort) module.Characteristics); // DLLFlags
const ulong stack_reserve = 0x100000;
const ulong stack_commit = 0x1000;
const ulong heap_reserve = 0x100000;
const ulong heap_commit = 0x1000;
if (!pe64) {
WriteUInt32 ((uint) stack_reserve);
WriteUInt32 ((uint) stack_commit);
WriteUInt32 ((uint) heap_reserve);
WriteUInt32 ((uint) heap_commit);
} else {
WriteUInt64 (stack_reserve);
WriteUInt64 (stack_commit);
WriteUInt64 (heap_reserve);
WriteUInt64 (heap_commit);
}
WriteUInt32 (0); // LoaderFlags
WriteUInt32 (16); // NumberOfDataDir
WriteZeroDataDirectory (); // ExportTable
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.ImportDirectory)); // ImportTable
if (rsrc != null) { // ResourceTable
WriteUInt32 (rsrc.VirtualAddress);
WriteUInt32 (rsrc.VirtualSize);
} else
WriteZeroDataDirectory ();
WriteZeroDataDirectory (); // ExceptionTable
WriteZeroDataDirectory (); // CertificateTable
WriteUInt32 (reloc != null ? reloc.VirtualAddress : 0); // BaseRelocationTable
WriteUInt32 (reloc != null ? reloc.VirtualSize : 0);
if (text_map.GetLength (TextSegment.DebugDirectory) > 0) {
WriteUInt32 (text_map.GetRVA (TextSegment.DebugDirectory));
WriteUInt32 (28u);
} else
WriteZeroDataDirectory ();
WriteZeroDataDirectory (); // Copyright
WriteZeroDataDirectory (); // GlobalPtr
WriteZeroDataDirectory (); // TLSTable
WriteZeroDataDirectory (); // LoadConfigTable
WriteZeroDataDirectory (); // BoundImport
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.ImportAddressTable)); // IAT
WriteZeroDataDirectory (); // DelayImportDesc
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.CLIHeader)); // CLIHeader
WriteZeroDataDirectory (); // Reserved
}
void WriteZeroDataDirectory ()
{
WriteUInt32 (0);
WriteUInt32 (0);
}
ushort GetSubSystem ()
{
switch (module.Kind) {
case ModuleKind.Console:
case ModuleKind.Dll:
case ModuleKind.NetModule:
return 0x3;
case ModuleKind.Windows:
return 0x2;
default:
throw new ArgumentOutOfRangeException ();
}
}
void WriteSectionHeaders ()
{
WriteSection (text, 0x60000020);
if (rsrc != null)
WriteSection (rsrc, 0x40000040);
if (reloc != null)
WriteSection (reloc, 0x42000040);
}
void WriteSection (Section section, uint characteristics)
{
var name = new byte [8];
var sect_name = section.Name;
for (int i = 0; i < sect_name.Length; i++)
name [i] = (byte) sect_name [i];
WriteBytes (name);
WriteUInt32 (section.VirtualSize);
WriteUInt32 (section.VirtualAddress);
WriteUInt32 (section.SizeOfRawData);
WriteUInt32 (section.PointerToRawData);
WriteUInt32 (0); // PointerToRelocations
WriteUInt32 (0); // PointerToLineNumbers
WriteUInt16 (0); // NumberOfRelocations
WriteUInt16 (0); // NumberOfLineNumbers
WriteUInt32 (characteristics);
}
void MoveTo (uint pointer)
{
BaseStream.Seek (pointer, SeekOrigin.Begin);
}
void MoveToRVA (Section section, RVA rva)
{
BaseStream.Seek (section.PointerToRawData + rva - section.VirtualAddress, SeekOrigin.Begin);
}
void MoveToRVA (TextSegment segment)
{
MoveToRVA (text, text_map.GetRVA (segment));
}
void WriteRVA (RVA rva)
{
if (!pe64)
WriteUInt32 (rva);
else
WriteUInt64 (rva);
}
void PrepareSection (Section section)
{
MoveTo (section.PointerToRawData);
const int buffer_size = 4096;
if (section.SizeOfRawData <= buffer_size) {
Write (new byte [section.SizeOfRawData]);
MoveTo (section.PointerToRawData);
return;
}
var written = 0;
var buffer = new byte [buffer_size];
while (written != section.SizeOfRawData) {
var write_size = System.Math.Min((int) section.SizeOfRawData - written, buffer_size);
Write (buffer, 0, write_size);
written += write_size;
}
MoveTo (section.PointerToRawData);
}
void WriteText ()
{
PrepareSection (text);
// ImportAddressTable
if (has_reloc) {
WriteRVA (text_map.GetRVA (TextSegment.ImportHintNameTable));
WriteRVA (0);
}
// CLIHeader
WriteUInt32 (0x48);
WriteUInt16 (2);
WriteUInt16 ((ushort) ((module.Runtime <= TargetRuntime.Net_1_1) ? 0 : 5));
WriteUInt32 (text_map.GetRVA (TextSegment.MetadataHeader));
WriteUInt32 (GetMetadataLength ());
WriteUInt32 ((uint) module.Attributes);
WriteUInt32 (metadata.entry_point.ToUInt32 ());
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.Resources));
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.StrongNameSignature));
WriteZeroDataDirectory (); // CodeManagerTable
WriteZeroDataDirectory (); // VTableFixups
WriteZeroDataDirectory (); // ExportAddressTableJumps
WriteZeroDataDirectory (); // ManagedNativeHeader
// Code
MoveToRVA (TextSegment.Code);
WriteBuffer (metadata.code);
// Resources
MoveToRVA (TextSegment.Resources);
WriteBuffer (metadata.resources);
// Data
if (metadata.data.length > 0) {
MoveToRVA (TextSegment.Data);
WriteBuffer (metadata.data);
}
// StrongNameSignature
// stays blank
// MetadataHeader
MoveToRVA (TextSegment.MetadataHeader);
WriteMetadataHeader ();
WriteMetadata ();
// DebugDirectory
if (text_map.GetLength (TextSegment.DebugDirectory) > 0) {
MoveToRVA (TextSegment.DebugDirectory);
WriteDebugDirectory ();
}
if (!has_reloc)
return;
// ImportDirectory
MoveToRVA (TextSegment.ImportDirectory);
WriteImportDirectory ();
// StartupStub
MoveToRVA (TextSegment.StartupStub);
WriteStartupStub ();
}
uint GetMetadataLength ()
{
return text_map.GetRVA (TextSegment.DebugDirectory) - text_map.GetRVA (TextSegment.MetadataHeader);
}
void WriteMetadataHeader ()
{
WriteUInt32 (0x424a5342); // Signature
WriteUInt16 (1); // MajorVersion
WriteUInt16 (1); // MinorVersion
WriteUInt32 (0); // Reserved
var version = GetZeroTerminatedString (module.runtime_version);
WriteUInt32 ((uint) version.Length);
WriteBytes (version);
WriteUInt16 (0); // Flags
WriteUInt16 (GetStreamCount ());
uint offset = text_map.GetRVA (TextSegment.TableHeap) - text_map.GetRVA (TextSegment.MetadataHeader);
WriteStreamHeader (ref offset, TextSegment.TableHeap, "#~");
WriteStreamHeader (ref offset, TextSegment.StringHeap, "#Strings");
WriteStreamHeader (ref offset, TextSegment.UserStringHeap, "#US");
WriteStreamHeader (ref offset, TextSegment.GuidHeap, "#GUID");
WriteStreamHeader (ref offset, TextSegment.BlobHeap, "#Blob");
}
ushort GetStreamCount ()
{
return (ushort) (
1 // #~
+ 1 // #Strings
+ (metadata.user_string_heap.IsEmpty ? 0 : 1) // #US
+ 1 // GUID
+ (metadata.blob_heap.IsEmpty ? 0 : 1)); // #Blob
}
void WriteStreamHeader (ref uint offset, TextSegment heap, string name)
{
var length = (uint) text_map.GetLength (heap);
if (length == 0)
return;
WriteUInt32 (offset);
WriteUInt32 (length);
WriteBytes (GetZeroTerminatedString (name));
offset += length;
}
static byte [] GetZeroTerminatedString (string @string)
{
return GetString (@string, (@string.Length + 1 + 3) & ~3);
}
static byte [] GetSimpleString (string @string)
{
return GetString (@string, @string.Length);
}
static byte [] GetString (string @string, int length)
{
var bytes = new byte [length];
for (int i = 0; i < @string.Length; i++)
bytes [i] = (byte) @string [i];
return bytes;
}
void WriteMetadata ()
{
WriteHeap (TextSegment.TableHeap, metadata.table_heap);
WriteHeap (TextSegment.StringHeap, metadata.string_heap);
WriteHeap (TextSegment.UserStringHeap, metadata.user_string_heap);
WriteGuidHeap ();
WriteHeap (TextSegment.BlobHeap, metadata.blob_heap);
}
void WriteHeap (TextSegment heap, HeapBuffer buffer)
{
if (buffer.IsEmpty)
return;
MoveToRVA (heap);
WriteBuffer (buffer);
}
void WriteGuidHeap ()
{
MoveToRVA (TextSegment.GuidHeap);
WriteBytes (module.Mvid.ToByteArray ());
}
void WriteDebugDirectory ()
{
WriteInt32 (debug_directory.Characteristics);
WriteUInt32 (time_stamp);
WriteInt16 (debug_directory.MajorVersion);
WriteInt16 (debug_directory.MinorVersion);
WriteInt32 (debug_directory.Type);
WriteInt32 (debug_directory.SizeOfData);
WriteInt32 (debug_directory.AddressOfRawData);
WriteInt32 ((int) BaseStream.Position + 4);
WriteBytes (debug_data);
}
void WriteImportDirectory ()
{
WriteUInt32 (text_map.GetRVA (TextSegment.ImportDirectory) + 40); // ImportLookupTable
WriteUInt32 (0); // DateTimeStamp
WriteUInt32 (0); // ForwarderChain
WriteUInt32 (text_map.GetRVA (TextSegment.ImportHintNameTable) + 14);
WriteUInt32 (text_map.GetRVA (TextSegment.ImportAddressTable));
Advance (20);
// ImportLookupTable
WriteUInt32 (text_map.GetRVA (TextSegment.ImportHintNameTable));
// ImportHintNameTable
MoveToRVA (TextSegment.ImportHintNameTable);
WriteUInt16 (0); // Hint
WriteBytes (GetRuntimeMain ());
WriteByte (0);
WriteBytes (GetSimpleString ("mscoree.dll"));
WriteUInt16 (0);
}
byte [] GetRuntimeMain ()
{
return module.Kind == ModuleKind.Dll || module.Kind == ModuleKind.NetModule
? GetSimpleString ("_CorDllMain")
: GetSimpleString ("_CorExeMain");
}
void WriteStartupStub ()
{
switch (module.Architecture) {
case TargetArchitecture.I386:
WriteUInt16 (0x25ff);
WriteUInt32 ((uint) image_base + text_map.GetRVA (TextSegment.ImportAddressTable));
return;
default:
throw new NotSupportedException ();
}
}
void WriteRsrc ()
{
PrepareSection (rsrc);
WriteBuffer (win32_resources);
}
void WriteReloc ()
{
PrepareSection (reloc);
var reloc_rva = text_map.GetRVA (TextSegment.StartupStub);
reloc_rva += module.Architecture == TargetArchitecture.IA64 ? 0x20u : 2;
var page_rva = reloc_rva & ~0xfffu;
WriteUInt32 (page_rva); // PageRVA
WriteUInt32 (0x000c); // Block Size
switch (module.Architecture) {
case TargetArchitecture.I386:
WriteUInt32 (0x3000 + reloc_rva - page_rva);
break;
default:
throw new NotSupportedException();
}
}
public void WriteImage ()
{
WriteDOSHeader ();
WritePEFileHeader ();
WriteOptionalHeaders ();
WriteSectionHeaders ();
WriteText ();
if (rsrc != null)
WriteRsrc ();
if (reloc != null)
WriteReloc ();
}
TextMap BuildTextMap ()
{
var map = metadata.text_map;
map.AddMap (TextSegment.Code, metadata.code.length, !pe64 ? 4 : 16);
map.AddMap (TextSegment.Resources, metadata.resources.length, 8);
map.AddMap (TextSegment.Data, metadata.data.length, 4);
if (metadata.data.length > 0)
metadata.table_heap.FixupData (map.GetRVA (TextSegment.Data));
map.AddMap (TextSegment.StrongNameSignature, GetStrongNameLength (), 4);
map.AddMap (TextSegment.MetadataHeader, GetMetadataHeaderLength ());
map.AddMap (TextSegment.TableHeap, metadata.table_heap.length, 4);
map.AddMap (TextSegment.StringHeap, metadata.string_heap.length, 4);
map.AddMap (TextSegment.UserStringHeap, metadata.user_string_heap.IsEmpty ? 0 : metadata.user_string_heap.length, 4);
map.AddMap (TextSegment.GuidHeap, 16);
map.AddMap (TextSegment.BlobHeap, metadata.blob_heap.IsEmpty ? 0 : metadata.blob_heap.length, 4);
int debug_dir_len = 0;
if (!debug_data.IsNullOrEmpty ()) {
const int debug_dir_header_len = 28;
debug_directory.AddressOfRawData = (int) map.GetNextRVA (TextSegment.BlobHeap) + debug_dir_header_len;
debug_dir_len = debug_data.Length + debug_dir_header_len;
}
map.AddMap (TextSegment.DebugDirectory, debug_dir_len, 4);
if (!has_reloc) {
var start = map.GetNextRVA (TextSegment.DebugDirectory);
map.AddMap (TextSegment.ImportDirectory, new Range (start, 0));
map.AddMap (TextSegment.ImportHintNameTable, new Range (start, 0));
map.AddMap (TextSegment.StartupStub, new Range (start, 0));
return map;
}
RVA import_dir_rva = map.GetNextRVA (TextSegment.DebugDirectory);
RVA import_hnt_rva = import_dir_rva + 48u;
import_hnt_rva = (import_hnt_rva + 15u) & ~15u;
uint import_dir_len = (import_hnt_rva - import_dir_rva) + 27u;
RVA startup_stub_rva = import_dir_rva + import_dir_len;
startup_stub_rva = module.Architecture == TargetArchitecture.IA64
? (startup_stub_rva + 15u) & ~15u
: 2 + ((startup_stub_rva + 3u) & ~3u);
map.AddMap (TextSegment.ImportDirectory, new Range (import_dir_rva, import_dir_len));
map.AddMap (TextSegment.ImportHintNameTable, new Range (import_hnt_rva, 0));
map.AddMap (TextSegment.StartupStub, new Range (startup_stub_rva, GetStartupStubLength ()));
return map;
}
uint GetStartupStubLength ()
{
switch (module.Architecture) {
case TargetArchitecture.I386:
return 6;
default:
throw new NotSupportedException ();
}
}
int GetMetadataHeaderLength ()
{
return
// MetadataHeader
40
// #~ header
+ 12
// #Strings header
+ 20
// #US header
+ (metadata.user_string_heap.IsEmpty ? 0 : 12)
// #GUID header
+ 16
// #Blob header
+ (metadata.blob_heap.IsEmpty ? 0 : 16);
}
int GetStrongNameLength ()
{
if (module.Assembly == null)
return 0;
var public_key = module.Assembly.Name.PublicKey;
if (public_key.IsNullOrEmpty ())
return 0;
// in fx 2.0 the key may be from 384 to 16384 bits
// so we must calculate the signature size based on
// the size of the public key (minus the 32 byte header)
int size = public_key.Length;
if (size > 32)
return size - 32;
// note: size == 16 for the ECMA "key" which is replaced
// by the runtime with a 1024 bits key (128 bytes)
return 128; // default strongname signature size
}
public DataDirectory GetStrongNameSignatureDirectory ()
{
return text_map.GetDataDirectory (TextSegment.StrongNameSignature);
}
public uint GetHeaderSize ()
{
return pe_header_size + (sections * section_header_size);
}
void PatchWin32Resources (ByteBuffer resources)
{
PatchResourceDirectoryTable (resources);
}
void PatchResourceDirectoryTable (ByteBuffer resources)
{
resources.Advance (12);
var entries = resources.ReadUInt16 () + resources.ReadUInt16 ();
for (int i = 0; i < entries; i++)
PatchResourceDirectoryEntry (resources);
}
void PatchResourceDirectoryEntry (ByteBuffer resources)
{
resources.Advance (4);
var child = resources.ReadUInt32 ();
var position = resources.position;
resources.position = (int) child & 0x7fffffff;
if ((child & 0x80000000) != 0)
PatchResourceDirectoryTable (resources);
else
PatchResourceDataEntry (resources);
resources.position = position;
}
void PatchResourceDataEntry (ByteBuffer resources)
{
var old_rsrc = GetImageResourceSection ();
var rva = resources.ReadUInt32 ();
resources.position -= 4;
resources.WriteUInt32 (rva - old_rsrc.VirtualAddress + rsrc.VirtualAddress);
}
}
}
#endif
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Reflection;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using System.Collections.Generic;
using System.Xml;
namespace OpenSim.Region.Framework.Scenes
{
public partial class SceneObjectGroup : EntityBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Force all task inventories of prims in the scene object to persist
/// </summary>
public void ForceInventoryPersistence()
{
lock (m_parts)
{
foreach (SceneObjectPart part in m_parts.Values)
{
part.Inventory.ForceInventoryPersistence();
}
}
}
/// <summary>
/// Start the scripts contained in all the prims in this group.
/// </summary>
public void CreateScriptInstances(int? startParam, ScriptStartFlags startFlags,
string engine, int stateSource, ICompilationListener listener)
{
// Don't start scripts if they're turned off in the region!
if (!m_scene.RegionInfo.RegionSettings.DisableScripts)
{
foreach (SceneObjectPart part in m_parts.Values)
{
part.Inventory.CreateScriptInstances(startParam, startFlags, engine, stateSource, listener);
}
}
}
/// <summary>
/// Stop the scripts contained in all the prims in this group
/// </summary>
public void RemoveScriptInstances()
{
SceneObjectPart[] parts = this.GetParts();
foreach (SceneObjectPart part in parts)
{
part.Inventory.RemoveScriptInstances();
}
}
/// <summary>
/// Resets all the scripts and item attributes in all prims in this group (when itemId == UUID.Zero).
/// If itemId is specified, only that specified script is reset.
/// </summary>
public void ResetItems(bool isNewInstance, bool isScriptReset, UUID itemId)
{
lock (m_parts)
{
foreach (SceneObjectPart part in m_parts.Values)
{
part.Inventory.ResetItems(isNewInstance, isScriptReset, itemId);
}
}
}
/// <summary>
/// Return serialized inventory metadata for the given constituent prim
/// </summary>
/// <param name="localID"></param>
/// <param name="xferManager"></param>
public void RequestInventoryFile(IClientAPI client, uint localID, IXfer xferManager)
{
SceneObjectPart part = GetChildPart(localID);
if (part == null)
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find part {0} in object group {1}, {2} to request inventory data",
localID, Name, UUID);
return;
}
/*
if (GetPartInventoryFileName(client, localID, xferManager))
SceneObjectPart part = GetChildPart(localID);
if (part != null)
{
return part.Inventory.AllocateInventoryFile(remoteClient, localID, xferManager);
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find part {0} in object group {1}, {2} to retreive prim inventory",
localID, Name, UUID);
}
return false;
*/
part.Inventory.RequestInventoryFile(client, xferManager);
}
/// <summary>
/// Add an inventory item to a prim in this group.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="localID"></param>
/// <param name="item"></param>
/// <param name="copyItemID">The item UUID that should be used by the new item.</param>
/// <returns></returns>
public bool AddInventoryItem(IClientAPI remoteClient, uint localID,
InventoryItemBase item, UUID copyItemID)
{
UUID newItemId = (copyItemID != UUID.Zero) ? copyItemID : item.ID;
SceneObjectPart part = GetChildPart(localID);
if (part != null)
{
TaskInventoryItem taskItem = new TaskInventoryItem();
taskItem.ItemID = newItemId;
taskItem.AssetID = item.AssetID;
taskItem.Name = item.Name;
taskItem.Description = item.Description;
taskItem.OwnerID = part.OwnerID; // Transfer ownership
taskItem.CreatorID = item.CreatorIdAsUuid;
taskItem.Type = item.AssetType;
taskItem.InvType = item.InvType;
if (remoteClient != null &&
remoteClient.AgentId != part.OwnerID &&
m_scene.Permissions.PropagatePermissions())
{
taskItem.BasePermissions = item.BasePermissions &
item.NextPermissions;
taskItem.CurrentPermissions = item.CurrentPermissions &
item.NextPermissions;
taskItem.EveryonePermissions = item.EveryOnePermissions &
item.NextPermissions;
taskItem.GroupPermissions = item.GroupPermissions &
item.NextPermissions;
taskItem.NextPermissions = item.NextPermissions;
} else {
taskItem.BasePermissions = item.BasePermissions;
taskItem.CurrentPermissions = item.CurrentPermissions;
taskItem.EveryonePermissions = item.EveryOnePermissions;
taskItem.GroupPermissions = item.GroupPermissions;
taskItem.NextPermissions = item.NextPermissions;
}
taskItem.Flags = item.Flags;
// TODO: These are pending addition of those fields to TaskInventoryItem
// taskItem.SalePrice = item.SalePrice;
// taskItem.SaleType = item.SaleType;
taskItem.CreationDate = (uint)item.CreationDate;
bool addFromAllowedDrop = false;
if (remoteClient!=null)
{
addFromAllowedDrop = remoteClient.AgentId != part.OwnerID;
}
part.Inventory.AddInventoryItem(taskItem, addFromAllowedDrop, true);
return true;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find prim local ID {0} in group {1}, {2} to add inventory item ID {3}",
localID, Name, UUID, newItemId);
}
return false;
}
/// <summary>
/// Returns an existing inventory item. Returns the original, so any changes will be live.
/// </summary>
/// <param name="primID"></param>
/// <param name="itemID"></param>
/// <returns>null if the item does not exist</returns>
public TaskInventoryItem GetInventoryItem(uint primID, UUID itemID)
{
SceneObjectPart part = GetChildPart(primID);
if (part != null)
{
return part.Inventory.GetInventoryItem(itemID);
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find prim local ID {0} in prim {1}, {2} to get inventory item ID {3}",
primID, part.Name, part.UUID, itemID);
}
return null;
}
/// <summary>
/// Update an existing inventory item with a new asset (ID).
/// </summary>
/// <param name="ParentPartID">The UUID of the prim containing the task inventory item.</param>
/// <param name="ItemID">The item to update. An item with the same id must already exist
/// in the inventory of the prim specified by ParentPartID.</param>
/// <param name="AssetID">The ID of the new asset to replace in the item above.</param>
/// <returns>false if the item did not exist or a null ID was passed, true if the update occurred successfully</returns>
public bool UpdateInventoryItemAsset(UUID ParentPartID, UUID ItemID, UUID AssetID)
{
SceneObjectPart part = GetChildPart(ParentPartID);
if (part != null)
{
part.Inventory.UpdateTaskInventoryItemAsset(ParentPartID, ItemID, AssetID);
return true;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find prim ID {0} to update item in {1}, {2}",
ParentPartID, this.UUID, ItemID);
}
return false;
}
/// <summary>
/// Update an existing inventory item.
/// </summary>
/// <param name="item">The updated item. An item with the same id must already exist
/// in the inventory of the prim specified by item.ParentPartID.</param>
/// <returns>false if the item did not exist, true if the update occurred successfully</returns>
public bool UpdateInventoryItemFromItem(TaskInventoryItem item)
{
SceneObjectPart part = GetChildPart(item.ParentPartID);
if (part != null)
{
part.Inventory.UpdateTaskInventoryItemFromItem(item);
return true;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find prim ID {0} to update item {1}, {2}",
item.ParentPartID, item.Name, item.ItemID);
}
return false;
}
public int RemoveInventoryItem(uint localID, UUID itemID)
{
SceneObjectPart part = GetChildPart(localID);
if (part != null)
{
int type = part.Inventory.RemoveInventoryItem(itemID);
return type;
}
return -1;
}
public uint GetEffectivePermissions(bool includeContents)
{
uint perms = (uint)(PermissionMask.All | PermissionMask.Export);
uint ownerMask = ScenePermBits.BASEMASK;
foreach (SceneObjectPart part in m_parts.Values)
{
ownerMask &= part.OwnerMask;
if (includeContents)
perms &= part.Inventory.MaskEffectivePermissions();
}
if ((ownerMask & (uint)PermissionMask.Modify) == 0)
perms &= ~(uint)PermissionMask.Modify;
if ((ownerMask & (uint)PermissionMask.Copy) == 0)
perms &= ~(uint)PermissionMask.Copy;
if ((ownerMask & (uint)PermissionMask.Transfer) == 0)
perms &= ~(uint)PermissionMask.Transfer;
if ((ownerMask & (uint)PermissionMask.Export) == 0)
perms &= ~(uint)PermissionMask.Export;
return perms;
}
public void ApplyNextOwnerPermissions()
{
foreach (SceneObjectPart part in m_parts.Values)
{
part.ApplyNextOwnerPermissions();
}
}
public uint GetEffectiveNextPermissions(bool includeContents)
{
uint perms = (uint)(PermissionMask.All | PermissionMask.Export);
uint nextOwnerMask = ScenePermBits.BASEMASK;
foreach (SceneObjectPart part in m_parts.Values)
{
nextOwnerMask &= part.NextOwnerMask;
if (includeContents)
perms &= part.Inventory.MaskEffectiveNextPermissions();
}
if ((nextOwnerMask & (uint)PermissionMask.Modify) == 0)
perms &= ~(uint)PermissionMask.Modify;
if ((nextOwnerMask & (uint)PermissionMask.Copy) == 0)
perms &= ~(uint)PermissionMask.Copy;
if ((nextOwnerMask & (uint)PermissionMask.Transfer) == 0)
perms &= ~(uint)PermissionMask.Transfer;
return perms;
}
public string GetStateSnapshot(bool fromCrossing)
{
//m_log.Debug(" >>> GetStateSnapshot <<<");
List<string> assemblies = new List<string>();
Dictionary<UUID, string> states = new Dictionary<UUID, string>();
StopScriptReason stopScriptReason = fromCrossing ? StopScriptReason.Crossing : StopScriptReason.Derez;
foreach (SceneObjectPart part in m_parts.Values)
{
foreach (KeyValuePair<UUID, string> s in part.Inventory.GetScriptStates(stopScriptReason))
{
states[s.Key] = s.Value;
}
}
if (states.Count < 1)
return "";
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "PhloxScriptData", "");
xmldoc.AppendChild(rootElement);
XmlElement wrapper = xmldoc.CreateElement("", "PhloxSS",
"");
rootElement.AppendChild(wrapper);
foreach (KeyValuePair<UUID, string> state in states)
{
XmlElement stateData = xmldoc.CreateElement("", "State", "");
XmlAttribute stateID = xmldoc.CreateAttribute("", "UUID", "");
stateID.Value = state.Key.ToString();
stateData.Attributes.Append(stateID);
stateData.InnerText = state.Value;
wrapper.AppendChild(stateData);
}
return xmldoc.InnerXml;
}
public void SetState(string objXMLData, UUID RegionID)
{
if (objXMLData == String.Empty)
return;
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(objXMLData);
}
catch (Exception) // (System.Xml.XmlException)
{
// We will get here if the XML is invalid or in unit
// tests. Really should determine which it is and either
// fail silently or log it
// Fail silently, for now.
// TODO: Fix this
//
return;
}
XmlNodeList rootL = doc.GetElementsByTagName("PhloxScriptData");
if (rootL.Count == 1)
{
XmlNode rootNode = rootL[0];
if (rootNode != null)
{
XmlNodeList partL = rootNode.ChildNodes;
foreach (XmlNode part in partL)
{
XmlNodeList nodeL = part.ChildNodes;
switch (part.Name)
{
case "PhloxSS":
foreach (XmlNode st in nodeL)
{
string id = st.Attributes.GetNamedItem("UUID").Value;
UUID uuid = new UUID(id);
if (m_savedScriptState == null)
{
m_savedScriptState = new Dictionary<UUID, string>();
}
m_savedScriptState[uuid] = st.InnerText;
}
break;
}
}
}
}
}
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="Columnid.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------
// <summary>
// </summary>
// ---------------------------------------------------------------------
namespace Microsoft.Database.Isam
{
using System;
using Microsoft.Isam.Esent.Interop;
using Microsoft.Isam.Esent.Interop.Vista;
/// <summary>
/// Identifies a column in a table
/// </summary>
/// <remarks>
/// A Columnid contains the name of a column and its internal identifier.
/// A Columnid also encodes the type of the column which is used for conversions to and from CLR objects.
/// Retrieving an column by columnid is more efficient than retrieving a column by name, as the name to
/// columnid and type lookup can be expensive
/// </remarks>
public class Columnid
{
/// <summary>
/// The columnid
/// </summary>
private readonly JET_COLUMNID columnid;
/// <summary>
/// The column type of this column.
/// </summary>
private readonly JET_coltyp coltyp;
/// <summary>
/// The name
/// </summary>
private readonly string name;
/// <summary>
/// The CLR type that closest represents the data stored in the database.
/// </summary>
private readonly Type type;
/// <summary>
/// Whether the column contains ASCII data (text columns only).
/// </summary>
private readonly bool isAscii;
/// <summary>
/// Initializes a new instance of the <see cref="Columnid"/> class.
/// </summary>
/// <param name="columnbase">The column identifier.</param>
internal Columnid(JET_COLUMNBASE columnbase)
: this(columnbase.szBaseColumnName, columnbase.columnid, columnbase.coltyp, columnbase.cp == JET_CP.ASCII)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Columnid"/> class.
/// </summary>
/// <param name="name">The column name.</param>
/// <param name="columnid">The column identifier.</param>
/// <param name="coltyp">The column type.</param>
/// <param name="isAscii">If it's a text column, whether the data is ASCII or Unicode.</param>
internal Columnid(string name, JET_COLUMNID columnid, JET_coltyp coltyp, bool isAscii)
{
this.name = name;
this.columnid = columnid;
this.coltyp = coltyp;
this.isAscii = isAscii;
switch (coltyp)
{
case JET_coltyp.Nil:
throw new ArgumentOutOfRangeException("columnid.Type", "Nil is not valid");
case JET_coltyp.Bit:
this.type = typeof(bool);
break;
case JET_coltyp.UnsignedByte:
this.type = typeof(byte);
break;
case JET_coltyp.Short:
this.type = typeof(short);
break;
case JET_coltyp.Long:
this.type = typeof(int);
break;
case JET_coltyp.Currency:
this.type = typeof(long);
break;
case JET_coltyp.IEEESingle:
this.type = typeof(float);
break;
case JET_coltyp.IEEEDouble:
this.type = typeof(double);
break;
case JET_coltyp.DateTime:
this.type = typeof(DateTime);
break;
case JET_coltyp.Binary:
this.type = typeof(byte[]);
break;
case JET_coltyp.Text:
this.type = typeof(string);
break;
case JET_coltyp.LongBinary:
this.type = typeof(byte[]);
break;
case JET_coltyp.LongText:
this.type = typeof(string);
break;
case VistaColtyp.UnsignedLong:
this.type = typeof(uint);
break;
case VistaColtyp.LongLong:
this.type = typeof(long);
break;
case VistaColtyp.GUID:
this.type = typeof(Guid);
break;
case VistaColtyp.UnsignedShort:
this.type = typeof(ushort);
break;
default:
throw new ArgumentOutOfRangeException("columnid.Coltyp", "unknown type");
}
}
/// <summary>
/// Gets a value indicating whether the column contains ASCII data (text columns only).
/// </summary>
public bool IsAscii
{
get
{
return this.isAscii;
}
}
/// <summary>
/// Gets the name of the column
/// </summary>
/// <remarks>
/// A column name is only unique in the context of a specific table.
/// </remarks>
public string Name
{
get
{
return this.name;
}
}
/// <summary>
/// Gets the type of the column.
/// </summary>
/// <value>
/// The type.
/// </value>
public Type Type
{
get
{
return this.type;
}
}
/// <summary>
/// Gets the interop columnid.
/// </summary>
/// <value>
/// The interop columnid.
/// </value>
internal JET_COLUMNID InteropColumnid
{
get
{
return this.columnid;
}
}
/// <summary>
/// Gets the underlying ESE <see cref="JET_coltyp"/> of the column.
/// </summary>
internal JET_coltyp Coltyp
{
get
{
return this.coltyp;
}
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
return string.Format("Columnid({0}, {1}, {2}, IsAscii={3})", this.Name, this.type.Name, this.coltyp, this.isAscii);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
using Xunit;
namespace System.IO.FileSystem.Tests
{
public class Directory_Exists : FileSystemTest
{
#region Utilities
public bool Exists(string path)
{
return Directory.Exists(path);
}
#endregion
#region UniversalTests
[Fact]
public void NullAsPath_ReturnsFalse()
{
Assert.False(Exists(null));
}
[Fact]
public void EmptyAsPath_ReturnsFalse()
{
Assert.False(Exists(string.Empty));
}
[Fact]
public void NonExistentValidPath_ReturnsFalse()
{
Assert.All((IOInputs.GetValidPathComponentNames()), (path) =>
{
Assert.False(Exists(path), path);
});
}
[Fact]
public void ValidPathExists_ReturnsTrue()
{
Assert.All((IOInputs.GetValidPathComponentNames()), (component) =>
{
string path = Path.Combine(TestDirectory, component);
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.True(Exists(path));
});
}
[Fact]
public void PathWithInvalidCharactersAsPath_ReturnsFalse()
{
// Checks that errors aren't thrown when calling Exists() on paths with impossible to create characters
char[] trimmed = { (char)0x9, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20, (char)0x85, (char)0xA0 };
Assert.All((IOInputs.GetPathsWithInvalidCharacters()), (component) =>
{
Assert.False(Exists(component));
if (!trimmed.Contains(component.ToCharArray()[0]))
Assert.False(Exists(TestDirectory + Path.DirectorySeparatorChar + component));
});
}
[Fact]
public void PathAlreadyExistsAsFile()
{
string path = GetTestFilePath();
File.Create(path).Dispose();
Assert.False(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[Fact]
public void PathAlreadyExistsAsDirectory()
{
string path = GetTestFilePath();
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.True(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[Fact]
public void DotAsPath_ReturnsTrue()
{
Assert.True(Exists(Path.Combine(TestDirectory, ".")));
}
[Fact]
public void DirectoryGetCurrentDirectoryAsPath_ReturnsTrue()
{
Assert.True(Exists(Directory.GetCurrentDirectory()));
}
[Fact]
public void DotDotAsPath_ReturnsTrue()
{
Assert.True(Exists(Path.Combine(TestDirectory, GetTestFileName(), "..")));
}
[Fact]
public void DirectoryLongerThanMaxPathAsPath_DoesntThrow()
{
Assert.All((IOInputs.GetPathsLongerThanMaxPath()), (path) =>
{
Assert.False(Exists(path), path);
});
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void ValidExtendedPathExists_ReturnsTrue()
{
Assert.All((IOInputs.GetValidPathComponentNames()), (component) =>
{
string path = @"\\?\" + Path.Combine(TestDirectory, "extended", component);
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.True(Exists(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void ExtendedPathAlreadyExistsAsFile()
{
string path = @"\\?\" + GetTestFilePath();
File.Create(path).Dispose();
Assert.False(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void ExtendedPathAlreadyExistsAsDirectory()
{
string path = @"\\?\" + GetTestFilePath();
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.True(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void DirectoryLongerThanMaxDirectoryAsPath_DoesntThrow()
{
Assert.All((IOInputs.GetPathsLongerThanMaxDirectory()), (path) =>
{
Assert.False(Exists(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // Unix equivalent tested already in CreateDirectory
public void WindowsWhiteSpaceAsPath_ReturnsFalse()
{
// Checks that errors aren't thrown when calling Exists() on impossible paths
Assert.All(IOInputs.GetWhiteSpace(), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows | PlatformID.OSX)]
public void DoesCaseInsensitiveInvariantComparisons()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.True(Exists(testDir.FullName));
Assert.True(Exists(testDir.FullName.ToUpperInvariant()));
Assert.True(Exists(testDir.FullName.ToLowerInvariant()));
}
[Fact]
[PlatformSpecific(PlatformID.Linux | PlatformID.FreeBSD)]
public void DoesCaseSensitiveComparisons()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.True(Exists(testDir.FullName));
Assert.False(Exists(testDir.FullName.ToUpperInvariant()));
Assert.False(Exists(testDir.FullName.ToLowerInvariant()));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // In Windows, trailing whitespace in a path is trimmed appropriately
public void TrailingWhitespaceExistence()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.All(IOInputs.GetWhiteSpace(), (component) =>
{
string path = testDir.FullName + component;
Assert.True(Exists(path), path); // string concat in case Path.Combine() trims whitespace before Exists gets to it
Assert.False(Exists(@"\\?\" + path), path);
});
Assert.All(IOInputs.GetSimpleWhiteSpace(), (component) =>
{
string path = GetTestFilePath(memberName: "Extended") + component;
testDir = Directory.CreateDirectory(@"\\?\" + path);
Assert.False(Exists(path), path);
Assert.True(Exists(testDir.FullName));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // alternate data stream
public void PathWithAlternateDataStreams_ReturnsFalse()
{
Assert.All(IOInputs.GetWhiteSpace(), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[OuterLoop]
[PlatformSpecific(PlatformID.Windows)] // device names
public void PathWithReservedDeviceNameAsPath_ReturnsFalse()
{
Assert.All((IOInputs.GetPathsWithReservedDeviceNames()), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // UNC paths
public void UncPathWithoutShareNameAsPath_ReturnsFalse()
{
Assert.All((IOInputs.GetUncPathsWithoutShareName()), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // max directory length not fixed on Unix
public void DirectoryEqualToMaxDirectory_ReturnsTrue()
{
// Creates directories up to the maximum directory length all at once
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
PathInfo path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory, maxComponent: 10);
Directory.CreateDirectory(path.FullPath);
Assert.True(Exists(path.FullPath));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // max directory length not fixed on Unix
public void DirectoryWithComponentLongerThanMaxComponentAsPath_ReturnsFalse()
{
Assert.All((IOInputs.GetPathsWithComponentLongerThanMaxComponent()), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[ActiveIssue(1221)]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public void NotReadyDriveAsPath_ReturnsFalse()
{
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
bool result = Exists(drive);
Assert.False(result);
}
[Fact]
[ActiveIssue(1221)]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public void SubdirectoryOnNotReadyDriveAsPath_ReturnsFalse()
{
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
bool result = Exists(Path.Combine(drive, "Subdirectory"));
Assert.False(result);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public void NonExistentDriveAsPath_ReturnsFalse()
{
Assert.False(Exists(IOServices.GetNonExistentDrive()));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public void SubdirectoryOnNonExistentDriveAsPath_ReturnsFalse()
{
Assert.False(Exists(Path.Combine(IOServices.GetNonExistentDrive(), "nonexistentsubdir")));
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
namespace Prism.Common
{
/// <summary>
/// A dictionary of lists.
/// </summary>
/// <typeparam name="TKey">The key to use for lists.</typeparam>
/// <typeparam name="TValue">The type of the value held by lists.</typeparam>
public sealed class ListDictionary<TKey, TValue> : IDictionary<TKey, IList<TValue>>
{
Dictionary<TKey, IList<TValue>> innerValues = new Dictionary<TKey, IList<TValue>>();
#region Public Methods
/// <summary>
/// If a list does not already exist, it will be created automatically.
/// </summary>
/// <param name="key">The key of the list that will hold the value.</param>
public void Add(TKey key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
CreateNewList(key);
}
/// <summary>
/// Adds a value to a list with the given key. If a list does not already exist,
/// it will be created automatically.
/// </summary>
/// <param name="key">The key of the list that will hold the value.</param>
/// <param name="value">The value to add to the list under the given key.</param>
public void Add(TKey key, TValue value)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (innerValues.ContainsKey(key))
{
innerValues[key].Add(value);
}
else
{
List<TValue> values = CreateNewList(key);
values.Add(value);
}
}
private List<TValue> CreateNewList(TKey key)
{
List<TValue> values = new List<TValue>();
innerValues.Add(key, values);
return values;
}
/// <summary>
/// Removes all entries in the dictionary.
/// </summary>
public void Clear()
{
innerValues.Clear();
}
/// <summary>
/// Determines whether the dictionary contains the specified value.
/// </summary>
/// <param name="value">The value to locate.</param>
/// <returns>true if the dictionary contains the value in any list; otherwise, false.</returns>
public bool ContainsValue(TValue value)
{
foreach (KeyValuePair<TKey, IList<TValue>> pair in innerValues)
{
if (pair.Value.Contains(value))
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether the dictionary contains the given key.
/// </summary>
/// <param name="key">The key to locate.</param>
/// <returns>true if the dictionary contains the given key; otherwise, false.</returns>
public bool ContainsKey(TKey key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return innerValues.ContainsKey(key);
}
/// <summary>
/// Retrieves the all the elements from the list which have a key that matches the condition
/// defined by the specified predicate.
/// </summary>
/// <param name="keyFilter">The filter with the condition to use to filter lists by their key.</param>
/// <returns>The elements that have a key that matches the condition defined by the specified predicate.</returns>
public IEnumerable<TValue> FindAllValuesByKey(Predicate<TKey> keyFilter)
{
foreach (KeyValuePair<TKey, IList<TValue>> pair in this)
{
if (keyFilter(pair.Key))
{
foreach (TValue value in pair.Value)
{
yield return value;
}
}
}
}
/// <summary>
/// Retrieves all the elements that match the condition defined by the specified predicate.
/// </summary>
/// <param name="valueFilter">The filter with the condition to use to filter values.</param>
/// <returns>The elements that match the condition defined by the specified predicate.</returns>
public IEnumerable<TValue> FindAllValues(Predicate<TValue> valueFilter)
{
foreach (KeyValuePair<TKey, IList<TValue>> pair in this)
{
foreach (TValue value in pair.Value)
{
if (valueFilter(value))
{
yield return value;
}
}
}
}
/// <summary>
/// Removes a list by key.
/// </summary>
/// <param name="key">The key of the list to remove.</param>
/// <returns><see langword="true" /> if the element was removed.</returns>
public bool Remove(TKey key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return innerValues.Remove(key);
}
/// <summary>
/// Removes a value from the list with the given key.
/// </summary>
/// <param name="key">The key of the list where the value exists.</param>
/// <param name="value">The value to remove.</param>
public void Remove(TKey key, TValue value)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (innerValues.ContainsKey(key))
{
List<TValue> innerList = (List<TValue>)innerValues[key];
innerList.RemoveAll(delegate(TValue item)
{
return value.Equals(item);
});
}
}
/// <summary>
/// Removes a value from all lists where it may be found.
/// </summary>
/// <param name="value">The value to remove.</param>
public void Remove(TValue value)
{
foreach (KeyValuePair<TKey, IList<TValue>> pair in innerValues)
{
Remove(pair.Key, value);
}
}
#endregion
#region Properties
/// <summary>
/// Gets a shallow copy of all values in all lists.
/// </summary>
/// <value>List of values.</value>
public IList<TValue> Values
{
get
{
List<TValue> values = new List<TValue>();
foreach (IEnumerable<TValue> list in innerValues.Values)
{
values.AddRange(list);
}
return values;
}
}
/// <summary>
/// Gets the list of keys in the dictionary.
/// </summary>
/// <value>Collection of keys.</value>
public ICollection<TKey> Keys
{
get { return innerValues.Keys; }
}
/// <summary>
/// Gets or sets the list associated with the given key. The
/// access always succeeds, eventually returning an empty list.
/// </summary>
/// <param name="key">The key of the list to access.</param>
/// <returns>The list associated with the key.</returns>
public IList<TValue> this[TKey key]
{
get
{
if (innerValues.ContainsKey(key) == false)
{
innerValues.Add(key, new List<TValue>());
}
return innerValues[key];
}
set { innerValues[key] = value; }
}
/// <summary>
/// Gets the number of lists in the dictionary.
/// </summary>
/// <value>Value indicating the values count.</value>
public int Count
{
get { return innerValues.Count; }
}
#endregion
#region IDictionary<TKey,List<TValue>> Members
/// <summary>
/// See <see cref="IDictionary{TKey,TValue}.Add"/> for more information.
/// </summary>
void IDictionary<TKey, IList<TValue>>.Add(TKey key, IList<TValue> value)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException(nameof(value));
innerValues.Add(key, value);
}
/// <summary>
/// See <see cref="IDictionary{TKey,TValue}.TryGetValue"/> for more information.
/// </summary>
bool IDictionary<TKey, IList<TValue>>.TryGetValue(TKey key, out IList<TValue> value)
{
value = this[key];
return true;
}
/// <summary>
/// See <see cref="IDictionary{TKey,TValue}.Values"/> for more information.
/// </summary>
ICollection<IList<TValue>> IDictionary<TKey, IList<TValue>>.Values
{
get { return innerValues.Values; }
}
#endregion
#region ICollection<KeyValuePair<TKey,List<TValue>>> Members
/// <summary>
/// See <see cref="ICollection{TValue}.Add"/> for more information.
/// </summary>
void ICollection<KeyValuePair<TKey, IList<TValue>>>.Add(KeyValuePair<TKey, IList<TValue>> item)
{
((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).Add(item);
}
/// <summary>
/// See <see cref="ICollection{TValue}.Contains"/> for more information.
/// </summary>
bool ICollection<KeyValuePair<TKey, IList<TValue>>>.Contains(KeyValuePair<TKey, IList<TValue>> item)
{
return ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).Contains(item);
}
/// <summary>
/// See <see cref="ICollection{TValue}.CopyTo"/> for more information.
/// </summary>
void ICollection<KeyValuePair<TKey, IList<TValue>>>.CopyTo(KeyValuePair<TKey, IList<TValue>>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).CopyTo(array, arrayIndex);
}
/// <summary>
/// See <see cref="ICollection{TValue}.IsReadOnly"/> for more information.
/// </summary>
bool ICollection<KeyValuePair<TKey, IList<TValue>>>.IsReadOnly
{
get { return ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).IsReadOnly; }
}
/// <summary>
/// See <see cref="ICollection{TValue}.Remove"/> for more information.
/// </summary>
bool ICollection<KeyValuePair<TKey, IList<TValue>>>.Remove(KeyValuePair<TKey, IList<TValue>> item)
{
return ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).Remove(item);
}
#endregion
#region IEnumerable<KeyValuePair<TKey,List<TValue>>> Members
/// <summary>
/// See <see cref="IEnumerable{TValue}.GetEnumerator"/> for more information.
/// </summary>
IEnumerator<KeyValuePair<TKey, IList<TValue>>> IEnumerable<KeyValuePair<TKey, IList<TValue>>>.GetEnumerator()
{
return innerValues.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// See <see cref="System.Collections.IEnumerable.GetEnumerator"/> for more information.
/// </summary>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return innerValues.GetEnumerator();
}
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// 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 ACTIONA
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using NUnit.TestUtilities.Collections;
namespace NUnit.Framework.Assertions
{
/// <summary>
/// Summary description for ArrayEqualTests.
/// </summary>
[TestFixture]
public class ArrayEqualsFixture
{
#pragma warning disable 183, 184 // error number varies in different runtimes
// Used to detect runtimes where ArraySegments implement IEnumerable
private static readonly bool ArraySegmentImplementsIEnumerable = new ArraySegment<int>() is IEnumerable;
#pragma warning restore 183, 184
[Test]
public void ArrayIsEqualToItself()
{
string[] array = { "one", "two", "three" };
Assert.That( array, Is.SameAs(array) );
Assert.AreEqual( array, array );
}
[Test]
public void ArraysOfString()
{
string[] array1 = { "one", "two", "three" };
string[] array2 = { "one", "two", "three" };
Assert.IsFalse( array1 == array2 );
Assert.AreEqual(array1, array2);
Assert.AreEqual(array2, array1);
}
[Test]
public void ArraysOfInt()
{
int[] a = new int[] { 1, 2, 3 };
int[] b = new int[] { 1, 2, 3 };
Assert.AreEqual(a, b);
Assert.AreEqual(b, a);
}
[Test]
public void ArraysOfDouble()
{
double[] a = new double[] { 1.0, 2.0, 3.0 };
double[] b = new double[] { 1.0, 2.0, 3.0 };
Assert.AreEqual(a, b);
Assert.AreEqual(b, a);
}
[Test]
public void ArraysOfDecimal()
{
decimal[] a = new decimal[] { 1.0m, 2.0m, 3.0m };
decimal[] b = new decimal[] { 1.0m, 2.0m, 3.0m };
Assert.AreEqual(a, b);
Assert.AreEqual(b, a);
}
[Test]
public void ArrayOfIntAndArrayOfDouble()
{
int[] a = new int[] { 1, 2, 3 };
double[] b = new double[] { 1.0, 2.0, 3.0 };
Assert.AreEqual(a, b);
Assert.AreEqual(b, a);
}
[Test]
public void ArraysDeclaredAsDifferentTypes()
{
string[] array1 = { "one", "two", "three" };
object[] array2 = { "one", "two", "three" };
Assert.AreEqual( array1, array2, "String[] not equal to Object[]" );
Assert.AreEqual( array2, array1, "Object[] not equal to String[]" );
}
[Test]
public void ArraysOfMixedTypes()
{
DateTime now = DateTime.Now;
object[] array1 = new object[] { 1, 2.0f, 3.5d, 7.000m, "Hello", now };
object[] array2 = new object[] { 1.0d, 2, 3.5, 7, "Hello", now };
Assert.AreEqual( array1, array2 );
Assert.AreEqual(array2, array1);
}
[Test]
public void DoubleDimensionedArrays()
{
int[,] a = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[,] b = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Assert.AreEqual(a, b);
Assert.AreEqual(b, a);
}
[Test]
public void TripleDimensionedArrays()
{
int[, ,] expected = new int[,,] { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
int[,,] actual = new int[,,] { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
Assert.AreEqual(expected, actual);
}
[Test]
public void FiveDimensionedArrays()
{
int[, , , ,] expected = new int[2, 2, 2, 2, 2] { { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } }, { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } } };
int[, , , ,] actual = new int[2, 2, 2, 2, 2] { { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } }, { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } } };
Assert.AreEqual(expected, actual);
}
[Test]
public void ArraysOfArrays()
{
int[][] a = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }, new int[] { 7, 8, 9 } };
int[][] b = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }, new int[] { 7, 8, 9 } };
Assert.AreEqual(a, b);
Assert.AreEqual(b, a);
}
[Test]
public void JaggedArrays()
{
int[][] expected = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6, 7 }, new int[] { 8, 9 } };
int[][] actual = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6, 7 }, new int[] { 8, 9 } };
Assert.AreEqual(expected, actual);
}
[Test]
public void ArraysPassedAsObjects()
{
object a = new int[] { 1, 2, 3 };
object b = new double[] { 1.0, 2.0, 3.0 };
Assert.AreEqual(a, b);
Assert.AreEqual(b, a);
}
[Test]
public void ArrayAndCollection()
{
int[] a = new int[] { 1, 2, 3 };
ICollection b = new SimpleObjectCollection( 1, 2, 3 );
Assert.AreEqual(a, b);
Assert.AreEqual(b, a);
}
[Test]
public void ArraysWithDifferentRanksComparedAsCollection()
{
int[] expected = new int[] { 1, 2, 3, 4 };
int[,] actual = new int[,] { { 1, 2 }, { 3, 4 } };
Assert.AreNotEqual(expected, actual);
Assert.That(actual, Is.EqualTo(expected).AsCollection);
}
[Test]
public void ArraysWithDifferentDimensionsMatchedAsCollection()
{
int[,] expected = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
int[,] actual = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
Assert.AreNotEqual(expected, actual);
Assert.That(actual, Is.EqualTo(expected).AsCollection);
}
#if !NETCF && !SILVERLIGHT && !PORTABLE
private static int[] underlyingArray = new int[] { 1, 2, 3, 4, 5 };
[Test]
public void ArraySegmentAndArray()
{
Assume.That(ArraySegmentImplementsIEnumerable);
Assert.That(new ArraySegment<int>(underlyingArray, 1, 3), Is.EqualTo(new int[] { 2, 3, 4 }));
}
[Test]
public void EmptyArraySegmentAndArray()
{
Assume.That(ArraySegmentImplementsIEnumerable);
Assert.That(new ArraySegment<int>(), Is.Not.EqualTo(new int[] { 2, 3, 4 }));
}
[Test]
public void ArrayAndArraySegment()
{
Assume.That(ArraySegmentImplementsIEnumerable);
Assert.That(new int[] { 2, 3, 4 }, Is.EqualTo(new ArraySegment<int>(underlyingArray, 1, 3)));
}
[Test]
public void ArrayAndEmptyArraySegment()
{
Assume.That(ArraySegmentImplementsIEnumerable);
Assert.That(new int[] { 2, 3, 4 }, Is.Not.EqualTo(new ArraySegment<int>()));
}
[Test]
public void TwoArraySegments()
{
Assume.That(ArraySegmentImplementsIEnumerable);
Assert.That(new ArraySegment<int>(underlyingArray, 1, 3), Is.EqualTo(new ArraySegment<int>(underlyingArray, 1, 3)));
}
[Test]
public void TwoEmptyArraySegments()
{
Assume.That(ArraySegmentImplementsIEnumerable);
Assert.That(new ArraySegment<int>(), Is.EqualTo(new ArraySegment<int>()));
}
#endif
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagve = Google.Ads.GoogleAds.V9.Enums;
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedGoogleAdsFieldServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetGoogleAdsFieldRequestObject()
{
moq::Mock<GoogleAdsFieldService.GoogleAdsFieldServiceClient> mockGrpcClient = new moq::Mock<GoogleAdsFieldService.GoogleAdsFieldServiceClient>(moq::MockBehavior.Strict);
GetGoogleAdsFieldRequest request = new GetGoogleAdsFieldRequest
{
ResourceNameAsGoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
};
gagvr::GoogleAdsField expectedResponse = new gagvr::GoogleAdsField
{
ResourceNameAsGoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
Category = gagve::GoogleAdsFieldCategoryEnum.Types.GoogleAdsFieldCategory.Segment,
DataType = gagve::GoogleAdsFieldDataTypeEnum.Types.GoogleAdsFieldDataType.Message,
GoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
Selectable = true,
Filterable = true,
Sortable = true,
SelectableWith =
{
"selectable_with6b2ad4c4",
},
AttributeResources =
{
"attribute_resources3f8a5e5c",
},
Metrics = { "metrics7cd659aa", },
Segments =
{
"segments982d981f",
},
EnumValues =
{
"enum_values30797dbe",
},
TypeUrl = "type_urlfde5623b",
IsRepeated = false,
};
mockGrpcClient.Setup(x => x.GetGoogleAdsField(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GoogleAdsFieldServiceClient client = new GoogleAdsFieldServiceClientImpl(mockGrpcClient.Object, null);
gagvr::GoogleAdsField response = client.GetGoogleAdsField(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetGoogleAdsFieldRequestObjectAsync()
{
moq::Mock<GoogleAdsFieldService.GoogleAdsFieldServiceClient> mockGrpcClient = new moq::Mock<GoogleAdsFieldService.GoogleAdsFieldServiceClient>(moq::MockBehavior.Strict);
GetGoogleAdsFieldRequest request = new GetGoogleAdsFieldRequest
{
ResourceNameAsGoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
};
gagvr::GoogleAdsField expectedResponse = new gagvr::GoogleAdsField
{
ResourceNameAsGoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
Category = gagve::GoogleAdsFieldCategoryEnum.Types.GoogleAdsFieldCategory.Segment,
DataType = gagve::GoogleAdsFieldDataTypeEnum.Types.GoogleAdsFieldDataType.Message,
GoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
Selectable = true,
Filterable = true,
Sortable = true,
SelectableWith =
{
"selectable_with6b2ad4c4",
},
AttributeResources =
{
"attribute_resources3f8a5e5c",
},
Metrics = { "metrics7cd659aa", },
Segments =
{
"segments982d981f",
},
EnumValues =
{
"enum_values30797dbe",
},
TypeUrl = "type_urlfde5623b",
IsRepeated = false,
};
mockGrpcClient.Setup(x => x.GetGoogleAdsFieldAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::GoogleAdsField>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GoogleAdsFieldServiceClient client = new GoogleAdsFieldServiceClientImpl(mockGrpcClient.Object, null);
gagvr::GoogleAdsField responseCallSettings = await client.GetGoogleAdsFieldAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::GoogleAdsField responseCancellationToken = await client.GetGoogleAdsFieldAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetGoogleAdsField()
{
moq::Mock<GoogleAdsFieldService.GoogleAdsFieldServiceClient> mockGrpcClient = new moq::Mock<GoogleAdsFieldService.GoogleAdsFieldServiceClient>(moq::MockBehavior.Strict);
GetGoogleAdsFieldRequest request = new GetGoogleAdsFieldRequest
{
ResourceNameAsGoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
};
gagvr::GoogleAdsField expectedResponse = new gagvr::GoogleAdsField
{
ResourceNameAsGoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
Category = gagve::GoogleAdsFieldCategoryEnum.Types.GoogleAdsFieldCategory.Segment,
DataType = gagve::GoogleAdsFieldDataTypeEnum.Types.GoogleAdsFieldDataType.Message,
GoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
Selectable = true,
Filterable = true,
Sortable = true,
SelectableWith =
{
"selectable_with6b2ad4c4",
},
AttributeResources =
{
"attribute_resources3f8a5e5c",
},
Metrics = { "metrics7cd659aa", },
Segments =
{
"segments982d981f",
},
EnumValues =
{
"enum_values30797dbe",
},
TypeUrl = "type_urlfde5623b",
IsRepeated = false,
};
mockGrpcClient.Setup(x => x.GetGoogleAdsField(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GoogleAdsFieldServiceClient client = new GoogleAdsFieldServiceClientImpl(mockGrpcClient.Object, null);
gagvr::GoogleAdsField response = client.GetGoogleAdsField(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetGoogleAdsFieldAsync()
{
moq::Mock<GoogleAdsFieldService.GoogleAdsFieldServiceClient> mockGrpcClient = new moq::Mock<GoogleAdsFieldService.GoogleAdsFieldServiceClient>(moq::MockBehavior.Strict);
GetGoogleAdsFieldRequest request = new GetGoogleAdsFieldRequest
{
ResourceNameAsGoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
};
gagvr::GoogleAdsField expectedResponse = new gagvr::GoogleAdsField
{
ResourceNameAsGoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
Category = gagve::GoogleAdsFieldCategoryEnum.Types.GoogleAdsFieldCategory.Segment,
DataType = gagve::GoogleAdsFieldDataTypeEnum.Types.GoogleAdsFieldDataType.Message,
GoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
Selectable = true,
Filterable = true,
Sortable = true,
SelectableWith =
{
"selectable_with6b2ad4c4",
},
AttributeResources =
{
"attribute_resources3f8a5e5c",
},
Metrics = { "metrics7cd659aa", },
Segments =
{
"segments982d981f",
},
EnumValues =
{
"enum_values30797dbe",
},
TypeUrl = "type_urlfde5623b",
IsRepeated = false,
};
mockGrpcClient.Setup(x => x.GetGoogleAdsFieldAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::GoogleAdsField>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GoogleAdsFieldServiceClient client = new GoogleAdsFieldServiceClientImpl(mockGrpcClient.Object, null);
gagvr::GoogleAdsField responseCallSettings = await client.GetGoogleAdsFieldAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::GoogleAdsField responseCancellationToken = await client.GetGoogleAdsFieldAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetGoogleAdsFieldResourceNames()
{
moq::Mock<GoogleAdsFieldService.GoogleAdsFieldServiceClient> mockGrpcClient = new moq::Mock<GoogleAdsFieldService.GoogleAdsFieldServiceClient>(moq::MockBehavior.Strict);
GetGoogleAdsFieldRequest request = new GetGoogleAdsFieldRequest
{
ResourceNameAsGoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
};
gagvr::GoogleAdsField expectedResponse = new gagvr::GoogleAdsField
{
ResourceNameAsGoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
Category = gagve::GoogleAdsFieldCategoryEnum.Types.GoogleAdsFieldCategory.Segment,
DataType = gagve::GoogleAdsFieldDataTypeEnum.Types.GoogleAdsFieldDataType.Message,
GoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
Selectable = true,
Filterable = true,
Sortable = true,
SelectableWith =
{
"selectable_with6b2ad4c4",
},
AttributeResources =
{
"attribute_resources3f8a5e5c",
},
Metrics = { "metrics7cd659aa", },
Segments =
{
"segments982d981f",
},
EnumValues =
{
"enum_values30797dbe",
},
TypeUrl = "type_urlfde5623b",
IsRepeated = false,
};
mockGrpcClient.Setup(x => x.GetGoogleAdsField(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GoogleAdsFieldServiceClient client = new GoogleAdsFieldServiceClientImpl(mockGrpcClient.Object, null);
gagvr::GoogleAdsField response = client.GetGoogleAdsField(request.ResourceNameAsGoogleAdsFieldName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetGoogleAdsFieldResourceNamesAsync()
{
moq::Mock<GoogleAdsFieldService.GoogleAdsFieldServiceClient> mockGrpcClient = new moq::Mock<GoogleAdsFieldService.GoogleAdsFieldServiceClient>(moq::MockBehavior.Strict);
GetGoogleAdsFieldRequest request = new GetGoogleAdsFieldRequest
{
ResourceNameAsGoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
};
gagvr::GoogleAdsField expectedResponse = new gagvr::GoogleAdsField
{
ResourceNameAsGoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
Category = gagve::GoogleAdsFieldCategoryEnum.Types.GoogleAdsFieldCategory.Segment,
DataType = gagve::GoogleAdsFieldDataTypeEnum.Types.GoogleAdsFieldDataType.Message,
GoogleAdsFieldName = gagvr::GoogleAdsFieldName.FromGoogleAdsField("[GOOGLE_ADS_FIELD]"),
Selectable = true,
Filterable = true,
Sortable = true,
SelectableWith =
{
"selectable_with6b2ad4c4",
},
AttributeResources =
{
"attribute_resources3f8a5e5c",
},
Metrics = { "metrics7cd659aa", },
Segments =
{
"segments982d981f",
},
EnumValues =
{
"enum_values30797dbe",
},
TypeUrl = "type_urlfde5623b",
IsRepeated = false,
};
mockGrpcClient.Setup(x => x.GetGoogleAdsFieldAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::GoogleAdsField>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GoogleAdsFieldServiceClient client = new GoogleAdsFieldServiceClientImpl(mockGrpcClient.Object, null);
gagvr::GoogleAdsField responseCallSettings = await client.GetGoogleAdsFieldAsync(request.ResourceNameAsGoogleAdsFieldName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::GoogleAdsField responseCancellationToken = await client.GetGoogleAdsFieldAsync(request.ResourceNameAsGoogleAdsFieldName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Windows.Forms;
namespace DotSpatial.Data.Forms
{
/// <summary>
/// DirectoryView
/// </summary>
public class DirectoryView : ScrollingControl
{
#region Fields
private string _directory;
private DirectoryItem _selectedItem; // the most recently selected
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryView"/> class.
/// </summary>
public DirectoryView()
{
Items = new List<DirectoryItem>();
InitializeComponent();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the string path that should be itemized in the view.
/// </summary>
public string Directory
{
get
{
return _directory;
}
set
{
_directory = value;
UpdateContent();
}
}
/// <summary>
/// Gets or sets the Font to be used for all of the items in this view.
/// </summary>
[Category("Appearance")]
[Description("Gets or sets the Font to be used for all of the items in this view.")]
public override Font Font
{
get
{
return base.Font;
}
set
{
base.Font = value;
UpdateContent();
}
}
/// <summary>
/// Gets or sets the collection of DirectoryItems to draw in this control
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public List<DirectoryItem> Items { get; set; }
/// <summary>
/// Gets or sets the selected item. In cases of a multiple select, this is the
/// last member added to the selection.
/// </summary>
public DirectoryItem SelectedItem
{
get
{
return _selectedItem;
}
set
{
_selectedItem = value;
Invalidate();
}
}
#endregion
#region Methods
/// <summary>
/// Removes the existing Directory Items from the control
/// </summary>
public virtual void Clear()
{
Items?.Clear();
}
/// <summary>
/// Updates the buffer in order to correctly re-draw this item, if it is on the page, and then invalidates
/// the area where this will be drawn.
/// </summary>
/// <param name="item">The directory item to invalidate</param>
public void RefreshItem(DirectoryItem item)
{
Graphics g = Graphics.FromImage(Page);
Brush b = new SolidBrush(item.BackColor);
g.FillRectangle(b, DocumentToClient(item.Bounds));
b.Dispose();
// first translate into document coordinates
Matrix mat = new Matrix();
mat.Translate(ClientRectangle.X, ClientRectangle.Y);
g.Transform = mat;
item.Draw(new PaintEventArgs(g, item.Bounds));
g.Dispose();
}
/// <summary>
/// Causes the control to refresh the current content.
/// </summary>
public void UpdateContent()
{
SuspendLayout();
int tp = 1;
Clear();
Graphics g = CreateGraphics();
SizeF fontSize = g.MeasureString("TEST", Font);
int fontHeight = (int)(fontSize.Height + 4);
if (fontHeight < 20) fontHeight = 20;
AddFolders(ref tp, fontHeight);
AddFiles(ref tp, fontHeight);
if (tp < fontHeight * Items.Count) tp = fontHeight * Items.Count;
DocumentRectangle = new Rectangle(DocumentRectangle.X, DocumentRectangle.Y, ClientRectangle.Width, tp);
ResetScroll();
ResumeLayout(false);
}
/// <summary>
/// Draws
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnInitialize(PaintEventArgs e)
{
UpdateContent();
// translate into document coordinates
Matrix oldMat = e.Graphics.Transform;
Matrix mat = new Matrix();
e.Graphics.Transform = mat;
foreach (DirectoryItem item in Items)
{
if (ControlRectangle.IntersectsWith(item.Bounds))
{
item.Draw(e);
}
}
e.Graphics.Transform = oldMat;
base.OnInitialize(e);
}
/// <summary>
/// Handles the situation where the mouse has been pressed down.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseDown(MouseEventArgs e)
{
foreach (DirectoryItem di in Items)
{
if (di.Bounds.Contains(e.Location))
{
di.IsSelected = true;
RefreshItem(di);
Invalidate(DocumentToClient(di.Bounds));
}
}
base.OnMouseDown(e);
}
private void AddFiles(ref int tp, int fontHeight)
{
if (_directory == null) return;
string[] files = System.IO.Directory.GetFiles(_directory);
foreach (string file in files)
{
FileItem fi = new FileItem(file);
if (fi.ItemType == ItemType.Custom) continue;
fi.Top = tp;
fi.Font = Font;
fi.Height = fontHeight;
Items.Add(fi);
tp += fontHeight;
}
}
private void AddFolders(ref int tp, int fontHeight)
{
if (_directory == null) return;
string temp = _directory.Trim(Path.DirectorySeparatorChar);
string[] currentDirectoryParts = temp.Split(Path.DirectorySeparatorChar);
if (currentDirectoryParts.Length > 1)
{
if (_directory != null)
{
DirectoryInfo parent = System.IO.Directory.GetParent(_directory);
if (parent != null)
{
FolderItem up = new FolderItem(parent.FullName)
{
Text = "..",
Font = Font,
Top = tp,
Height = fontHeight
};
Items.Add(up);
}
}
tp += fontHeight;
}
if (_directory != null)
{
string[] subDirs = System.IO.Directory.GetDirectories(_directory);
if (Items == null) Items = new List<DirectoryItem>();
foreach (string dir in subDirs)
{
FolderItem di = new FolderItem(dir)
{
Font = Font,
Top = tp,
Height = fontHeight
};
Items.Add(di);
tp += fontHeight;
}
}
}
private void InitializeComponent()
{
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using Internal.Runtime.Augments;
using System.Diagnostics;
namespace System.Runtime.InteropServices
{
/// <summary>
/// Hooks for System.Private.Interop.dll code to access internal functionality in System.Private.CoreLib.dll.
///
/// Methods added to InteropExtensions should also be added to the System.Private.CoreLib.InteropServices contract
/// in order to be accessible from System.Private.Interop.dll.
/// </summary>
[CLSCompliant(false)]
public static class InteropExtensions
{
// Converts a managed DateTime to native OLE datetime
// Used by MCG marshalling code
public static double ToNativeOleDate(DateTime dateTime)
{
return dateTime.ToOADate();
}
// Converts native OLE datetime to managed DateTime
// Used by MCG marshalling code
public static DateTime FromNativeOleDate(double nativeOleDate)
{
return new DateTime(DateTime.DoubleDateToTicks(nativeOleDate));
}
// Used by MCG's SafeHandle marshalling code to initialize a handle
public static void InitializeHandle(SafeHandle safeHandle, IntPtr win32Handle)
{
safeHandle.InitializeHandle(win32Handle);
}
// Used for methods in System.Private.Interop.dll that need to work from offsets on boxed structs
public static unsafe void PinObjectAndCall(Object obj, Action<IntPtr> del)
{
fixed (IntPtr* pEEType = &obj.m_pEEType)
{
del((IntPtr)pEEType);
}
}
public static int GetElementSize(this Array array)
{
return array.EETypePtr.ComponentSize;
}
internal static bool MightBeBlittable(this EETypePtr eeType)
{
//
// This is used as the approximate implementation of MethodTable::IsBlittable(). It will err in the direction of declaring
// things blittable since it is used for argument validation only.
//
return !eeType.HasPointers;
}
public static bool IsBlittable(this RuntimeTypeHandle handle)
{
return handle.ToEETypePtr().MightBeBlittable();
}
public static bool IsBlittable(this Object obj)
{
return obj.EETypePtr.MightBeBlittable();
}
public static bool IsGenericType(this RuntimeTypeHandle handle)
{
EETypePtr eeType = handle.ToEETypePtr();
return eeType.IsGeneric;
}
public static bool IsGenericTypeDefinition(this RuntimeTypeHandle handle)
{
EETypePtr eeType = handle.ToEETypePtr();
return eeType.IsGenericTypeDefinition;
}
public static unsafe int GetGenericArgumentCount(this RuntimeTypeHandle genericTypeDefinitionHandle)
{
Debug.Assert(IsGenericTypeDefinition(genericTypeDefinitionHandle));
return genericTypeDefinitionHandle.ToEETypePtr().ToPointer()->GenericArgumentCount;
}
//TODO:Remove Delegate.GetNativeFunctionPointer
public static IntPtr GetNativeFunctionPointer(this Delegate del)
{
return del.GetNativeFunctionPointer();
}
public static IntPtr GetFunctionPointer(this Delegate del, out RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate)
{
bool dummyIsOpenInstanceFunction;
return del.GetFunctionPointer(out typeOfFirstParameterIfInstanceDelegate, out dummyIsOpenInstanceFunction);
}
//
// Returns the raw function pointer for a open static delegate - if the function has a jump stub
// it returns the jump target. Therefore the function pointer returned
// by two delegates may NOT be unique
//
public static IntPtr GetRawFunctionPointerForOpenStaticDelegate(this Delegate del)
{
//If it is not open static then return IntPtr.Zero
if (!del.IsOpenStatic)
return IntPtr.Zero;
bool dummyIsOpenInstanceFunction;
RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate;
IntPtr funcPtr = del.GetFunctionPointer(out typeOfFirstParameterIfInstanceDelegate, out dummyIsOpenInstanceFunction);
// if the function pointer points to a jump stub return the target
return RuntimeImports.RhGetJmpStubCodeTarget(funcPtr);
}
public static IntPtr GetRawValue(this RuntimeTypeHandle handle)
{
return handle.RawValue;
}
/// <summary>
/// Comparing RuntimeTypeHandle with an object's RuntimeTypeHandle, avoiding going through expensive Object.GetType().TypeHandle path
/// </summary>
public static bool IsOfType(this Object obj, RuntimeTypeHandle handle)
{
RuntimeTypeHandle objType = new RuntimeTypeHandle(obj.EETypePtr);
return handle.Equals(objType);
}
public static bool IsNull(this RuntimeTypeHandle handle)
{
return handle.IsNull;
}
public static Type GetTypeFromHandle(IntPtr typeHandle)
{
return Type.GetTypeFromHandle(new RuntimeTypeHandle(new EETypePtr(typeHandle)));
}
public static Type GetTypeFromHandle(RuntimeTypeHandle typeHandle)
{
return Type.GetTypeFromHandle(typeHandle);
}
public static int GetValueTypeSize(this RuntimeTypeHandle handle)
{
return (int)handle.ToEETypePtr().ValueTypeSize;
}
public static bool IsValueType(this RuntimeTypeHandle handle)
{
return handle.ToEETypePtr().IsValueType;
}
public static bool IsClass(this RuntimeTypeHandle handle)
{
return handle.ToEETypePtr().IsDefType && !handle.ToEETypePtr().IsInterface && !handle.ToEETypePtr().IsValueType && !handle.IsDelegate();
}
public static bool IsEnum(this RuntimeTypeHandle handle)
{
return handle.ToEETypePtr().IsEnum;
}
public static bool IsInterface(this RuntimeTypeHandle handle)
{
return handle.ToEETypePtr().IsInterface;
}
public static bool IsPrimitive(this RuntimeTypeHandle handle)
{
return handle.ToEETypePtr().IsPrimitive;
}
public static bool IsDelegate(this RuntimeTypeHandle handle)
{
return InteropExtensions.AreTypesAssignable(handle, typeof(MulticastDelegate).TypeHandle) ||
InteropExtensions.AreTypesAssignable(handle, typeof(Delegate).TypeHandle);
}
public static bool AreTypesAssignable(RuntimeTypeHandle sourceType, RuntimeTypeHandle targetType)
{
return RuntimeImports.AreTypesAssignable(sourceType.ToEETypePtr(), targetType.ToEETypePtr());
}
public static unsafe void Memcpy(IntPtr destination, IntPtr source, int bytesToCopy)
{
Buffer.Memmove((byte*)destination, (byte*)source, (uint)bytesToCopy);
}
public static bool RuntimeRegisterGcCalloutForGCStart(IntPtr pCalloutMethod)
{
return RuntimeImports.RhRegisterGcCallout(RuntimeImports.GcRestrictedCalloutKind.StartCollection, pCalloutMethod);
}
public static bool RuntimeRegisterGcCalloutForGCEnd(IntPtr pCalloutMethod)
{
return RuntimeImports.RhRegisterGcCallout(RuntimeImports.GcRestrictedCalloutKind.EndCollection, pCalloutMethod);
}
public static bool RuntimeRegisterGcCalloutForAfterMarkPhase(IntPtr pCalloutMethod)
{
return RuntimeImports.RhRegisterGcCallout(RuntimeImports.GcRestrictedCalloutKind.AfterMarkPhase, pCalloutMethod);
}
public static bool RuntimeRegisterRefCountedHandleCallback(IntPtr pCalloutMethod, RuntimeTypeHandle pTypeFilter)
{
return RuntimeImports.RhRegisterRefCountedHandleCallback(pCalloutMethod, pTypeFilter.ToEETypePtr());
}
public static void RuntimeUnregisterRefCountedHandleCallback(IntPtr pCalloutMethod, RuntimeTypeHandle pTypeFilter)
{
RuntimeImports.RhUnregisterRefCountedHandleCallback(pCalloutMethod, pTypeFilter.ToEETypePtr());
}
/// <summary>
/// The type of a RefCounted handle
/// A ref-counted handle is a handle that acts as strong if the callback returns true, and acts as
/// weak handle if the callback returns false, which is perfect for controlling lifetime of a CCW
/// </summary>
internal const int RefCountedHandleType = 5;
public static IntPtr RuntimeHandleAllocRefCounted(Object value)
{
return RuntimeImports.RhHandleAlloc(value, (GCHandleType)RefCountedHandleType);
}
public static void RuntimeHandleSet(IntPtr handle, Object value)
{
RuntimeImports.RhHandleSet(handle, value);
}
public static void RuntimeHandleFree(IntPtr handle)
{
RuntimeImports.RhHandleFree(handle);
}
public static IntPtr RuntimeHandleAllocDependent(object primary, object secondary)
{
return RuntimeImports.RhHandleAllocDependent(primary, secondary);
}
public static bool RuntimeIsPromoted(object obj)
{
return RuntimeImports.RhIsPromoted(obj);
}
public static void RuntimeHandleSetDependentSecondary(IntPtr handle, Object secondary)
{
RuntimeImports.RhHandleSetDependentSecondary(handle, secondary);
}
public static T UncheckedCast<T>(object obj) where T : class
{
return Unsafe.As<T>(obj);
}
public static bool IsArray(RuntimeTypeHandle type)
{
return type.ToEETypePtr().IsArray;
}
public static RuntimeTypeHandle GetArrayElementType(RuntimeTypeHandle arrayType)
{
return new RuntimeTypeHandle(arrayType.ToEETypePtr().ArrayElementType);
}
/// <summary>
/// Whether the type is a single dimension zero lower bound array
/// </summary>
/// <param name="type">specified type</param>
/// <returns>true iff it is a single dimension zeo lower bound array</returns>
public static bool IsSzArray(RuntimeTypeHandle type)
{
return type.ToEETypePtr().IsSzArray;
}
public static RuntimeTypeHandle GetTypeHandle(this object target)
{
return new RuntimeTypeHandle(target.EETypePtr);
}
public static bool IsInstanceOf(object obj, RuntimeTypeHandle typeHandle)
{
return (null != RuntimeImports.IsInstanceOf(obj, typeHandle.ToEETypePtr()));
}
public static bool IsInstanceOfClass(object obj, RuntimeTypeHandle classTypeHandle)
{
return (null != RuntimeImports.IsInstanceOfClass(obj, classTypeHandle.ToEETypePtr()));
}
public static bool IsInstanceOfInterface(object obj, RuntimeTypeHandle interfaceTypeHandle)
{
return (null != RuntimeImports.IsInstanceOfInterface(obj, interfaceTypeHandle.ToEETypePtr()));
}
public static bool GuidEquals(ref Guid left, ref Guid right)
{
return left.Equals(ref right);
}
public static bool ComparerEquals<T>(T left, T right)
{
return EqualOnlyComparer<T>.Equals(left, right);
}
public static object RuntimeNewObject(RuntimeTypeHandle typeHnd)
{
return RuntimeImports.RhNewObject(typeHnd.ToEETypePtr());
}
public static unsafe void UnsafeCopyTo(this System.Text.StringBuilder stringBuilder, char* destination)
{
stringBuilder.UnsafeCopyTo(destination);
}
public static unsafe void ReplaceBuffer(this System.Text.StringBuilder stringBuilder, char* newBuffer)
{
stringBuilder.ReplaceBuffer(newBuffer);
}
public static void ReplaceBuffer(this System.Text.StringBuilder stringBuilder, char[] newBuffer)
{
stringBuilder.ReplaceBuffer(newBuffer);
}
public static char[] GetBuffer(this System.Text.StringBuilder stringBuilder, out int len)
{
return stringBuilder.GetBuffer(out len);
}
public static IntPtr RuntimeHandleAllocVariable(Object value, uint type)
{
return RuntimeImports.RhHandleAllocVariable(value, type);
}
public static uint RuntimeHandleGetVariableType(IntPtr handle)
{
return RuntimeImports.RhHandleGetVariableType(handle);
}
public static void RuntimeHandleSetVariableType(IntPtr handle, uint type)
{
RuntimeImports.RhHandleSetVariableType(handle, type);
}
public static uint RuntimeHandleCompareExchangeVariableType(IntPtr handle, uint oldType, uint newType)
{
return RuntimeImports.RhHandleCompareExchangeVariableType(handle, oldType, newType);
}
public static void SetExceptionErrorCode(Exception exception, int hr)
{
exception.SetErrorCode(hr);
}
public static void SetExceptionMessage(Exception exception, string message)
{
exception.SetMessage(message);
}
public static Exception CreateDataMisalignedException(string message)
{
return new DataMisalignedException(message);
}
public static Delegate CreateDelegate(RuntimeTypeHandle typeHandleForDelegate, IntPtr ldftnResult, Object thisObject, bool isStatic, bool isVirtual, bool isOpen)
{
return Delegate.CreateDelegate(typeHandleForDelegate.ToEETypePtr(), ldftnResult, thisObject, isStatic, isOpen);
}
public enum VariableHandleType
{
WeakShort = 0x00000100,
WeakLong = 0x00000200,
Strong = 0x00000400,
Pinned = 0x00000800,
}
public static void AddExceptionDataForRestrictedErrorInfo(Exception ex, string restrictedError, string restrictedErrorReference, string restrictedCapabilitySid, object restrictedErrorObject)
{
ex.AddExceptionDataForRestrictedErrorInfo(restrictedError, restrictedErrorReference, restrictedCapabilitySid, restrictedErrorObject);
}
public static bool TryGetRestrictedErrorObject(Exception ex, out object restrictedErrorObject)
{
return ex.TryGetRestrictedErrorObject(out restrictedErrorObject);
}
public static bool TryGetRestrictedErrorDetails(Exception ex, out string restrictedError, out string restrictedErrorReference, out string restrictedCapabilitySid)
{
return ex.TryGetRestrictedErrorDetails(out restrictedError, out restrictedErrorReference, out restrictedCapabilitySid);
}
public static TypeInitializationException CreateTypeInitializationException(string message)
{
return new TypeInitializationException(message);
}
public static unsafe IntPtr GetObjectID(object obj)
{
fixed (void* p = &obj.m_pEEType)
{
return (IntPtr)p;
}
}
public static bool RhpETWShouldWalkCom()
{
return RuntimeImports.RhpETWShouldWalkCom();
}
public static void RhpETWLogLiveCom(int eventType, IntPtr CCWHandle, IntPtr objectID, IntPtr typeRawValue, IntPtr IUnknown, IntPtr VTable, Int32 comRefCount, Int32 jupiterRefCount, Int32 flags)
{
RuntimeImports.RhpETWLogLiveCom(eventType, CCWHandle, objectID, typeRawValue, IUnknown, VTable, comRefCount, jupiterRefCount, flags);
}
public static bool SupportsReflection(this Type type)
{
return RuntimeAugments.Callbacks.SupportsReflection(type);
}
public static void SuppressReentrantWaits()
{
RuntimeThread.SuppressReentrantWaits();
}
public static void RestoreReentrantWaits()
{
RuntimeThread.RestoreReentrantWaits();
}
public static IntPtr GetCriticalHandle(CriticalHandle criticalHandle)
{
return criticalHandle.GetHandleInternal();
}
public static void SetCriticalHandle(CriticalHandle criticalHandle, IntPtr handle)
{
criticalHandle.SetHandleInternal(handle);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="RichTextBoxConstants.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
//=--------------------------------------------------------------------------=
// RichTextBoxConstants.cs
//=--------------------------------------------------------------------------=
// Copyright (c) 1997 Microsoft Corporation. All Rights Reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//=--------------------------------------------------------------------------=
namespace System.Windows.Forms {
using System.Diagnostics;
using System;
using System.Drawing;
using Microsoft.Win32;
/// <include file='doc\RichTextBoxConstants.uex' path='docs/doc[@for="RichTextBoxConstants"]/*' />
/// <devdoc>
/// </devdoc>
internal static class RichTextBoxConstants {
// flags for enum that we don't want public
//
internal const int RTB_HORIZ = 0x0001;
internal const int RTB_VERT = 0x0002;
internal const int RTB_FORCE = 0x0010;
/* Richedit dll name */
internal const string RICHEDIT_DLL10 = "RichEd32.DLL";
internal const string RICHEDIT_DLL20 = "RichEd20.DLL";
internal const string RICHEDIT_DLL30 = RICHEDIT_DLL20;
/* Richedit1.0 Window Class */
internal const string RICHEDIT_CLASS10A = "RICHEDIT";
/* Richedit2.0 Window Class. */
internal const string RICHEDIT_CLASS20A = "RichEdit20A";
internal const string RICHEDIT_CLASS20W = "RichEdit20W";
/* Richedit3.0 Window Class */
internal const string RICHEDIT_CLASS30A = RICHEDIT_CLASS20A;
internal const string RICHEDIT_CLASS30W = RICHEDIT_CLASS20W;
internal const string DLL_RICHEDIT = RICHEDIT_DLL30;
internal const string WC_RICHEDITA = RICHEDIT_CLASS30A;
internal const string WC_RICHEDITW = RICHEDIT_CLASS30W;
/* RichTextBox messages */
internal const int WM_CONTEXTMENU = 0x007B;
internal const int WM_PRINTCLIENT = 0x0318;
internal const int EM_GETLIMITTEXT = (NativeMethods.WM_USER + 37);
internal const int EM_POSFROMCHAR = (NativeMethods.WM_USER + 38);
internal const int EM_CHARFROMPOS = (NativeMethods.WM_USER + 39);
internal const int EM_SCROLLCARET = (NativeMethods.WM_USER + 49);
internal const int EM_CANPASTE = (NativeMethods.WM_USER + 50);
internal const int EM_DISPLAYBAND = (NativeMethods.WM_USER + 51);
internal const int EM_EXGETSEL = (NativeMethods.WM_USER + 52);
internal const int EM_EXLIMITTEXT = (NativeMethods.WM_USER + 53);
internal const int EM_EXLINEFROMCHAR = (NativeMethods.WM_USER + 54);
internal const int EM_EXSETSEL = (NativeMethods.WM_USER + 55);
internal const int EM_FINDTEXT = (NativeMethods.WM_USER + 56);
internal const int EM_FORMATRANGE = (NativeMethods.WM_USER + 57);
internal const int EM_GETCHARFORMAT = (NativeMethods.WM_USER + 58);
internal const int EM_GETEVENTMASK = (NativeMethods.WM_USER + 59);
internal const int EM_GETOLEINTERFACE = (NativeMethods.WM_USER + 60);
internal const int EM_GETPARAFORMAT = (NativeMethods.WM_USER + 61);
internal const int EM_GETSELTEXT = (NativeMethods.WM_USER + 62);
internal const int EM_HIDESELECTION = (NativeMethods.WM_USER + 63);
internal const int EM_PASTESPECIAL = (NativeMethods.WM_USER + 64);
internal const int EM_REQUESTRESIZE = (NativeMethods.WM_USER + 65);
internal const int EM_SELECTIONTYPE = (NativeMethods.WM_USER + 66);
internal const int EM_SETBKGNDCOLOR = (NativeMethods.WM_USER + 67);
internal const int EM_SETCHARFORMAT = (NativeMethods.WM_USER + 68);
internal const int EM_SETEVENTMASK = (NativeMethods.WM_USER + 69);
internal const int EM_SETOLECALLBACK = (NativeMethods.WM_USER + 70);
internal const int EM_SETPARAFORMAT = (NativeMethods.WM_USER + 71);
internal const int EM_SETTARGETDEVICE = (NativeMethods.WM_USER + 72);
internal const int EM_STREAMIN = (NativeMethods.WM_USER + 73);
internal const int EM_STREAMOUT = (NativeMethods.WM_USER + 74);
internal const int EM_GETTEXTRANGE = (NativeMethods.WM_USER + 75);
internal const int EM_FINDWORDBREAK = (NativeMethods.WM_USER + 76);
internal const int EM_SETOPTIONS = (NativeMethods.WM_USER + 77);
internal const int EM_GETOPTIONS = (NativeMethods.WM_USER + 78);
internal const int EM_FINDTEXTEX = (NativeMethods.WM_USER + 79);
internal const int EM_GETWORDBREAKPROCEX = (NativeMethods.WM_USER + 80);
internal const int EM_SETWORDBREAKPROCEX = (NativeMethods.WM_USER + 81);
// Richedit v2.0 messages
internal const int EM_SETUNDOLIMIT = (NativeMethods.WM_USER + 82);
internal const int EM_REDO = (NativeMethods.WM_USER + 84);
internal const int EM_CANREDO = (NativeMethods.WM_USER + 85);
internal const int EM_GETUNDONAME = (NativeMethods.WM_USER + 86);
internal const int EM_GETREDONAME = (NativeMethods.WM_USER + 87);
internal const int EM_STOPGROUPTYPING = (NativeMethods.WM_USER + 88);
internal const int EM_SETTEXTMODE = (NativeMethods.WM_USER + 89);
internal const int EM_GETTEXTMODE = (NativeMethods.WM_USER + 90);
internal const int EM_AUTOURLDETECT = (NativeMethods.WM_USER + 91);
internal const int EM_GETAUTOURLDETECT = (NativeMethods.WM_USER + 92);
internal const int EM_SETPALETTE = (NativeMethods.WM_USER + 93);
internal const int EM_GETTEXTEX = (NativeMethods.WM_USER + 94);
internal const int EM_GETTEXTLENGTHEX = (NativeMethods.WM_USER + 95);
// Asia specific messages
internal const int EM_SETPUNCTUATION = (NativeMethods.WM_USER + 100);
internal const int EM_GETPUNCTUATION = (NativeMethods.WM_USER + 101);
internal const int EM_SETWORDWRAPMODE = (NativeMethods.WM_USER + 102);
internal const int EM_GETWORDWRAPMODE = (NativeMethods.WM_USER + 103);
internal const int EM_SETIMECOLOR = (NativeMethods.WM_USER + 104);
internal const int EM_GETIMECOLOR = (NativeMethods.WM_USER + 105);
internal const int EM_SETIMEOPTIONS = (NativeMethods.WM_USER + 106);
internal const int EM_GETIMEOPTIONS = (NativeMethods.WM_USER + 107);
internal const int EM_CONVPOSITION = (NativeMethods.WM_USER + 108);
internal const int EM_SETLANGOPTIONS = (NativeMethods.WM_USER + 120);
internal const int EM_GETLANGOPTIONS = (NativeMethods.WM_USER + 121);
internal const int EM_GETIMECOMPMODE = (NativeMethods.WM_USER + 122);
internal const int EM_FINDTEXTW = (NativeMethods.WM_USER + 123);
internal const int EM_FINDTEXTEXW = (NativeMethods.WM_USER + 124);
//Rich TextBox 3.0 Asia msgs
internal const int EM_RECONVERSION = (NativeMethods.WM_USER + 125);
internal const int EM_SETIMEMODEBIAS = (NativeMethods.WM_USER + 126);
internal const int EM_GETIMEMODEBIAS = (NativeMethods.WM_USER + 127);
// BiDi Specific messages
internal const int EM_SETBIDIOPTIONS = (NativeMethods.WM_USER + 200);
internal const int EM_GETBIDIOPTIONS = (NativeMethods.WM_USER + 201);
internal const int EM_SETTYPOGRAPHYOPTIONS = (NativeMethods.WM_USER + 202);
internal const int EM_GETTYPOGRAPHYOPTIONS = (NativeMethods.WM_USER + 203);
// Extended TextBox style specific messages
internal const int EM_SETEDITSTYLE = (NativeMethods.WM_USER + 204);
internal const int EM_GETEDITSTYLE = (NativeMethods.WM_USER + 205);
// Ole Objects Disabling message
internal const int EM_SETQUERYRTFOBJ = (NativeMethods.WM_USER + 270);
// Extended edit style masks
internal const int SES_EMULATESYSEDIT = 1;
internal const int SES_BEEPONMAXTEXT = 2;
internal const int SES_EXTENDBACKCOLOR = 4;
internal const int SES_MAPCPS = 8;
internal const int SES_EMULATE10 = 16;
internal const int SES_USECRLF = 32;
internal const int SES_USEAIMM = 64;
internal const int SES_NOIME = 128;
internal const int SES_ALLOWBEEPS = 256;
internal const int SES_UPPERCASE = 512;
internal const int SES_LOWERCASE = 1024;
internal const int SES_NOINPUTSEQUENCECHK = 2048;
internal const int SES_BIDI = 4096;
internal const int SES_SCROLLONKILLFOCUS = 8192;
internal const int SES_XLTCRCRLFTOCR = 16384;
// Options for EM_SETLANGOPTIONS and EM_GETLANGOPTIONS
internal const int IMF_AUTOKEYBOARD = 0x0001;
internal const int IMF_AUTOFONT = 0x0002;
internal const int IMF_IMECANCELCOMPLETE = 0x0004; // high completes the comp string when aborting, low cancels.
internal const int IMF_IMEALWAYSSENDNOTIFY = 0x0008;
internal const int IMF_AUTOFONTSIZEADJUST = 0x0010;
internal const int IMF_UIFONTS = 0x0020;
internal const int IMF_DUALFONT = 0x0080;
// Values for EM_GETIMECOMPMODE
internal const int ICM_NOTOPEN = 0x0000;
internal const int ICM_LEVEL3 = 0x0001;
internal const int ICM_LEVEL2 = 0x0002;
internal const int ICM_LEVEL2_5 = 0x0003;
internal const int ICM_LEVEL2_SUI = 0x0004;
// Pegasus outline mode messages (RE 3.0)
// Outline mode message
internal const int EM_OUTLINE = NativeMethods.WM_USER + 220;
// Message for getting and restoring scroll pos
internal const int EM_GETSCROLLPOS = NativeMethods.WM_USER + 221;
internal const int EM_SETSCROLLPOS = NativeMethods.WM_USER + 222;
// Change fontsize in current selection by wparam
internal const int EM_SETFONTSIZE = NativeMethods.WM_USER + 223;
internal const int EM_GETZOOM = NativeMethods.WM_USER + 224;
internal const int EM_SETZOOM = NativeMethods.WM_USER + 225;
// Outline mode wparam values
internal const int EMO_EXIT = 0; // enter normal mode, lparam ignored
internal const int EMO_ENTER = 1; // enter outline mode, lparam ignored
internal const int EMO_PROMOTE = 2; // LOWORD(lparam) == 0 ==>
// promote to body-text
// LOWORD(lparam) != 0 ==>
// promote/demote current selection
// by indicated number of levels
internal const int EMO_EXPAND = 3; // HIWORD(lparam) = EMO_EXPANDSELECTION
// -> expands selection to level
// indicated in LOWORD(lparam)
// LOWORD(lparam) = -1/+1 corresponds
// to collapse/expand button presses
// in winword (other values are
// equivalent to having pressed these
// buttons more than once)
// HIWORD(lparam) = EMO_EXPANDDOCUMENT
// -> expands whole document to
// indicated level
internal const int EMO_MOVESELECTION = 4; // LOWORD(lparam) != 0 -> move current
// selection up/down by indicated
// amount
internal const int EMO_GETVIEWMODE = 5; // Returns VM_NORMAL or VM_OUTLINE
// EMO_EXPAND options
internal const int EMO_EXPANDSELECTION = 0;
internal const int EMO_EXPANDDOCUMENT = 1;
internal const int VM_NORMAL = 4; // Agrees with RTF \viewkindN
internal const int VM_OUTLINE = 2;
// New notifications
internal const int EN_MSGFILTER = 0x0700;
internal const int EN_REQUESTRESIZE = 0x0701;
internal const int EN_SELCHANGE = 0x0702;
internal const int EN_DROPFILES = 0x0703;
internal const int EN_PROTECTED = 0x0704;
internal const int EN_CORRECTTEXT = 0x0705; /* PenWin specific */
internal const int EN_STOPNOUNDO = 0x0706;
internal const int EN_IMECHANGE = 0x0707; /* Asia specific */
internal const int EN_SAVECLIPBOARD = 0x0708;
internal const int EN_OLEOPFAILED = 0x0709;
internal const int EN_OBJECTPOSITIONS = 0x070a;
internal const int EN_LINK = 0x070b;
internal const int EN_DRAGDROPDONE = 0x070c;
internal const int EN_PARAGRAPHEXPANDED = 0x070d;
// BiDi specific notifications
internal const int EN_ALIGNLTR = 0x0710;
internal const int EN_ALIGNRTL = 0x0711;
// Event notification masks */
internal const int ENM_NONE = 0x00000000;
internal const int ENM_CHANGE = 0x00000001;
internal const int ENM_UPDATE = 0x00000002;
internal const int ENM_SCROLL = 0x00000004;
internal const int ENM_KEYEVENTS = 0x00010000;
internal const int ENM_MOUSEEVENTS = 0x00020000;
internal const int ENM_REQUESTRESIZE = 0x00040000;
internal const int ENM_SELCHANGE = 0x00080000;
internal const int ENM_DROPFILES = 0x00100000;
internal const int ENM_PROTECTED = 0x00200000;
internal const int ENM_CORRECTTEXT = 0x00400000; /* PenWin specific */
internal const int ENM_SCROLLEVENTS = 0x00000008;
internal const int ENM_DRAGDROPDONE = 0x00000010;
internal const int ENM_PARAGRAPHEXPANDED = 0x00000020;
/* Asia specific notification mask */
internal const int ENM_IMECHANGE = 0x00800000; /* unused by RE2.0 */
internal const int ENM_LANGCHANGE = 0x01000000;
internal const int ENM_OBJECTPOSITIONS = 0x02000000;
internal const int ENM_LINK = 0x04000000;
/* New edit control styles */
internal const int ES_SAVESEL = 0x00008000;
internal const int ES_SUNKEN = 0x00004000;
internal const int ES_DISABLENOSCROLL = 0x00002000;
/* same as WS_MAXIMIZE, but that doesn't make sense so we re-use the value */
internal const int ES_SELECTIONBAR = 0x01000000;
/* same as ES_UPPERCASE, but re-used to completely disable OLE drag'n'drop */
internal const int ES_NOOLEDRAGDROP = 0x00000008;
/* New edit control extended style */
internal const int ES_EX_NOCALLOLEINIT = 0x01000000;
/* These flags are used in FE Windows */
internal const int ES_VERTICAL = 0x00400000; // NOT IN RE3.0/2.0
internal const int ES_NOIME = 0x00080000;
internal const int ES_SELFIME = 0x00040000;
/* TextBox control options */
internal const int ECO_AUTOWORDSELECTION = 0x00000001;
internal const int ECO_AUTOVSCROLL = 0x00000040;
internal const int ECO_AUTOHSCROLL = 0x00000080;
internal const int ECO_NOHIDESEL = 0x00000100;
internal const int ECO_READONLY = 0x00000800;
internal const int ECO_WANTRETURN = 0x00001000;
internal const int ECO_SAVESEL = 0x00008000;
internal const int ECO_SELECTIONBAR = 0x01000000; // guessing this is selection margin
internal const int ECO_VERTICAL = 0x00400000; /* FE specific */
/* ECO operations */
internal const int ECOOP_SET = 0x0001;
internal const int ECOOP_OR = 0x0002;
internal const int ECOOP_AND = 0x0003;
internal const int ECOOP_XOR = 0x0004;
/* new word break function actions */
internal const int WB_CLASSIFY = 3;
internal const int WB_MOVEWORDLEFT = 4;
internal const int WB_MOVEWORDRIGHT = 5;
internal const int WB_LEFTBREAK = 6;
internal const int WB_RIGHTBREAK = 7;
/* Asia specific flags */
internal const int WB_MOVEWORDPREV = 4;
internal const int WB_MOVEWORDNEXT = 5;
internal const int WB_PREVBREAK = 6;
internal const int WB_NEXTBREAK = 7;
internal const int PC_FOLLOWING = 1;
internal const int PC_LEADING = 2;
internal const int PC_OVERFLOW = 3;
internal const int PC_DELIMITER = 4;
internal const int WBF_WORDWRAP = 0x010;
internal const int WBF_WORDBREAK = 0x020;
internal const int WBF_OVERFLOW = 0x040;
internal const int WBF_LEVEL1 = 0x080;
internal const int WBF_LEVEL2 = 0x100;
internal const int WBF_CUSTOM = 0x200;
/* for use with EM_GET/SETTEXTMODE */
internal const int TM_PLAINTEXT = 1;
internal const int TM_RICHTEXT = 2; /* default behavior */
internal const int TM_SINGLELEVELUNDO = 4;
internal const int TM_MULTILEVELUNDO = 8; /* default behavior */
internal const int TM_SINGLECODEPAGE = 16;
internal const int TM_MULTICODEPAGE = 32; /* default behavior */
/* Asia specific flags */
internal const int IMF_FORCENONE = 0x0001;
internal const int IMF_FORCEENABLE = 0x0002;
internal const int IMF_FORCEDISABLE = 0x0004;
internal const int IMF_CLOSESTATUSWINDOW = 0x0008;
internal const int IMF_VERTICAL = 0x0020;
internal const int IMF_FORCEACTIVE = 0x0040;
internal const int IMF_FORCEINACTIVE = 0x0080;
internal const int IMF_FORCEREMEMBER = 0x0100;
internal const int IMF_MULTIPLEEDIT = 0x0400;
/* Word break flags (used with WB_CLASSIFY) */
internal const int WBF_CLASS = 0x0F;
internal const int WBF_ISWHITE = 0x10;
internal const int WBF_BREAKLINE = 0x20;
internal const int WBF_BREAKAFTER = 0x40;
internal const int cchTextLimitDefault = 32767;
/* CHARFORMAT masks */
internal const int CFM_BOLD = 0x00000001;
internal const int CFM_ITALIC = 0x00000002;
internal const int CFM_UNDERLINE = 0x00000004;
internal const int CFM_STRIKEOUT = 0x00000008;
internal const int CFM_PROTECTED = 0x00000010;
internal const int CFM_LINK = 0x00000020; /* Exchange hyperlink extension */
internal const int CFM_SIZE = unchecked((int)0x80000000);
internal const int CFM_COLOR = 0x40000000;
internal const int CFM_FACE = 0x20000000;
internal const int CFM_OFFSET = 0x10000000;
internal const int CFM_CHARSET = 0x08000000;
/* CHARFORMAT effects */
internal const int CFE_BOLD = 0x0001;
internal const int CFE_ITALIC = 0x0002;
internal const int CFE_UNDERLINE = 0x0004;
internal const int CFE_STRIKEOUT = 0x0008;
internal const int CFE_PROTECTED = 0x0010;
internal const int CFE_LINK = 0x0020;
internal const int CFE_AUTOCOLOR = 0x40000000; /* NOTE: this corresponds to */
/* CFM_COLOR, which controls it */
internal const int yHeightCharPtsMost = 1638;
/* EM_SETCHARFORMAT wparam masks */
internal const int SCF_SELECTION = 0x0001;
internal const int SCF_WORD = 0x0002;
internal const int SCF_DEFAULT = 0x0000; // set the default charformat or paraformat
internal const int SCF_ALL = 0x0004; // not valid with SCF_SELECTION or SCF_WORD
internal const int SCF_USEUIRULES = 0x0008; // modifier for SCF_SELECTION; says that
// the format came from a toolbar, etc. and
// therefore UI formatting rules should be
// used instead of strictly formatting the
// selection.
/* stream formats */
internal const int SF_TEXT = 0x0001;
internal const int SF_RTF = 0x0002;
internal const int SF_RTFNOOBJS = 0x0003; /* outbound only */
internal const int SF_TEXTIZED = 0x0004; /* outbound only */
internal const int SF_UNICODE = 0x0010; /* Unicode file of some kind */
/* Flag telling stream operations to operate on the selection only */
/* EM_STREAMIN will replace the current selection */
/* EM_STREAMOUT will stream out the current selection */
internal const int SFF_SELECTION = 0x8000;
/* Flag telling stream operations to operate on the common RTF keyword only */
/* EM_STREAMIN will accept the only common RTF keyword */
/* EM_STREAMOUT will stream out the only common RTF keyword */
internal const int SFF_PLAINRTF = 0x4000;
/* all paragraph measurements are in twips */
internal const int MAX_TAB_STOPS = 32;
internal const int lDefaultTab = 720;
/* PARAFORMAT mask values */
internal const int PFM_STARTINDENT = 0x00000001;
internal const int PFM_RIGHTINDENT = 0x00000002;
internal const int PFM_OFFSET = 0x00000004;
internal const int PFM_ALIGNMENT = 0x00000008;
internal const int PFM_TABSTOPS = 0x00000010;
internal const int PFM_NUMBERING = 0x00000020;
internal const int PFM_OFFSETINDENT = unchecked((int)0x80000000);
/* PARAFORMAT numbering options */
internal const int PFN_BULLET = 0x0001;
/* PARAFORMAT alignment options */
internal const int PFA_LEFT = 0x0001;
internal const int PFA_RIGHT = 0x0002;
internal const int PFA_CENTER = 0x0003;
/* CHARFORMAT and PARAFORMAT "ALL" masks
CFM_COLOR mirrors CFE_AUTOCOLOR, a little
code to easily deal with autocolor */
internal const int CFM_EFFECTS = (CFM_BOLD | CFM_ITALIC |
CFM_UNDERLINE | CFM_COLOR |
CFM_STRIKEOUT | CFE_PROTECTED |
CFM_LINK);
internal const int CFM_ALL = (CFM_EFFECTS | CFM_SIZE |
CFM_FACE | CFM_OFFSET | CFM_CHARSET);
internal const int PFM_ALL = (PFM_STARTINDENT | PFM_RIGHTINDENT |
PFM_OFFSET | PFM_ALIGNMENT |
PFM_TABSTOPS | PFM_NUMBERING |
PFM_OFFSETINDENT);
/* New masks and effects -- a parenthesized asterisk indicates that
the data is stored by RichEdit2.0, but not displayed */
internal const int CFM_SMALLCAPS = 0x0040; /* (*) */
internal const int CFM_ALLCAPS = 0x0080; /* (*) */
internal const int CFM_HIDDEN = 0x0100; /* (*) */
internal const int CFM_OUTLINE = 0x0200; /* (*) */
internal const int CFM_SHADOW = 0x0400; /* (*) */
internal const int CFM_EMBOSS = 0x0800; /* (*) */
internal const int CFM_IMPRINT = 0x1000; /* (*) */
internal const int CFM_DISABLED = 0x2000;
internal const int CFM_REVISED = 0x4000;
internal const int CFM_BACKCOLOR = 0x04000000;
internal const int CFM_LCID = 0x02000000;
internal const int CFM_UNDERLINETYPE = 0x00800000; /* (*) */
internal const int CFM_WEIGHT = 0x00400000;
internal const int CFM_SPACING = 0x00200000; /* (*) */
internal const int CFM_KERNING = 0x00100000; /* (*) */
internal const int CFM_STYLE = 0x00080000; /* (*) */
internal const int CFM_ANIMATION = 0x00040000; /* (*) */
internal const int CFM_REVAUTHOR = 0x00008000;
internal const int CFE_SUBSCRIPT = 0x00010000; /* Superscript and subscript are */
internal const int CFE_SUPERSCRIPT = 0x00020000; /* mutually exclusive */
internal const int CFM_SUBSCRIPT = (CFE_SUBSCRIPT | CFE_SUPERSCRIPT);
internal const int CFM_SUPERSCRIPT = CFM_SUBSCRIPT;
internal const int CFM_EFFECTS2 = (CFM_EFFECTS | CFM_DISABLED |
CFM_SMALLCAPS | CFM_ALLCAPS |
CFM_HIDDEN | CFM_OUTLINE |
CFM_SHADOW | CFM_EMBOSS |
CFM_IMPRINT | CFM_DISABLED |
CFM_REVISED | CFM_SUBSCRIPT |
CFM_SUPERSCRIPT | CFM_BACKCOLOR);
internal const int CFM_ALL2 = (CFM_ALL | CFM_EFFECTS2 |
CFM_BACKCOLOR | CFM_LCID |
CFM_UNDERLINETYPE | CFM_WEIGHT |
CFM_REVAUTHOR | CFM_SPACING |
CFM_KERNING | CFM_STYLE |
CFM_ANIMATION);
internal const int CFE_SMALLCAPS = CFM_SMALLCAPS;
internal const int CFE_ALLCAPS = CFM_ALLCAPS;
internal const int CFE_HIDDEN = CFM_HIDDEN;
internal const int CFE_OUTLINE = CFM_OUTLINE;
internal const int CFE_SHADOW = CFM_SHADOW;
internal const int CFE_EMBOSS = CFM_EMBOSS;
internal const int CFE_IMPRINT = CFM_IMPRINT;
internal const int CFE_DISABLED = CFM_DISABLED;
internal const int CFE_REVISED = CFM_REVISED;
/* NOTE: CFE_AUTOCOLOR and CFE_AUTOBACKCOLOR correspond to CFM_COLOR and
CFM_BACKCOLOR, respectively, which control them */
internal const int CFE_AUTOBACKCOLOR = CFM_BACKCOLOR;
/* Underline types */
internal const int CFU_CF1UNDERLINE = 0xFF; /* map charformat's bit underline to CF2.*/
internal const int CFU_INVERT = 0xFE; /* For IME composition fake a selection.*/
internal const int CFU_UNDERLINEDOTTED = 0x4; /* (*) displayed as ordinary underline */
internal const int CFU_UNDERLINEDOUBLE = 0x3; /* (*) displayed as ordinary underline */
internal const int CFU_UNDERLINEWORD = 0x2; /* (*) displayed as ordinary underline */
internal const int CFU_UNDERLINE = 0x1;
internal const int CFU_UNDERLINENONE = 0;
/* PARAFORMAT 2.0 masks and effects */
internal const int PFM_SPACEBEFORE = 0x00000040;
internal const int PFM_SPACEAFTER = 0x00000080;
internal const int PFM_LINESPACING = 0x00000100;
internal const int PFM_STYLE = 0x00000400;
internal const int PFM_BORDER = 0x00000800; /* (*) */
internal const int PFM_SHADING = 0x00001000; /* (*) */
internal const int PFM_NUMBERINGSTYLE = 0x00002000; /* (*) */
internal const int PFM_NUMBERINGTAB = 0x00004000; /* (*) */
internal const int PFM_NUMBERINGSTART = 0x00008000; /* (*) */
internal const int PFM_RTLPARA = 0x00010000;
internal const int PFM_KEEP = 0x00020000; /* (*) */
internal const int PFM_KEEPNEXT = 0x00040000; /* (*) */
internal const int PFM_PAGEBREAKBEFORE = 0x00080000; /* (*) */
internal const int PFM_NOLINENUMBER = 0x00100000; /* (*) */
internal const int PFM_NOWIDOWCONTROL = 0x00200000; /* (*) */
internal const int PFM_DONOTHYPHEN = 0x00400000; /* (*) */
internal const int PFM_SIDEBYSIDE = 0x00800000; /* (*) */
internal const int PFM_TABLE = unchecked((int)0xc0000000); /* (*) */
/* Note: PARAFORMAT has no effects */
internal const int PFM_EFFECTS = (PFM_RTLPARA | PFM_KEEP |
PFM_KEEPNEXT | PFM_TABLE |
PFM_PAGEBREAKBEFORE | PFM_NOLINENUMBER |
PFM_NOWIDOWCONTROL | PFM_DONOTHYPHEN |
PFM_SIDEBYSIDE | PFM_TABLE);
internal const int PFM_ALL2 = (PFM_ALL | PFM_EFFECTS |
PFM_SPACEBEFORE | PFM_SPACEAFTER |
PFM_LINESPACING | PFM_STYLE |
PFM_SHADING | PFM_BORDER |
PFM_NUMBERINGTAB | PFM_NUMBERINGSTART |
PFM_NUMBERINGSTYLE);
internal const int PFE_RTLPARA = (PFM_RTLPARA >> 16);
internal const int PFE_KEEP = (PFM_KEEP >> 16); /* (*) */
internal const int PFE_KEEPNEXT = (PFM_KEEPNEXT >> 16); /* (*) */
internal const int PFE_PAGEBREAKBEFORE = (PFM_PAGEBREAKBEFORE >> 16); /* (*) */
internal const int PFE_NOLINENUMBER = (PFM_NOLINENUMBER >> 16); /* (*) */
internal const int PFE_NOWIDOWCONTROL = (PFM_NOWIDOWCONTROL >> 16); /* (*) */
internal const int PFE_DONOTHYPHEN = (PFM_DONOTHYPHEN >> 16); /* (*) */
internal const int PFE_SIDEBYSIDE = (PFM_SIDEBYSIDE >> 16); /* (*) */
internal const int PFE_TABLEROW = 0xc000; /* These 3 options are mutually */
internal const int PFE_TABLECELLEND = 0x8000; /* exclusive and each imply */
internal const int PFE_TABLECELL = 0x4000; /* that para is part of a table*/
/*
* PARAFORMAT numbering options (values for wNumbering):
*
* Numbering Type Value Meaning
* tomNoNumbering 0 Turn off paragraph numbering
* tomNumberAsLCLetter 1 a, b, c, ...
* tomNumberAsUCLetter 2 A, B, C, ...
* tomNumberAsLCRoman 3 i, ii, iii, ...
* tomNumberAsUCRoman 4 I, II, III, ...
* tomNumberAsSymbols 5 default is bullet
* tomNumberAsNumber 6 0, 1, 2, ...
* tomNumberAsSequence 7 tomNumberingStart is first Unicode to use
*
* Other valid Unicode chars are Unicodes for bullets.
*/
internal const int PFA_JUSTIFY = 4; /* New paragraph-alignment option 2.0 (*) */
internal const int SEL_EMPTY = 0x0000;
internal const int SEL_TEXT = 0x0001;
internal const int SEL_OBJECT = 0x0002;
internal const int SEL_MULTICHAR = 0x0004;
internal const int SEL_MULTIOBJECT = 0x0008;
internal const int tomTrue = -1,
tomFalse = 0,
tomNone = 0,
tomUndefined = -9999999,
tomAutoColor = -9999997;
/* used with IRichEditOleCallback::GetContextMenu, this flag will be
passed as a "selection type". It indicates that a context menu for
a right-mouse drag drop should be generated. The IOleObject parameter
will really be the IDataObject for the drop
*/
internal const int GCM_RIGHTMOUSEDROP = 0x8000;
internal const int OLEOP_DOVERB = 1;
/* clipboard formats - use as parameter to RegisterClipboardFormat() */
internal const string CF_RTF = "Rich Text Format";
internal const string CF_RTFNOOBJS = "Rich Text Format Without Objects";
internal const string CF_RETEXTOBJ = "RichEdit Text and Objects";
/* UndoName info */
internal const int UID_UNKNOWN = 0;
internal const int UID_TYPING = 1;
internal const int UID_DELETE = 2;
internal const int UID_DRAGDROP = 3;
internal const int UID_CUT = 4;
internal const int UID_PASTE = 5;
/* flags for the GETEXTEX data structure */
internal const int GT_DEFAULT = 0;
internal const int GT_USECRLF = 1;
/* flags for the GETTEXTLENGTHEX data structure */
internal const int GTL_DEFAULT = 0; /* do the default (return # of chars) */
internal const int GTL_USECRLF = 1; /* compute answer using CRLFs for paragraphs*/
internal const int GTL_PRECISE = 2; /* compute a precise answer */
internal const int GTL_CLOSE = 4; /* fast computation of a "close" answer */
internal const int GTL_NUMCHARS = 8; /* return the number of characters */
internal const int GTL_NUMBYTES = 16; /* return the number of _bytes_ */
/* UNICODE embedding character */
// disable csharp compiler warning #0414: field assigned unused value
#pragma warning disable 0414
internal static readonly char WCH_EMBEDDING = (char)0xFFFC;
#pragma warning restore 0414
/* flags for the find text options */
internal const int FR_DOWN = 0x00000001;
internal const int FR_WHOLEWORD = 0x00000002;
internal const int FR_MATCHCASE = 0x00000004;
}
}
| |
/********************************************************************************************
Copyright (c) Microsoft Corporation
All rights reserved.
Microsoft Public License:
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free copyright license to reproduce its contribution, prepare derivative works of
its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free license under its licensed patents to make, have made, use, sell, offer for
sale, import, and/or otherwise dispose of its contribution in the software or derivative
works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors'
name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are
infringed by the software, your patent license from such contributor to the software ends
automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent,
trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only
under this license by including a complete copy of this license with your distribution.
If you distribute any portion of the software in compiled or object code form, you may only
do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give
no express warranties, guarantees or conditions. You may have additional consumer rights
under your local laws which this license cannot change. To the extent permitted under your
local laws, the contributors exclude the implied warranties of merchantability, fitness for
a particular purpose and non-infringement.
********************************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
//#define ConfigTrace
using Microsoft.VisualStudio.Shell.Interop;
using MSBuild = Microsoft.Build.Evaluation;
using MSBuildExecution = Microsoft.Build.Execution;
using MSBuildConstruction = Microsoft.Build.Construction;
namespace Microsoft.VisualStudio.Project
{
[CLSCompliant(false), ComVisible(true)]
public class ProjectConfig :
IVsCfg,
IVsProjectCfg,
IVsProjectCfg2,
IVsProjectFlavorCfg,
IVsDebuggableProjectCfg,
ISpecifyPropertyPages,
IVsSpecifyProjectDesignerPages,
IVsCfgBrowseObject
{
#region constants
internal const string Debug = "Debug";
internal const string Release = "Release";
internal const string AnyCPU = "AnyCPU";
#endregion
#region fields
private ProjectNode project;
private string configName;
private MSBuildExecution.ProjectInstance currentConfig;
private List<OutputGroup> outputGroups;
private IProjectConfigProperties configurationProperties;
private IVsProjectFlavorCfg flavoredCfg;
private BuildableProjectConfig buildableCfg;
#endregion
#region properties
public ProjectNode ProjectMgr
{
get
{
return this.project;
}
}
public string ConfigName
{
get
{
return this.configName;
}
set
{
this.configName = value;
}
}
public virtual object ConfigurationProperties
{
get
{
if(this.configurationProperties == null)
{
this.configurationProperties = new ProjectConfigProperties(this);
}
return this.configurationProperties;
}
}
protected IList<OutputGroup> OutputGroups
{
get
{
if(null == this.outputGroups)
{
// Initialize output groups
this.outputGroups = new List<OutputGroup>();
// Get the list of group names from the project.
// The main reason we get it from the project is to make it easier for someone to modify
// it by simply overriding that method and providing the correct MSBuild target(s).
IList<KeyValuePair<string, string>> groupNames = project.GetOutputGroupNames();
if(groupNames != null)
{
// Populate the output array
foreach(KeyValuePair<string, string> group in groupNames)
{
OutputGroup outputGroup = CreateOutputGroup(project, group);
this.outputGroups.Add(outputGroup);
}
}
}
return this.outputGroups;
}
}
#endregion
#region ctors
public ProjectConfig(ProjectNode project, string configuration)
{
this.project = project;
this.configName = configuration;
// Because the project can be aggregated by a flavor, we need to make sure
// we get the outer most implementation of that interface (hence: project --> IUnknown --> Interface)
IntPtr projectUnknown = Marshal.GetIUnknownForObject(this.ProjectMgr);
try
{
IVsProjectFlavorCfgProvider flavorCfgProvider = (IVsProjectFlavorCfgProvider)Marshal.GetTypedObjectForIUnknown(projectUnknown, typeof(IVsProjectFlavorCfgProvider));
ErrorHandler.ThrowOnFailure(flavorCfgProvider.CreateProjectFlavorCfg(this, out flavoredCfg));
if(flavoredCfg == null)
throw new COMException();
}
finally
{
if(projectUnknown != IntPtr.Zero)
Marshal.Release(projectUnknown);
}
// if the flavored object support XML fragment, initialize it
IPersistXMLFragment persistXML = flavoredCfg as IPersistXMLFragment;
if(null != persistXML)
{
this.project.LoadXmlFragment(persistXML, this.DisplayName);
}
}
#endregion
#region methods
protected virtual OutputGroup CreateOutputGroup(ProjectNode project, KeyValuePair<string, string> group)
{
OutputGroup outputGroup = new OutputGroup(group.Key, group.Value, project, this);
return outputGroup;
}
public void PrepareBuild(bool clean)
{
project.PrepareBuild(this.configName, clean);
}
public virtual string GetConfigurationProperty(string propertyName, bool resetCache)
{
MSBuildExecution.ProjectPropertyInstance property = GetMsBuildProperty(propertyName, resetCache);
if (property == null)
return null;
return property.EvaluatedValue;
}
public virtual void SetConfigurationProperty(string propertyName, string propertyValue)
{
if(!this.project.QueryEditProjectFile(false))
{
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
string condition = String.Format(CultureInfo.InvariantCulture, ConfigProvider.configString, this.ConfigName);
SetPropertyUnderCondition(propertyName, propertyValue, condition);
// property cache will need to be updated
this.currentConfig = null;
// Signal the output groups that something is changed
foreach(OutputGroup group in this.OutputGroups)
{
group.InvalidateGroup();
}
this.project.SetProjectFileDirty(true);
return;
}
/// <summary>
/// Emulates the behavior of SetProperty(name, value, condition) on the old MSBuild object model.
/// This finds a property group with the specified condition (or creates one if necessary) then sets the property in there.
/// </summary>
private void SetPropertyUnderCondition(string propertyName, string propertyValue, string condition)
{
string conditionTrimmed = (condition == null) ? String.Empty : condition.Trim();
if (conditionTrimmed.Length == 0)
{
this.project.BuildProject.SetProperty(propertyName, propertyValue);
return;
}
// New OM doesn't have a convenient equivalent for setting a property with a particular property group condition.
// So do it ourselves.
MSBuildConstruction.ProjectPropertyGroupElement newGroup = null;
foreach (MSBuildConstruction.ProjectPropertyGroupElement group in this.project.BuildProject.Xml.PropertyGroups)
{
if (String.Equals(group.Condition.Trim(), conditionTrimmed, StringComparison.OrdinalIgnoreCase))
{
newGroup = group;
break;
}
}
if (newGroup == null)
{
newGroup = this.project.BuildProject.Xml.AddPropertyGroup(); // Adds after last existing PG, else at start of project
newGroup.Condition = condition;
}
foreach (MSBuildConstruction.ProjectPropertyElement property in newGroup.PropertiesReversed) // If there's dupes, pick the last one so we win
{
if (String.Equals(property.Name, propertyName, StringComparison.OrdinalIgnoreCase) && property.Condition.Length == 0)
{
property.Value = propertyValue;
return;
}
}
newGroup.AddProperty(propertyName, propertyValue);
}
/// <summary>
/// If flavored, and if the flavor config can be dirty, ask it if it is dirty
/// </summary>
/// <param name="storageType">Project file or user file</param>
/// <returns>0 = not dirty</returns>
internal int IsFlavorDirty(_PersistStorageType storageType)
{
int isDirty = 0;
if(this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment)
{
ErrorHandler.ThrowOnFailure(((IPersistXMLFragment)this.flavoredCfg).IsFragmentDirty((uint)storageType, out isDirty));
}
return isDirty;
}
/// <summary>
/// If flavored, ask the flavor if it wants to provide an XML fragment
/// </summary>
/// <param name="flavor">Guid of the flavor</param>
/// <param name="storageType">Project file or user file</param>
/// <param name="fragment">Fragment that the flavor wants to save</param>
/// <returns>HRESULT</returns>
internal int GetXmlFragment(Guid flavor, _PersistStorageType storageType, out string fragment)
{
fragment = null;
int hr = VSConstants.S_OK;
if(this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment)
{
Guid flavorGuid = flavor;
hr = ((IPersistXMLFragment)this.flavoredCfg).Save(ref flavorGuid, (uint)storageType, out fragment, 1);
}
return hr;
}
#endregion
#region IVsSpecifyPropertyPages
public void GetPages(CAUUID[] pages)
{
this.GetCfgPropertyPages(pages);
}
#endregion
#region IVsSpecifyProjectDesignerPages
/// <summary>
/// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration dependent.
/// </summary>
/// <param name="pages">The pages to return.</param>
/// <returns>VSConstants.S_OK</returns>
public virtual int GetProjectDesignerPages(CAUUID[] pages)
{
this.GetCfgPropertyPages(pages);
return VSConstants.S_OK;
}
#endregion
#region IVsCfg methods
/// <summary>
/// The display name is a two part item
/// first part is the config name, 2nd part is the platform name
/// </summary>
public virtual int get_DisplayName(out string name)
{
name = DisplayName;
return VSConstants.S_OK;
}
private string DisplayName
{
get
{
string name;
string[] platform = new string[1];
uint[] actual = new uint[1];
name = this.configName;
// currently, we only support one platform, so just add it..
IVsCfgProvider provider;
ErrorHandler.ThrowOnFailure(project.GetCfgProvider(out provider));
ErrorHandler.ThrowOnFailure(((IVsCfgProvider2)provider).GetPlatformNames(1, platform, actual));
if(!string.IsNullOrEmpty(platform[0]))
{
name += "|" + platform[0];
}
return name;
}
}
public virtual int get_IsDebugOnly(out int fDebug)
{
fDebug = 0;
if(this.configName == "Debug")
{
fDebug = 1;
}
return VSConstants.S_OK;
}
public virtual int get_IsReleaseOnly(out int fRelease)
{
CCITracing.TraceCall();
fRelease = 0;
if(this.configName == "Release")
{
fRelease = 1;
}
return VSConstants.S_OK;
}
#endregion
#region IVsProjectCfg methods
public virtual int EnumOutputs(out IVsEnumOutputs eo)
{
CCITracing.TraceCall();
eo = null;
return VSConstants.E_NOTIMPL;
}
public virtual int get_BuildableProjectCfg(out IVsBuildableProjectCfg pb)
{
CCITracing.TraceCall();
if(buildableCfg == null)
buildableCfg = new BuildableProjectConfig(this);
pb = buildableCfg;
return VSConstants.S_OK;
}
public virtual int get_CanonicalName(out string name)
{
return ((IVsCfg)this).get_DisplayName(out name);
}
public virtual int get_IsPackaged(out int pkgd)
{
CCITracing.TraceCall();
pkgd = 0;
return VSConstants.S_OK;
}
public virtual int get_IsSpecifyingOutputSupported(out int f)
{
CCITracing.TraceCall();
f = 1;
return VSConstants.S_OK;
}
public virtual int get_Platform(out Guid platform)
{
CCITracing.TraceCall();
platform = Guid.Empty;
return VSConstants.E_NOTIMPL;
}
public virtual int get_ProjectCfgProvider(out IVsProjectCfgProvider p)
{
CCITracing.TraceCall();
p = null;
IVsCfgProvider cfgProvider = null;
this.project.GetCfgProvider(out cfgProvider);
if(cfgProvider != null)
{
p = cfgProvider as IVsProjectCfgProvider;
}
return (null == p) ? VSConstants.E_NOTIMPL : VSConstants.S_OK;
}
public virtual int get_RootURL(out string root)
{
CCITracing.TraceCall();
root = null;
return VSConstants.S_OK;
}
public virtual int get_TargetCodePage(out uint target)
{
CCITracing.TraceCall();
target = (uint)System.Text.Encoding.Default.CodePage;
return VSConstants.S_OK;
}
public virtual int get_UpdateSequenceNumber(ULARGE_INTEGER[] li)
{
if (li == null)
{
throw new ArgumentNullException("li");
}
CCITracing.TraceCall();
li[0] = new ULARGE_INTEGER();
li[0].QuadPart = 0;
return VSConstants.S_OK;
}
public virtual int OpenOutput(string name, out IVsOutput output)
{
CCITracing.TraceCall();
output = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsDebuggableProjectCfg methods
/// <summary>
/// Called by the vs shell to start debugging (managed or unmanaged).
/// Override this method to support other debug engines.
/// </summary>
/// <param name="grfLaunch">A flag that determines the conditions under which to start the debugger. For valid grfLaunch values, see __VSDBGLAUNCHFLAGS</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code</returns>
public virtual int DebugLaunch(uint grfLaunch)
{
CCITracing.TraceCall();
try
{
VsDebugTargetInfo info = new VsDebugTargetInfo();
info.cbSize = (uint)Marshal.SizeOf(info);
info.dlo = Microsoft.VisualStudio.Shell.Interop.DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;
// On first call, reset the cache, following calls will use the cached values
string property = GetConfigurationProperty("StartProgram", true);
if(string.IsNullOrEmpty(property))
{
info.bstrExe = this.project.GetOutputAssembly(this.ConfigName);
}
else
{
info.bstrExe = property;
}
property = GetConfigurationProperty("WorkingDirectory", false);
if(string.IsNullOrEmpty(property))
{
info.bstrCurDir = Path.GetDirectoryName(info.bstrExe);
}
else
{
info.bstrCurDir = property;
}
property = GetConfigurationProperty("CmdArgs", false);
if(!string.IsNullOrEmpty(property))
{
info.bstrArg = property;
}
property = GetConfigurationProperty("RemoteDebugMachine", false);
if(property != null && property.Length > 0)
{
info.bstrRemoteMachine = property;
}
info.fSendStdoutToOutputWindow = 0;
property = GetConfigurationProperty("EnableUnmanagedDebugging", false);
if(property != null && string.Compare(property, "true", StringComparison.OrdinalIgnoreCase) == 0)
{
//Set the unmanged debugger
//TODO change to vsconstant when it is available in VsConstants (guidNativeOnlyEng was the old name, maybe it has got a new name)
info.clsidCustom = new Guid("{3B476D35-A401-11D2-AAD4-00C04F990171}");
}
else
{
//Set the managed debugger
info.clsidCustom = VSConstants.CLSID_ComPlusOnlyDebugEngine;
}
info.grfLaunch = grfLaunch;
VsShellUtilities.LaunchDebugger(this.project.Site, info);
}
catch(Exception e)
{
Trace.WriteLine("Exception : " + e.Message);
return Marshal.GetHRForException(e);
}
return VSConstants.S_OK;
}
/// <summary>
/// Determines whether the debugger can be launched, given the state of the launch flags.
/// </summary>
/// <param name="flags">Flags that determine the conditions under which to launch the debugger.
/// For valid grfLaunch values, see __VSDBGLAUNCHFLAGS or __VSDBGLAUNCHFLAGS2.</param>
/// <param name="fCanLaunch">true if the debugger can be launched, otherwise false</param>
/// <returns>S_OK if the method succeeds, otherwise an error code</returns>
public virtual int QueryDebugLaunch(uint flags, out int fCanLaunch)
{
CCITracing.TraceCall();
string assembly = this.project.GetAssemblyName(this.ConfigName);
fCanLaunch = (assembly != null && assembly.ToUpperInvariant().EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) ? 1 : 0;
if(fCanLaunch == 0)
{
string property = GetConfigurationProperty("StartProgram", true);
fCanLaunch = (property != null && property.Length > 0) ? 1 : 0;
}
return VSConstants.S_OK;
}
#endregion
#region IVsProjectCfg2 Members
public virtual int OpenOutputGroup(string szCanonicalName, out IVsOutputGroup ppIVsOutputGroup)
{
ppIVsOutputGroup = null;
// Search through our list of groups to find the one they are looking forgroupName
foreach(OutputGroup group in OutputGroups)
{
string groupName;
group.get_CanonicalName(out groupName);
if(String.Compare(groupName, szCanonicalName, StringComparison.OrdinalIgnoreCase) == 0)
{
ppIVsOutputGroup = group;
break;
}
}
return (ppIVsOutputGroup != null) ? VSConstants.S_OK : VSConstants.E_FAIL;
}
public virtual int OutputsRequireAppRoot(out int pfRequiresAppRoot)
{
pfRequiresAppRoot = 0;
return VSConstants.E_NOTIMPL;
}
public virtual int get_CfgType(ref Guid iidCfg, out IntPtr ppCfg)
{
// Delegate to the flavored configuration (to enable a flavor to take control)
// Since we can be asked for Configuration we don't support, avoid throwing and return the HRESULT directly
int hr = flavoredCfg.get_CfgType(ref iidCfg, out ppCfg);
return hr;
}
public virtual int get_IsPrivate(out int pfPrivate)
{
pfPrivate = 0;
return VSConstants.S_OK;
}
public virtual int get_OutputGroups(uint celt, IVsOutputGroup[] rgpcfg, uint[] pcActual)
{
// Are they only asking for the number of groups?
if(celt == 0)
{
if((null == pcActual) || (0 == pcActual.Length))
{
throw new ArgumentNullException("pcActual");
}
pcActual[0] = (uint)OutputGroups.Count;
return VSConstants.S_OK;
}
// Check that the array of output groups is not null
if((null == rgpcfg) || (rgpcfg.Length == 0))
{
throw new ArgumentNullException("rgpcfg");
}
// Fill the array with our output groups
uint count = 0;
foreach(OutputGroup group in OutputGroups)
{
if(rgpcfg.Length > count && celt > count && group != null)
{
rgpcfg[count] = group;
++count;
}
}
if(pcActual != null && pcActual.Length > 0)
pcActual[0] = count;
// If the number asked for does not match the number returned, return S_FALSE
return (count == celt) ? VSConstants.S_OK : VSConstants.S_FALSE;
}
public virtual int get_VirtualRoot(out string pbstrVRoot)
{
pbstrVRoot = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsCfgBrowseObject
/// <summary>
/// Maps back to the configuration corresponding to the browse object.
/// </summary>
/// <param name="cfg">The IVsCfg object represented by the browse object</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetCfg(out IVsCfg cfg)
{
cfg = this;
return VSConstants.S_OK;
}
/// <summary>
/// Maps back to the hierarchy or project item object corresponding to the browse object.
/// </summary>
/// <param name="hier">Reference to the hierarchy object.</param>
/// <param name="itemid">Reference to the project item.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid)
{
if(this.project == null || this.project.NodeProperties == null)
{
throw new InvalidOperationException();
}
return this.project.NodeProperties.GetProjectItem(out hier, out itemid);
}
#endregion
#region helper methods
/// <summary>
/// Splits the canonical configuration name into platform and configuration name.
/// </summary>
/// <param name="canonicalName">The canonicalName name.</param>
/// <param name="configName">The name of the configuration.</param>
/// <param name="platformName">The name of the platform.</param>
/// <returns>true if successfull.</returns>
internal static bool TrySplitConfigurationCanonicalName(string canonicalName, out string configName, out string platformName)
{
configName = String.Empty;
platformName = String.Empty;
if(String.IsNullOrEmpty(canonicalName))
{
return false;
}
string[] splittedCanonicalName = canonicalName.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
if(splittedCanonicalName == null || (splittedCanonicalName.Length != 1 && splittedCanonicalName.Length != 2))
{
return false;
}
configName = splittedCanonicalName[0];
if(splittedCanonicalName.Length == 2)
{
platformName = splittedCanonicalName[1];
}
return true;
}
private MSBuildExecution.ProjectPropertyInstance GetMsBuildProperty(string propertyName, bool resetCache)
{
if (resetCache || this.currentConfig == null)
{
// Get properties for current configuration from project file and cache it
this.project.SetConfiguration(this.ConfigName);
this.project.BuildProject.ReevaluateIfNecessary();
// Create a snapshot of the evaluated project in its current state
this.currentConfig = this.project.BuildProject.CreateProjectInstance();
// Restore configuration
project.SetCurrentConfiguration();
}
if (this.currentConfig == null)
throw new Exception("Failed to retrieve properties");
// return property asked for
return this.currentConfig.GetProperty(propertyName);
}
/// <summary>
/// Retrieves the configuration dependent property pages.
/// </summary>
/// <param name="pages">The pages to return.</param>
private void GetCfgPropertyPages(CAUUID[] pages)
{
// We do not check whether the supportsProjectDesigner is set to true on the ProjectNode.
// We rely that the caller knows what to call on us.
if(pages == null)
{
throw new ArgumentNullException("pages");
}
if(pages.Length == 0)
{
throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "pages");
}
// Retrive the list of guids from hierarchy properties.
// Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy
string guidsList = String.Empty;
IVsHierarchy hierarchy = this.project.InteropSafeIVsHierarchy;
object variant = null;
ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList, out variant), new int[] { VSConstants.DISP_E_MEMBERNOTFOUND, VSConstants.E_NOTIMPL });
guidsList = (string)variant;
Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList);
if(guids == null || guids.Length == 0)
{
pages[0] = new CAUUID();
pages[0].cElems = 0;
}
else
{
pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids);
}
}
#endregion
#region IVsProjectFlavorCfg Members
/// <summary>
/// This is called to let the flavored config let go
/// of any reference it may still be holding to the base config
/// </summary>
/// <returns></returns>
int IVsProjectFlavorCfg.Close()
{
// This is used to release the reference the flavored config is holding
// on the base config, but in our scenario these 2 are the same object
// so we have nothing to do here.
return VSConstants.S_OK;
}
/// <summary>
/// Actual implementation of get_CfgType.
/// When not flavored or when the flavor delegate to use
/// we end up creating the requested config if we support it.
/// </summary>
/// <param name="iidCfg">IID representing the type of config object we should create</param>
/// <param name="ppCfg">Config object that the method created</param>
/// <returns>HRESULT</returns>
int IVsProjectFlavorCfg.get_CfgType(ref Guid iidCfg, out IntPtr ppCfg)
{
ppCfg = IntPtr.Zero;
// See if this is an interface we support
if(iidCfg == typeof(IVsDebuggableProjectCfg).GUID)
ppCfg = Marshal.GetComInterfaceForObject(this, typeof(IVsDebuggableProjectCfg));
else if(iidCfg == typeof(IVsBuildableProjectCfg).GUID)
{
IVsBuildableProjectCfg buildableConfig;
this.get_BuildableProjectCfg(out buildableConfig);
ppCfg = Marshal.GetComInterfaceForObject(buildableConfig, typeof(IVsBuildableProjectCfg));
}
// If not supported
if(ppCfg == IntPtr.Zero)
return VSConstants.E_NOINTERFACE;
return VSConstants.S_OK;
}
#endregion
}
//=============================================================================
// NOTE: advises on out of proc build execution to maximize
// future cross-platform targeting capabilities of the VS tools.
[CLSCompliant(false)]
[ComVisible(true)]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Buildable")]
public class BuildableProjectConfig : IVsBuildableProjectCfg
{
#region fields
ProjectConfig config = null;
EventSinkCollection callbacks = new EventSinkCollection();
#endregion
#region ctors
public BuildableProjectConfig(ProjectConfig config)
{
this.config = config;
}
#endregion
#region IVsBuildableProjectCfg methods
public virtual int AdviseBuildStatusCallback(IVsBuildStatusCallback callback, out uint cookie)
{
CCITracing.TraceCall();
cookie = callbacks.Add(callback);
return VSConstants.S_OK;
}
public virtual int get_ProjectCfg(out IVsProjectCfg p)
{
CCITracing.TraceCall();
p = config;
return VSConstants.S_OK;
}
public virtual int QueryStartBuild(uint options, int[] supported, int[] ready)
{
CCITracing.TraceCall();
if(supported != null && supported.Length > 0)
supported[0] = 1;
if(ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStartClean(uint options, int[] supported, int[] ready)
{
CCITracing.TraceCall();
config.PrepareBuild(false);
if(supported != null && supported.Length > 0)
supported[0] = 1;
if(ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStartUpToDateCheck(uint options, int[] supported, int[] ready)
{
CCITracing.TraceCall();
config.PrepareBuild(false);
if(supported != null && supported.Length > 0)
supported[0] = 0; // TODO:
if(ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStatus(out int done)
{
CCITracing.TraceCall();
done = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int StartBuild(IVsOutputWindowPane pane, uint options)
{
CCITracing.TraceCall();
config.PrepareBuild(false);
// Current version of MSBuild wish to be called in an STA
uint flags = VSConstants.VS_BUILDABLEPROJECTCFGOPTS_REBUILD;
// If we are not asked for a rebuild, then we build the default target (by passing null)
this.Build(options, pane, ((options & flags) != 0) ? MsBuildTarget.Rebuild : null);
return VSConstants.S_OK;
}
public virtual int StartClean(IVsOutputWindowPane pane, uint options)
{
CCITracing.TraceCall();
config.PrepareBuild(true);
// Current version of MSBuild wish to be called in an STA
this.Build(options, pane, MsBuildTarget.Clean);
return VSConstants.S_OK;
}
public virtual int StartUpToDateCheck(IVsOutputWindowPane pane, uint options)
{
CCITracing.TraceCall();
return VSConstants.E_NOTIMPL;
}
public virtual int Stop(int fsync)
{
CCITracing.TraceCall();
return VSConstants.S_OK;
}
public virtual int UnadviseBuildStatusCallback(uint cookie)
{
CCITracing.TraceCall();
callbacks.RemoveAt(cookie);
return VSConstants.S_OK;
}
public virtual int Wait(uint ms, int fTickWhenMessageQNotEmpty)
{
CCITracing.TraceCall();
return VSConstants.E_NOTIMPL;
}
#endregion
#region helpers
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private bool NotifyBuildBegin()
{
int shouldContinue = 1;
foreach (IVsBuildStatusCallback cb in callbacks)
{
try
{
ErrorHandler.ThrowOnFailure(cb.BuildBegin(ref shouldContinue));
if (shouldContinue == 0)
{
return false;
}
}
catch (Exception e)
{
// If those who ask for status have bugs in their code it should not prevent the build/notification from happening
Debug.Fail(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.BuildEventError, CultureInfo.CurrentUICulture), e.Message));
}
}
return true;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void NotifyBuildEnd(MSBuildResult result, string buildTarget)
{
int success = ((result == MSBuildResult.Successful) ? 1 : 0);
foreach (IVsBuildStatusCallback cb in callbacks)
{
try
{
ErrorHandler.ThrowOnFailure(cb.BuildEnd(success));
}
catch (Exception e)
{
// If those who ask for status have bugs in their code it should not prevent the build/notification from happening
Debug.Fail(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.BuildEventError, CultureInfo.CurrentUICulture), e.Message));
}
finally
{
// We want to refresh the references if we are building with the Build or Rebuild target or if the project was opened for browsing only.
bool shouldRepaintReferences = (buildTarget == null || buildTarget == MsBuildTarget.Build || buildTarget == MsBuildTarget.Rebuild);
// Now repaint references if that is needed.
// We hardly rely here on the fact the ResolveAssemblyReferences target has been run as part of the build.
// One scenario to think at is when an assembly reference is renamed on disk thus becomming unresolvable,
// but msbuild can actually resolve it.
// Another one if the project was opened only for browsing and now the user chooses to build or rebuild.
if (shouldRepaintReferences && (result == MSBuildResult.Successful))
{
this.RefreshReferences();
}
}
}
}
private void Build(uint options, IVsOutputWindowPane output, string target)
{
if (!this.NotifyBuildBegin())
{
return;
}
try
{
config.ProjectMgr.BuildAsync(options, this.config.ConfigName, output, target, (result, buildTarget) => this.NotifyBuildEnd(result, buildTarget));
}
catch(Exception e)
{
Trace.WriteLine("Exception : " + e.Message);
ErrorHandler.ThrowOnFailure(output.OutputStringThreadSafe("Unhandled Exception:" + e.Message + "\n"));
this.NotifyBuildEnd(MSBuildResult.Failed, target);
throw;
}
finally
{
ErrorHandler.ThrowOnFailure(output.FlushToTaskList());
}
}
/// <summary>
/// Refreshes references and redraws them correctly.
/// </summary>
private void RefreshReferences()
{
// Refresh the reference container node for assemblies that could be resolved.
IReferenceContainer referenceContainer = this.config.ProjectMgr.GetReferenceContainer();
foreach(ReferenceNode referenceNode in referenceContainer.EnumReferences())
{
referenceNode.RefreshReference();
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.MarkdigEngine.Extensions
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Markdig.Helpers;
using Markdig.Parsers;
public static class ExtensionsHelper
{
public static readonly Regex HtmlEscapeWithEncode = new Regex(@"&", RegexOptions.Compiled);
public static readonly Regex HtmlEscapeWithoutEncode = new Regex(@"&(?!#?\w+;)", RegexOptions.Compiled);
public static readonly Regex HtmlUnescape = new Regex(@"&([#\w]+);", RegexOptions.Compiled);
public static char SkipSpaces(ref StringSlice slice)
{
var c = slice.CurrentChar;
while (c.IsSpaceOrTab())
{
c = slice.NextChar();
}
return c;
}
public static string Escape(string html, bool encode = false)
{
return html
.ReplaceRegex(encode ? HtmlEscapeWithEncode : HtmlEscapeWithoutEncode, "&")
.Replace("<", "<")
.Replace(">", ">")
.Replace("\"", """)
.Replace("'", "'");
}
public static string Unescape(string html)
{
return HtmlUnescape.Replace(html, match =>
{
var n = match.Groups[1].Value;
n = n.ToLower();
if (n == "amp") return "&";
if (n == "colon") return ":";
if (n[0] == '#')
{
return n[1] == 'x'
? ((char)Convert.ToInt32(n.Substring(2), 16)).ToString()
: ((char)Convert.ToInt32(n.Substring(1))).ToString();
}
return string.Empty;
});
}
public static string ReplaceRegex(this string input, Regex pattern, string replacement)
{
return pattern.Replace(input, replacement);
}
public static string NormalizePath(string path)
{
if (string.IsNullOrEmpty(path))
{
return path;
}
return Path.GetFullPath(path).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
public static bool MatchStart(ref StringSlice slice, string startString, bool isCaseSensitive = true)
{
var c = slice.CurrentChar;
var index = 0;
while (c != '\0' && index < startString.Length && CharEqual(c, startString[index], isCaseSensitive))
{
c = slice.NextChar();
index++;
}
return index == startString.Length;
}
public static void ResetLineIndent(BlockProcessor processor)
{
processor.GoToColumn(processor.ColumnBeforeIndent);
}
public static bool MatchStart(BlockProcessor processor, string startString, bool isCaseSensitive = true)
{
var c = processor.CurrentChar;
var index = 0;
while (c != '\0' && index < startString.Length && CharEqual(c, startString[index], isCaseSensitive))
{
c = processor.NextChar();
index++;
}
return index == startString.Length;
}
public static bool MatchLink(ref StringSlice slice, ref string title, ref string path)
{
if (MatchTitle(ref slice, ref title) && MatchPath(ref slice, ref path))
{
return true;
}
return false;
}
public static bool MatchInclusionEnd(ref StringSlice slice)
{
if (slice.CurrentChar != ']')
{
return false;
}
slice.NextChar();
return true;
}
public static void SkipWhitespace(ref StringSlice slice)
{
var c = slice.CurrentChar;
while (c != '\0' && c.IsWhitespace())
{
c = slice.NextChar();
}
}
public static string TryGetStringBeforeChars(IEnumerable<char> chars, ref StringSlice slice, bool breakOnWhitespace = false)
{
StringSlice savedSlice = slice;
var c = slice.CurrentChar;
var hasEscape = false;
var builder = StringBuilderCache.Local();
while (c != '\0' && (!breakOnWhitespace || !c.IsWhitespace()) && (hasEscape || !chars.Contains(c)))
{
if (c == '\\' && !hasEscape)
{
hasEscape = true;
}
else
{
builder.Append(c);
hasEscape = false;
}
c = slice.NextChar();
}
if (c == '\0' && !chars.Contains('\0'))
{
slice = savedSlice;
builder.Length = 0;
return null;
}
else
{
var result = builder.ToString().Trim();
builder.Length = 0;
return result;
}
}
#region private methods
private static string GetAbsolutePathWithTildeCore(string basePath, string tildePath)
{
var index = 1;
var ch = tildePath[index];
while (ch == '/' || ch == '\\')
{
index++;
ch = tildePath[index];
}
if (index == tildePath.Length)
{
return basePath;
}
var pathWithoutTilde = tildePath.Substring(index);
return NormalizePath(Path.Combine(basePath, pathWithoutTilde));
}
private static bool CharEqual(char ch1, char ch2, bool isCaseSensitive)
{
return isCaseSensitive ? ch1 == ch2 : Char.ToLower(ch1) == Char.ToLower(ch2);
}
private static bool MatchTitle(ref StringSlice slice, ref string title)
{
while (slice.CurrentChar == ' ')
{
slice.NextChar();
}
if (slice.CurrentChar != '[')
{
return false;
}
var c = slice.NextChar();
var str = StringBuilderCache.Local();
var hasEscape = false;
while (c != '\0' && (c != ']' || hasEscape))
{
if (c == '\\' && !hasEscape)
{
hasEscape = true;
}
else
{
str.Append(c);
hasEscape = false;
}
c = slice.NextChar();
}
if (c == ']')
{
title = str.ToString().Trim();
slice.NextChar();
return true;
}
return false;
}
public static bool IsEscaped(StringSlice slice)
{
return slice.PeekCharExtra(-1) == '\\';
}
private static bool MatchPath(ref StringSlice slice, ref string path)
{
if (slice.CurrentChar != '(')
{
return false;
}
slice.NextChar();
SkipWhitespace(ref slice);
string includedFilePath;
if (slice.CurrentChar == '<')
{
includedFilePath = TryGetStringBeforeChars(new char[] { ')', '>' }, ref slice, breakOnWhitespace: true);
}
else
{
includedFilePath = TryGetStringBeforeChars(new char[] { ')' }, ref slice, breakOnWhitespace: true);
};
if (includedFilePath == null)
{
return false;
}
if (includedFilePath.Length >= 1 && includedFilePath.First() == '<' && slice.CurrentChar == '>')
{
includedFilePath = includedFilePath.Substring(1, includedFilePath.Length - 1).Trim();
}
if (slice.CurrentChar == ')')
{
path = includedFilePath;
slice.NextChar();
return true;
}
else
{
var title = TryGetStringBeforeChars(new char[] { ')' }, ref slice, breakOnWhitespace: false);
if (title == null)
{
return false;
}
else
{
if (title.Length >= 2 && title.First() == '\'' && title.Last() == '\'')
{
title = title.Substring(1, title.Length - 2).Trim();
}
else if (title.Length >= 2 && title.First() == '\"' && title.Last() == '\"')
{
title = title.Substring(1, title.Length - 2).Trim();
}
path = includedFilePath;
slice.NextChar();
return true;
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using Aga.Controls.Tree;
using Duality.Plugins.Tilemaps;
using Duality.Editor.UndoRedoActions;
using Duality.Editor.Plugins.Tilemaps;
using Duality.Editor.Plugins.Tilemaps.Properties;
using Duality.Editor.Plugins.Tilemaps.UndoRedoActions;
namespace Duality.Editor.Plugins.Tilemaps.TilesetEditorModes
{
/// <summary>
/// Allows to edit a Tileset's AutoTile layers, which define how similar adjacent tiles join together.
/// </summary>
public class AutoTileTilesetEditorMode : TilesetEditorMode, IHelpProvider
{
/// <summary>
/// Describes how the current user drawing operation will affect existing AutoTile data.
/// </summary>
private enum AutoTileDrawMode
{
Add,
Remove,
}
private class AutoTileInputNode : TilesetEditorLayerNode
{
private TilesetAutoTileInput autoTile = null;
public override string Title
{
get { return this.autoTile.Name; }
}
public override string Description
{
get { return this.autoTile.Id; }
}
public TilesetAutoTileInput AutoTileInput
{
get { return this.autoTile; }
}
public AutoTileInputNode(TilesetAutoTileInput autoTile) : base()
{
this.autoTile = autoTile;
this.Image = Properties.TilemapsResCache.IconTilesetAutoTileLayer;
}
public void Invalidate()
{
this.NotifyModel();
}
}
private TilesetAutoTileInput currentAutoTile = null;
private TreeModel treeModel = new TreeModel();
private TileConnection hoveredArea = TileConnection.None;
private bool isUserDrawing = false;
private bool isBaseTileDraw = false;
private bool isExternalDraw = false;
private AutoTileDrawMode userDrawMode = AutoTileDrawMode.Add;
public override string Id
{
get { return "AutoTileTilesetEditorMode"; }
}
public override string Name
{
get { return TilemapsRes.TilesetEditorMode_AutoTile_Name; }
}
public override Image Icon
{
get { return TilemapsResCache.IconTilesetAutoTile; }
}
public override int SortOrder
{
get { return -30; }
}
public override ITreeModel LayerModel
{
get { return this.treeModel; }
}
public override LayerEditingCaps AllowLayerEditing
{
get { return LayerEditingCaps.All; }
}
private void UpdateTreeModel()
{
Tileset tileset = this.SelectedTileset.Res;
// If the tileset is unavailable, or none is selected, there are no nodes
if (tileset == null)
{
this.treeModel.Nodes.Clear();
return;
}
// Remove nodes that no longer have an equivalent in the Tileset
foreach (AutoTileInputNode node in this.treeModel.Nodes.ToArray())
{
if (!tileset.AutoTileConfig.Contains(node.AutoTileInput))
{
this.treeModel.Nodes.Remove(node);
}
}
// Notify the model of changes for the existing nodes to account for name and id changes.
// This is only okay because we have so few notes in total. Don't do this for actual data.
foreach (AutoTileInputNode node in this.treeModel.Nodes)
{
node.Invalidate();
}
// Add nodes that don't have a corresponding tree model node yet
foreach (TilesetAutoTileInput autoTile in tileset.AutoTileConfig)
{
if (!this.treeModel.Nodes.Any(node => (node as AutoTileInputNode).AutoTileInput == autoTile))
{
this.treeModel.Nodes.Add(new AutoTileInputNode(autoTile));
}
}
}
/// <inheritdoc />
public override void AddLayer()
{
base.AddLayer();
Tileset tileset = this.SelectedTileset.Res;
if (tileset == null) return;
// Decide upon an id for our new layer
string autoTileId = TilesetAutoTileInput.DefaultId + (tileset.AutoTileConfig.Count).ToString();
string autoTileName = TilesetAutoTileInput.DefaultName;
// Create a new AutoTile using an UndoRedo action
TilesetAutoTileInput newAutoTile = new TilesetAutoTileInput
{
Id = autoTileId,
Name = autoTileName
};
UndoRedoManager.Do(new AddTilesetConfigLayerAction<TilesetAutoTileInput>(
tileset,
TilemapsReflectionInfo.Property_Tileset_AutoTileConfig,
newAutoTile));
// Select the newly created AutoTile
AutoTileInputNode modelNode = this.treeModel
.Nodes
.OfType<AutoTileInputNode>()
.FirstOrDefault(n => n.AutoTileInput == newAutoTile);
this.SelectLayer(modelNode);
}
/// <inheritdoc />
public override void RemoveLayer()
{
base.RemoveLayer();
Tileset tileset = this.SelectedTileset.Res;
TilesetAutoTileInput autoTile = this.currentAutoTile;
if (tileset == null) return;
if (autoTile == null) return;
UndoRedoManager.Do(new RemoveTilesetConfigLayerAction<TilesetAutoTileInput>(
tileset,
TilemapsReflectionInfo.Property_Tileset_AutoTileConfig,
autoTile));
}
protected override void OnEnter()
{
this.UpdateTreeModel();
this.TilesetView.PaintTiles += this.TilesetView_PaintTiles;
this.TilesetView.MouseMove += this.TilesetView_MouseMove;
this.TilesetView.MouseDown += this.TilesetView_MouseDown;
this.TilesetView.MouseUp += this.TilesetView_MouseUp;
this.TilesetView.KeyDown += this.TilesetView_KeyDown;
this.TilesetView.KeyUp += this.TilesetView_KeyUp;
}
protected override void OnLeave()
{
base.OnLeave();
this.TilesetView.PaintTiles -= this.TilesetView_PaintTiles;
this.TilesetView.MouseMove -= this.TilesetView_MouseMove;
this.TilesetView.MouseDown -= this.TilesetView_MouseDown;
this.TilesetView.MouseUp -= this.TilesetView_MouseUp;
this.TilesetView.KeyDown -= this.TilesetView_KeyDown;
this.TilesetView.KeyUp -= this.TilesetView_KeyUp;
}
protected override void OnTilesetSelectionChanged(TilesetSelectionChangedEventArgs args)
{
this.currentAutoTile = null;
this.UpdateTreeModel();
}
protected override void OnTilesetModified(ObjectPropertyChangedEventArgs args)
{
Tileset tileset = this.SelectedTileset.Res;
// If an AutoTile was modified, emit an editor-wide change event for
// the Tileset as well, so the editor knows it will need to save this Resource.
if (tileset != null && args.HasAnyObject(tileset.AutoTileConfig))
{
DualityEditorApp.NotifyObjPropChanged(
this,
new ObjectSelection(tileset),
TilemapsReflectionInfo.Property_Tileset_AutoTileConfig);
}
this.UpdateTreeModel();
}
protected override void OnLayerSelectionChanged(LayerSelectionChangedEventArgs args)
{
base.OnLayerSelectionChanged(args);
Tileset tileset = this.SelectedTileset.Res;
AutoTileInputNode selectedNode = args.SelectedNodeTag as AutoTileInputNode;
// Update global editor selection, so an Object Inspector can pick up the AutoTile for editing
if (selectedNode != null)
{
this.currentAutoTile = selectedNode.AutoTileInput;
DualityEditorApp.Select(this, new ObjectSelection(new object[] { selectedNode.AutoTileInput }));
}
else
{
this.currentAutoTile = null;
DualityEditorApp.Deselect(this, obj => obj is TilesetAutoTileInput);
}
this.TilesetView.Invalidate();
}
private void TilesetView_PaintTiles(object sender, TilesetViewPaintTilesEventArgs e)
{
Color highlightColor = Color.FromArgb(255, 255, 255);
Color baseTileDrawColor = Color.FromArgb(255, 192, 128);
Color externalDrawColor = Color.FromArgb(128, 192, 255);
Color nonConnectedColor = Color.FromArgb(128, 0, 0, 0);
Brush brushNonConnected = new SolidBrush(nonConnectedColor);
TilesetAutoTileInput autoTile = this.currentAutoTile;
// Early-out if there is nothing we can edit right now
if (autoTile == null)
return;
// If we're in a special draw mode, switch highlight colors to indicate this.
if (this.isExternalDraw)
highlightColor = externalDrawColor;
else if (this.isBaseTileDraw)
highlightColor = baseTileDrawColor;
// Set up shared working data
TilesetAutoTileItem[] tileInput = autoTile.TileInput.Data;
TilesetViewPaintTileData hoveredData = default(TilesetViewPaintTileData);
TilesetAutoTileItem hoveredItem = default(TilesetAutoTileItem);
GraphicsPath connectedOutlines = new GraphicsPath();
GraphicsPath connectedRegion = new GraphicsPath();
// Draw all the tiles that we're supposed to paint
for (int i = 0; i < e.PaintedTiles.Count; i++)
{
TilesetViewPaintTileData paintData = e.PaintedTiles[i];
// Prepare some data we'll need for drawing the per-tile info overlay
bool tileHovered = this.TilesetView.HoveredTileIndex == paintData.TileIndex;
bool isBaseTile = autoTile.BaseTileIndex == paintData.TileIndex;
TilesetAutoTileItem item = (autoTile.TileInput.Count > paintData.TileIndex) ?
tileInput[paintData.TileIndex] :
default(TilesetAutoTileItem);
// Remember hovered item data for later (post-overlay)
if (tileHovered)
{
hoveredData = paintData;
hoveredItem = item;
}
// Accumulate a shared region for displaying connectivity, as well as a path of all their outlines
if (item.IsAutoTile)
{
Rectangle centerRect = GetConnectivityRegionRect(TileConnection.None, paintData.ViewRect);
connectedRegion.AddRectangle(centerRect);
DrawConnectivityRegion(connectedRegion, item.Neighbours, paintData.ViewRect);
DrawConnectivityOutlines(connectedOutlines, item.Neighbours, paintData.ViewRect);
}
else if (item.ConnectsToAutoTile)
{
connectedRegion.AddRectangle(paintData.ViewRect);
}
// Highlight base tile and external connecting tiles
if (isBaseTile)
DrawTileHighlight(e.Graphics, paintData.ViewRect, baseTileDrawColor);
else if (!item.IsAutoTile && item.ConnectsToAutoTile)
DrawTileHighlight(e.Graphics, paintData.ViewRect, externalDrawColor);
}
// Fill all non-connected regions with the overlay brush
Region surroundingRegion = new Region();
surroundingRegion.MakeInfinite();
surroundingRegion.Exclude(connectedRegion);
e.Graphics.IntersectClip(surroundingRegion);
e.Graphics.FillRectangle(brushNonConnected, this.TilesetView.ClientRectangle);
e.Graphics.ResetClip();
// Draw connected region outlines
e.Graphics.DrawPath(Pens.White, connectedOutlines);
// Draw a tile-based hover indicator
if (!hoveredData.ViewRect.IsEmpty && !this.isBaseTileDraw && !this.isExternalDraw)
DrawHoverIndicator(e.Graphics, hoveredData.ViewRect, 64, highlightColor);
// Draw a hover indicator for a specific hovered region
if (!hoveredData.ViewRect.IsEmpty)
{
if (!this.isBaseTileDraw && !this.isExternalDraw)
DrawHoverIndicator(e.Graphics, GetConnectivityRegionRect(this.hoveredArea, hoveredData.ViewRect), 255, highlightColor);
else
DrawHoverIndicator(e.Graphics, hoveredData.ViewRect, 255, highlightColor);
}
}
private void TilesetView_MouseMove(object sender, MouseEventArgs e)
{
Size tileSize = this.TilesetView.DisplayedTileSize;
Point tilePos = this.TilesetView.GetTileIndexLocation(this.TilesetView.HoveredTileIndex);
Point posOnTile = new Point(e.X - tilePos.X, e.Y - tilePos.Y);
Size centerSize = new Size(tileSize.Width / 2, tileSize.Height / 2);
// Determine the hovered tile hotspot for user interaction
TileConnection lastHoveredArea = this.hoveredArea;
if (posOnTile.X > (tileSize.Width - centerSize.Width) / 2 &&
posOnTile.Y > (tileSize.Height - centerSize.Height) / 2 &&
posOnTile.X < (tileSize.Width + centerSize.Width) / 2 &&
posOnTile.Y < (tileSize.Height + centerSize.Height) / 2)
{
this.hoveredArea = TileConnection.None;
}
else
{
float angle = MathF.Angle(tileSize.Width / 2, tileSize.Height / 2, posOnTile.X, posOnTile.Y);
float threshold = MathF.DegToRad(22.5f);
if (MathF.CircularDist(angle, MathF.DegToRad(315.0f)) <= threshold) this.hoveredArea = TileConnection.TopLeft;
else if (MathF.CircularDist(angle, MathF.DegToRad( 0.0f)) <= threshold) this.hoveredArea = TileConnection.Top;
else if (MathF.CircularDist(angle, MathF.DegToRad( 45.0f)) <= threshold) this.hoveredArea = TileConnection.TopRight;
else if (MathF.CircularDist(angle, MathF.DegToRad(270.0f)) <= threshold) this.hoveredArea = TileConnection.Left;
else if (MathF.CircularDist(angle, MathF.DegToRad( 90.0f)) <= threshold) this.hoveredArea = TileConnection.Right;
else if (MathF.CircularDist(angle, MathF.DegToRad(225.0f)) <= threshold) this.hoveredArea = TileConnection.BottomLeft;
else if (MathF.CircularDist(angle, MathF.DegToRad(180.0f)) <= threshold) this.hoveredArea = TileConnection.Bottom;
else this.hoveredArea = TileConnection.BottomRight;
}
// Update action state
TilesetAutoTileInput autoTile = this.currentAutoTile;
if (autoTile != null)
{
this.isBaseTileDraw =
autoTile.BaseTileIndex == -1 ||
autoTile.BaseTileIndex == this.TilesetView.HoveredTileIndex;
}
this.UpdateExternalDrawMode();
// If the user is in the process of setting or clearing bits, perform the drawing operation
if (this.isUserDrawing)
this.PerformUserDrawAction();
if (lastHoveredArea != this.hoveredArea)
this.TilesetView.InvalidateTile(this.TilesetView.HoveredTileIndex, 0);
}
private void TilesetView_MouseUp(object sender, MouseEventArgs e)
{
this.isUserDrawing = false;
this.TilesetView.InvalidateTile(this.TilesetView.HoveredTileIndex, 0);
}
private void TilesetView_MouseDown(object sender, MouseEventArgs e)
{
Tileset tileset = this.SelectedTileset.Res;
if (tileset == null) return;
TilesetAutoTileInput autoTile = this.currentAutoTile;
if (autoTile == null) return;
int tileIndex = this.TilesetView.HoveredTileIndex;
if (tileIndex < 0 || tileIndex > tileset.TileCount) return;
// Update modifier key based drawing state
this.UpdateExternalDrawMode();
// Draw operation on left click
if (e.Button == MouseButtons.Left)
{
this.isUserDrawing = true;
this.userDrawMode = AutoTileDrawMode.Add;
}
// Clear operation on right click
else if (e.Button == MouseButtons.Right)
{
this.isUserDrawing = true;
this.userDrawMode = AutoTileDrawMode.Remove;
}
// Perform the drawing operation
this.PerformUserDrawAction();
this.TilesetView.InvalidateTile(tileIndex, 0);
}
private void TilesetView_KeyDown(object sender, KeyEventArgs e)
{
this.UpdateExternalDrawMode();
}
private void TilesetView_KeyUp(object sender, KeyEventArgs e)
{
this.UpdateExternalDrawMode();
}
private void UpdateExternalDrawMode()
{
TilesetAutoTileInput autoTile = this.currentAutoTile;
if (autoTile == null) return;
bool lastExternalDraw = this.isExternalDraw;
int hoveredTile = this.TilesetView.HoveredTileIndex;
TilesetAutoTileItem item = (hoveredTile >= 0 && hoveredTile < autoTile.TileInput.Count) ?
autoTile.TileInput[hoveredTile] :
default(TilesetAutoTileItem);
this.isExternalDraw = Control.ModifierKeys.HasFlag(Keys.Shift) || item.ConnectsToAutoTile;
if (lastExternalDraw != this.isExternalDraw)
this.TilesetView.InvalidateTile(this.TilesetView.HoveredTileIndex, 0);
}
private void PerformUserDrawAction()
{
Tileset tileset = this.SelectedTileset.Res;
if (tileset == null) return;
TilesetAutoTileInput autoTile = this.currentAutoTile;
if (autoTile == null) return;
int tileIndex = this.TilesetView.HoveredTileIndex;
if (tileIndex < 0 || tileIndex > tileset.TileCount) return;
// Determine data before the operation, and set up data for afterwards
bool lastIsBaseTile = autoTile.BaseTileIndex == tileIndex;
bool newIsBaseTile = lastIsBaseTile;
TilesetAutoTileItem lastInput = (autoTile.TileInput.Count > tileIndex) ?
autoTile.TileInput[tileIndex] :
default(TilesetAutoTileItem);
TilesetAutoTileItem newInput = lastInput;
// Determine how data is modified due to our user operation
if (this.userDrawMode == AutoTileDrawMode.Add)
{
if (this.isExternalDraw)
{
newInput.Neighbours = TileConnection.None;
newInput.ConnectsToAutoTile = true;
newInput.IsAutoTile = false;
newIsBaseTile = false;
}
else if (this.isBaseTileDraw)
{
newInput.Neighbours = TileConnection.All;
newInput.IsAutoTile = true;
newInput.ConnectsToAutoTile = false;
newIsBaseTile = true;
}
else
{
newInput.Neighbours |= this.hoveredArea;
newInput.IsAutoTile = true;
newInput.ConnectsToAutoTile = false;
}
}
else if (this.userDrawMode == AutoTileDrawMode.Remove)
{
if (this.isExternalDraw || this.isBaseTileDraw || this.hoveredArea == TileConnection.None)
{
newInput.Neighbours = TileConnection.None;
newInput.ConnectsToAutoTile = false;
newInput.IsAutoTile = false;
newIsBaseTile = false;
}
else
{
newInput.Neighbours &= ~this.hoveredArea;
newInput.IsAutoTile = (newInput.Neighbours != TileConnection.None);
}
}
// Apply the new, modified data to the actual data using an UndoRedo operation
if (newIsBaseTile != lastIsBaseTile)
{
UndoRedoManager.Do(new EditPropertyAction(
null,
TilemapsReflectionInfo.Property_TilesetAutoTileInput_BaseTile,
new object[] { autoTile },
new object[] { newIsBaseTile ? tileIndex : -1 }));
}
if (!object.Equals(lastInput, newInput))
{
UndoRedoManager.Do(new EditTilesetAutoTileItemAction(
tileset,
autoTile,
tileIndex,
newInput));
}
}
HelpInfo IHelpProvider.ProvideHoverHelp(Point localPos, ref bool captured)
{
Point globalPos = this.TilesetEditor.PointToScreen(localPos);
Point viewPos = this.TilesetView.PointToClient(globalPos);
if (this.TilesetView.ClientRectangle.Contains(viewPos))
{
return HelpInfo.FromText(
TilemapsRes.TilesetEditorMode_AutoTile_Name,
TilemapsRes.TilesetEditorMode_AutoTile_ViewDesc);
}
return null;
}
private static void DrawTileHighlight(Graphics graphics, Rectangle rect, Color color)
{
rect.Width -= 1;
rect.Height -= 1;
graphics.DrawRectangle(new Pen(Color.FromArgb(255, color)), rect);
rect.Inflate(-1, -1);
graphics.DrawRectangle(new Pen(Color.FromArgb(128, color)), rect);
rect.Inflate(-1, -1);
graphics.DrawRectangle(new Pen(Color.FromArgb(64, color)), rect);
}
private static void DrawHoverIndicator(Graphics graphics, Rectangle rect, int alpha, Color color)
{
rect.Width -= 1;
rect.Height -= 1;
graphics.DrawRectangle(new Pen(Color.FromArgb(alpha, Color.Black)), rect);
rect.Inflate(-1, -1);
graphics.DrawRectangle(new Pen(Color.FromArgb(alpha, color)), rect);
rect.Inflate(-1, -1);
graphics.DrawRectangle(new Pen(Color.FromArgb(alpha, Color.Black)), rect);
}
private static void DrawConnectivityOutlines(GraphicsPath path, TileConnection connectivity, Rectangle baseRect)
{
if (connectivity == TileConnection.All) return;
Rectangle fullRect = baseRect;
fullRect.Width -= 1;
fullRect.Height -= 1;
Rectangle centerRect = GetConnectivityRegionRect(TileConnection.None, baseRect);
centerRect.Width -= 1;
centerRect.Height -= 1;
// Add lines for the 4-neighbourhood that is not connected
if (!connectivity.HasFlag(TileConnection.Top))
{
path.AddLine(centerRect.Left, centerRect.Top, centerRect.Right, centerRect.Top);
path.StartFigure();
}
if (!connectivity.HasFlag(TileConnection.Bottom))
{
path.AddLine(centerRect.Left, centerRect.Bottom, centerRect.Right, centerRect.Bottom);
path.StartFigure();
}
if (!connectivity.HasFlag(TileConnection.Left))
{
path.AddLine(centerRect.Left, centerRect.Top, centerRect.Left, centerRect.Bottom);
path.StartFigure();
}
if (!connectivity.HasFlag(TileConnection.Right))
{
path.AddLine(centerRect.Right, centerRect.Top, centerRect.Right, centerRect.Bottom);
path.StartFigure();
}
// Add lines for connectivity borders between the four corners and the main area
if (connectivity.HasFlag(TileConnection.TopLeft) && (connectivity.HasFlag(TileConnection.Top) != connectivity.HasFlag(TileConnection.Left)))
{
path.AddLine(fullRect.Left, fullRect.Top, centerRect.Left, centerRect.Top);
path.StartFigure();
}
else
{
if (connectivity.HasFlag(TileConnection.TopLeft) != connectivity.HasFlag(TileConnection.Top))
{
path.AddLine(centerRect.Left, centerRect.Top, centerRect.Left, fullRect.Top);
path.StartFigure();
}
if (connectivity.HasFlag(TileConnection.TopLeft) != connectivity.HasFlag(TileConnection.Left))
{
path.AddLine(centerRect.Left, centerRect.Top, fullRect.Left, centerRect.Top);
path.StartFigure();
}
}
if (connectivity.HasFlag(TileConnection.TopRight) && (connectivity.HasFlag(TileConnection.Top) != connectivity.HasFlag(TileConnection.Right)))
{
path.AddLine(fullRect.Right, fullRect.Top, centerRect.Right, centerRect.Top);
path.StartFigure();
}
else
{
if (connectivity.HasFlag(TileConnection.TopRight) != connectivity.HasFlag(TileConnection.Top))
{
path.AddLine(centerRect.Right, centerRect.Top, centerRect.Right, fullRect.Top);
path.StartFigure();
}
if (connectivity.HasFlag(TileConnection.TopRight) != connectivity.HasFlag(TileConnection.Right))
{
path.AddLine(centerRect.Right, centerRect.Top, fullRect.Right, centerRect.Top);
path.StartFigure();
}
}
if (connectivity.HasFlag(TileConnection.BottomLeft) && (connectivity.HasFlag(TileConnection.Bottom) != connectivity.HasFlag(TileConnection.Left)))
{
path.AddLine(fullRect.Left, fullRect.Bottom, centerRect.Left, centerRect.Bottom);
path.StartFigure();
}
else
{
if (connectivity.HasFlag(TileConnection.BottomLeft) != connectivity.HasFlag(TileConnection.Bottom))
{
path.AddLine(centerRect.Left, centerRect.Bottom, centerRect.Left, fullRect.Bottom);
path.StartFigure();
}
if (connectivity.HasFlag(TileConnection.BottomLeft) != connectivity.HasFlag(TileConnection.Left))
{
path.AddLine(centerRect.Left, centerRect.Bottom, fullRect.Left, centerRect.Bottom);
path.StartFigure();
}
}
if (connectivity.HasFlag(TileConnection.BottomRight) && (connectivity.HasFlag(TileConnection.Bottom) != connectivity.HasFlag(TileConnection.Right)))
{
path.AddLine(fullRect.Right, fullRect.Bottom, centerRect.Right, centerRect.Bottom);
path.StartFigure();
}
else
{
if (connectivity.HasFlag(TileConnection.BottomRight) != connectivity.HasFlag(TileConnection.Bottom))
{
path.AddLine(centerRect.Right, centerRect.Bottom, centerRect.Right, fullRect.Bottom);
path.StartFigure();
}
if (connectivity.HasFlag(TileConnection.BottomRight) != connectivity.HasFlag(TileConnection.Right))
{
path.AddLine(centerRect.Right, centerRect.Bottom, fullRect.Right, centerRect.Bottom);
path.StartFigure();
}
}
}
private static void DrawConnectivityRegion(GraphicsPath path, TileConnection connectivity, Rectangle baseRect)
{
if (connectivity == TileConnection.None) return;
Rectangle fullRect = baseRect;
Rectangle centerRect = GetConnectivityRegionRect(TileConnection.None, baseRect);
// Add rects for the 4-neighbourhood that is connected
if (connectivity.HasFlag(TileConnection.Top))
path.AddRectangle(new Rectangle(centerRect.Left, fullRect.Top, centerRect.Width, centerRect.Top - fullRect.Top));
if (connectivity.HasFlag(TileConnection.Bottom))
path.AddRectangle(new Rectangle(centerRect.Left, centerRect.Bottom, centerRect.Width, fullRect.Bottom - centerRect.Bottom));
if (connectivity.HasFlag(TileConnection.Left))
path.AddRectangle(new Rectangle(fullRect.Left, centerRect.Top, centerRect.Left - fullRect.Left, centerRect.Height));
if (connectivity.HasFlag(TileConnection.Right))
path.AddRectangle(new Rectangle(centerRect.Right, centerRect.Top, fullRect.Right - centerRect.Right, centerRect.Height));
// Add rects for the corners of the connected 8-neighbourhood
if (connectivity.HasFlag(TileConnection.TopLeft))
{
if (connectivity.HasFlag(TileConnection.Top) && !connectivity.HasFlag(TileConnection.Left))
{
path.AddPolygon(new Point[]
{
new Point(fullRect.Left, fullRect.Top),
new Point(centerRect.Left, fullRect.Top),
new Point(centerRect.Left, centerRect.Top),
});
}
else if (!connectivity.HasFlag(TileConnection.Top) && connectivity.HasFlag(TileConnection.Left))
{
path.AddPolygon(new Point[]
{
new Point(fullRect.Left, fullRect.Top),
new Point(fullRect.Left, centerRect.Top),
new Point(centerRect.Left, centerRect.Top),
});
}
else
{
path.AddRectangle(new Rectangle(fullRect.Left, fullRect.Top, centerRect.Left - fullRect.Left, centerRect.Top - fullRect.Top));
}
}
if (connectivity.HasFlag(TileConnection.TopRight))
{
if (connectivity.HasFlag(TileConnection.Top) && !connectivity.HasFlag(TileConnection.Right))
{
path.AddPolygon(new Point[]
{
new Point(fullRect.Right, fullRect.Top),
new Point(centerRect.Right, fullRect.Top),
new Point(centerRect.Right, centerRect.Top),
});
}
else if (!connectivity.HasFlag(TileConnection.Top) && connectivity.HasFlag(TileConnection.Right))
{
path.AddPolygon(new Point[]
{
new Point(fullRect.Right, fullRect.Top),
new Point(fullRect.Right, centerRect.Top),
new Point(centerRect.Right, centerRect.Top),
});
}
else
{
path.AddRectangle(new Rectangle(centerRect.Right, fullRect.Top, fullRect.Right - centerRect.Right, centerRect.Top - fullRect.Top));
}
}
if (connectivity.HasFlag(TileConnection.BottomRight))
{
if (connectivity.HasFlag(TileConnection.Bottom) && !connectivity.HasFlag(TileConnection.Right))
{
path.AddPolygon(new Point[]
{
new Point(fullRect.Right, fullRect.Bottom),
new Point(centerRect.Right, fullRect.Bottom),
new Point(centerRect.Right, centerRect.Bottom),
});
}
else if (!connectivity.HasFlag(TileConnection.Bottom) && connectivity.HasFlag(TileConnection.Right))
{
path.AddPolygon(new Point[]
{
new Point(fullRect.Right, fullRect.Bottom),
new Point(fullRect.Right, centerRect.Bottom),
new Point(centerRect.Right, centerRect.Bottom),
});
}
else
{
path.AddRectangle(new Rectangle(centerRect.Right, centerRect.Bottom, fullRect.Right - centerRect.Right, fullRect.Bottom - centerRect.Bottom));
}
}
if (connectivity.HasFlag(TileConnection.BottomLeft))
{
if (connectivity.HasFlag(TileConnection.Bottom) && !connectivity.HasFlag(TileConnection.Left))
{
path.AddPolygon(new Point[]
{
new Point(fullRect.Left, fullRect.Bottom),
new Point(centerRect.Left, fullRect.Bottom),
new Point(centerRect.Left, centerRect.Bottom),
});
}
else if (!connectivity.HasFlag(TileConnection.Bottom) && connectivity.HasFlag(TileConnection.Left))
{
path.AddPolygon(new Point[]
{
new Point(fullRect.Left, fullRect.Bottom),
new Point(fullRect.Left, centerRect.Bottom),
new Point(centerRect.Left, centerRect.Bottom),
});
}
else
{
path.AddRectangle(new Rectangle(fullRect.Left, centerRect.Bottom, centerRect.Left - fullRect.Left, fullRect.Bottom - centerRect.Bottom));
}
}
}
private static Rectangle GetConnectivityRegionRect(TileConnection connectivity, Rectangle baseRect)
{
Size borderSize = new Size(
baseRect.Width / 4,
baseRect.Height / 4);
switch (connectivity)
{
default:
case TileConnection.All: return
baseRect;
case TileConnection.TopLeft: return new Rectangle(
baseRect.X,
baseRect.Y,
borderSize.Width,
borderSize.Height);
case TileConnection.Top: return new Rectangle(
baseRect.X + borderSize.Width,
baseRect.Y,
baseRect.Width - borderSize.Width * 2,
borderSize.Height);
case TileConnection.TopRight: return new Rectangle(
baseRect.X + baseRect.Width - borderSize.Width,
baseRect.Y,
borderSize.Width,
borderSize.Height);
case TileConnection.Left: return new Rectangle(
baseRect.X,
baseRect.Y + borderSize.Height,
borderSize.Width,
baseRect.Height - borderSize.Height * 2);
case TileConnection.None: return new Rectangle(
baseRect.X + borderSize.Width,
baseRect.Y + borderSize.Height,
baseRect.Width - borderSize.Width * 2,
baseRect.Height - borderSize.Height * 2);
case TileConnection.Right: return new Rectangle(
baseRect.X + baseRect.Width - borderSize.Width,
baseRect.Y + borderSize.Height,
borderSize.Width,
baseRect.Height - borderSize.Height * 2);
case TileConnection.BottomLeft: return new Rectangle(
baseRect.X,
baseRect.Y + baseRect.Height - borderSize.Height,
borderSize.Width,
borderSize.Height);
case TileConnection.Bottom: return new Rectangle(
baseRect.X + borderSize.Width,
baseRect.Y + baseRect.Height - borderSize.Height,
baseRect.Width - borderSize.Width * 2,
borderSize.Height);
case TileConnection.BottomRight: return new Rectangle(
baseRect.X + baseRect.Width - borderSize.Width,
baseRect.Y + baseRect.Height - borderSize.Height,
borderSize.Width,
borderSize.Height);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace ContactSample.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Xml;
using System.Reflection;
using System.Globalization;
using System.IO;
using NLog;
using NLog.Config;
using NUnit.Framework;
#if !NUNIT
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute;
#endif
namespace NLog.UnitTests.LayoutRenderers
{
[TestFixture]
public class MessageTests : NLogTestBase
{
[Test]
public void MessageWithoutPaddingTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Logger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "a");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", "a1");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01/01/2005 00:00:00");
}
[Test]
public void MessageRightPaddingTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=3}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Logger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", " a");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", " a1");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01/01/2005 00:00:00");
}
[Test]
public void MessageFixedLengthRightPaddingTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=3:fixedlength=true}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Logger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", " a");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", " a1");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01");
}
[Test]
public void MessageLeftPaddingTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=-3:padcharacter=x}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Logger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "axx");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", "a1x");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01/01/2005 00:00:00");
}
[Test]
public void MessageFixedLengthLeftPaddingTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=-3:padcharacter=x:fixedlength=true}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Logger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "axx");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", "a1x");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01");
}
[Test]
public void MessageWithExceptionTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:withException=true}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Logger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "a");
var ex = new InvalidOperationException("Exception message.");
logger.DebugException("Foo", ex);
#if !SILVERLIGHT && !NET_CF
string newline = Environment.NewLine;
#else
string newline = "\r\n";
#endif
AssertDebugLastMessage("debug", "Foo" + newline + ex.ToString());
}
[Test]
public void MessageWithExceptionAndCustomSeparatorTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:withException=true:exceptionSeparator=,}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Logger logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "a");
var ex = new InvalidOperationException("Exception message.");
logger.DebugException("Foo", ex);
AssertDebugLastMessage("debug", "Foo," + ex.ToString());
}
}
}
| |
using System;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;
using Hydra.Framework.XmlSerialization.Common.XPath;
namespace Hydra.Framework.XmlSerialization.Common
{
//
//**********************************************************************
/// <summary>
/// Creates <see cref="XmlNode"/> wrapper instances
/// for different XML APIs, for use in XML serialization.
/// </summary>
/// <remarks>
/// <see cref="XmlNode"/> instances returned by this factory only
/// support the <see cref="XmlNode.WriteTo"/> and <see cref="XmlNode.WriteContentTo"/>
/// methods, as they are intended for use only for serialization, and to avoid
/// <see cref="XmlDocument"/> loading for fast performance. All other members
/// will throw an <see cref="NotSupportedException"/>.
/// </remarks>
//**********************************************************************
//
public class XmlNodeFactory
{
private XmlNodeFactory() { }
#region Create overloads
//
//**********************************************************************
/// <summary>
/// Creates an <see cref="XmlNode"/> wrapper for any object,
/// to be serialized through the <see cref="XmlSerializer"/>.
/// </summary>
/// <param name="value">The object to wrap.</param>
/// <returns>A node that can only be used for XML serialization.</returns>
//**********************************************************************
//
public static XmlNode Create(object value)
{
return new ObjectNode(value);
}
//
//**********************************************************************
/// <summary>
/// Creates an <see cref="XmlNode"/> serializable
/// wrapper for an <see cref="XPathNavigator"/>.
/// </summary>
/// <param name="navigator">The navigator to wrap.</param>
/// <returns>A node that can only be used for XML serialization.</returns>
//**********************************************************************
//
public static XmlNode Create(XPathNavigator navigator)
{
return new XPathNavigatorNode(navigator);
}
//
//**********************************************************************
/// <summary>
/// Creates an <see cref="XmlNode"/> serializable
/// wrapper for an <see cref="XmlReader"/>.
/// </summary>
/// <param name="reader">The reader to wrap.</param>
/// <returns>A node that can only be used for XML serialization.</returns>
/// <remarks>
/// After serialization, the reader is automatically closed.
/// </remarks>
//**********************************************************************
//
public static XmlNode Create(XmlReader reader)
{
return Create(reader, false);
}
//
//**********************************************************************
/// <summary>
/// Creates an <see cref="XmlDocument"/> serializable
/// wrapper for an <see cref="XPathNavigator"/>.
/// </summary>
/// <param name="reader">The reader to wrap.</param>
/// <param name="defaultAttrs">Whether default attributes should be serialized.</param>
/// <returns>A document that can only be used for XML serialization.</returns>
/// <remarks>
/// After serialization, the reader is automatically closed.
/// </remarks>
//**********************************************************************
//
public static XmlNode Create(XmlReader reader, bool defaultAttrs)
{
return new XmlReaderNode(reader, defaultAttrs);
}
#endregion Create overloads
#region SerializableNode
private abstract class SerializableNode : XmlElement
{
public SerializableNode() : base("", "dummy", "", new XmlDocument()) { }
public override XmlNode AppendChild(XmlNode newChild)
{
throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM);
}
public override XmlAttributeCollection Attributes
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override string BaseURI
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override XmlNodeList ChildNodes
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override XmlNode Clone()
{
throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM);
}
public override XmlNode CloneNode(bool deep)
{
throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM);
}
public override XmlNode FirstChild
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override string GetNamespaceOfPrefix(string prefix)
{
throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM);
}
public override string GetPrefixOfNamespace(string namespaceURI)
{
throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM);
}
public override bool HasChildNodes
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override string InnerText
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
set { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override string InnerXml
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
set { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override XmlNode InsertAfter(XmlNode newChild, XmlNode refChild)
{
throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM);
}
public override XmlNode InsertBefore(XmlNode newChild, XmlNode refChild)
{
throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM);
}
public override bool IsReadOnly
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override XmlNode LastChild
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override string LocalName
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override string Name
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override string NamespaceURI
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override XmlNode NextSibling
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override XmlNodeType NodeType
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override void Normalize()
{
throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM);
}
public override string OuterXml
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override XmlDocument OwnerDocument
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override XmlNode ParentNode
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override string Prefix
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
set { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override XmlNode PrependChild(XmlNode newChild)
{
throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM);
}
public override XmlNode PreviousSibling
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override void RemoveAll()
{
throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM);
}
public override XmlNode RemoveChild(XmlNode oldChild)
{
throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM);
}
public override XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild)
{
throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM);
}
public override bool Supports(string feature, string version)
{
throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM);
}
public override XmlElement this[string localname, string ns]
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override XmlElement this[string name]
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override string Value
{
get { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
set { throw new NotSupportedException(SR.XmlDocumentFactory_NotImplementedDOM); }
}
public override void WriteContentTo(XmlWriter w)
{
WriteTo(w);
}
public abstract override void WriteTo(XmlWriter w);
}
#endregion SerializableNode
#region XPathNavigatorNode
private class XPathNavigatorNode : SerializableNode
{
private XPathNavigator _navigator;
public XPathNavigatorNode() { }
public XPathNavigatorNode(XPathNavigator navigator)
{
_navigator = navigator;
}
public override void WriteTo(XmlWriter w)
{
w.WriteNode(_navigator.ReadSubtree(), false);
}
}
#endregion XPathNavigatorNode
#region XmlReaderNode
private class XmlReaderNode : SerializableNode
{
private XmlReader _reader;
private bool _default;
public XmlReaderNode() { }
public XmlReaderNode(XmlReader reader, bool defaultAttrs)
{
_reader = reader;
_reader.MoveToContent();
_default = defaultAttrs;
}
public override void WriteTo(XmlWriter w)
{
w.WriteNode(_reader, _default);
_reader.Close();
}
}
#endregion XmlReaderNode
#region ObjectNode
private class ObjectNode : SerializableNode
{
private object serializableObject;
public ObjectNode() { }
public ObjectNode(object serializableObject)
{
this.serializableObject = serializableObject;
}
public override void WriteTo(XmlWriter w)
{
XmlSerializer ser = new XmlSerializer(serializableObject.GetType());
ser.Serialize(w, serializableObject);
}
}
#endregion XmlReaderNode
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Web;
using ServiceStack.MiniProfiler;
using ServiceStack.WebHost.Endpoints.Support.Markdown;
namespace ServiceStack.RazorEngine
{
public class ViewPage
{
public RazorFormat RazorFormat { get; set; }
public string Layout { get; set; }
public string FilePath { get; set; }
public string Name { get; set; }
public string Contents { get; set; }
public RazorPageType PageType { get; set; }
public string TemplatePath { get; set; }
public string DirectiveTemplatePath { get; set; }
public DateTime? LastModified { get; set; }
public List<IExpirable> Dependents { get; private set; }
public const string ModelName = "Model";
public ViewPage()
{
this.Dependents = new List<IExpirable>();
}
public ViewPage(RazorFormat razorFormat, string fullPath, string name, string contents)
: this(razorFormat, fullPath, name, contents, RazorPageType.ViewPage) {}
public ViewPage(RazorFormat razorFormat, string fullPath, string name, string contents, RazorPageType pageType)
: this()
{
RazorFormat = razorFormat;
FilePath = fullPath;
Name = name;
Contents = contents;
PageType = pageType;
}
public DateTime? GetLastModified()
{
//if (!hasCompletedFirstRun) return null;
var lastModified = this.LastModified;
foreach (var expirable in this.Dependents)
{
if (!expirable.LastModified.HasValue) continue;
if (!lastModified.HasValue || expirable.LastModified > lastModified)
{
lastModified = expirable.LastModified;
}
}
return lastModified;
}
public string GetTemplatePath()
{
return this.DirectiveTemplatePath ?? this.TemplatePath;
}
public string PageName
{
get
{
return this.PageType == RazorPageType.Template
|| this.PageType == RazorPageType.ContentPage
? this.FilePath
: this.Name;
}
}
public void Prepare()
{
Razor.Compile(this.Contents, PageName);
}
private int timesRun;
private Exception initException;
readonly object readWriteLock = new object();
private bool isBusy;
public void Reload()
{
var contents = File.ReadAllText(this.FilePath);
Reload(contents);
}
public void Reload(string contents)
{
var fi = new FileInfo(this.FilePath);
var lastModified = fi.LastWriteTime;
lock (readWriteLock)
{
try
{
isBusy = true;
this.Contents = contents;
foreach (var markdownReplaceToken in RazorFormat.MarkdownReplaceTokens)
{
this.Contents = this.Contents.Replace(markdownReplaceToken.Key, markdownReplaceToken.Value);
}
this.LastModified = lastModified;
initException = null;
timesRun = 0;
Prepare();
}
catch (Exception ex)
{
initException = ex;
}
isBusy = false;
Monitor.PulseAll(readWriteLock);
}
}
public string RenderToHtml()
{
return RenderToString((object)null);
}
public string RenderToHtml<T>(T model)
{
return RenderToString(model);
}
public string RenderToString<T>(T model)
{
var template = RazorFormat.ExecuteTemplate(model, this.PageName, this.TemplatePath);
return template.Result;
}
public IRazorTemplate GetRazorTemplate()
{
return Razor.DefaultTemplateService.GetTemplate(this.PageName);
}
//From https://github.com/NancyFx/Nancy/blob/master/src/Nancy.ViewEngines.Razor/NancyRazorViewBase.cs
public virtual void Write(object value)
{
WriteLiteral(HtmlEncode(value));
}
public virtual void WriteLiteral(object value)
{
//contents.Append(value);
}
public virtual void WriteTo(TextWriter writer, object value)
{
writer.Write(HtmlEncode(value));
}
public virtual void WriteLiteralTo(TextWriter writer, object value)
{
writer.Write(value);
}
public virtual void WriteTo(TextWriter writer, HelperResult value)
{
if (value != null)
{
value.WriteTo(writer);
}
}
public virtual void WriteLiteralTo(TextWriter writer, HelperResult value)
{
//if (value != null)
//{
// value.WriteTo(writer);
//}
}
public virtual void DefineSection(string sectionName, Action action)
{
//this.Sections.Add(sectionName, action);
}
public virtual object RenderBody()
{
//this.contents.Append(this.childBody);
return null;
}
public virtual object RenderSection(string sectionName)
{
return this.RenderSection(sectionName, true);
}
public virtual object RenderSection(string sectionName, bool required)
{
//string sectionContent;
//var exists = this.childSections.TryGetValue(sectionName, out sectionContent);
//if (!exists && required)
//{
// throw new InvalidOperationException("Section name " + sectionName + " not found and is required.");
//}
//this.contents.Append(sectionContent ?? String.Empty);
return null;
}
public virtual bool IsSectionDefined(string sectionName)
{
//return this.childSections.ContainsKey(sectionName);
return false;
}
private static string HtmlEncode(object value)
{
if (value == null)
{
return null;
}
var str = value as IHtmlString;
return str != null ? str.ToHtmlString() : HttpUtility.HtmlEncode(Convert.ToString(value, CultureInfo.CurrentCulture));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ConvertToInt64Vector128Single()
{
var test = new SimdScalarUnaryOpConvertTest__ConvertToInt64Vector128Single();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimdScalarUnaryOpConvertTest__ConvertToInt64Vector128Single
{
private struct TestStruct
{
public Vector128<Single> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimdScalarUnaryOpConvertTest__ConvertToInt64Vector128Single testClass)
{
var result = Sse.X64.ConvertToInt64(_fld);
testClass.ValidateResult(_fld, result);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data = new Single[Op1ElementCount];
private static Vector128<Single> _clsVar;
private Vector128<Single> _fld;
private SimdScalarUnaryOpTest__DataTable<Single> _dataTable;
static SimdScalarUnaryOpConvertTest__ConvertToInt64Vector128Single()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimdScalarUnaryOpConvertTest__ConvertToInt64Vector128Single()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new SimdScalarUnaryOpTest__DataTable<Single>(_data, LargestVectorSize);
}
public bool IsSupported => Sse.X64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse.X64.ConvertToInt64(
Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr)
);
ValidateResult(_dataTable.inArrayPtr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse.X64.ConvertToInt64(
Sse.LoadVector128((Single*)(_dataTable.inArrayPtr))
);
ValidateResult(_dataTable.inArrayPtr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse.X64.ConvertToInt64(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr))
);
ValidateResult(_dataTable.inArrayPtr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse.X64).GetMethod(nameof(Sse.X64.ConvertToInt64), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr)
});
ValidateResult(_dataTable.inArrayPtr, (Int64)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse.X64).GetMethod(nameof(Sse.X64.ConvertToInt64), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArrayPtr))
});
ValidateResult(_dataTable.inArrayPtr, (Int64)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse.X64).GetMethod(nameof(Sse.X64.ConvertToInt64), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr))
});
ValidateResult(_dataTable.inArrayPtr, (Int64)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse.X64.ConvertToInt64(
_clsVar
);
ValidateResult(_clsVar, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr);
var result = Sse.X64.ConvertToInt64(firstOp);
ValidateResult(firstOp, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse.LoadVector128((Single*)(_dataTable.inArrayPtr));
var result = Sse.X64.ConvertToInt64(firstOp);
ValidateResult(firstOp, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr));
var result = Sse.X64.ConvertToInt64(firstOp);
ValidateResult(firstOp, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimdScalarUnaryOpConvertTest__ConvertToInt64Vector128Single();
var result = Sse.X64.ConvertToInt64(test._fld);
ValidateResult(test._fld, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse.X64.ConvertToInt64(_fld);
ValidateResult(_fld, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse.X64.ConvertToInt64(test._fld);
ValidateResult(test._fld, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> firstOp, Int64 result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), firstOp);
ValidateResult(inArray, result, method);
}
private void ValidateResult(void* firstOp, Int64 result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray, result, method);
}
private void ValidateResult(Single[] firstOp, Int64 result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((long)Math.Round(firstOp[0]) != result)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse.X64)}.{nameof(Sse.X64.ConvertToInt64)}<Int64>(Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: result");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/*
* Deed API
*
* Land Registry Deed API
*
* OpenAPI spec version: 1.3.8
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using IO.Swagger.Client;
using IO.Swagger.Model;
namespace IO.Swagger.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IDeedApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Deed
/// </summary>
/// <remarks>
/// The Deed endpoint returns details of a specific deed based on the unique deed reference. The response includes the Title Number, Property information, Borrower(s) information and deed information.
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="deedReference">Unique reference of the deed.</param>
/// <param name="accept">Pass application/json for the deed as JSON or application/pdf to get a pdf</param>
/// <returns>OperativeDeed</returns>
OperativeDeed DeedDeedReferenceGet (string deedReference, string accept);
/// <summary>
/// Deed
/// </summary>
/// <remarks>
/// The Deed endpoint returns details of a specific deed based on the unique deed reference. The response includes the Title Number, Property information, Borrower(s) information and deed information.
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="deedReference">Unique reference of the deed.</param>
/// <param name="accept">Pass application/json for the deed as JSON or application/pdf to get a pdf</param>
/// <returns>ApiResponse of OperativeDeed</returns>
ApiResponse<OperativeDeed> DeedDeedReferenceGetWithHttpInfo (string deedReference, string accept);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Deed
/// </summary>
/// <remarks>
/// The Deed endpoint returns details of a specific deed based on the unique deed reference. The response includes the Title Number, Property information, Borrower(s) information and deed information.
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="deedReference">Unique reference of the deed.</param>
/// <param name="accept">Pass application/json for the deed as JSON or application/pdf to get a pdf</param>
/// <returns>Task of OperativeDeed</returns>
System.Threading.Tasks.Task<OperativeDeed> DeedDeedReferenceGetAsync (string deedReference, string accept);
/// <summary>
/// Deed
/// </summary>
/// <remarks>
/// The Deed endpoint returns details of a specific deed based on the unique deed reference. The response includes the Title Number, Property information, Borrower(s) information and deed information.
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="deedReference">Unique reference of the deed.</param>
/// <param name="accept">Pass application/json for the deed as JSON or application/pdf to get a pdf</param>
/// <returns>Task of ApiResponse (OperativeDeed)</returns>
System.Threading.Tasks.Task<ApiResponse<OperativeDeed>> DeedDeedReferenceGetAsyncWithHttpInfo (string deedReference, string accept);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class DeedApi : IDeedApi
{
private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="DeedApi"/> class.
/// </summary>
/// <returns></returns>
public DeedApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="DeedApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public DeedApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public IO.Swagger.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Deed The Deed endpoint returns details of a specific deed based on the unique deed reference. The response includes the Title Number, Property information, Borrower(s) information and deed information.
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="deedReference">Unique reference of the deed.</param>
/// <param name="accept">Pass application/json for the deed as JSON or application/pdf to get a pdf</param>
/// <returns>OperativeDeed</returns>
public OperativeDeed DeedDeedReferenceGet (string deedReference, string accept)
{
ApiResponse<OperativeDeed> localVarResponse = DeedDeedReferenceGetWithHttpInfo(deedReference, accept);
return localVarResponse.Data;
}
/// <summary>
/// Deed The Deed endpoint returns details of a specific deed based on the unique deed reference. The response includes the Title Number, Property information, Borrower(s) information and deed information.
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="deedReference">Unique reference of the deed.</param>
/// <param name="accept">Pass application/json for the deed as JSON or application/pdf to get a pdf</param>
/// <returns>ApiResponse of OperativeDeed</returns>
public ApiResponse< OperativeDeed > DeedDeedReferenceGetWithHttpInfo (string deedReference, string accept)
{
// verify the required parameter 'deedReference' is set
if (deedReference == null)
throw new ApiException(400, "Missing required parameter 'deedReference' when calling DeedApi->DeedDeedReferenceGet");
// verify the required parameter 'accept' is set
if (accept == null)
throw new ApiException(400, "Missing required parameter 'accept' when calling DeedApi->DeedDeedReferenceGet");
var localVarPath = "/deed/{deed_reference}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/pdf"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (deedReference != null) localVarPathParams.Add("deed_reference", Configuration.ApiClient.ParameterToString(deedReference)); // path parameter
//Commented out from Swagger to allow working program
//if (accept != null) localVarHeaderParams.Add("Accept", Configuration.ApiClient.ParameterToString(accept)); // header parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("DeedDeedReferenceGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<OperativeDeed>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(OperativeDeed) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OperativeDeed)));
}
/// <summary>
/// Deed The Deed endpoint returns details of a specific deed based on the unique deed reference. The response includes the Title Number, Property information, Borrower(s) information and deed information.
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="deedReference">Unique reference of the deed.</param>
/// <param name="accept">Pass application/json for the deed as JSON or application/pdf to get a pdf</param>
/// <returns>Task of OperativeDeed</returns>
public async System.Threading.Tasks.Task<OperativeDeed> DeedDeedReferenceGetAsync (string deedReference, string accept)
{
ApiResponse<OperativeDeed> localVarResponse = await DeedDeedReferenceGetAsyncWithHttpInfo(deedReference, accept);
return localVarResponse.Data;
}
/// <summary>
/// Deed The Deed endpoint returns details of a specific deed based on the unique deed reference. The response includes the Title Number, Property information, Borrower(s) information and deed information.
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="deedReference">Unique reference of the deed.</param>
/// <param name="accept">Pass application/json for the deed as JSON or application/pdf to get a pdf</param>
/// <returns>Task of ApiResponse (OperativeDeed)</returns>
public async System.Threading.Tasks.Task<ApiResponse<OperativeDeed>> DeedDeedReferenceGetAsyncWithHttpInfo (string deedReference, string accept)
{
// verify the required parameter 'deedReference' is set
if (deedReference == null)
throw new ApiException(400, "Missing required parameter 'deedReference' when calling DeedApi->DeedDeedReferenceGet");
// verify the required parameter 'accept' is set
if (accept == null)
throw new ApiException(400, "Missing required parameter 'accept' when calling DeedApi->DeedDeedReferenceGet");
var localVarPath = "/deed/{deed_reference}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json",
"application/pdf"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (deedReference != null) localVarPathParams.Add("deed_reference", Configuration.ApiClient.ParameterToString(deedReference)); // path parameter
if (accept != null) localVarHeaderParams.Add("Accept", Configuration.ApiClient.ParameterToString(accept)); // header parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("DeedDeedReferenceGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<OperativeDeed>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(OperativeDeed) Configuration.ApiClient.Deserialize(localVarResponse, typeof(OperativeDeed)));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Security.Cryptography;
using Microsoft.SqlServer.TDS.FeatureExtAck;
using Microsoft.SqlServer.TDS.PreLogin;
namespace Microsoft.SqlServer.TDS.Login7
{
/// <summary>
/// The Federated authentication library type.
/// </summary>
public enum TDSFedAuthLibraryType : byte
{
IDCRL = 0x00,
SECURITY_TOKEN = 0x01,
ADAL = 0x02,
UNSUPPORTED = 0x03,
}
public enum TDSFedAuthADALWorkflow : byte
{
USERNAME_PASSWORD = 0X01,
}
/// <summary>
/// Feature option token definition.
/// </summary>
public class TDSLogin7FedAuthOptionToken : TDSLogin7FeatureOptionToken
{
/// <summary>
/// Nonce's length
/// </summary>
private static readonly uint s_nonceDataLength = 32;
/// <summary>
/// Signature's length
/// </summary>
private static readonly uint s_signatureDataLength = 32;
/// <summary>
/// Feature type
/// </summary>
public override TDSFeatureID FeatureID { get { return TDSFeatureID.FederatedAuthentication; } }
/// <summary>
/// Federated Authentication option length
/// </summary>
public uint Length
{
get
{
return (uint)(sizeof(byte) // Option (library + echo)
+ sizeof(uint) // Token length variable
+ (Token == null ? 0 : Token.Length) // Actual token length
+ (Nonce == null ? 0 : s_nonceDataLength) // Nonce Length
+ (ChannelBingingToken == null ? 0 : ChannelBingingToken.Length) // Channel binding token
+ (Signature == null ? 0 : s_signatureDataLength) // signature
+ (Library == TDSFedAuthLibraryType.ADAL ? 1 : 0)); // Workflow
}
}
/// <summary>
/// Federated authentication library.
/// </summary>
public TDSFedAuthLibraryType Library { get; private set; }
/// <summary>
/// FedAuthEcho: The intention of this flag is for the client to echo the server's FEDAUTHREQUIRED prelogin option.
/// </summary>
public TdsPreLoginFedAuthRequiredOption Echo { get; private set; }
/// <summary>
/// Whether this protocol is requesting further information from server to perform authentication.
/// </summary>
public bool IsRequestingAuthenticationInfo { get; private set; }
/// <summary>
/// Federated authentication token generated by the specified federated authentication library.
/// </summary>
public byte[] Token { get; private set; }
/// <summary>
/// The nonce provided by the server during prelogin exchange
/// </summary>
public byte[] Nonce { get; private set; }
/// <summary>
/// Channel binding token associated with the underlying SSL stream.
/// </summary>
public byte[] ChannelBingingToken { get; private set; }
/// <summary>
/// The HMAC-SHA-256 [RFC6234] of the server-specified nonce
/// </summary>
public byte[] Signature { get; private set; }
public TDSFedAuthADALWorkflow Workflow { get; private set; }
/// <summary>
/// Default constructor
/// </summary>
public TDSLogin7FedAuthOptionToken()
{
}
/// <summary>
/// Initialization Constructor.
/// </summary>
public TDSLogin7FedAuthOptionToken(TdsPreLoginFedAuthRequiredOption echo,
TDSFedAuthLibraryType libraryType,
byte[] token,
byte[] nonce,
byte[] channelBindingToken,
bool fIncludeSignature,
bool fRequestingFurtherInfo,
TDSFedAuthADALWorkflow workflow = TDSFedAuthADALWorkflow.USERNAME_PASSWORD)
: this()
{
Echo = echo;
Library = libraryType;
Token = token;
Nonce = nonce;
ChannelBingingToken = channelBindingToken;
IsRequestingAuthenticationInfo = fRequestingFurtherInfo;
Workflow = workflow;
if (libraryType != TDSFedAuthLibraryType.SECURITY_TOKEN && fIncludeSignature)
{
Signature = new byte[s_signatureDataLength];
Signature = _GenerateRandomBytes(32);
}
}
/// <summary>
/// Inflating constructor
/// </summary>
public TDSLogin7FedAuthOptionToken(Stream source)
: this()
{
// Inflate feature extension data
Inflate(source);
}
/// <summary>
/// Inflate the token
/// </summary>
/// <param name="source">Stream to inflate the token from</param>
/// <returns>TRUE if inflation is complete</returns>
public override bool Inflate(Stream source)
{
// Reset inflation size
InflationSize = 0;
// We skip option identifier because it was read by construction factory
// Read the length of the data for the option
uint optionDataLength = TDSUtilities.ReadUInt(source);
// Update inflation offset
InflationSize += sizeof(uint);
// Read one byte for the flags
byte temp = (byte)source.ReadByte();
// Update inflation offset
InflationSize += sizeof(byte);
// Get the bit and set as a fedauth echo bit
Echo = (TdsPreLoginFedAuthRequiredOption)(temp & 0x01);
// Get the remaining 7 bits and set as a library.
Library = (TDSFedAuthLibraryType)(temp >> 1);
// When using the ADAL library, a FedAuthToken is never included, nor is its length included
if (Library != TDSFedAuthLibraryType.ADAL)
{
// Length of the FedAuthToken
uint fedauthTokenLen = TDSUtilities.ReadUInt(source);
// Update inflation offset
InflationSize += sizeof(uint);
// Check if the fedauth token is in the login7
if (fedauthTokenLen > 0)
{
// Allocate a container
Token = new byte[fedauthTokenLen];
// Read the Fedauth token.
source.Read(Token, 0, (int)fedauthTokenLen);
// Update inflation offset
InflationSize += fedauthTokenLen;
}
}
else
{
// Instead the workflow is included
Workflow = (TDSFedAuthADALWorkflow)source.ReadByte();
}
switch (Library)
{
case TDSFedAuthLibraryType.IDCRL:
IsRequestingAuthenticationInfo = false;
return ReadIDCRLLogin(source, optionDataLength);
case TDSFedAuthLibraryType.SECURITY_TOKEN:
IsRequestingAuthenticationInfo = false;
return ReadSecurityTokenLogin(source, optionDataLength);
case TDSFedAuthLibraryType.ADAL:
IsRequestingAuthenticationInfo = true;
return true;
default:
return false;
}
}
/// <summary>
/// Deflate the token
/// </summary>
/// <param name="destination">Stream to deflate token to</param>
public override void Deflate(Stream destination)
{
// Write option identifier
destination.WriteByte((byte)FeatureID);
// Calculate Feature Data length
uint optionDataLength = (uint)(sizeof(byte) // Options size (library and Echo)
+ ((Token == null && IsRequestingAuthenticationInfo) ? 0 : sizeof(uint)) // Fedauth token length
+ (Token == null ? 0 : (uint)Token.Length) // Fedauth Token
+ (Nonce == null ? 0 : s_nonceDataLength) // Nonce
+ (ChannelBingingToken == null ? 0 : (uint)ChannelBingingToken.Length) // Channel binding
+ (Signature == null ? 0 : s_signatureDataLength) // Signature
+ (Library == TDSFedAuthLibraryType.ADAL ? 1 : 0)); // Workflow
// Write the cache length into the destination
TDSUtilities.WriteUInt(destination, optionDataLength);
// Construct a byte from fedauthlibrary and fedauth echo.
byte temp = (byte)((((byte)(Library) << 1) | (byte)(Echo)));
destination.WriteByte(temp);
// Write FederatedAuthenticationRequired token.
if (Token == null && !IsRequestingAuthenticationInfo)
{
// Write the length of the token is 0
TDSUtilities.WriteUInt(destination, 0);
}
else if (Token != null)
{
// Write the FederatedAuthenticationRequired token length.
TDSUtilities.WriteUInt(destination, (uint)Token.Length);
// Write the token.
destination.Write(Token, 0, Token.Length);
}
if (Nonce != null)
{
// Write the nonce
destination.Write(Nonce, 0, Nonce.Length);
}
// Write the Channel Binding length
if (ChannelBingingToken != null)
{
destination.Write(ChannelBingingToken, 0, ChannelBingingToken.Length);
}
if (Signature != null)
{
// Write Signature
destination.Write(Signature, 0, (int)s_signatureDataLength);
}
if (Library == TDSFedAuthLibraryType.ADAL)
{
// Write Workflow
destination.WriteByte((byte)Workflow);
}
}
/// <summary>
/// Read the stream for IDCRL based login
/// </summary>
/// <param name="source">source</param>
/// <param name="optionDataLength">option data length</param>
/// <returns></returns>
private bool ReadIDCRLLogin(Stream source, uint optionDataLength)
{
// Allocate a container
Nonce = new byte[s_nonceDataLength];
// Read the nonce
source.Read(Nonce, 0, (int)s_nonceDataLength);
// Update inflation offset
InflationSize += s_nonceDataLength;
// Calculate the Channel binding data length.
uint channelBindingTokenLength = optionDataLength
- sizeof(byte) // Options size (library and Echo)
- sizeof(uint) // Token size
- (Token == null ? 0 : (uint)Token.Length) // Token
- s_nonceDataLength // Nonce length
- s_signatureDataLength; // Signature Length
// Read the channelBindingToken
if (channelBindingTokenLength > 0)
{
// Allocate a container
ChannelBingingToken = new byte[channelBindingTokenLength];
// Read the channel binding part.
source.Read(ChannelBingingToken, 0, (int)channelBindingTokenLength);
// Update inflation offset
InflationSize += channelBindingTokenLength;
}
// Allocate Signature
Signature = new byte[s_signatureDataLength];
// Read the Signature
source.Read(Signature, 0, (int)s_signatureDataLength);
// Update inflation offset
InflationSize += s_signatureDataLength;
return true;
}
/// <summary>
/// Read the stream for SecurityToken based login
/// </summary>
/// <param name="source">source</param>
/// <param name="optionDataLength">option data length</param>
/// <returns></returns>
private bool ReadSecurityTokenLogin(Stream source, uint optionDataLength)
{
// Check if any data is available
if (optionDataLength > InflationSize)
{
// Allocate a container
Nonce = new byte[s_nonceDataLength];
// Read the nonce
source.Read(Nonce, 0, (int)s_nonceDataLength);
// Update inflation offset
InflationSize += s_nonceDataLength;
}
return true;
}
/// <summary>
/// Generates random bytes
/// </summary>
/// <param name="count">The number of bytes to be generated.</param>
/// <returns>Generated random bytes.</returns>
private byte[] _GenerateRandomBytes(int count)
{
byte[] randomBytes = new byte[count];
RNGCryptoServiceProvider gen = new RNGCryptoServiceProvider();
// Generate bytes
gen.GetBytes(randomBytes);
return randomBytes;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Apache.Geode.Client;
using Apache.Geode.Client.Internal;
namespace PdxTests
{
public class AddressR
{
int _aptNumber;
string _street;
string _city;
public AddressR()
{ }
public override string ToString()
{
return _aptNumber + " :" + _street + " : " + _city;
}
public AddressR(int aptN, string street, string city)
{
_aptNumber = aptN;
_street = street;
_city = city;
}
public override bool Equals(object obj)
{
Debug.WriteLine("in addreddR equal");
if (obj == null)
return false;
AddressR other = obj as AddressR;
if (other == null)
return false;
Debug.WriteLine("in addreddr equal2 " + this.ToString() + " : : " + other.ToString());
if (_aptNumber == other._aptNumber
&& _street == other._street
&& _city == other._city)
return true;
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
public class PdxTypesReflectionTest
{
char m_char;
bool m_bool;
sbyte m_byte;
sbyte m_sbyte;
short m_int16;
short m_uint16;
Int32 m_int32;
Int32 m_uint32;
long m_long;
Int64 m_ulong;
float m_float;
double m_double;
string m_string;
bool[] m_boolArray;
byte[] m_byteArray;
byte[] m_sbyteArray;
char[] m_charArray;
DateTime m_dateTime;
Int16[] m_int16Array;
Int16[] m_uint16Array;
Int32[] m_int32Array;
Int32[] m_uint32Array;
long[] m_longArray;
Int64[] m_ulongArray;
float[] m_floatArray;
double[] m_doubleArray;
byte[][] m_byteByteArray;
string[] m_stringArray;
List<object> m_arraylist = new List<object>();
IDictionary<object, object> m_map = new Dictionary<object, object>();
Hashtable m_hashtable = new Hashtable();
ArrayList m_vector = new ArrayList();
CacheableHashSet m_chs = CacheableHashSet.Create();
CacheableLinkedHashSet m_clhs = CacheableLinkedHashSet.Create();
byte[] m_byte252 = new byte[252];
byte[] m_byte253 = new byte[253];
byte[] m_byte65535 = new byte[65535];
byte[] m_byte65536 = new byte[65536];
pdxEnumTest m_pdxEnum = pdxEnumTest.pdx3;
AddressR[] m_address = new AddressR[10];
LinkedList<Object> m_LinkedList = new LinkedList<Object>();
public void Init()
{
m_char = 'C';
m_bool = true;
m_byte = 0x74;
m_sbyte = 0x67;
m_int16 = 0xab;
m_uint16 = 0x2dd5;
m_int32 = 0x2345abdc;
m_uint32 = 0x2a65c434;
m_long = 324897980;
m_ulong = 238749898;
m_float = 23324.324f;
m_double = 3243298498d;
m_string = "gfestring";
m_boolArray = new bool[] { true, false, true };
m_byteArray = new byte[] { 0x34, 0x64 };
m_sbyteArray = new byte[] { 0x34, 0x64 };
m_charArray = new char[] { 'c', 'v' };
long ticks = 634460644691540000L;
m_dateTime = new DateTime(ticks);
Debug.WriteLine(m_dateTime.Ticks);
m_int16Array = new short[] { 0x2332, 0x4545 };
m_uint16Array = new short[] { 0x3243, 0x3232 };
m_int32Array = new int[] { 23, 676868, 34343, 2323 };
m_uint32Array = new int[] { 435, 234324, 324324, 23432432 };
m_longArray = new long[] { 324324L, 23434545L };
m_ulongArray = new Int64[] { 3245435, 3425435 };
m_floatArray = new float[] { 232.565f, 2343254.67f };
m_doubleArray = new double[] { 23423432d, 4324235435d };
m_byteByteArray = new byte[][]{new byte[] {0x23},
new byte[]{0x34, 0x55}
};
m_stringArray = new string[] { "one", "two" };
m_arraylist = new List<object>();
m_arraylist.Add(1);
m_arraylist.Add(2);
m_LinkedList = new LinkedList<Object>();
m_LinkedList.AddFirst("Item1");
m_LinkedList.AddLast("Item2");
m_LinkedList.AddLast("Item3");
m_map = new Dictionary<object, object>();
m_map.Add(1, 1);
m_map.Add(2, 2);
m_hashtable = new Hashtable();
m_hashtable.Add(1, "1111111111111111");
m_hashtable.Add(2, "2222222222221111111111111111");
m_vector = new ArrayList();
m_vector.Add(1);
m_vector.Add(2);
m_vector.Add(3);
m_chs.Add(1);
m_clhs.Add(1);
m_clhs.Add(2);
m_pdxEnum = pdxEnumTest.pdx3;
m_address = new AddressR[10];
for (int i = 0; i < m_address.Length; i++)
{
m_address[i] = new AddressR(i, "street" + i, "city" + i);
}
}
public PdxTypesReflectionTest()
{
}
public PdxTypesReflectionTest(bool initialize)
{
if (initialize)
Init();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
PdxTypesReflectionTest other = obj as PdxTypesReflectionTest;
if (other == null)
return false;
this.checkEquality(other);
return true;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region IPdxSerializable Members
byte[][] compareByteByteArray(byte[][] baa, byte[][] baa2)
{
if (baa.Length == baa2.Length)
{
int i = 0;
while (i < baa.Length)
{
compareByteArray(baa[i], baa2[i]);
i++;
}
if (i == baa2.Length)
return baa2;
}
throw new IllegalStateException("Not got expected value for type: " + baa2.GetType().ToString());
}
bool compareBool(bool b, bool b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
bool[] compareBoolArray(bool[] a, bool[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
byte compareByte(byte b, byte b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
byte[] compareByteArray(byte[] a, byte[] a2)
{
Debug.WriteLine("Compare byte array " + a.Length + " ; " + a2.Length);
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
Debug.WriteLine("Compare byte array " + a[i] + " : " + a2[i]);
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
char[] compareCharArray(char[] a, char[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
List<object> compareCompareCollection(List<object> a, List<object> a2)
{
if (a.Count == a2.Count)
{
int i = 0;
while (i < a.Count)
{
if (!a[i].Equals(a2[i]))
break;
else
i++;
}
if (i == a2.Count)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
LinkedList<object> compareCompareCollection(LinkedList<object> a, LinkedList<object> a2)
{
if (a.Count == a2.Count)
{
LinkedList<Object>.Enumerator e1 = a.GetEnumerator();
LinkedList<Object>.Enumerator e2 = a2.GetEnumerator();
while (e1.MoveNext() && e2.MoveNext())
{
if (!e1.Current.Equals(e2.Current))
break;
}
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
DateTime compareData(DateTime b, DateTime b2)
{
Debug.WriteLine("date " + b.Ticks + " : " + b2.Ticks);
//TODO:
// return b;
if ((b.Ticks / 10000L) == (b2.Ticks / 10000L))
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
Double compareDouble(Double b, Double b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
double[] compareDoubleArray(double[] a, double[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
float compareFloat(float b, float b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
float[] compareFloatArray(float[] a, float[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
Int16 compareInt16(Int16 b, Int16 b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
Int32 compareInt32(Int32 b, Int32 b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
Int64 compareInt64(Int64 b, Int64 b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
Int32[] compareIntArray(Int32[] a, Int32[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
long[] compareLongArray(long[] a, long[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
Int16[] compareSHortArray(Int16[] a, Int16[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
sbyte compareSByte(sbyte b, sbyte b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
sbyte[] compareSByteArray(sbyte[] a, sbyte[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
string[] compareStringArray(string[] a, string[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
UInt16 compareUInt16(UInt16 b, UInt16 b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
UInt32 compareUInt32(UInt32 b, UInt32 b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
UInt64 compareUint64(UInt64 b, UInt64 b2)
{
if (b == b2)
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
UInt32[] compareUnsignedIntArray(UInt32[] a, UInt32[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
UInt64[] compareUnsignedLongArray(UInt64[] a, UInt64[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
UInt16[] compareUnsignedShortArray(UInt16[] a, UInt16[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (a[i] != a2[i])
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
T[] GenericCompare<T>(T[] a, T[] a2)
{
if (a.Length == a2.Length)
{
int i = 0;
while (i < a.Length)
{
if (!a[i].Equals(a2[i]))
break;
else
i++;
}
if (i == a2.Length)
return a2;
}
throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString());
}
T GenericValCompare<T>(T b, T b2)
{
if (b.Equals(b2))
return b;
throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString());
}
public void checkEquality(PdxTypesReflectionTest other)
{
byte[][] baa = other.m_byteByteArray;
m_byteByteArray = compareByteByteArray(baa, m_byteByteArray);
m_char = GenericValCompare(other.m_char, m_char);
m_bool = GenericValCompare(other.m_bool, m_bool);
m_boolArray = GenericCompare(other.m_boolArray, m_boolArray);
m_byte = GenericValCompare(other.m_byte, m_byte);
m_byteArray = GenericCompare(other.m_byteArray, m_byteArray);
m_charArray = GenericCompare(other.m_charArray, m_charArray);
List<object> tmpl = new List<object>();
m_arraylist = compareCompareCollection(other.m_arraylist, m_arraylist);
m_LinkedList = compareCompareCollection(other.m_LinkedList, m_LinkedList);
IDictionary<object, object> tmpM = other.m_map;
if (tmpM.Count != m_map.Count)
throw new IllegalStateException("Not got expected value for type: " + m_map.GetType().ToString());
Hashtable tmpH = other.m_hashtable;
if (tmpH.Count != m_hashtable.Count)
throw new IllegalStateException("Not got expected value for type: " + m_hashtable.GetType().ToString());
ArrayList arrAl = other.m_vector;
if (arrAl.Count != m_vector.Count)
throw new IllegalStateException("Not got expected value for type: " + m_vector.GetType().ToString());
CacheableHashSet rmpChs = other.m_chs;
if (rmpChs.Count != m_chs.Count)
throw new IllegalStateException("Not got expected value for type: " + m_chs.GetType().ToString());
CacheableLinkedHashSet rmpClhs = other.m_clhs;
if (rmpClhs.Count != m_clhs.Count)
throw new IllegalStateException("Not got expected value for type: " + m_clhs.GetType().ToString());
m_string = GenericValCompare(other.m_string, m_string);
m_dateTime = compareData(other.m_dateTime, m_dateTime);
m_double = GenericValCompare(other.m_double, m_double);
m_doubleArray = GenericCompare(other.m_doubleArray, m_doubleArray);
m_float = GenericValCompare(other.m_float, m_float);
m_floatArray = GenericCompare(other.m_floatArray, m_floatArray);
m_int16 = GenericValCompare(other.m_int16, m_int16);
m_int32 = GenericValCompare(other.m_int32, m_int32);
m_long = GenericValCompare(other.m_long, m_long);
m_int32Array = GenericCompare(other.m_int32Array, m_int32Array);
m_longArray = GenericCompare(other.m_longArray, m_longArray);
m_int16Array = GenericCompare(other.m_int16Array, m_int16Array);
m_sbyte = GenericValCompare(other.m_sbyte, m_sbyte);
m_sbyteArray = GenericCompare(other.m_sbyteArray, m_sbyteArray);
m_stringArray = GenericCompare(other.m_stringArray, m_stringArray);
m_uint16 = GenericValCompare(other.m_uint16, m_uint16);
m_uint32 = GenericValCompare(other.m_uint32, m_uint32);
m_ulong = GenericValCompare(other.m_ulong, m_ulong);
m_uint32Array = GenericCompare(other.m_uint32Array, m_uint32Array);
m_ulongArray = GenericCompare(other.m_ulongArray, m_ulongArray);
m_uint16Array = GenericCompare(other.m_uint16Array, m_uint16Array);
byte[] ret = other.m_byte252;
if (ret.Length != 252)
throw new Exception("Array len 252 not found");
ret = other.m_byte253;
if (ret.Length != 253)
throw new Exception("Array len 253 not found");
ret = other.m_byte65535 ;
if (ret.Length != 65535)
throw new Exception("Array len 65535 not found");
ret = other.m_byte65536;
if (ret.Length != 65536)
throw new Exception("Array len 65536 not found");
if(other.m_pdxEnum != m_pdxEnum )
throw new Exception("Pdx enum is not equal");
//byte[] m_byte252 = new byte[252];
//byte[] m_byte253 = new byte[253];
//byte[] m_byte65535 = new byte[65535];
//byte[] m_byte65536 = new byte[65536];
AddressR[] otherA = other.m_address;
for (int i = 0; i < m_address.Length; i++)
{
if(!m_address[i].Equals(otherA[i]))
throw new Exception("AddressR array is not equal " + i);
}
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR
{
using Debugging;
using Microsoft.Zelig.Runtime.TypeSystem;
using System;
using System.Diagnostics;
public sealed class InliningPathAnnotation
: Annotation
, IInliningPathAnnotation
{
//
// State
//
// this is the original path used in the inlining heuristics unmodified for compatibility
private MethodRepresentation[] m_path;
// This contains the locations where the operator that this annotation is attached to was inlined into
private DebugInfo[] m_InlinedAt;
//
// Constructor Methods
//
private InliningPathAnnotation( MethodRepresentation[] path, DebugInfo[] inlinedAt )
{
Debug.Assert(path.Length == inlinedAt.Length);
Debug.Assert(path.Length != 0);
m_path = path;
m_InlinedAt = inlinedAt;
}
public static InliningPathAnnotation Create( TypeSystemForIR ts ,
InliningPathAnnotation anOuter ,
MethodRepresentation md ,
DebugInfo debugInfo,
InliningPathAnnotation anInner )
{
Debug.Assert(anOuter == null || anOuter.DebugInfoPath.Length == anOuter.Path.Length);
Debug.Assert(anInner == null || anInner.DebugInfoPath.Length == anInner.Path.Length);
var pathOuter = anOuter != null ? anOuter.m_path : MethodRepresentation.SharedEmptyArray;
var pathInner = anInner != null ? anInner.Path : MethodRepresentation.SharedEmptyArray;
var path = ArrayUtility.AppendToNotNullArray( pathOuter, md );
path = ArrayUtility.AppendNotNullArrayToNotNullArray( path, pathInner );
// if the operator or varialbe didn't have debug info, then use the method itself
if (debugInfo == null)
debugInfo = md.DebugInfo;
var debugInfoOuter = anOuter?.m_InlinedAt ?? DebugInfo.SharedEmptyArray;
var debugInfoInner = anInner?.m_InlinedAt ?? DebugInfo.SharedEmptyArray;
var debugInfoPath = ArrayUtility.AppendToNotNullArray( debugInfoOuter, debugInfo );
debugInfoPath = ArrayUtility.AppendNotNullArrayToNotNullArray( debugInfoPath, debugInfoInner );
return (InliningPathAnnotation)MakeUnique( ts, new InliningPathAnnotation( path, debugInfoPath ) );
}
//
// Equality Methods
//
public override bool Equals( Object obj )
{
if(obj is InliningPathAnnotation)
{
InliningPathAnnotation other = (InliningPathAnnotation)obj;
return ArrayUtility.ArrayEqualsNotNull( this.m_path, other.m_path, 0 );
}
return false;
}
public override int GetHashCode()
{
if(m_path.Length > 0)
{
return m_path[0].GetHashCode();
}
return 0;
}
//
// Helper Methods
//
public override Annotation Clone( CloningContext context )
{
MethodRepresentation[] path = context.ConvertMethods( m_path );
if(Object.ReferenceEquals( path, m_path ))
{
return this; // Nothing to change.
}
return RegisterAndCloneState( context, MakeUnique( context.TypeSystem, new InliningPathAnnotation( path, m_InlinedAt ) ) );
}
//--//
public override void ApplyTransformation( TransformationContextForIR context )
{
context.Push( this );
base.ApplyTransformation( context );
object origin = context.GetTransformInitiator();
if(origin is CompilationSteps.ComputeCallsClosure.Context)
{
//
// Don't propagate the path, it might include methods that don't exist anymore.
//
}
else if (context is TypeSystemForCodeTransformation.FlagProhibitedUses)
{
TypeSystemForCodeTransformation ts = (TypeSystemForCodeTransformation)context.GetTypeSystem();
for (int i = m_path.Length; --i >= 0;)
{
MethodRepresentation md = m_path[i];
if (ts.ReachabilitySet.IsProhibited(md))
{
m_path = ArrayUtility.RemoveAtPositionFromNotNullArray(m_path, i);
// REVIEW:
// Consider implications of not removing the entry, but instead
// setting the scope to null, this would keep the Source and line debug
// info so the debug info code gneration could treat this like a
// pre-processor macro substitution instead of an inlined call to
// a function that doesn't exist anymore.
m_InlinedAt = ArrayUtility.RemoveAtPositionFromNotNullArray(m_InlinedAt, i);
IsSquashed = true;
}
}
}
else
{
context.Transform( ref m_path );
// TODO: Handle m_DebugInfo - there is no Transform method for DebugInfo[] so this info isn't serialized, etc...
}
context.Pop();
Debug.Assert(m_path.Length == m_InlinedAt.Length);
Debug.Assert(m_path.Length != 0 || IsSquashed);
}
//--//
//
// Access Methods
//
public bool IsSquashed { get; private set; }
/// <summary>Method path for an inlined operator</summary>
/// <remarks>
/// The last entry in the array contains the original source method for the operator this annotation is attached to.
/// </remarks>
public MethodRepresentation[] Path => m_path;
/// <summary>Retrieves the source location information for the inlining chain</summary>
/// <remarks>
/// <para>It is possible for entries in this array to be null if there was no debug information
/// for the call site the method is inlined into.</para>
/// <para>It is worth noting that the debug info path does not "line up" with the <see cref="Path"/>
/// array, it is in fact off by one index. This is due to the fact that the operator that this
/// annotation applies to has its own DebugInfo indicating its source location. Thus, the last
/// entry in DebugInfoPath contains the source location where the operator was inlined *into*.</para>
/// </remarks>
public Debugging.DebugInfo[] DebugInfoPath => m_InlinedAt;
//--//
//
// Debug Methods
//
public override string FormatOutput( IIntermediateRepresentationDumper dumper )
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append( "<Inlining Path:" );
bool fFirst = true;
foreach(MethodRepresentation md in m_path)
{
if(!fFirst)
{
sb.AppendLine();
}
else
{
fFirst = false;
}
sb.AppendFormat( " {0}", md.ToShortString() );
}
sb.Append( ">" );
sb.Append("<DebugInfo Path:");
fFirst = true;
foreach (var debugInfo in m_InlinedAt )
{
if (!fFirst)
{
sb.AppendLine();
}
else
{
fFirst = false;
}
sb.AppendFormat(" {0}", m_InlinedAt );
}
sb.Append(">");
return sb.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using BinaryEncoding;
using Multiformats.Address.Protocols;
using Multiformats.Hash;
namespace Multiformats.Address
{
public class Multiaddress : IEquatable<Multiaddress>
{
static Multiaddress()
{
Setup<IP4>("ip4", 4, 32, false, ip => ip != null ? new IP4((IPAddress)ip) : new IP4());
Setup<IP6>("ip6", 41, 128, false, ip => ip != null ? new IP6((IPAddress)ip) : new IP6());
Setup<TCP>("tcp", 6, 16, false, port => port != null ? new TCP((ushort)port) : new TCP());
Setup<UDP>("udp", 17, 16, false, port => port != null ? new UDP((ushort)port) : new UDP());
Setup<P2P>("p2p", 420, -1, false, address => address != null ? address is Multihash ? new P2P((Multihash)address) : new P2P((string)address) : new P2P());
Setup<IPFS>("ipfs", 421, -1, false, address => address != null ? address is Multihash ? new IPFS((Multihash)address) : new IPFS((string)address) : new IPFS());
Setup<WebSocket>("ws", 477, 0, false, _ => new WebSocket());
Setup<WebSocketSecure>("wss", 478, 0, false, _ => new WebSocketSecure());
Setup<DCCP>("dccp", 33, 16, false, port => port != null ? new DCCP((short)port) : new DCCP());
Setup<SCTP>("sctp", 132, 16, false, port => port != null ? new SCTP((short)port) : new SCTP());
Setup<Unix>("unix", 400, -1, true, address => address != null ? new Unix((string)address) : new Unix());
Setup<Onion>("onion", 444, 96, false, address => address != null ? new Onion((string)address) : new Onion());
Setup<QUIC>("quic", 460, 0, false, _ => new QUIC());
Setup<HTTP>("http", 480, 0, false, _ => new HTTP());
Setup<HTTPS>("https", 443, 0, false, _ => new HTTPS());
Setup<UTP>("utp", 301, 0, false, _ => new UTP());
Setup<UDT>("udt", 302, 0, false, _ => new UDT());
Setup<DNS>("dns", 53, -1, false, address => address != null ? new DNS((string)address) : new DNS());
Setup<DNS4>("dns4", 54, -1, false, address => address != null ? new DNS4((string)address) : new DNS4());
Setup<DNS6>("dns6", 55, -1, false, address => address != null ? new DNS6((string)address) : new DNS6());
Setup<P2PCircuit>("p2p-circuit", 290, 0, false, _ => new P2PCircuit());
Setup<P2PWebRTCStar>("p2p-webrtc-star", 275, 0, false, _ => new P2PWebRTCStar());
Setup<P2PWebRTCDirect>("p2p-webrtc-direct", 276, 0, false, _ => new P2PWebRTCStar());
Setup<P2PWebSocketStar>("p2p-websocket-star", 479, 0, false, _ => new P2PWebSocketStar());
}
private class Protocol
{
public string Name { get; }
public int Code { get; }
public int Size { get; }
public Func<object, MultiaddressProtocol> Factory { get; }
public Type Type { get; }
public bool Path { get; }
public Protocol(string name, int code, int size, Type type, bool path, Func<object, MultiaddressProtocol> factory)
{
Name = name;
Code = code;
Size = size;
Type = type;
Path = path;
Factory = factory;
}
}
private static readonly List<Protocol> _protocols = new List<Protocol>();
private static void Setup<TProtocol>(string name, int code, int size, bool path, Func<object, MultiaddressProtocol> factory)
where TProtocol : MultiaddressProtocol
{
_protocols.Add(new Protocol(name, code, size, typeof(TProtocol), path, factory));
}
public List<MultiaddressProtocol> Protocols { get; }
public Multiaddress()
{
Protocols = new List<MultiaddressProtocol>();
}
public Multiaddress Add<TProtocol>(object value)
where TProtocol : MultiaddressProtocol
{
var proto = _protocols.SingleOrDefault(p => p.Type == typeof(TProtocol));
Protocols.Add(proto.Factory(value));
return this;
}
public Multiaddress Add<TProtocol>() where TProtocol : MultiaddressProtocol => Add<TProtocol>(null);
public Multiaddress Add(params MultiaddressProtocol[] protocols)
{
Protocols.AddRange(protocols);
return this;
}
public TProtocol Get<TProtocol>() where TProtocol : MultiaddressProtocol => Protocols.OfType<TProtocol>().SingleOrDefault();
public void Remove<TProtocol>() where TProtocol : MultiaddressProtocol
{
var protocol = Get<TProtocol>();
if (protocol != null)
Protocols.Remove(protocol);
}
private static bool SupportsProtocol(string name) => _protocols.Any(p => p.Name.Equals(name));
private static bool SupportsProtocol(int code) => _protocols.Any(p => p.Code.Equals(code));
private static MultiaddressProtocol CreateProtocol(string name) => _protocols.SingleOrDefault(p => p.Name == name)?.Factory(null);
private static MultiaddressProtocol CreateProtocol(int code) => _protocols.SingleOrDefault(p => p.Code == code)?.Factory(null);
public static Multiaddress Decode(string value) => new Multiaddress().Add(DecodeProtocols(value.Split(new [] { '/' }, StringSplitOptions.RemoveEmptyEntries)).ToArray());
public static Multiaddress Decode(byte[] bytes) => new Multiaddress().Add(DecodeProtocols(bytes).ToArray());
private static IEnumerable<MultiaddressProtocol> DecodeProtocols(params string[] parts)
{
for (var i = 0; i < parts.Length; i++)
{
if (!SupportsProtocol(parts[i]))
throw new NotSupportedException(parts[i]);
var protocol = CreateProtocol(parts[i]);
if (protocol.Size != 0)
{
if (i + 1 >= parts.Length)
throw new Exception("Required parameter not found");
if (_protocols.SingleOrDefault(p => p.Code == protocol.Code).Path)
{
protocol.Decode(string.Join("/", parts.Slice(i + 1)));
i = parts.Length - 1;
}
else
{
protocol.Decode(parts[++i]);
}
}
yield return protocol;
}
}
private static IEnumerable<MultiaddressProtocol> DecodeProtocols(byte[] bytes)
{
var offset = 0;
short code = 0;
MultiaddressProtocol protocol = null;
while (offset < bytes.Length)
{
offset += ParseProtocolCode(bytes, offset, out code);
if (SupportsProtocol(code))
{
offset += ParseProtocol(bytes, offset, code, out protocol);
yield return protocol;
}
}
}
private static int ParseProtocol(byte[] bytes, int offset, short code, out MultiaddressProtocol protocol)
{
var start = offset;
protocol = CreateProtocol(code);
offset += DecodeProtocol(protocol, bytes, offset);
return offset - start;
}
private static int ParseProtocolCode(byte[] bytes, int offset, out short code)
{
code = Binary.LittleEndian.GetInt16(bytes, offset);
return 2;
}
private static int DecodeProtocol(MultiaddressProtocol protocol, byte[] bytes, int offset)
{
int start = offset;
int count = 0;
if (protocol.Size > 0)
{
count = protocol.Size/8;
}
else if (protocol.Size == -1)
{
uint proxy = 0;
offset += Binary.Varint.Read(bytes, offset, out proxy);
count = (int) proxy;
}
if (count > 0)
{
protocol.Decode(bytes.Slice(offset, count));
offset += count;
}
return offset - start;
}
public override string ToString() => Protocols.Count > 0 ? "/" + string.Join("/", Protocols.SelectMany(ProtocolToStrings)) : string.Empty;
private static IEnumerable<string> ProtocolToStrings(MultiaddressProtocol p)
{
yield return p.Name;
if (p.Value != null)
yield return p.Value.ToString();
}
public byte[] ToBytes() => Protocols.SelectMany(EncodeProtocol).ToArray();
private static IEnumerable<byte> EncodeProtocol(MultiaddressProtocol p)
{
var code = Binary.Varint.GetBytes((ulong)p.Code);
if (p.Size == 0)
return code;
var bytes = p.ToBytes();
if (p.Size > 0)
return code.Concat(bytes);
var prefix = Binary.Varint.GetBytes((ulong)bytes.Length);
return code.Concat(prefix).Concat(bytes);
}
public IEnumerable<Multiaddress> Split() => Protocols.Select(p => new Multiaddress().Add(p));
public static Multiaddress Join(IEnumerable<Multiaddress> addresses)
{
var result = new Multiaddress();
foreach (var address in addresses)
{
result.Add(address.Protocols.ToArray());
}
return result;
}
public Multiaddress Encapsulate(Multiaddress address)
{
return new Multiaddress()
.Add(Protocols.Concat(address.Protocols).ToArray());
}
public Multiaddress Decapsulate(Multiaddress address)
{
return new Multiaddress()
.Add(Protocols.TakeWhile(p => !address.Protocols.Any(p.Equals)).ToArray());
}
public override bool Equals(object obj) => Equals((Multiaddress)obj);
public bool Equals(Multiaddress other) => other != null && ToBytes().SequenceEqual(other.ToBytes());
}
}
| |
//===--- Slice.cs ---------------------------------------------------------===//
//
// Copyright (c) 2015 Joe Duffy. All rights reserved.
//
// This file is distributed under the MIT License. See LICENSE.md for details.
//
//===----------------------------------------------------------------------===//
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace System
{
/// <summary>
/// Slice is a uniform API for dealing with arrays and subarrays, strings
/// and substrings, and unmanaged memory buffers. It adds minimal overhead
/// to regular accesses and is a struct so that creation and subslicing do
/// not require additional allocations. It is type- and memory-safe.
/// </summary>
public partial struct Slice<T> : IEnumerable<T>
{
/// <summary>A managed array/string; or null for native ptrs.</summary>
readonly object m_object;
/// <summary>An byte-offset into the array/string; or a native ptr.</summary>
readonly UIntPtr m_offset;
/// <summary>Fetches the number of elements this Slice contains.</summary>
public readonly int Length;
/// <summary>
/// Creates a new slice over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentException">
/// Thrown if the 'array' parameter is null.
/// </exception>
public Slice(T[] array)
{
Contract.Requires(array != null);
m_object = array;
m_offset = new UIntPtr((uint)SliceHelpers<T>.OffsetToArrayData);
Length = array.Length;
}
/// <summary>
/// Creates a new slice over the portion of the target array beginning
/// at 'start' index.
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the slice.</param>
/// <exception cref="System.ArgumentException">
/// Thrown if the 'array' parameter is null.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified start index is not in range (<0 or >&eq;length).
/// </exception>
public Slice(T[] array, int start)
{
Contract.Requires(array != null);
Contract.RequiresInInclusiveRange(start, array.Length);
if (start < array.Length) {
m_object = array;
m_offset = new UIntPtr(
(uint)(SliceHelpers<T>.OffsetToArrayData + (start * PtrUtils.SizeOf<T>())));
Length = array.Length - start;
}
else {
m_object = null;
m_offset = UIntPtr.Zero;
Length = 0;
}
}
/// <summary>
/// Creates a new slice over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the slice.</param>
/// <param name="end">The index at which to end the slice (exclusive).</param>
/// <exception cref="System.ArgumentException">
/// Thrown if the 'array' parameter is null.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified start or end index is not in range (<0 or >&eq;length).
/// </exception>
public Slice(T[] array, int start, int end)
{
Contract.Requires(array != null);
Contract.RequiresInInclusiveRange(start, array.Length);
if (start < array.Length) {
m_object = array;
m_offset = new UIntPtr(
(uint)(SliceHelpers<T>.OffsetToArrayData + (start * PtrUtils.SizeOf<T>())));
Length = end - start;
}
else {
m_object = null;
m_offset = UIntPtr.Zero;
Length = 0;
}
}
/// <summary>
/// Creates a new slice over the target unmanaged buffer. Clearly this
/// is quite dangerous, because we are creating arbitrarily typed T's
/// out of a void*-typed block of memory. And the length is not checked.
/// But if this creation is correct, then all subsequent uses are correct.
/// </summary>
/// <param name="ptr">An unmanaged pointer to memory.</param>
/// <param name="length">The number of T elements the memory contains.</param>
public unsafe Slice(void* ptr, int length)
{
Contract.Requires(length >= 0);
Contract.Requires(length == 0 || ptr != null);
m_object = null;
m_offset = new UIntPtr(ptr);
Length = length;
}
/// <summary>
/// An internal helper for creating slices. Not for public use.
/// </summary>
internal Slice(object obj, UIntPtr offset, int length)
{
m_object = obj;
m_offset = offset;
Length = length;
}
/// <summary>
/// Fetches the managed object (if any) that this Slice points at.
/// </summary>
internal object Object
{
get { return m_object; }
}
/// <summary>
/// Fetches the offset -- or sometimes, raw pointer -- for this Slice.
/// </summary>
internal UIntPtr Offset
{
get { return m_offset; }
}
/// <summary>
/// Fetches the element at the specified index.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified index is not in range (<0 or >&eq;length).
/// </exception>
public T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)] // it makes enumeration via IEnumerable faster
get {
Contract.RequiresInRange(index, Length);
return PtrUtils.Get<T>(
m_object, m_offset + (index * PtrUtils.SizeOf<T>()));
}
set {
Contract.RequiresInRange(index, Length);
PtrUtils.Set<T>(
m_object, m_offset + (index * PtrUtils.SizeOf<T>()), value);
}
}
/// <summary>
/// Copies the contents of this Slice into a new array. This heap
/// allocates, so should generally be avoided, however is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] Copy()
{
var dest = new T[Length];
CopyTo(dest.Slice());
return dest;
}
/// <summary>
/// Copies the contents of this Slice into another. The destination
/// must be at least as big as the source, and may be bigger.
/// </summary>
/// <param name="dest">The Slice to copy items into.</param>
public void CopyTo(Slice<T> dest)
{
Contract.Requires(dest.Length >= Length);
if (Length == 0) {
return;
}
// TODO(joe): specialize to use a fast memcpy if T is pointerless.
for (int i = 0; i < Length; i++) {
dest[i] = this[i];
}
}
/// <summary>
/// Forms a subslice out of the given slice, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this subslice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified start index is not in range (<0 or >&eq;length).
/// </exception>
public Slice<T> Sub(int start)
{
return Sub(start, Length);
}
/// <summary>
/// Forms a subslice out of the given slice, beginning at 'start', and
/// ending at 'end' (exclusive).
/// </summary>
/// <param name="start">The index at which to begin this subslice.</param>
/// <param name="end">The index at which to end this subslice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified start or end index is not in range (<0 or >&eq;length).
/// </exception>
public Slice<T> Sub(int start, int end)
{
Contract.RequiresInInclusiveRange(start, end, Length);
return new Slice<T>(
m_object, m_offset + (start * PtrUtils.SizeOf<T>()), end - start);
}
/// <summary>
/// Checks to see if two slices point at the same memory. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public bool ReferenceEquals(Slice<T> other)
{
return Object == other.Object &&
Offset == other.Offset && Length == other.Length;
}
/// <summary>
/// Returns item from given index without the boundaries check
/// use only in places where moving outside the boundaries is impossible
/// gain: performance: no boundaries check (single operation)
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal T GetItemWithoutBoundariesCheck(int index)
{
return PtrUtils.Get<T>(
m_object, m_offset + (index * PtrUtils.SizeOf<T>()));
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HPSF.Basic
{
using System;
using System.IO;
using System.Collections;
using NUnit.Framework;
using NPOI.HPSF;
using NPOI.POIFS.EventFileSystem;
using NPOI.Util;
using System.Collections.Generic;
/**
* Static utility methods needed by the HPSF Test cases.
*
* @author Rainer Klute ([email protected])
* @since 2002-07-20
* @version $Id: Util.java 489730 2006-12-22 19:18:16Z bayard $
*/
public class Util
{
/**
* Reads bytes from an input stream and Writes them to an
* output stream until end of file is encountered.
*
* @param in the input stream to Read from
*
* @param out the output stream to Write to
*
* @exception IOException if an I/O exception occurs
*/
public static void Copy(Stream in1, Stream out1)
{
int BUF_SIZE = 1000;
byte[] b = new byte[BUF_SIZE];
int Read;
bool eof = false;
while (!eof)
{
try
{
Read = in1.Read(b, 0, BUF_SIZE);
if (Read > 0)
out1.Write(b, 0, Read);
else
eof = true;
}
catch
{
eof = true;
}
}
}
/**
* Reads all files from a POI filesystem and returns them as an
* array of {@link POIFile} instances. This method loads all files
* into memory and thus does not cope well with large POI
* filessystems.
*
* @param poiFs The name of the POI filesystem as seen by the
* operating system. (This is the "filename".)
*
* @return The POI files. The elements are ordered in the same way
* as the files in the POI filesystem.
*
* @exception FileNotFoundException if the file containing the POI
* filesystem does not exist
*
* @exception IOException if an I/O exception occurs
*/
public static POIFile[] ReadPOIFiles(Stream poiFs)
{
return ReadPOIFiles(poiFs, null);
}
/**
* Reads a Set of files from a POI filesystem and returns them
* as an array of {@link POIFile} instances. This method loads all
* files into memory and thus does not cope well with large POI
* filessystems.
*
* @param poiFs The name of the POI filesystem as seen by the
* operating system. (This is the "filename".)
*
* @param poiFiles The names of the POI files to be Read.
*
* @return The POI files. The elements are ordered in the same way
* as the files in the POI filesystem.
*
* @exception FileNotFoundException if the file containing the POI
* filesystem does not exist
*
* @exception IOException if an I/O exception occurs
*/
public static POIFile[] ReadPOIFiles(Stream poiFs,
String[] poiFiles)
{
List<POIFile> files = new List<POIFile>();
POIFSReader reader1 = new POIFSReader();
//reader1.StreamReaded += new POIFSReaderEventHandler(reader1_StreamReaded);
POIFSReaderListener pfl = new POIFSReaderListener0(files);
if (poiFiles == null)
/* Register the listener for all POI files. */
reader1.RegisterListener(pfl);
else
/* Register the listener for the specified POI files
* only. */
for (int i = 0; i < poiFiles.Length; i++)
reader1.RegisterListener(pfl, poiFiles[i]);
/* Read the POI filesystem. */
try
{
reader1.Read(poiFs);
}
finally
{
poiFs.Close();
}
POIFile[] result = new POIFile[files.Count];
for (int i = 0; i < result.Length; i++)
result[i] = (POIFile)files[i];
return result;
}
private class POIFSReaderListener0 : POIFSReaderListener
{
#region POIFSReaderListener members
private List<POIFile> files;
public POIFSReaderListener0(List<POIFile> files)
{
this.files = files;
}
public void ProcessPOIFSReaderEvent(POIFSReaderEvent evt)
{
try
{
POIFile f = new POIFile();
f.SetName(evt.Name);
f.SetPath(evt.Path);
MemoryStream out1 =
new MemoryStream();
Util.Copy(evt.Stream, out1);
out1.Close();
f.SetBytes(out1.ToArray());
files.Add(f);
}
catch (IOException ex)
{
throw new RuntimeException(ex.Message);
}
}
#endregion
}
/**
* Read all files from a POI filesystem which are property Set streams
* and returns them as an array of {@link org.apache.poi.hpsf.PropertySet}
* instances.
*
* @param poiFs The name of the POI filesystem as seen by the
* operating system. (This is the "filename".)
*
* @return The property Sets. The elements are ordered in the same way
* as the files in the POI filesystem.
*
* @exception FileNotFoundException if the file containing the POI
* filesystem does not exist
*
* @exception IOException if an I/O exception occurs
*/
public static POIFile[] ReadPropertySets(FileStream poifs)
{
List<POIFile> files = new List<POIFile>(7);
POIFSReader reader2 = new POIFSReader();
//reader2.StreamReaded += new POIFSReaderEventHandler(reader2_StreamReaded);
POIFSReaderListener pfl = new POIFSReaderListener1(files);
reader2.RegisterListener(pfl);
/* Read the POI filesystem. */
try
{
reader2.Read(poifs);
}
finally
{
}
POIFile[] result = new POIFile[files.Count];
for (int i = 0; i < result.Length; i++)
result[i] = files[i];
return result;
}
private class POIFSReaderListener1:POIFSReaderListener
{
#region POIFSReaderListener members
private List<POIFile> files;
public POIFSReaderListener1(List<POIFile> files)
{
this.files = files;
}
public void ProcessPOIFSReaderEvent(POIFSReaderEvent e)
{
try
{
POIFile f = new POIFile();
f.SetName(e.Name);
f.SetPath(e.Path);
Stream in1 = e.Stream;
if (PropertySet.IsPropertySetStream(in1))
{
using (MemoryStream out1 = new MemoryStream())
{
Util.Copy(in1, out1);
//out1.Close();
f.SetBytes(out1.ToArray());
files.Add(f);
}
}
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
}
#endregion
}
/**
* Prints the system properties to System.out.
*/
public static void PrintSystemProperties()
{
IDictionary p = Environment.GetEnvironmentVariables();
List<string> names = new List<string>();
for (IEnumerator i = p.GetEnumerator(); i.MoveNext(); )
names.Add(i.Current.ToString());
names.Sort();
for (IEnumerator<string> i = names.GetEnumerator(); i.MoveNext(); )
{
String name = i.Current;
String value = (string)p[name];
Console.WriteLine(name + ": " + value);
}
Console.WriteLine("Current directory: " +
Environment.GetEnvironmentVariable("user.dir"));
}
}
}
| |
using System.Web.Mvc;
using Autofac.Core.Lifetime;
using Autofac.Integration.Mvc;
using NUnit.Framework;
namespace Autofac.Tests.Integration.Mvc
{
[TestFixture]
public class ViewRegistrationSourceFixture
{
[Test]
public void RegistrationFoundForWebViewPageWithoutModel()
{
var builder = new ContainerBuilder();
builder.RegisterType<ViewDependency>().AsSelf();
builder.RegisterSource(new ViewRegistrationSource());
var container = builder.Build();
using (var lifetimeScope = container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
{
var webViewPage = lifetimeScope.Resolve<GeneratedWebViewPage>();
Assert.That(webViewPage, Is.Not.Null);
Assert.That(webViewPage.Dependency, Is.Not.Null);
}
}
[Test]
public void RegistrationFoundForWebViewPageWithModel()
{
var builder = new ContainerBuilder();
builder.RegisterType<ViewDependency>().AsSelf();
builder.RegisterSource(new ViewRegistrationSource());
var container = builder.Build();
using (var lifetimeScope = container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
{
var webViewPage = lifetimeScope.Resolve<GeneratedWebViewPageWithModel>();
Assert.That(webViewPage, Is.Not.Null);
Assert.That(webViewPage.Dependency, Is.Not.Null);
}
}
[Test]
public void RegistrationFoundForViewPageWithoutModel()
{
var builder = new ContainerBuilder();
builder.RegisterType<ViewDependency>().AsSelf();
builder.RegisterSource(new ViewRegistrationSource());
var container = builder.Build();
using (var lifetimeScope = container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
{
var viewPage = lifetimeScope.Resolve<GeneratedViewPage>();
Assert.That(viewPage, Is.Not.Null);
Assert.That(viewPage.Dependency, Is.Not.Null);
}
}
[Test]
public void RegistrationFoundForViewPageWithModel()
{
var builder = new ContainerBuilder();
builder.RegisterType<ViewDependency>().AsSelf();
builder.RegisterSource(new ViewRegistrationSource());
var container = builder.Build();
using (var lifetimeScope = container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
{
var viewPage = lifetimeScope.Resolve<GeneratedViewPageWithModel>();
Assert.That(viewPage, Is.Not.Null);
Assert.That(viewPage.Dependency, Is.Not.Null);
}
}
[Test]
public void RegistrationFoundForViewMasterPageWithoutModel()
{
var builder = new ContainerBuilder();
builder.RegisterType<ViewDependency>().AsSelf();
builder.RegisterSource(new ViewRegistrationSource());
var container = builder.Build();
using (var lifetimeScope = container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
{
var viewMasterPage = lifetimeScope.Resolve<GeneratedViewMasterPage>();
Assert.That(viewMasterPage, Is.Not.Null);
Assert.That(viewMasterPage.Dependency, Is.Not.Null);
}
}
[Test]
public void RegistrationFoundForViewMasterPageWithModel()
{
var builder = new ContainerBuilder();
builder.RegisterType<ViewDependency>().AsSelf();
builder.RegisterSource(new ViewRegistrationSource());
var container = builder.Build();
using (var lifetimeScope = container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
{
var viewMasterPage = lifetimeScope.Resolve<GeneratedViewMasterPageWithModel>();
Assert.That(viewMasterPage, Is.Not.Null);
Assert.That(viewMasterPage.Dependency, Is.Not.Null);
}
}
[Test]
public void RegistrationFoundForViewUserControlWithoutModel()
{
var builder = new ContainerBuilder();
builder.RegisterType<ViewDependency>().AsSelf();
builder.RegisterSource(new ViewRegistrationSource());
var container = builder.Build();
using (var lifetimeScope = container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
{
var viewUserControl = lifetimeScope.Resolve<GeneratedViewUserControl>();
Assert.That(viewUserControl, Is.Not.Null);
Assert.That(viewUserControl.Dependency, Is.Not.Null);
}
}
[Test]
public void RegistrationFoundForViewUserControlWithModel()
{
var builder = new ContainerBuilder();
builder.RegisterType<ViewDependency>().AsSelf();
builder.RegisterSource(new ViewRegistrationSource());
var container = builder.Build();
using (var lifetimeScope = container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
{
var viewUserControl = lifetimeScope.Resolve<GeneratedViewUserControlWithModel>();
Assert.That(viewUserControl, Is.Not.Null);
Assert.That(viewUserControl.Dependency, Is.Not.Null);
}
}
[Test]
public void IsNotAdapterForIndividualComponents()
{
Assert.That(new ViewRegistrationSource().IsAdapterForIndividualComponents, Is.False);
}
[Test]
public void ViewRegistrationIsInstancePerDependency()
{
var builder = new ContainerBuilder();
builder.RegisterType<ViewDependency>().AsSelf();
builder.RegisterSource(new ViewRegistrationSource());
var container = builder.Build();
using (var lifetimeScope = container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
{
var viewPage1 = lifetimeScope.Resolve<GeneratedWebViewPageWithModel>();
var viewPage2 = lifetimeScope.Resolve<GeneratedWebViewPageWithModel>();
Assert.That(viewPage1, Is.Not.SameAs(viewPage2));
}
}
[Test]
public void ViewCanHaveInstancePerHttpRequestDependency()
{
var builder = new ContainerBuilder();
builder.RegisterType<ViewDependency>().AsSelf().InstancePerRequest();
builder.RegisterSource(new ViewRegistrationSource());
var container = builder.Build();
using (var lifetimeScope = container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
{
var viewPage1 = lifetimeScope.Resolve<GeneratedWebViewPageWithModel>();
var viewPage2 = lifetimeScope.Resolve<GeneratedWebViewPageWithModel>();
Assert.That(viewPage1.Dependency, Is.SameAs(viewPage2.Dependency));
}
}
}
public class ViewDependency { }
public class ViewModel { }
public abstract class AbstractWebViewPage : WebViewPage
{
public ViewDependency Dependency { get; set; }
}
public abstract class AbstractWebViewPageWithModel<T> : WebViewPage<T>
{
public ViewDependency Dependency { get; set; }
}
public class GeneratedWebViewPage : AbstractWebViewPage
{
public override void Execute() { }
}
public class GeneratedWebViewPageWithModel : AbstractWebViewPageWithModel<Model>
{
public override void Execute() { }
}
public abstract class AbstractViewPage : ViewPage
{
public ViewDependency Dependency { get; set; }
}
public abstract class AbstractViewPageWithModel<T> : ViewPage<T>
{
public ViewDependency Dependency { get; set; }
}
public class GeneratedViewPage : AbstractViewPage { }
public class GeneratedViewPageWithModel : AbstractViewPageWithModel<Model> { }
public abstract class AbstractViewMasterPage : ViewMasterPage
{
public ViewDependency Dependency { get; set; }
}
public abstract class AbstractViewMasterPageWithModel<T> : ViewMasterPage<T>
{
public ViewDependency Dependency { get; set; }
}
public class GeneratedViewMasterPage : AbstractViewMasterPage { }
public class GeneratedViewMasterPageWithModel : AbstractViewMasterPageWithModel<Model> { }
public abstract class AbstractViewUserControl : ViewUserControl
{
public ViewDependency Dependency { get; set; }
}
public abstract class AbstractViewUserControlWithModel<T> : ViewUserControl<T>
{
public ViewDependency Dependency { get; set; }
}
public class GeneratedViewUserControl : AbstractViewUserControl { }
public class GeneratedViewUserControlWithModel : AbstractViewUserControlWithModel<Model> { }
}
| |
/*
* [The "BSD license"]
* Copyright (c) 2011 Terence Parr
* All rights reserved.
*
* Conversion to C#:
* Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace TypeSql.Antlr.Runtime.Tree
{
using System;
using System.Collections.Generic;
using StringBuilder = System.Text.StringBuilder;
/** <summary>
* A generic tree implementation with no payload. You must subclass to
* actually have any user data. ANTLR v3 uses a list of children approach
* instead of the child-sibling approach in v2. A flat tree (a list) is
* an empty node whose children represent the list. An empty, but
* non-null node is called "nil".
* </summary>
*/
[System.Serializable]
[System.Diagnostics.DebuggerTypeProxy(typeof(AntlrRuntime_BaseTreeDebugView))]
public abstract class BaseTree : ITree
{
private IList<ITree> _children;
public BaseTree()
{
}
/** <summary>
* Create a new node from an existing node does nothing for BaseTree
* as there are no fields other than the children list, which cannot
* be copied as the children are not considered part of this node.
* </summary>
*/
public BaseTree( ITree node )
{
}
/** <summary>
* Get the children internal List; note that if you directly mess with
* the list, do so at your own risk.
* </summary>
*/
public virtual IList<ITree> Children
{
get
{
return _children;
}
private set
{
_children = value;
}
}
#region ITree Members
public virtual int ChildCount
{
get
{
if ( Children == null )
return 0;
return Children.Count;
}
}
/** <summary>BaseTree doesn't track parent pointers.</summary> */
public virtual ITree Parent
{
get
{
return null;
}
set
{
}
}
/** <summary>BaseTree doesn't track child indexes.</summary> */
public virtual int ChildIndex
{
get
{
return 0;
}
set
{
}
}
public virtual bool IsNil
{
get
{
return false;
}
}
public abstract int TokenStartIndex
{
get;
set;
}
public abstract int TokenStopIndex
{
get;
set;
}
public abstract int Type
{
get;
set;
}
public abstract string Text
{
get;
set;
}
public virtual int Line
{
get;
set;
}
public virtual int CharPositionInLine
{
get;
set;
}
#endregion
public virtual ITree GetChild( int i )
{
if (i < 0)
throw new ArgumentOutOfRangeException();
if ( Children == null || i >= Children.Count )
return null;
return Children[i];
}
public virtual ITree GetFirstChildWithType( int type )
{
foreach ( ITree child in Children )
{
if ( child.Type == type )
return child;
}
return null;
}
/** <summary>Add t as child of this node.</summary>
*
* <remarks>
* Warning: if t has no children, but child does
* and child isNil then this routine moves children to t via
* t.children = child.children; i.e., without copying the array.
* </remarks>
*/
public virtual void AddChild( ITree t )
{
//System.out.println("add child "+t.toStringTree()+" "+this.toStringTree());
//System.out.println("existing children: "+children);
if ( t == null )
{
return; // do nothing upon addChild(null)
}
if ( t.IsNil )
{
// t is an empty node possibly with children
BaseTree childTree = t as BaseTree;
if ( childTree != null && this.Children != null && this.Children == childTree.Children )
{
throw new Exception( "attempt to add child list to itself" );
}
// just add all of childTree's children to this
if ( t.ChildCount > 0 )
{
if ( this.Children != null || childTree == null )
{
if ( this.Children == null )
this.Children = CreateChildrenList();
// must copy, this has children already
int n = t.ChildCount;
for ( int i = 0; i < n; i++ )
{
ITree c = t.GetChild( i );
this.Children.Add( c );
// handle double-link stuff for each child of nil root
c.Parent = this;
c.ChildIndex = Children.Count - 1;
}
}
else
{
// no children for this but t is a BaseTree with children;
// just set pointer call general freshener routine
this.Children = childTree.Children;
this.FreshenParentAndChildIndexes();
}
}
}
else
{
// child is not nil (don't care about children)
if ( Children == null )
{
Children = CreateChildrenList(); // create children list on demand
}
Children.Add( t );
t.Parent = this;
t.ChildIndex = Children.Count - 1;
}
// System.out.println("now children are: "+children);
}
/** <summary>Add all elements of kids list as children of this node</summary> */
public virtual void AddChildren( IEnumerable<ITree> kids )
{
if (kids == null)
throw new ArgumentNullException("kids");
foreach ( ITree t in kids )
AddChild( t );
}
public virtual void SetChild( int i, ITree t )
{
if (i < 0)
throw new ArgumentOutOfRangeException("i");
if ( t == null )
{
return;
}
if ( t.IsNil )
{
throw new ArgumentException( "Can't set single child to a list" );
}
if ( Children == null )
{
Children = CreateChildrenList();
}
Children[i] = t;
t.Parent = this;
t.ChildIndex = i;
}
/** Insert child t at child position i (0..n-1) by shifting children
* i+1..n-1 to the right one position. Set parent / indexes properly
* but does NOT collapse nil-rooted t's that come in here like addChild.
*/
public virtual void InsertChild(int i, ITree t)
{
if (i < 0)
throw new ArgumentOutOfRangeException("i");
if (i > ChildCount)
throw new ArgumentException();
if (i == ChildCount)
{
AddChild(t);
return;
}
Children.Insert(i, t);
// walk others to increment their child indexes
// set index, parent of this one too
this.FreshenParentAndChildIndexes(i);
}
public virtual object DeleteChild( int i )
{
if (i < 0)
throw new ArgumentOutOfRangeException("i");
if (i >= ChildCount)
throw new ArgumentException();
if ( Children == null )
return null;
ITree killed = Children[i];
Children.RemoveAt( i );
// walk rest and decrement their child indexes
this.FreshenParentAndChildIndexes( i );
return killed;
}
/** <summary>
* Delete children from start to stop and replace with t even if t is
* a list (nil-root tree). num of children can increase or decrease.
* For huge child lists, inserting children can force walking rest of
* children to set their childindex; could be slow.
* </summary>
*/
public virtual void ReplaceChildren( int startChildIndex, int stopChildIndex, object t )
{
if (startChildIndex < 0)
throw new ArgumentOutOfRangeException();
if (stopChildIndex < 0)
throw new ArgumentOutOfRangeException();
if (t == null)
throw new ArgumentNullException("t");
if (stopChildIndex < startChildIndex)
throw new ArgumentException();
/*
System.out.println("replaceChildren "+startChildIndex+", "+stopChildIndex+
" with "+((BaseTree)t).toStringTree());
System.out.println("in="+toStringTree());
*/
if ( Children == null )
{
throw new ArgumentException( "indexes invalid; no children in list" );
}
int replacingHowMany = stopChildIndex - startChildIndex + 1;
int replacingWithHowMany;
ITree newTree = (ITree)t;
IList<ITree> newChildren = null;
// normalize to a list of children to add: newChildren
if ( newTree.IsNil )
{
BaseTree baseTree = newTree as BaseTree;
if ( baseTree != null && baseTree.Children != null )
{
newChildren = baseTree.Children;
}
else
{
newChildren = CreateChildrenList();
int n = newTree.ChildCount;
for ( int i = 0; i < n; i++ )
newChildren.Add( newTree.GetChild( i ) );
}
}
else
{
newChildren = new List<ITree>( 1 );
newChildren.Add( newTree );
}
replacingWithHowMany = newChildren.Count;
int numNewChildren = newChildren.Count;
int delta = replacingHowMany - replacingWithHowMany;
// if same number of nodes, do direct replace
if ( delta == 0 )
{
int j = 0; // index into new children
for ( int i = startChildIndex; i <= stopChildIndex; i++ )
{
ITree child = newChildren[j];
Children[i] = child;
child.Parent = this;
child.ChildIndex = i;
j++;
}
}
else if ( delta > 0 )
{
// fewer new nodes than there were
// set children and then delete extra
for ( int j = 0; j < numNewChildren; j++ )
{
Children[startChildIndex + j] = newChildren[j];
}
int indexToDelete = startChildIndex + numNewChildren;
for ( int c = indexToDelete; c <= stopChildIndex; c++ )
{
// delete same index, shifting everybody down each time
Children.RemoveAt( indexToDelete );
}
FreshenParentAndChildIndexes( startChildIndex );
}
else
{
// more new nodes than were there before
// fill in as many children as we can (replacingHowMany) w/o moving data
for ( int j = 0; j < replacingHowMany; j++ )
{
Children[startChildIndex + j] = newChildren[j];
}
int numToInsert = replacingWithHowMany - replacingHowMany;
for ( int j = replacingHowMany; j < replacingWithHowMany; j++ )
{
Children.Insert( startChildIndex + j, newChildren[j] );
}
FreshenParentAndChildIndexes( startChildIndex );
}
//System.out.println("out="+toStringTree());
}
/** <summary>Override in a subclass to change the impl of children list</summary> */
protected virtual IList<ITree> CreateChildrenList()
{
return new List<ITree>();
}
/** <summary>Set the parent and child index values for all child of t</summary> */
public virtual void FreshenParentAndChildIndexes()
{
FreshenParentAndChildIndexes( 0 );
}
public virtual void FreshenParentAndChildIndexes( int offset )
{
int n = ChildCount;
for ( int c = offset; c < n; c++ )
{
ITree child = GetChild( c );
child.ChildIndex = c;
child.Parent = this;
}
}
public virtual void FreshenParentAndChildIndexesDeeply()
{
FreshenParentAndChildIndexesDeeply(0);
}
public virtual void FreshenParentAndChildIndexesDeeply(int offset)
{
int n = ChildCount;
for (int c = offset; c < n; c++)
{
ITree child = GetChild(c);
child.ChildIndex = c;
child.Parent = this;
BaseTree baseTree = child as BaseTree;
if (baseTree != null)
baseTree.FreshenParentAndChildIndexesDeeply();
}
}
public virtual void SanityCheckParentAndChildIndexes()
{
SanityCheckParentAndChildIndexes( null, -1 );
}
public virtual void SanityCheckParentAndChildIndexes( ITree parent, int i )
{
if ( parent != this.Parent )
{
throw new InvalidOperationException( "parents don't match; expected " + parent + " found " + this.Parent );
}
if ( i != this.ChildIndex )
{
throw new InvalidOperationException( "child indexes don't match; expected " + i + " found " + this.ChildIndex );
}
int n = this.ChildCount;
for ( int c = 0; c < n; c++ )
{
BaseTree child = (BaseTree)this.GetChild( c );
child.SanityCheckParentAndChildIndexes( this, c );
}
}
/** <summary>Walk upwards looking for ancestor with this token type.</summary> */
public virtual bool HasAncestor( int ttype )
{
return GetAncestor( ttype ) != null;
}
/** <summary>Walk upwards and get first ancestor with this token type.</summary> */
public virtual ITree GetAncestor( int ttype )
{
ITree t = this;
t = t.Parent;
while ( t != null )
{
if ( t.Type == ttype )
return t;
t = t.Parent;
}
return null;
}
/** <summary>
* Return a list of all ancestors of this node. The first node of
* list is the root and the last is the parent of this node.
* </summary>
*/
public virtual IList<ITree> GetAncestors()
{
if ( Parent == null )
return null;
List<ITree> ancestors = new List<ITree>();
ITree t = this;
t = t.Parent;
while ( t != null )
{
ancestors.Insert( 0, t ); // insert at start
t = t.Parent;
}
return ancestors;
}
/** <summary>Print out a whole tree not just a node</summary> */
public virtual string ToStringTree()
{
if ( Children == null || Children.Count == 0 )
{
return this.ToString();
}
StringBuilder buf = new StringBuilder();
if ( !IsNil )
{
buf.Append( "(" );
buf.Append( this.ToString() );
buf.Append( ' ' );
}
for ( int i = 0; Children != null && i < Children.Count; i++ )
{
ITree t = Children[i];
if ( i > 0 )
{
buf.Append( ' ' );
}
buf.Append( t.ToStringTree() );
}
if ( !IsNil )
{
buf.Append( ")" );
}
return buf.ToString();
}
/** <summary>Override to say how a node (not a tree) should look as text</summary> */
public override abstract string ToString();
#region Tree Members
public abstract ITree DupNode();
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Testing;
using Xunit;
namespace Microsoft.AspNetCore.Routing.Tests
{
public class RouteValueDictionaryTests
{
[Fact]
public void DefaultCtor_UsesEmptyStorage()
{
// Arrange
// Act
var dict = new RouteValueDictionary();
// Assert
Assert.Empty(dict);
Assert.Empty(dict._arrayStorage);
Assert.Null(dict._propertyStorage);
}
[Fact]
public void CreateFromNull_UsesEmptyStorage()
{
// Arrange
// Act
var dict = new RouteValueDictionary(null);
// Assert
Assert.Empty(dict);
Assert.Empty(dict._arrayStorage);
Assert.Null(dict._propertyStorage);
}
[Fact]
public void CreateFromRouteValueDictionary_WithArrayStorage_CopiesStorage()
{
// Arrange
var other = new RouteValueDictionary()
{
{ "1", 1 }
};
// Act
var dict = new RouteValueDictionary(other);
// Assert
Assert.Equal(other, dict);
Assert.Single(dict._arrayStorage);
Assert.Null(dict._propertyStorage);
var storage = Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
var otherStorage = Assert.IsType<KeyValuePair<string, object?>[]>(other._arrayStorage);
Assert.NotSame(otherStorage, storage);
}
[Fact]
public void CreateFromRouteValueDictionary_WithPropertyStorage_CopiesStorage()
{
// Arrange
var other = new RouteValueDictionary(new { key = "value" });
// Act
var dict = new RouteValueDictionary(other);
// Assert
Assert.Equal(other, dict);
AssertEmptyArrayStorage(dict);
var storage = dict._propertyStorage;
var otherStorage = other._propertyStorage;
Assert.Same(otherStorage, storage);
}
public static IEnumerable<object[]> IEnumerableKeyValuePairData
{
get
{
var routeValues = new[]
{
new KeyValuePair<string, object?>("Name", "James"),
new KeyValuePair<string, object?>("Age", 30),
new KeyValuePair<string, object?>("Address", new Address() { City = "Redmond", State = "WA" })
};
yield return new object[] { routeValues.ToDictionary(kvp => kvp.Key, kvp => kvp.Value) };
yield return new object[] { routeValues.ToList() };
yield return new object[] { routeValues };
}
}
public static IEnumerable<object[]> IEnumerableStringValuePairData
{
get
{
var routeValues = new[]
{
new KeyValuePair<string, string>("First Name", "James"),
new KeyValuePair<string, string>("Last Name", "Henrik"),
new KeyValuePair<string, string>("Middle Name", "Bob")
};
yield return new object[] { routeValues.ToDictionary(kvp => kvp.Key, kvp => kvp.Value) };
yield return new object[] { routeValues.ToList() };
yield return new object[] { routeValues };
}
}
[Theory]
[MemberData(nameof(IEnumerableKeyValuePairData))]
public void CreateFromIEnumerableKeyValuePair_CopiesValues(object values)
{
// Arrange & Act
var dict = new RouteValueDictionary(values);
// Assert
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
Assert.Collection(
dict.OrderBy(kvp => kvp.Key),
kvp =>
{
Assert.Equal("Address", kvp.Key);
var address = Assert.IsType<Address>(kvp.Value);
Assert.Equal("Redmond", address.City);
Assert.Equal("WA", address.State);
},
kvp => { Assert.Equal("Age", kvp.Key); Assert.Equal(30, kvp.Value); },
kvp => { Assert.Equal("Name", kvp.Key); Assert.Equal("James", kvp.Value); });
}
[Theory]
[MemberData(nameof(IEnumerableStringValuePairData))]
public void CreateFromIEnumerableStringValuePair_CopiesValues(object values)
{
// Arrange & Act
var dict = new RouteValueDictionary(values);
// Assert
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
Assert.Collection(
dict.OrderBy(kvp => kvp.Key),
kvp => { Assert.Equal("First Name", kvp.Key); Assert.Equal("James", kvp.Value); },
kvp => { Assert.Equal("Last Name", kvp.Key); Assert.Equal("Henrik", kvp.Value); },
kvp => { Assert.Equal("Middle Name", kvp.Key); Assert.Equal("Bob", kvp.Value); });
}
[Fact]
public void CreateFromIEnumerableKeyValuePair_ThrowsExceptionForDuplicateKey()
{
// Arrange
var values = new List<KeyValuePair<string, object?>>()
{
new KeyValuePair<string, object?>("name", "Billy"),
new KeyValuePair<string, object?>("Name", "Joey"),
};
// Act & Assert
ExceptionAssert.ThrowsArgument(
() => new RouteValueDictionary(values),
"key",
$"An element with the key 'Name' already exists in the {nameof(RouteValueDictionary)}.");
}
[Fact]
public void CreateFromIEnumerableStringValuePair_ThrowsExceptionForDuplicateKey()
{
// Arrange
var values = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("name", "Billy"),
new KeyValuePair<string, string>("Name", "Joey"),
};
// Act & Assert
ExceptionAssert.ThrowsArgument(
() => new RouteValueDictionary(values),
"key",
$"An element with the key 'Name' already exists in the {nameof(RouteValueDictionary)}.");
}
[Fact]
public void CreateFromObject_CopiesPropertiesFromAnonymousType()
{
// Arrange
var obj = new { cool = "beans", awesome = 123 };
// Act
var dict = new RouteValueDictionary(obj);
// Assert
Assert.NotNull(dict._propertyStorage);
Assert.Collection(
dict.OrderBy(kvp => kvp.Key),
kvp => { Assert.Equal("awesome", kvp.Key); Assert.Equal(123, kvp.Value); },
kvp => { Assert.Equal("cool", kvp.Key); Assert.Equal("beans", kvp.Value); });
}
[Fact]
public void CreateFromObject_CopiesPropertiesFromRegularType()
{
// Arrange
var obj = new RegularType() { CoolnessFactor = 73 };
// Act
var dict = new RouteValueDictionary(obj);
// Assert
Assert.NotNull(dict._propertyStorage);
Assert.Collection(
dict.OrderBy(kvp => kvp.Key),
kvp =>
{
Assert.Equal("CoolnessFactor", kvp.Key);
Assert.Equal(73, kvp.Value);
},
kvp =>
{
Assert.Equal("IsAwesome", kvp.Key);
var value = Assert.IsType<bool>(kvp.Value);
Assert.False(value);
});
}
[Fact]
public void CreateFromObject_CopiesPropertiesFromRegularType_PublicOnly()
{
// Arrange
var obj = new Visibility() { IsPublic = true, ItsInternalDealWithIt = 5 };
// Act
var dict = new RouteValueDictionary(obj);
// Assert
Assert.NotNull(dict._propertyStorage);
Assert.Collection(
dict.OrderBy(kvp => kvp.Key),
kvp =>
{
Assert.Equal("IsPublic", kvp.Key);
var value = Assert.IsType<bool>(kvp.Value);
Assert.True(value);
});
}
[Fact]
public void CreateFromObject_CopiesPropertiesFromRegularType_IgnoresStatic()
{
// Arrange
var obj = new StaticProperty();
// Act
var dict = new RouteValueDictionary(obj);
// Assert
Assert.NotNull(dict._propertyStorage);
AssertEmptyArrayStorage(dict);
Assert.Empty(dict);
}
[Fact]
public void CreateFromObject_CopiesPropertiesFromRegularType_IgnoresSetOnly()
{
// Arrange
var obj = new SetterOnly() { CoolSetOnly = false };
// Act
var dict = new RouteValueDictionary(obj);
// Assert
Assert.NotNull(dict._propertyStorage);
AssertEmptyArrayStorage(dict);
Assert.Empty(dict);
}
[Fact]
public void CreateFromObject_CopiesPropertiesFromRegularType_IncludesInherited()
{
// Arrange
var obj = new Derived() { TotallySweetProperty = true, DerivedProperty = false };
// Act
var dict = new RouteValueDictionary(obj);
// Assert
Assert.NotNull(dict._propertyStorage);
AssertEmptyArrayStorage(dict);
Assert.Collection(
dict.OrderBy(kvp => kvp.Key),
kvp =>
{
Assert.Equal("DerivedProperty", kvp.Key);
var value = Assert.IsType<bool>(kvp.Value);
Assert.False(value);
},
kvp =>
{
Assert.Equal("TotallySweetProperty", kvp.Key);
var value = Assert.IsType<bool>(kvp.Value);
Assert.True(value);
});
}
[Fact]
public void CreateFromObject_CopiesPropertiesFromRegularType_WithHiddenProperty()
{
// Arrange
var obj = new DerivedHiddenProperty() { DerivedProperty = 5 };
// Act
var dict = new RouteValueDictionary(obj);
// Assert
Assert.NotNull(dict._propertyStorage);
AssertEmptyArrayStorage(dict);
Assert.Collection(
dict.OrderBy(kvp => kvp.Key),
kvp => { Assert.Equal("DerivedProperty", kvp.Key); Assert.Equal(5, kvp.Value); });
}
[Fact]
public void CreateFromObject_CopiesPropertiesFromRegularType_WithIndexerProperty()
{
// Arrange
var obj = new IndexerProperty();
// Act
var dict = new RouteValueDictionary(obj);
// Assert
Assert.NotNull(dict._propertyStorage);
AssertEmptyArrayStorage(dict);
Assert.Empty(dict);
}
[Fact]
public void CreateFromObject_MixedCaseThrows()
{
// Arrange
var obj = new { controller = "Home", Controller = "Home" };
var message =
$"The type '{obj.GetType().FullName}' defines properties 'controller' and 'Controller' which differ " +
$"only by casing. This is not supported by {nameof(RouteValueDictionary)} which uses " +
$"case-insensitive comparisons.";
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(() =>
{
var dictionary = new RouteValueDictionary(obj);
});
// Ignoring case to make sure we're not testing reflection's ordering.
Assert.Equal(message, exception.Message, ignoreCase: true);
}
// Our comparer is hardcoded to be OrdinalIgnoreCase no matter what.
[Fact]
public void Comparer_IsOrdinalIgnoreCase()
{
// Arrange
// Act
var dict = new RouteValueDictionary();
// Assert
Assert.Same(StringComparer.OrdinalIgnoreCase, dict.Comparer);
}
// Our comparer is hardcoded to be IsReadOnly==false no matter what.
[Fact]
public void IsReadOnly_False()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
var result = ((ICollection<KeyValuePair<string, object?>>)dict).IsReadOnly;
// Assert
Assert.False(result);
}
[Fact]
public void IndexGet_EmptyStringIsAllowed()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
var value = dict[""];
// Assert
Assert.Null(value);
}
[Fact]
public void IndexGet_EmptyStorage_ReturnsNull()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
var value = dict["key"];
// Assert
Assert.Null(value);
}
[Fact]
public void IndexGet_PropertyStorage_NoMatch_ReturnsNull()
{
// Arrange
var dict = new RouteValueDictionary(new { age = 30 });
// Act
var value = dict["key"];
// Assert
Assert.Null(value);
Assert.NotNull(dict._propertyStorage);
}
[Fact]
public void IndexGet_PropertyStorage_Match_ReturnsValue()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
// Act
var value = dict["key"];
// Assert
Assert.Equal("value", value);
Assert.NotNull(dict._propertyStorage);
}
[Fact]
public void IndexGet_PropertyStorage_MatchIgnoreCase_ReturnsValue()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
// Act
var value = dict["kEy"];
// Assert
Assert.Equal("value", value);
Assert.NotNull(dict._propertyStorage);
}
[Fact]
public void IndexGet_ArrayStorage_NoMatch_ReturnsNull()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "age", 30 },
};
// Act
var value = dict["key"];
// Assert
Assert.Null(value);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void IndexGet_ListStorage_Match_ReturnsValue()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
var value = dict["key"];
// Assert
Assert.Equal("value", value);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void IndexGet_ListStorage_MatchIgnoreCase_ReturnsValue()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
var value = dict["kEy"];
// Assert
Assert.Equal("value", value);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void IndexSet_EmptyStringIsAllowed()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
dict[""] = "foo";
// Assert
Assert.Equal("foo", dict[""]);
}
[Fact]
public void IndexSet_EmptyStorage_UpgradesToList()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
dict["key"] = "value";
// Assert
Assert.Collection(dict, kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void IndexSet_PropertyStorage_NoMatch_AddsValue()
{
// Arrange
var dict = new RouteValueDictionary(new { age = 30 });
// Act
dict["key"] = "value";
// Assert
Assert.Collection(
dict.OrderBy(kvp => kvp.Key),
kvp => { Assert.Equal("age", kvp.Key); Assert.Equal(30, kvp.Value); },
kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void IndexSet_PropertyStorage_Match_SetsValue()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
// Act
dict["key"] = "value";
// Assert
Assert.Collection(dict, kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void IndexSet_PropertyStorage_MatchIgnoreCase_SetsValue()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
// Act
dict["kEy"] = "value";
// Assert
Assert.Collection(dict, kvp => { Assert.Equal("kEy", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void IndexSet_ListStorage_NoMatch_AddsValue()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "age", 30 },
};
// Act
dict["key"] = "value";
// Assert
Assert.Collection(
dict.OrderBy(kvp => kvp.Key),
kvp => { Assert.Equal("age", kvp.Key); Assert.Equal(30, kvp.Value); },
kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void IndexSet_ListStorage_Match_SetsValue()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
dict["key"] = "value";
// Assert
Assert.Collection(dict, kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void IndexSet_ListStorage_MatchIgnoreCase_SetsValue()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
dict["key"] = "value";
// Assert
Assert.Collection(dict, kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Count_EmptyStorage()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
var count = dict.Count;
// Assert
Assert.Equal(0, count);
}
[Fact]
public void Count_PropertyStorage()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value", });
// Act
var count = dict.Count;
// Assert
Assert.Equal(1, count);
Assert.NotNull(dict._propertyStorage);
}
[Fact]
public void Count_ListStorage()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
var count = dict.Count;
// Assert
Assert.Equal(1, count);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Keys_EmptyStorage()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
var keys = dict.Keys;
// Assert
Assert.Empty(keys);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Keys_PropertyStorage()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value", });
// Act
var keys = dict.Keys;
// Assert
Assert.Equal(new[] { "key" }, keys);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Keys_ListStorage()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
var keys = dict.Keys;
// Assert
Assert.Equal(new[] { "key" }, keys);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Values_EmptyStorage()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
var values = dict.Values;
// Assert
Assert.Empty(values);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Values_PropertyStorage()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value", });
// Act
var values = dict.Values;
// Assert
Assert.Equal(new object[] { "value" }, values);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Values_ListStorage()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
var values = dict.Values;
// Assert
Assert.Equal(new object[] { "value" }, values);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Add_EmptyStorage()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
dict.Add("key", "value");
// Assert
Assert.Collection(dict, kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Add_EmptyStringIsAllowed()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
dict.Add("", "foo");
// Assert
Assert.Equal("foo", dict[""]);
}
[Fact]
public void Add_PropertyStorage()
{
// Arrange
var dict = new RouteValueDictionary(new { age = 30 });
// Act
dict.Add("key", "value");
// Assert
Assert.Collection(
dict.OrderBy(kvp => kvp.Key),
kvp => { Assert.Equal("age", kvp.Key); Assert.Equal(30, kvp.Value); },
kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
// The upgrade from property -> array should make space for at least 4 entries
Assert.Collection(
dict._arrayStorage,
kvp => Assert.Equal(new KeyValuePair<string, object?>("age", 30), kvp),
kvp => Assert.Equal(new KeyValuePair<string, object?>("key", "value"), kvp),
kvp => Assert.Equal(default, kvp),
kvp => Assert.Equal(default, kvp));
}
[Fact]
public void Add_ListStorage()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "age", 30 },
};
// Act
dict.Add("key", "value");
// Assert
Assert.Collection(
dict.OrderBy(kvp => kvp.Key),
kvp => { Assert.Equal("age", kvp.Key); Assert.Equal(30, kvp.Value); },
kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Add_DuplicateKey()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
var message = $"An element with the key 'key' already exists in the {nameof(RouteValueDictionary)}";
// Act & Assert
ExceptionAssert.ThrowsArgument(() => dict.Add("key", "value2"), "key", message);
// Assert
Assert.Collection(
dict.OrderBy(kvp => kvp.Key),
kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Add_DuplicateKey_CaseInsensitive()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
var message = $"An element with the key 'kEy' already exists in the {nameof(RouteValueDictionary)}";
// Act & Assert
ExceptionAssert.ThrowsArgument(() => dict.Add("kEy", "value2"), "key", message);
// Assert
Assert.Collection(
dict.OrderBy(kvp => kvp.Key),
kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Add_KeyValuePair()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "age", 30 },
};
// Act
((ICollection<KeyValuePair<string, object?>>)dict).Add(new KeyValuePair<string, object?>("key", "value"));
// Assert
Assert.Collection(
dict.OrderBy(kvp => kvp.Key),
kvp => { Assert.Equal("age", kvp.Key); Assert.Equal(30, kvp.Value); },
kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Clear_EmptyStorage()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
dict.Clear();
// Assert
Assert.Empty(dict);
}
[Fact]
public void Clear_PropertyStorage_AlreadyEmpty()
{
// Arrange
var dict = new RouteValueDictionary(new { });
// Act
dict.Clear();
// Assert
Assert.Empty(dict);
Assert.NotNull(dict._propertyStorage);
AssertEmptyArrayStorage(dict);
}
[Fact]
public void Clear_PropertyStorage()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
// Act
dict.Clear();
// Assert
Assert.Empty(dict);
Assert.Null(dict._propertyStorage);
Assert.Empty(dict._arrayStorage);
}
[Fact]
public void Clear_ListStorage()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
dict.Clear();
// Assert
Assert.Empty(dict);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
Assert.Null(dict._propertyStorage);
}
[Fact]
public void Contains_ListStorage_KeyValuePair_True()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
var input = new KeyValuePair<string, object?>("key", "value");
// Act
var result = ((ICollection<KeyValuePair<string, object?>>)dict).Contains(input);
// Assert
Assert.True(result);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Contains_ListStory_KeyValuePair_True_CaseInsensitive()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
var input = new KeyValuePair<string, object?>("KEY", "value");
// Act
var result = ((ICollection<KeyValuePair<string, object?>>)dict).Contains(input);
// Assert
Assert.True(result);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Contains_ListStorage_KeyValuePair_False()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
var input = new KeyValuePair<string, object?>("other", "value");
// Act
var result = ((ICollection<KeyValuePair<string, object?>>)dict).Contains(input);
// Assert
Assert.False(result);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
// Value comparisons use the default equality comparer.
[Fact]
public void Contains_ListStorage_KeyValuePair_False_ValueComparisonIsDefault()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
var input = new KeyValuePair<string, object?>("key", "valUE");
// Act
var result = ((ICollection<KeyValuePair<string, object?>>)dict).Contains(input);
// Assert
Assert.False(result);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Contains_PropertyStorage_KeyValuePair_True()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
var input = new KeyValuePair<string, object?>("key", "value");
// Act
var result = ((ICollection<KeyValuePair<string, object?>>)dict).Contains(input);
// Assert
Assert.True(result);
Assert.NotNull(dict._propertyStorage);
AssertEmptyArrayStorage(dict);
Assert.Collection(
dict,
kvp => Assert.Equal(new KeyValuePair<string, object?>("key", "value"), kvp));
}
[Fact]
public void Contains_PropertyStory_KeyValuePair_True_CaseInsensitive()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
var input = new KeyValuePair<string, object?>("KEY", "value");
// Act
var result = ((ICollection<KeyValuePair<string, object?>>)dict).Contains(input);
// Assert
Assert.True(result);
Assert.NotNull(dict._propertyStorage);
AssertEmptyArrayStorage(dict);
Assert.Collection(
dict,
kvp => Assert.Equal(new KeyValuePair<string, object?>("key", "value"), kvp));
}
[Fact]
public void Contains_PropertyStorage_KeyValuePair_False()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
var input = new KeyValuePair<string, object?>("other", "value");
// Act
var result = ((ICollection<KeyValuePair<string, object?>>)dict).Contains(input);
// Assert
Assert.False(result);
Assert.NotNull(dict._propertyStorage);
AssertEmptyArrayStorage(dict);
Assert.Collection(
dict,
kvp => Assert.Equal(new KeyValuePair<string, object?>("key", "value"), kvp));
}
// Value comparisons use the default equality comparer.
[Fact]
public void Contains_PropertyStorage_KeyValuePair_False_ValueComparisonIsDefault()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
var input = new KeyValuePair<string, object?>("key", "valUE");
// Act
var result = ((ICollection<KeyValuePair<string, object?>>)dict).Contains(input);
// Assert
Assert.False(result);
Assert.NotNull(dict._propertyStorage);
AssertEmptyArrayStorage(dict);
Assert.Collection(
dict,
kvp => Assert.Equal(new KeyValuePair<string, object?>("key", "value"), kvp));
}
[Fact]
public void ContainsKey_EmptyStorage()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
var result = dict.ContainsKey("key");
// Assert
Assert.False(result);
}
[Fact]
public void ContainsKey_EmptyStringIsAllowed()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
var result = dict.ContainsKey("");
// Assert
Assert.False(result);
}
[Fact]
public void ContainsKey_PropertyStorage_False()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
// Act
var result = dict.ContainsKey("other");
// Assert
Assert.False(result);
Assert.NotNull(dict._propertyStorage);
AssertEmptyArrayStorage(dict);
}
[Fact]
public void ContainsKey_PropertyStorage_True()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
// Act
var result = dict.ContainsKey("key");
// Assert
Assert.True(result);
Assert.NotNull(dict._propertyStorage);
AssertEmptyArrayStorage(dict);
}
[Fact]
public void ContainsKey_PropertyStorage_True_CaseInsensitive()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
// Act
var result = dict.ContainsKey("kEy");
// Assert
Assert.True(result);
Assert.NotNull(dict._propertyStorage);
AssertEmptyArrayStorage(dict);
}
[Fact]
public void ContainsKey_ListStorage_False()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
var result = dict.ContainsKey("other");
// Assert
Assert.False(result);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void ContainsKey_ListStorage_True()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
var result = dict.ContainsKey("key");
// Assert
Assert.True(result);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void ContainsKey_ListStorage_True_CaseInsensitive()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
var result = dict.ContainsKey("kEy");
// Assert
Assert.True(result);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void CopyTo()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
var array = new KeyValuePair<string, object?>[2];
// Act
((ICollection<KeyValuePair<string, object?>>)dict).CopyTo(array, 1);
// Assert
Assert.Equal(
new KeyValuePair<string, object?>[]
{
default(KeyValuePair<string, object?>),
new KeyValuePair<string, object?>("key", "value")
},
array);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_KeyValuePair_True()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
var input = new KeyValuePair<string, object?>("key", "value");
// Act
var result = ((ICollection<KeyValuePair<string, object?>>)dict).Remove(input);
// Assert
Assert.True(result);
Assert.Empty(dict);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_KeyValuePair_True_CaseInsensitive()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
var input = new KeyValuePair<string, object?>("KEY", "value");
// Act
var result = ((ICollection<KeyValuePair<string, object?>>)dict).Remove(input);
// Assert
Assert.True(result);
Assert.Empty(dict);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_KeyValuePair_False()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
var input = new KeyValuePair<string, object?>("other", "value");
// Act
var result = ((ICollection<KeyValuePair<string, object?>>)dict).Remove(input);
// Assert
Assert.False(result);
Assert.Collection(dict, kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
// Value comparisons use the default equality comparer.
[Fact]
public void Remove_KeyValuePair_False_ValueComparisonIsDefault()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
var input = new KeyValuePair<string, object?>("key", "valUE");
// Act
var result = ((ICollection<KeyValuePair<string, object?>>)dict).Remove(input);
// Assert
Assert.False(result);
Assert.Collection(dict, kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_EmptyStorage()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
var result = dict.Remove("key");
// Assert
Assert.False(result);
}
[Fact]
public void Remove_EmptyStringIsAllowed()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
var result = dict.Remove("");
// Assert
Assert.False(result);
}
[Fact]
public void Remove_PropertyStorage_Empty()
{
// Arrange
var dict = new RouteValueDictionary(new { });
// Act
var result = dict.Remove("other");
// Assert
Assert.False(result);
Assert.Empty(dict);
Assert.NotNull(dict._propertyStorage);
}
[Fact]
public void Remove_PropertyStorage_False()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
// Act
var result = dict.Remove("other");
// Assert
Assert.False(result);
Assert.Collection(dict, kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_PropertyStorage_True()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
// Act
var result = dict.Remove("key");
// Assert
Assert.True(result);
Assert.Empty(dict);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_PropertyStorage_True_CaseInsensitive()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
// Act
var result = dict.Remove("kEy");
// Assert
Assert.True(result);
Assert.Empty(dict);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_ListStorage_False()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
var result = dict.Remove("other");
// Assert
Assert.False(result);
Assert.Collection(dict, kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_ListStorage_True()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
var result = dict.Remove("key");
// Assert
Assert.True(result);
Assert.Empty(dict);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_ListStorage_True_CaseInsensitive()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
var result = dict.Remove("kEy");
// Assert
Assert.True(result);
Assert.Empty(dict);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_KeyAndOutValue_EmptyStorage()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
var result = dict.Remove("key", out var removedValue);
// Assert
Assert.False(result);
Assert.Null(removedValue);
}
[Fact]
public void Remove_KeyAndOutValue_EmptyStringIsAllowed()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
var result = dict.Remove("", out var removedValue);
// Assert
Assert.False(result);
Assert.Null(removedValue);
}
[Fact]
public void Remove_KeyAndOutValue_PropertyStorage_Empty()
{
// Arrange
var dict = new RouteValueDictionary(new { });
// Act
var result = dict.Remove("other", out var removedValue);
// Assert
Assert.False(result);
Assert.Null(removedValue);
Assert.Empty(dict);
Assert.NotNull(dict._propertyStorage);
}
[Fact]
public void Remove_KeyAndOutValue_PropertyStorage_False()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
// Act
var result = dict.Remove("other", out var removedValue);
// Assert
Assert.False(result);
Assert.Null(removedValue);
Assert.Collection(dict, kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_KeyAndOutValue_PropertyStorage_True()
{
// Arrange
object value = "value";
var dict = new RouteValueDictionary(new { key = value });
// Act
var result = dict.Remove("key", out var removedValue);
// Assert
Assert.True(result);
Assert.Same(value, removedValue);
Assert.Empty(dict);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_KeyAndOutValue_PropertyStorage_True_CaseInsensitive()
{
// Arrange
object value = "value";
var dict = new RouteValueDictionary(new { key = value });
// Act
var result = dict.Remove("kEy", out var removedValue);
// Assert
Assert.True(result);
Assert.Same(value, removedValue);
Assert.Empty(dict);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_KeyAndOutValue_ListStorage_False()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
var result = dict.Remove("other", out var removedValue);
// Assert
Assert.False(result);
Assert.Null(removedValue);
Assert.Collection(dict, kvp => { Assert.Equal("key", kvp.Key); Assert.Equal("value", kvp.Value); });
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_KeyAndOutValue_ListStorage_True()
{
// Arrange
object value = "value";
var dict = new RouteValueDictionary()
{
{ "key", value }
};
// Act
var result = dict.Remove("key", out var removedValue);
// Assert
Assert.True(result);
Assert.Same(value, removedValue);
Assert.Empty(dict);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_KeyAndOutValue_ListStorage_True_CaseInsensitive()
{
// Arrange
object value = "value";
var dict = new RouteValueDictionary()
{
{ "key", value }
};
// Act
var result = dict.Remove("kEy", out var removedValue);
// Assert
Assert.True(result);
Assert.Same(value, removedValue);
Assert.Empty(dict);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_KeyAndOutValue_ListStorage_KeyExists_First()
{
// Arrange
object value = "value";
var dict = new RouteValueDictionary()
{
{ "key", value },
{ "other", 5 },
{ "dotnet", "rocks" }
};
// Act
var result = dict.Remove("key", out var removedValue);
// Assert
Assert.True(result);
Assert.Same(value, removedValue);
Assert.Equal(2, dict.Count);
Assert.False(dict.ContainsKey("key"));
Assert.True(dict.ContainsKey("other"));
Assert.True(dict.ContainsKey("dotnet"));
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_KeyAndOutValue_ListStorage_KeyExists_Middle()
{
// Arrange
object value = "value";
var dict = new RouteValueDictionary()
{
{ "other", 5 },
{ "key", value },
{ "dotnet", "rocks" }
};
// Act
var result = dict.Remove("key", out var removedValue);
// Assert
Assert.True(result);
Assert.Same(value, removedValue);
Assert.Equal(2, dict.Count);
Assert.False(dict.ContainsKey("key"));
Assert.True(dict.ContainsKey("other"));
Assert.True(dict.ContainsKey("dotnet"));
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void Remove_KeyAndOutValue_ListStorage_KeyExists_Last()
{
// Arrange
object value = "value";
var dict = new RouteValueDictionary()
{
{ "other", 5 },
{ "dotnet", "rocks" },
{ "key", value }
};
// Act
var result = dict.Remove("key", out var removedValue);
// Assert
Assert.True(result);
Assert.Same(value, removedValue);
Assert.Equal(2, dict.Count);
Assert.False(dict.ContainsKey("key"));
Assert.True(dict.ContainsKey("other"));
Assert.True(dict.ContainsKey("dotnet"));
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void TryAdd_EmptyStringIsAllowed()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
var result = dict.TryAdd("", "foo");
// Assert
Assert.True(result);
}
[Fact]
public void TryAdd_PropertyStorage_KeyDoesNotExist_ConvertsPropertyStorageToArrayStorage()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value", });
// Act
var result = dict.TryAdd("otherKey", "value");
// Assert
Assert.True(result);
Assert.Null(dict._propertyStorage);
Assert.Collection(
dict._arrayStorage,
kvp => Assert.Equal(new KeyValuePair<string, object?>("key", "value"), kvp),
kvp => Assert.Equal(new KeyValuePair<string, object?>("otherKey", "value"), kvp),
kvp => Assert.Equal(default, kvp),
kvp => Assert.Equal(default, kvp));
}
[Fact]
public void TryAdd_PropertyStory_KeyExist_DoesNotConvertPropertyStorageToArrayStorage()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value", });
// Act
var result = dict.TryAdd("key", "value");
// Assert
Assert.False(result);
AssertEmptyArrayStorage(dict);
Assert.NotNull(dict._propertyStorage);
Assert.Collection(
dict,
kvp => Assert.Equal(new KeyValuePair<string, object?>("key", "value"), kvp));
}
[Fact]
public void TryAdd_EmptyStorage_CanAdd()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
var result = dict.TryAdd("key", "value");
// Assert
Assert.True(result);
Assert.Collection(
dict._arrayStorage,
kvp => Assert.Equal(new KeyValuePair<string, object?>("key", "value"), kvp),
kvp => Assert.Equal(default, kvp),
kvp => Assert.Equal(default, kvp),
kvp => Assert.Equal(default, kvp));
}
[Fact]
public void TryAdd_ArrayStorage_CanAdd()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key0", "value0" },
};
// Act
var result = dict.TryAdd("key1", "value1");
// Assert
Assert.True(result);
Assert.Collection(
dict._arrayStorage,
kvp => Assert.Equal(new KeyValuePair<string, object?>("key0", "value0"), kvp),
kvp => Assert.Equal(new KeyValuePair<string, object?>("key1", "value1"), kvp),
kvp => Assert.Equal(default, kvp),
kvp => Assert.Equal(default, kvp));
}
[Fact]
public void TryAdd_ArrayStorage_CanAddWithResize()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key0", "value0" },
{ "key1", "value1" },
{ "key2", "value2" },
{ "key3", "value3" },
};
// Act
var result = dict.TryAdd("key4", "value4");
// Assert
Assert.True(result);
Assert.Collection(
dict._arrayStorage,
kvp => Assert.Equal(new KeyValuePair<string, object?>("key0", "value0"), kvp),
kvp => Assert.Equal(new KeyValuePair<string, object?>("key1", "value1"), kvp),
kvp => Assert.Equal(new KeyValuePair<string, object?>("key2", "value2"), kvp),
kvp => Assert.Equal(new KeyValuePair<string, object?>("key3", "value3"), kvp),
kvp => Assert.Equal(new KeyValuePair<string, object?>("key4", "value4"), kvp),
kvp => Assert.Equal(default, kvp),
kvp => Assert.Equal(default, kvp),
kvp => Assert.Equal(default, kvp));
}
[Fact]
public void TryAdd_ArrayStorage_DoesNotAddWhenKeyIsPresent()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key0", "value0" },
};
// Act
var result = dict.TryAdd("key0", "value1");
// Assert
Assert.False(result);
Assert.Collection(
dict._arrayStorage,
kvp => Assert.Equal(new KeyValuePair<string, object?>("key0", "value0"), kvp),
kvp => Assert.Equal(default, kvp),
kvp => Assert.Equal(default, kvp),
kvp => Assert.Equal(default, kvp));
}
[Fact]
public void TryGetValue_EmptyStorage()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
var result = dict.TryGetValue("key", out var value);
// Assert
Assert.False(result);
Assert.Null(value);
}
[Fact]
public void TryGetValue_EmptyStringIsAllowed()
{
// Arrange
var dict = new RouteValueDictionary();
// Act
var result = dict.TryGetValue("", out var value);
// Assert
Assert.False(result);
Assert.Null(value);
}
[Fact]
public void TryGetValue_PropertyStorage_False()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
// Act
var result = dict.TryGetValue("other", out var value);
// Assert
Assert.False(result);
Assert.Null(value);
Assert.NotNull(dict._propertyStorage);
}
[Fact]
public void TryGetValue_PropertyStorage_True()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
// Act
var result = dict.TryGetValue("key", out var value);
// Assert
Assert.True(result);
Assert.Equal("value", value);
Assert.NotNull(dict._propertyStorage);
}
[Fact]
public void TryGetValue_PropertyStorage_True_CaseInsensitive()
{
// Arrange
var dict = new RouteValueDictionary(new { key = "value" });
// Act
var result = dict.TryGetValue("kEy", out var value);
// Assert
Assert.True(result);
Assert.Equal("value", value);
Assert.NotNull(dict._propertyStorage);
}
[Fact]
public void TryGetValue_ListStorage_False()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
var result = dict.TryGetValue("other", out var value);
// Assert
Assert.False(result);
Assert.Null(value);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void TryGetValue_ListStorage_True()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
var result = dict.TryGetValue("key", out var value);
// Assert
Assert.True(result);
Assert.Equal("value", value);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void TryGetValue_ListStorage_True_CaseInsensitive()
{
// Arrange
var dict = new RouteValueDictionary()
{
{ "key", "value" },
};
// Act
var result = dict.TryGetValue("kEy", out var value);
// Assert
Assert.True(result);
Assert.Equal("value", value);
Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
}
[Fact]
public void ListStorage_DynamicallyAdjustsCapacity()
{
// Arrange
var dict = new RouteValueDictionary();
// Act 1
dict.Add("key", "value");
// Assert 1
var storage = Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
Assert.Equal(4, storage.Length);
// Act 2
dict.Add("key2", "value2");
dict.Add("key3", "value3");
dict.Add("key4", "value4");
dict.Add("key5", "value5");
// Assert 2
storage = Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
Assert.Equal(8, storage.Length);
}
[Fact]
public void ListStorage_RemoveAt_RearrangesInnerArray()
{
// Arrange
var dict = new RouteValueDictionary();
dict.Add("key", "value");
dict.Add("key2", "value2");
dict.Add("key3", "value3");
// Assert 1
var storage = Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
Assert.Equal(3, dict.Count);
// Act
dict.Remove("key2");
// Assert 2
storage = Assert.IsType<KeyValuePair<string, object?>[]>(dict._arrayStorage);
Assert.Equal(2, dict.Count);
Assert.Equal("key", storage[0].Key);
Assert.Equal("value", storage[0].Value);
Assert.Equal("key3", storage[1].Key);
Assert.Equal("value3", storage[1].Value);
}
[Fact]
public void FromArray_TakesOwnershipOfArray()
{
// Arrange
var array = new KeyValuePair<string, object?>[]
{
new KeyValuePair<string, object?>("a", 0),
new KeyValuePair<string, object?>("b", 1),
new KeyValuePair<string, object?>("c", 2),
};
var dictionary = RouteValueDictionary.FromArray(array);
// Act - modifying the array should modify the dictionary
array[0] = new KeyValuePair<string, object?>("aa", 10);
// Assert
Assert.Equal(3, dictionary.Count);
Assert.Equal(10, dictionary["aa"]);
}
[Fact]
public void FromArray_EmptyArray()
{
// Arrange
var array = Array.Empty<KeyValuePair<string, object?>>();
// Act
var dictionary = RouteValueDictionary.FromArray(array);
// Assert
Assert.Empty(dictionary);
}
[Fact]
public void FromArray_RemovesGapsInArray()
{
// Arrange
var array = new KeyValuePair<string, object?>[]
{
new KeyValuePair<string, object?>(null!, null),
new KeyValuePair<string, object?>("a", 0),
new KeyValuePair<string, object?>(null!, null),
new KeyValuePair<string, object?>(null!, null),
new KeyValuePair<string, object?>("b", 1),
new KeyValuePair<string, object?>("c", 2),
new KeyValuePair<string, object?>("d", 3),
new KeyValuePair<string, object?>(null!, null),
};
// Act - calling From should modify the array
var dictionary = RouteValueDictionary.FromArray(array);
// Assert
Assert.Equal(4, dictionary.Count);
Assert.Equal(
new KeyValuePair<string, object?>[]
{
new KeyValuePair<string, object?>("d", 3),
new KeyValuePair<string, object?>("a", 0),
new KeyValuePair<string, object?>("c", 2),
new KeyValuePair<string, object?>("b", 1),
new KeyValuePair<string, object?>(null!, null),
new KeyValuePair<string, object?>(null!, null),
new KeyValuePair<string, object?>(null!, null),
new KeyValuePair<string, object?>(null!, null),
},
array);
}
private void AssertEmptyArrayStorage(RouteValueDictionary value)
{
Assert.Same(Array.Empty<KeyValuePair<string, object?>>(), value._arrayStorage);
}
private class RegularType
{
public bool IsAwesome { get; set; }
public int CoolnessFactor { get; set; }
}
private class Visibility
{
private string? PrivateYo { get; set; }
internal int ItsInternalDealWithIt { get; set; }
public bool IsPublic { get; set; }
}
private class StaticProperty
{
public static bool IsStatic { get; set; }
}
private class SetterOnly
{
private bool _coolSetOnly;
public bool CoolSetOnly { set { _coolSetOnly = value; } }
}
private class Base
{
public bool DerivedProperty { get; set; }
}
private class Derived : Base
{
public bool TotallySweetProperty { get; set; }
}
private class DerivedHiddenProperty : Base
{
public new int DerivedProperty { get; set; }
}
private class IndexerProperty
{
public bool this[string key]
{
get { return false; }
set { }
}
}
private class Address
{
public string? City { get; set; }
public string? State { get; set; }
}
}
}
| |
/********************************************************
* ADO.NET 2.0 Data Provider for SQLite Version 3.X
* Written by Robert Simpson ([email protected])
*
* Released to the public domain, use at your own risk!
********************************************************/
namespace Mono.Data.Sqlite
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Globalization;
/// <summary>
/// This abstract class is designed to handle user-defined functions easily. An instance of the derived class is made for each
/// connection to the database.
/// </summary>
/// <remarks>
/// Although there is one instance of a class derived from SqliteFunction per database connection, the derived class has no access
/// to the underlying connection. This is necessary to deter implementers from thinking it would be a good idea to make database
/// calls during processing.
///
/// It is important to distinguish between a per-connection instance, and a per-SQL statement context. One instance of this class
/// services all SQL statements being stepped through on that connection, and there can be many. One should never store per-statement
/// information in member variables of user-defined function classes.
///
/// For aggregate functions, always create and store your per-statement data in the contextData object on the 1st step. This data will
/// be automatically freed for you (and Dispose() called if the item supports IDisposable) when the statement completes.
/// </remarks>
public abstract class SqliteFunction : IDisposable
{
private class AggregateData
{
internal int _count = 1;
internal object _data = null;
}
/// <summary>
/// The base connection this function is attached to
/// </summary>
internal SQLiteBase _base;
/// <summary>
/// Internal array used to keep track of aggregate function context data
/// </summary>
private Dictionary<long, AggregateData> _contextDataList;
/// <summary>
/// Holds a reference to the callback function for user functions
/// </summary>
private SQLiteCallback _InvokeFunc;
/// <summary>
/// Holds a reference to the callbakc function for stepping in an aggregate function
/// </summary>
private SQLiteCallback _StepFunc;
/// <summary>
/// Holds a reference to the callback function for finalizing an aggregate function
/// </summary>
private SQLiteFinalCallback _FinalFunc;
/// <summary>
/// Holds a reference to the callback function for collation sequences
/// </summary>
private SQLiteCollation _CompareFunc;
private SQLiteCollation _CompareFunc16;
/// <summary>
/// Current context of the current callback. Only valid during a callback
/// </summary>
internal IntPtr _context;
/// <summary>
/// This static list contains all the user-defined functions declared using the proper attributes.
/// </summary>
private static List<SqliteFunctionAttribute> _registeredFunctions = new List<SqliteFunctionAttribute>();
/// <summary>
/// Internal constructor, initializes the function's internal variables.
/// </summary>
protected SqliteFunction()
{
_contextDataList = new Dictionary<long, AggregateData>();
}
/// <summary>
/// Returns a reference to the underlying connection's SqliteConvert class, which can be used to convert
/// strings and DateTime's into the current connection's encoding schema.
/// </summary>
public SqliteConvert SqliteConvert
{
get
{
return _base;
}
}
/// <summary>
/// Scalar functions override this method to do their magic.
/// </summary>
/// <remarks>
/// Parameters passed to functions have only an affinity for a certain data type, there is no underlying schema available
/// to force them into a certain type. Therefore the only types you will ever see as parameters are
/// DBNull.Value, Int64, Double, String or byte[] array.
/// </remarks>
/// <param name="args">The arguments for the command to process</param>
/// <returns>You may return most simple types as a return value, null or DBNull.Value to return null, DateTime, or
/// you may return an Exception-derived class if you wish to return an error to SQLite. Do not actually throw the error,
/// just return it!</returns>
public virtual object Invoke(object[] args)
{
return null;
}
/// <summary>
/// Aggregate functions override this method to do their magic.
/// </summary>
/// <remarks>
/// Typically you'll be updating whatever you've placed in the contextData field and returning as quickly as possible.
/// </remarks>
/// <param name="args">The arguments for the command to process</param>
/// <param name="stepNumber">The 1-based step number. This is incrememted each time the step method is called.</param>
/// <param name="contextData">A placeholder for implementers to store contextual data pertaining to the current context.</param>
public virtual void Step(object[] args, int stepNumber, ref object contextData)
{
}
/// <summary>
/// Aggregate functions override this method to finish their aggregate processing.
/// </summary>
/// <remarks>
/// If you implemented your aggregate function properly,
/// you've been recording and keeping track of your data in the contextData object provided, and now at this stage you should have
/// all the information you need in there to figure out what to return.
/// NOTE: It is possible to arrive here without receiving a previous call to Step(), in which case the contextData will
/// be null. This can happen when no rows were returned. You can either return null, or 0 or some other custom return value
/// if that is the case.
/// </remarks>
/// <param name="contextData">Your own assigned contextData, provided for you so you can return your final results.</param>
/// <returns>You may return most simple types as a return value, null or DBNull.Value to return null, DateTime, or
/// you may return an Exception-derived class if you wish to return an error to SQLite. Do not actually throw the error,
/// just return it!
/// </returns>
public virtual object Final(object contextData)
{
return null;
}
/// <summary>
/// User-defined collation sequences override this method to provide a custom string sorting algorithm.
/// </summary>
/// <param name="param1">The first string to compare</param>
/// <param name="param2">The second strnig to compare</param>
/// <returns>1 if param1 is greater than param2, 0 if they are equal, or -1 if param1 is less than param2</returns>
public virtual int Compare(string param1, string param2)
{
return 0;
}
/// <summary>
/// Converts an IntPtr array of context arguments to an object array containing the resolved parameters the pointers point to.
/// </summary>
/// <remarks>
/// Parameters passed to functions have only an affinity for a certain data type, there is no underlying schema available
/// to force them into a certain type. Therefore the only types you will ever see as parameters are
/// DBNull.Value, Int64, Double, String or byte[] array.
/// </remarks>
/// <param name="nArgs">The number of arguments</param>
/// <param name="argsptr">A pointer to the array of arguments</param>
/// <returns>An object array of the arguments once they've been converted to .NET values</returns>
internal object[] ConvertParams(int nArgs, IntPtr argsptr)
{
object[] parms = new object[nArgs];
#if !PLATFORM_COMPACTFRAMEWORK
IntPtr[] argint = new IntPtr[nArgs];
#else
int[] argint = new int[nArgs];
#endif
Marshal.Copy(argsptr, argint, 0, nArgs);
for (int n = 0; n < nArgs; n++)
{
switch (_base.GetParamValueType((IntPtr)argint[n]))
{
case TypeAffinity.Null:
parms[n] = DBNull.Value;
break;
case TypeAffinity.Int64:
parms[n] = _base.GetParamValueInt64((IntPtr)argint[n]);
break;
case TypeAffinity.Double:
parms[n] = _base.GetParamValueDouble((IntPtr)argint[n]);
break;
case TypeAffinity.Text:
parms[n] = _base.GetParamValueText((IntPtr)argint[n]);
break;
case TypeAffinity.Blob:
{
int x;
byte[] blob;
x = (int)_base.GetParamValueBytes((IntPtr)argint[n], 0, null, 0, 0);
blob = new byte[x];
_base.GetParamValueBytes((IntPtr)argint[n], 0, blob, 0, x);
parms[n] = blob;
}
break;
case TypeAffinity.DateTime: // Never happens here but what the heck, maybe it will one day.
parms[n] = _base.ToDateTime(_base.GetParamValueText((IntPtr)argint[n]));
break;
}
}
return parms;
}
/// <summary>
/// Takes the return value from Invoke() and Final() and figures out how to return it to SQLite's context.
/// </summary>
/// <param name="context">The context the return value applies to</param>
/// <param name="returnValue">The parameter to return to SQLite</param>
void SetReturnValue(IntPtr context, object returnValue)
{
if (returnValue == null || returnValue == DBNull.Value)
{
_base.ReturnNull(context);
return;
}
Type t = returnValue.GetType();
if (t == typeof(DateTime))
{
_base.ReturnText(context, _base.ToString((DateTime)returnValue));
return;
}
else
{
Exception r = returnValue as Exception;
if (r != null)
{
_base.ReturnError(context, r.Message);
return;
}
}
switch (SqliteConvert.TypeToAffinity(t))
{
case TypeAffinity.Null:
_base.ReturnNull(context);
return;
case TypeAffinity.Int64:
_base.ReturnInt64(context, Convert.ToInt64(returnValue, CultureInfo.CurrentCulture));
return;
case TypeAffinity.Double:
_base.ReturnDouble(context, Convert.ToDouble(returnValue, CultureInfo.CurrentCulture));
return;
case TypeAffinity.Text:
_base.ReturnText(context, returnValue.ToString());
return;
case TypeAffinity.Blob:
_base.ReturnBlob(context, (byte[])returnValue);
return;
}
}
/// <summary>
/// Internal scalar callback function, which wraps the raw context pointer and calls the virtual Invoke() method.
/// </summary>
/// <param name="context">A raw context pointer</param>
/// <param name="nArgs">Number of arguments passed in</param>
/// <param name="argsptr">A pointer to the array of arguments</param>
internal void ScalarCallback(IntPtr context, int nArgs, IntPtr argsptr)
{
_context = context;
SetReturnValue(context, Invoke(ConvertParams(nArgs, argsptr)));
}
/// <summary>
/// Internal collation sequence function, which wraps up the raw string pointers and executes the Compare() virtual function.
/// </summary>
/// <param name="ptr">Not used</param>
/// <param name="len1">Length of the string pv1</param>
/// <param name="ptr1">Pointer to the first string to compare</param>
/// <param name="len2">Length of the string pv2</param>
/// <param name="ptr2">Pointer to the second string to compare</param>
/// <returns>Returns -1 if the first string is less than the second. 0 if they are equal, or 1 if the first string is greater
/// than the second.</returns>
internal int CompareCallback(IntPtr ptr, int len1, IntPtr ptr1, int len2, IntPtr ptr2)
{
return Compare(SqliteConvert.UTF8ToString(ptr1, len1), SqliteConvert.UTF8ToString(ptr2, len2));
}
internal int CompareCallback16(IntPtr ptr, int len1, IntPtr ptr1, int len2, IntPtr ptr2)
{
return Compare(SQLite3_UTF16.UTF16ToString(ptr1, len1), SQLite3_UTF16.UTF16ToString(ptr2, len2));
}
/// <summary>
/// The internal aggregate Step function callback, which wraps the raw context pointer and calls the virtual Step() method.
/// </summary>
/// <remarks>
/// This function takes care of doing the lookups and getting the important information put together to call the Step() function.
/// That includes pulling out the user's contextData and updating it after the call is made. We use a sorted list for this so
/// binary searches can be done to find the data.
/// </remarks>
/// <param name="context">A raw context pointer</param>
/// <param name="nArgs">Number of arguments passed in</param>
/// <param name="argsptr">A pointer to the array of arguments</param>
internal void StepCallback(IntPtr context, int nArgs, IntPtr argsptr)
{
long nAux;
AggregateData data;
nAux = (long)_base.AggregateContext(context);
if (_contextDataList.TryGetValue(nAux, out data) == false)
{
data = new AggregateData();
_contextDataList[nAux] = data;
}
try
{
_context = context;
Step(ConvertParams(nArgs, argsptr), data._count, ref data._data);
}
finally
{
data._count++;
}
}
/// <summary>
/// An internal aggregate Final function callback, which wraps the context pointer and calls the virtual Final() method.
/// </summary>
/// <param name="context">A raw context pointer</param>
internal void FinalCallback(IntPtr context)
{
long n = (long)_base.AggregateContext(context);
object obj = null;
if (_contextDataList.ContainsKey(n))
{
obj = _contextDataList[n]._data;
_contextDataList.Remove(n);
}
_context = context;
SetReturnValue(context, Final(obj));
IDisposable disp = obj as IDisposable;
if (disp != null) disp.Dispose();
}
/// <summary>
/// Placeholder for a user-defined disposal routine
/// </summary>
/// <param name="disposing">True if the object is being disposed explicitly</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
IDisposable disp;
foreach (KeyValuePair<long, AggregateData> kv in _contextDataList)
{
disp = kv.Value._data as IDisposable;
if (disp != null)
disp.Dispose();
}
_contextDataList.Clear();
_InvokeFunc = null;
_StepFunc = null;
_FinalFunc = null;
_CompareFunc = null;
_base = null;
_contextDataList = null;
}
}
/// <summary>
/// Disposes of any active contextData variables that were not automatically cleaned up. Sometimes this can happen if
/// someone closes the connection while a DataReader is open.
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// Using reflection, enumerate all assemblies in the current appdomain looking for classes that
/// have a SqliteFunctionAttribute attribute, and registering them accordingly.
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[global::System.Security.Permissions.FileIOPermission(global::System.Security.Permissions.SecurityAction.Assert, AllFiles = global::System.Security.Permissions.FileIOPermissionAccess.PathDiscovery)]
#endif
static SqliteFunction()
{
try
{
#if !PLATFORM_COMPACTFRAMEWORK
SqliteFunctionAttribute at;
System.Reflection.Assembly[] arAssemblies = System.AppDomain.CurrentDomain.GetAssemblies();
int w = arAssemblies.Length;
System.Reflection.AssemblyName sqlite = System.Reflection.Assembly.GetCallingAssembly().GetName();
for (int n = 0; n < w; n++)
{
Type[] arTypes;
bool found = false;
System.Reflection.AssemblyName[] references;
try
{
// Inspect only assemblies that reference SQLite
references = arAssemblies[n].GetReferencedAssemblies();
int t = references.Length;
for (int z = 0; z < t; z++)
{
if (references[z].Name == sqlite.Name)
{
found = true;
break;
}
}
if (found == false)
continue;
arTypes = arAssemblies[n].GetTypes();
}
catch (global::System.Reflection.ReflectionTypeLoadException e)
{
arTypes = e.Types;
}
int v = arTypes.Length;
for (int x = 0; x < v; x++)
{
if (arTypes[x] == null) continue;
object[] arAtt = arTypes[x].GetCustomAttributes(typeof(SqliteFunctionAttribute), false);
int u = arAtt.Length;
for (int y = 0; y < u; y++)
{
at = arAtt[y] as SqliteFunctionAttribute;
if (at != null)
{
at._instanceType = arTypes[x];
_registeredFunctions.Add(at);
}
}
}
}
#endif
}
catch // SQLite provider can continue without being able to find built-in functions
{
}
}
/// <summary>
/// Manual method of registering a function. The type must still have the SqliteFunctionAttributes in order to work
/// properly, but this is a workaround for the Compact Framework where enumerating assemblies is not currently supported.
/// </summary>
/// <param name="typ">The type of the function to register</param>
public static void RegisterFunction(Type typ)
{
object[] arAtt = typ.GetCustomAttributes(typeof(SqliteFunctionAttribute), false);
int u = arAtt.Length;
SqliteFunctionAttribute at;
for (int y = 0; y < u; y++)
{
at = arAtt[y] as SqliteFunctionAttribute;
if (at != null)
{
at._instanceType = typ;
_registeredFunctions.Add(at);
}
}
}
/// <summary>
/// Called by SQLiteBase derived classes, this function binds all user-defined functions to a connection.
/// It is done this way so that all user-defined functions will access the database using the same encoding scheme
/// as the connection (UTF-8 or UTF-16).
/// </summary>
/// <remarks>
/// The wrapper functions that interop with SQLite will create a unique cookie value, which internally is a pointer to
/// all the wrapped callback functions. The interop function uses it to map CDecl callbacks to StdCall callbacks.
/// </remarks>
/// <param name="sqlbase">The base object on which the functions are to bind</param>
/// <returns>Returns an array of functions which the connection object should retain until the connection is closed.</returns>
internal static SqliteFunction[] BindFunctions(SQLiteBase sqlbase)
{
SqliteFunction f;
List<SqliteFunction> lFunctions = new List<SqliteFunction>();
foreach (SqliteFunctionAttribute pr in _registeredFunctions)
{
f = (SqliteFunction)Activator.CreateInstance(pr._instanceType);
f._base = sqlbase;
f._InvokeFunc = (pr.FuncType == FunctionType.Scalar) ? new SQLiteCallback(f.ScalarCallback) : null;
f._StepFunc = (pr.FuncType == FunctionType.Aggregate) ? new SQLiteCallback(f.StepCallback) : null;
f._FinalFunc = (pr.FuncType == FunctionType.Aggregate) ? new SQLiteFinalCallback(f.FinalCallback) : null;
f._CompareFunc = (pr.FuncType == FunctionType.Collation) ? new SQLiteCollation(f.CompareCallback) : null;
f._CompareFunc16 = (pr.FuncType == FunctionType.Collation) ? new SQLiteCollation(f.CompareCallback16) : null;
if (pr.FuncType != FunctionType.Collation)
sqlbase.CreateFunction(pr.Name, pr.Arguments, (f is SqliteFunctionEx), f._InvokeFunc, f._StepFunc, f._FinalFunc);
else {
#if MONOTOUCH
GCHandle handle = GCHandle.Alloc (f);
sqlbase.CreateCollation(pr.Name, collation_callback, collation_callback16, GCHandle.ToIntPtr (handle));
#else
sqlbase.CreateCollation(pr.Name, f._CompareFunc, f._CompareFunc16, IntPtr.Zero);
#endif
}
lFunctions.Add(f);
}
SqliteFunction[] arFunctions = new SqliteFunction[lFunctions.Count];
lFunctions.CopyTo(arFunctions, 0);
return arFunctions;
}
#if MONOTOUCH
[MonoTouch.MonoPInvokeCallback (typeof (SQLiteCollation))]
internal static int collation_callback (IntPtr puser, int len1, IntPtr pv1, int len2, IntPtr pv2)
{
var handle = GCHandle.FromIntPtr (puser);
var func = (SqliteFunction) handle.Target;
return func._CompareFunc (IntPtr.Zero, len1, pv1, len2, pv2);
}
[MonoTouch.MonoPInvokeCallback (typeof (SQLiteCollation))]
internal static int collation_callback16 (IntPtr puser, int len1, IntPtr pv1, int len2, IntPtr pv2)
{
var handle = GCHandle.FromIntPtr (puser);
var func = (SqliteFunction) handle.Target;
return func._CompareFunc16 (IntPtr.Zero, len1, pv1, len2, pv2);
}
#endif
}
/// <summary>
/// Extends SqliteFunction and allows an inherited class to obtain the collating sequence associated with a function call.
/// </summary>
/// <remarks>
/// User-defined functions can call the GetCollationSequence() method in this class and use it to compare strings and char arrays.
/// </remarks>
public class SqliteFunctionEx : SqliteFunction
{
/// <summary>
/// Obtains the collating sequence in effect for the given function.
/// </summary>
/// <returns></returns>
protected CollationSequence GetCollationSequence()
{
return _base.GetCollationSequence(this, _context);
}
}
/// <summary>
/// The type of user-defined function to declare
/// </summary>
public enum FunctionType
{
/// <summary>
/// Scalar functions are designed to be called and return a result immediately. Examples include ABS(), Upper(), Lower(), etc.
/// </summary>
Scalar = 0,
/// <summary>
/// Aggregate functions are designed to accumulate data until the end of a call and then return a result gleaned from the accumulated data.
/// Examples include SUM(), COUNT(), AVG(), etc.
/// </summary>
Aggregate = 1,
/// <summary>
/// Collation sequences are used to sort textual data in a custom manner, and appear in an ORDER BY clause. Typically text in an ORDER BY is
/// sorted using a straight case-insensitive comparison function. Custom collating sequences can be used to alter the behavior of text sorting
/// in a user-defined manner.
/// </summary>
Collation = 2,
}
/// <summary>
/// An internal callback delegate declaration.
/// </summary>
/// <param name="context">Raw context pointer for the user function</param>
/// <param name="nArgs">Count of arguments to the function</param>
/// <param name="argsptr">A pointer to the array of argument pointers</param>
#if !PLATFORM_COMPACTFRAMEWORK
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
#endif
internal delegate void SQLiteCallback(IntPtr context, int nArgs, IntPtr argsptr);
/// <summary>
/// An internal final callback delegate declaration.
/// </summary>
/// <param name="context">Raw context pointer for the user function</param>
#if !PLATFORM_COMPACTFRAMEWORK
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
#endif
internal delegate void SQLiteFinalCallback(IntPtr context);
/// <summary>
/// Internal callback delegate for implementing collation sequences
/// </summary>
/// <param name="puser">Not used</param>
/// <param name="len1">Length of the string pv1</param>
/// <param name="pv1">Pointer to the first string to compare</param>
/// <param name="len2">Length of the string pv2</param>
/// <param name="pv2">Pointer to the second string to compare</param>
/// <returns>Returns -1 if the first string is less than the second. 0 if they are equal, or 1 if the first string is greater
/// than the second.</returns>
#if !PLATFORM_COMPACTFRAMEWORK
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
#endif
internal delegate int SQLiteCollation(IntPtr puser, int len1, IntPtr pv1, int len2, IntPtr pv2);
/// <summary>
/// The type of collating sequence
/// </summary>
public enum CollationTypeEnum
{
/// <summary>
/// The built-in BINARY collating sequence
/// </summary>
Binary = 1,
/// <summary>
/// The built-in NOCASE collating sequence
/// </summary>
NoCase = 2,
/// <summary>
/// The built-in REVERSE collating sequence
/// </summary>
Reverse = 3,
/// <summary>
/// A custom user-defined collating sequence
/// </summary>
Custom = 0,
}
/// <summary>
/// The encoding type the collation sequence uses
/// </summary>
public enum CollationEncodingEnum
{
/// <summary>
/// The collation sequence is UTF8
/// </summary>
UTF8 = 1,
/// <summary>
/// The collation sequence is UTF16 little-endian
/// </summary>
UTF16LE = 2,
/// <summary>
/// The collation sequence is UTF16 big-endian
/// </summary>
UTF16BE = 3,
}
/// <summary>
/// A struct describing the collating sequence a function is executing in
/// </summary>
public struct CollationSequence
{
/// <summary>
/// The name of the collating sequence
/// </summary>
public string Name;
/// <summary>
/// The type of collating sequence
/// </summary>
public CollationTypeEnum Type;
/// <summary>
/// The text encoding of the collation sequence
/// </summary>
public CollationEncodingEnum Encoding;
/// <summary>
/// Context of the function that requested the collating sequence
/// </summary>
internal SqliteFunction _func;
/// <summary>
/// Calls the base collating sequence to compare two strings
/// </summary>
/// <param name="s1">The first string to compare</param>
/// <param name="s2">The second string to compare</param>
/// <returns>-1 if s1 is less than s2, 0 if s1 is equal to s2, and 1 if s1 is greater than s2</returns>
public int Compare(string s1, string s2)
{
return _func._base.ContextCollateCompare(Encoding, _func._context, s1, s2);
}
/// <summary>
/// Calls the base collating sequence to compare two character arrays
/// </summary>
/// <param name="c1">The first array to compare</param>
/// <param name="c2">The second array to compare</param>
/// <returns>-1 if c1 is less than c2, 0 if c1 is equal to c2, and 1 if c1 is greater than c2</returns>
public int Compare(char[] c1, char[] c2)
{
return _func._base.ContextCollateCompare(Encoding, _func._context, c1, c2);
}
}
}
| |
/*
* Moba Camera Script v1.1
* - created by Jacob Penner 2013
*
* Notes:
* - Enabling useFixedUpdate may make camera jumpy when being locked
* to a target.
* - Boundaries dont restrict on the y axis
*
* Plans:
* - Add following of terrain for camera height
* - Add ability to have camera look towards a target location
* - Add terrain height following
*
* Version:
* v1.1
* - Removed the boundary list from the MobaCamera script
* - Created a separate static class that will contain all boundary and do calculations.
* - Created a Boundary component that can be attach to a boundary that will automaticly add it to the boundary list
* - Added cube boundaries are able to be rotated on their Y axis
* - Boundaries can now be both cubes and spheres
* - Added Axes and Buttons to use the Input Manager instead of KeyCodes
* - Added Option to turn on and off use of KeyCodes
*
* v0.5
* -Organized Code structure
* -Fixed SetCameraRotation function
* -Restrict Camera X rotation on range from -89 to 89
* -Added property for currentCameraRotation
* -Added property for currentCameraZoomAmount
* -Can now set the CameraRotation and CameraZoomAmount at runtime with the
* corresponding properties
*
* v0.4
* -Fixed issue with camera colliding with boundaries when locked to target
*
* v0.3
* -Added boundaries
* -Added defualt height value to camera
* -Allow Camera to Change height value form defult to the locked target's height
*
* v0.2
* -Changed Handling of Player Input with rotation
* -Changed Handling of Player Input with zoom
* -fix offset calculation for rotation
* -Added Helper classes for better organization
*
*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
////////////////////////////////////////////////////////////////////////////////////////////////////
// Helper Classes
[System.Serializable]
public class Moba_Camera_Requirements
{
// Objects that are requirements for the script to work
public Transform pivot = null;
public Transform offset = null;
public Camera camera = null;
}
[System.Serializable]
public class Moba_Camera_KeyCodes
{
// Allows camera to be rotated while pressed
public KeyCode RotateCamera = KeyCode.Mouse2;
// Toggle lock camera to lockTargetTransform position
public KeyCode LockCamera = KeyCode.L;
// Lock camera to lockTargetTransform position while being pressed
public KeyCode characterFocus = KeyCode.Space;
// Move camera based on camera direction
public KeyCode CameraMoveLeft = KeyCode.LeftArrow;
public KeyCode CameraMoveRight = KeyCode.RightArrow;
public KeyCode CameraMoveForward = KeyCode.UpArrow;
public KeyCode CameraMoveBackward = KeyCode.DownArrow;
}
[System.Serializable]
public class Moba_Camera_Axis {
// Input Axis
public string DeltaScrollWheel = "Mouse ScrollWheel";
public string DeltaMouseHorizontal = "Mouse X";
public string DeltaMouseVertical = "Mouse Y";
// Allows camera to be rotated while pressed
public string button_rotate_camera = "Moba Rotate Camera";
// Toggle lock camera to lockTargetTransform position
public string button_lock_camera = "Moba Lock Camera";
// Lock camera to lockTargetTransform position while being pressed
public string button_char_focus = "Moba Char Focus";
// Move camera based on camera direction
public string button_camera_move_left = "Moba Camera Move Left";
public string button_camera_move_right = "Moba Camera Move Right";
public string button_camera_move_forward = "Moba Camera Move Forward";
public string button_camera_move_backward = "Moba Camera Move Backward";
}
[System.Serializable]
public class Moba_Camera_Inputs {
// set to true for quick testing with keycodes
// set to false for use with Input Manager
public bool useKeyCodeInputs = true;
public Moba_Camera_KeyCodes keycodes = new Moba_Camera_KeyCodes();
public Moba_Camera_Axis axis = new Moba_Camera_Axis();
}
[System.Serializable]
public class Moba_Camera_Settings
{
// Is the camera restricted to only inside boundaries
public bool useBoundaries = true;
// Is the camera locked to a target
public bool cameraLocked = false;
// Target for camera to move to when locked
public Transform lockTargetTransform = null;
// Helper classes for organization
public Moba_Camera_Settings_Movement movement = new Moba_Camera_Settings_Movement();
public Moba_Camera_Settings_Rotation rotation = new Moba_Camera_Settings_Rotation();
public Moba_Camera_Settings_Zoom zoom = new Moba_Camera_Settings_Zoom();
}
[System.Serializable]
public class Moba_Camera_Settings_Movement {
// The rate the camera will transition from its current position to target
public float lockTransitionRate = 0.1f;
// How fast the camera moves
public float cameraMovementRate = 1.0f;
// Does camera move if mouse is near the edge of the screen
public bool edgeHoverMovement = true;
// The Distance from the edge of the screen
public float edgeHoverOffset = 10.0f;
// The defualt value for the height of the pivot y position
public float defualtHeight = 0.0f;
// Will set the pivot's y position to the defualtHeight when true
public bool useDefualtHeight = true;
// Uses the lock targets y position when camera locked is true
public bool useLockTargetHeight = true;
}
[System.Serializable]
public class Moba_Camera_Settings_Rotation {
// Zoom rate does not change based on speed of mouse
public bool constRotationRate = false;
// Lock the rotations axies
public bool lockRotationX = true;
public bool lockRotationY = true;
// rotation that is used when the game starts
public Vector2 defualtRotation = new Vector2(-45.0f, 0.0f);
// How fast the camera rotates
public Vector2 cameraRotationRate = new Vector2(100.0f, 100.0f);
}
[System.Serializable]
public class Moba_Camera_Settings_Zoom {
// Changed direction zoomed
public bool invertZoom = false;
// Starting Zoom value
public float defaultZoom = 15.0f;
// Minimum and Maximum zoom values
public float minZoom = 10.0f;
public float maxZoom = 20.0f;
// How fast the camera zooms in and out
public float zoomRate = 10.0f;
// Zoom rate does not chance based on scroll speed
public bool constZoomRate = false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Moba_Camera Class
public class Moba_Camera : MonoBehaviour {
// Use fixed update
public bool useFixedUpdate = false;
// Helper classes
public Moba_Camera_Requirements requirements = new Moba_Camera_Requirements();
public Moba_Camera_Inputs inputs = new Moba_Camera_Inputs();
public Moba_Camera_Settings settings = new Moba_Camera_Settings();
// The Current Zoom value for the camera; Not shown in Inspector
private float _currentZoomAmount = 0.0f;
public float currentZoomAmount {
get {
return _currentZoomAmount;
}
set {
_currentZoomAmount = value;
changeInCamera = true;
}
}
// the current Camera Rotation
private Vector2 _currentCameraRotation = Vector3.zero;
public Vector3 currentCameraRotation {
get {
return _currentCameraRotation;
}
set {
_currentCameraRotation = value;
changeInCamera = true;
}
}
// True if either the zoom amount or the rotation value changed
private bool changeInCamera = true;
// The amount the mouse has to move before the camera is rotated
// Only Used when constRotation rate is true
private float deltaMouseDeadZone = 0.2f;
// Constant values
private const float MAXROTATIONXAXIS = 89.0f;
private const float MINROTATIONXAXIS = -89.0f;
// Use this for initialization
void Start () {
if(!requirements.pivot || !requirements.offset || !requirements.camera) {
string missingRequirements = "";
if(requirements.pivot == null) {
missingRequirements += " / Pivot";
this.enabled = false;
}
if(requirements.offset == null) {
missingRequirements += " / Offset";
this.enabled = false;
}
if(requirements.camera == null) {
missingRequirements += " / Camera";
this.enabled = false;
}
Debug.LogWarning("Moba_Camera Requirements Missing" + missingRequirements + ". Add missing objects to the requirement tab under the Moba_camera script in the Inspector.");
Debug.LogWarning("Moba_Camera script requires two empty gameobjects, Pivot and Offset, and a camera." +
"Parent the Offset to the Pivot and the Camera to the Offset. See the Moba_Camera Readme for more information on setup.");
}
// set values to the defualt values
_currentZoomAmount = settings.zoom.defaultZoom;
_currentCameraRotation = settings.rotation.defualtRotation;
// if using the defualt height
if(settings.movement.useDefualtHeight && this.enabled) {
// set the pivots height to the defualt height
Vector3 tempPos = requirements.pivot.transform.position;
tempPos.y = settings.movement.defualtHeight;
requirements.pivot.transform.position = tempPos;
}
}
// Update is called once per frame
void Update() {
if(!useFixedUpdate) {
CameraUpdate();
}
}
// Update is called once per frame
void FixedUpdate () {
if(useFixedUpdate) {
CameraUpdate();
}
}
// Called from Update or FixedUpdate Depending on value of useFixedUpdate
void CameraUpdate()
{
CalculateCameraZoom();
CalculateCameraRotation();
CalculateCameraMovement();
CalculateCameraUpdates();
CalculateCameraBoundaries();
}
void CalculateCameraZoom() {
////////////////////////////////////////////////////////////////////////////////////////////////////
// Camera Zoom In/Out
float zoomChange = 0.0f;
int inverted = 1;
float mouseScrollWheel = Input.GetAxis(inputs.axis.DeltaScrollWheel);
if(mouseScrollWheel != 0.0f)
{
// Set the a camera value has changed
changeInCamera = true;
if(settings.zoom.constZoomRate) {
if(mouseScrollWheel != 0.0) {
if(mouseScrollWheel > 0.0) zoomChange = 1;
else zoomChange = -1;
}
}
else {
zoomChange = mouseScrollWheel;
}
}
// change the zoom amount based on if zoom is inverted
if(!settings.zoom.invertZoom) inverted = -1;
_currentZoomAmount += zoomChange * settings.zoom.zoomRate * inverted * Time.deltaTime;
}
void CalculateCameraRotation() {
////////////////////////////////////////////////////////////////////////////////////////////////////
// Camera rotate
float changeInRotationX = 0.0f;
float changeInRotationY = 0.0f;
Screen.lockCursor = false;
if((inputs.useKeyCodeInputs)?
(Input.GetKey(inputs.keycodes.RotateCamera)&&inputs.useKeyCodeInputs):
(Input.GetButton(inputs.axis.button_rotate_camera))) {
// Lock the cursor to the center of the screen and hide the cursor
Screen.lockCursor = true;
if(!settings.rotation.lockRotationX) {
float deltaMouseVertical = Input.GetAxis(inputs.axis.DeltaMouseVertical);
if(deltaMouseVertical != 0.0) {
if(settings.rotation.constRotationRate) {
if(deltaMouseVertical > deltaMouseDeadZone) changeInRotationX = 1.0f;
else if(deltaMouseVertical < -deltaMouseDeadZone) changeInRotationX = -1.0f;
}
else {
changeInRotationX = deltaMouseVertical;
}
changeInCamera = true;
}
}
if(!settings.rotation.lockRotationY) {
float deltaMouseHorizontal = Input.GetAxis(inputs.axis.DeltaMouseHorizontal);
if(deltaMouseHorizontal != 0.0f) {
if(settings.rotation.constRotationRate) {
if(deltaMouseHorizontal > deltaMouseDeadZone) changeInRotationY = 1.0f;
else if(deltaMouseHorizontal < -deltaMouseDeadZone) changeInRotationY = -1.0f;
}
else {
changeInRotationY = deltaMouseHorizontal;
}
changeInCamera = true;
}
}
}
// apply change in Y rotation
_currentCameraRotation.y += changeInRotationY * settings.rotation.cameraRotationRate.y * Time.deltaTime;
_currentCameraRotation.x += changeInRotationX * settings.rotation.cameraRotationRate.x * Time.deltaTime;
}
void CalculateCameraMovement() {
////////////////////////////////////////////////////////////////////////////////////////////////////
// Camera Movement : When mouse is near the screens edge
// Lock / Unlock camera movement
if((inputs.useKeyCodeInputs)?
(Input.GetKeyDown(inputs.keycodes.LockCamera)):
(Input.GetButtonDown(inputs.axis.button_lock_camera)) &&
settings.lockTargetTransform != null)
{
if(settings.lockTargetTransform != null)
{
//flip bool value
settings.cameraLocked = !settings.cameraLocked;
}
}
// if camera is locked or if character focus, set move pivot to target
if(settings.lockTargetTransform != null && (settings.cameraLocked ||
((inputs.useKeyCodeInputs)?
(Input.GetKey(inputs.keycodes.characterFocus)):
(Input.GetButton(inputs.axis.button_char_focus)))))
{
Vector3 target = settings.lockTargetTransform.position;
if((requirements.pivot.position - target).magnitude > 0.2f) {
if(settings.movement.useDefualtHeight
&& !settings.movement.useLockTargetHeight)
{
target.y = settings.movement.defualtHeight;
}
else if (!settings.movement.useLockTargetHeight)
{
target.y = requirements.pivot.position.y;
}
// Lerp between the target and current position
requirements.pivot.position = Vector3.Lerp(requirements.pivot.position, target, settings.movement.lockTransitionRate);
}
}
else
{
Vector3 movementVector = new Vector3(0,0,0);
// Move camera when mouse is near the edge of the screen
if((Input.mousePosition.x < settings.movement.edgeHoverOffset && settings.movement.edgeHoverMovement)
|| ((inputs.useKeyCodeInputs)?
(Input.GetKey(inputs.keycodes.CameraMoveLeft)):
(Input.GetButton(inputs.axis.button_camera_move_left))))
{
movementVector += requirements.pivot.transform.right;
}
if((Input.mousePosition.x > Screen.width - settings.movement.edgeHoverOffset && settings.movement.edgeHoverMovement)
|| ((inputs.useKeyCodeInputs)?
(Input.GetKey(inputs.keycodes.CameraMoveRight)):
(Input.GetButton(inputs.axis.button_camera_move_right))))
{
movementVector -= requirements.pivot.transform.right;
}
if((Input.mousePosition.y < settings.movement.edgeHoverOffset && settings.movement.edgeHoverMovement)
|| ((inputs.useKeyCodeInputs)?
(Input.GetKey(inputs.keycodes.CameraMoveBackward)):
(Input.GetButton(inputs.axis.button_camera_move_backward))))
{
movementVector += requirements.pivot.transform.forward;
}
if((Input.mousePosition.y > Screen.height - settings.movement.edgeHoverOffset && settings.movement.edgeHoverMovement)
|| ((inputs.useKeyCodeInputs)?
(Input.GetKey(inputs.keycodes.CameraMoveForward)):
(Input.GetButton(inputs.axis.button_camera_move_forward))))
{
movementVector -= requirements.pivot.transform.forward;
}
requirements.pivot.position += movementVector.normalized * settings.movement.cameraMovementRate * Time.deltaTime;
// Lerp between the z position if magnitude is greater than value
Vector3 target = Vector3.zero;
Vector3 current = new Vector3(0, requirements.pivot.position.y, 0);
if(settings.movement.useDefualtHeight)
target.y = settings.movement.defualtHeight;
else
target.y = requirements.pivot.position.y;
if((target - current).magnitude > 0.2f){
Vector3 shift = Vector3.Lerp(current, target, settings.movement.lockTransitionRate);
requirements.pivot.position = new Vector3(requirements.pivot.position.x, shift.y, requirements.pivot.position.z);
}
}
}
void CalculateCameraUpdates() {
////////////////////////////////////////////////////////////////////////////////////////////////////
// Update the camera position relative to the pivot if there was a change in the camera transforms
// if there is no change in the camera exit update
if(!changeInCamera) return;
// Check if the fMaxZoomVal is greater than the fMinZoomVal
if(settings.zoom.maxZoom < settings.zoom.minZoom)
settings.zoom.maxZoom = settings.zoom.minZoom + 1;
// Check if Camera Zoom is between the min and max
if(_currentZoomAmount < settings.zoom.minZoom)
_currentZoomAmount = settings.zoom.minZoom;
if(_currentZoomAmount > settings.zoom.maxZoom)
_currentZoomAmount = settings.zoom.maxZoom;
// Restrict rotation X value
if(_currentCameraRotation.x > MAXROTATIONXAXIS)
_currentCameraRotation.x = MAXROTATIONXAXIS;
else if(_currentCameraRotation.x < MINROTATIONXAXIS)
_currentCameraRotation.x = MINROTATIONXAXIS;
// Calculate the new position of the camera
// rotate pivot by the change int camera
Vector3 forwardRotation = Quaternion.AngleAxis(_currentCameraRotation.y, Vector3.up) * Vector3.forward;
requirements.pivot.transform.rotation = Quaternion.LookRotation(forwardRotation);
//requirements.pivot.transform.Rotate(Vector3.up, changeInRotationY);
Vector3 CamVec = requirements.pivot.transform.TransformDirection(Vector3.forward);
// Apply Camera Rotations
CamVec = Quaternion.AngleAxis(_currentCameraRotation.x, requirements.pivot.transform.TransformDirection(Vector3.right)) * CamVec;
//CamVec = Quaternion.AngleAxis(_currentCameraRotation.y, Vector3.up) * CamVec;
// Move camera along CamVec by ZoomAmount
requirements.offset.position = CamVec * _currentZoomAmount + requirements.pivot.position;
// Make Camera look at the pivot
requirements.offset.transform.LookAt(requirements.pivot);
// reset the change in camera value to false
changeInCamera = false;
}
void CalculateCameraBoundaries() {
if(settings.useBoundaries && !
((inputs.useKeyCodeInputs)?
(Input.GetKey(inputs.keycodes.CameraMoveRight)):
(Input.GetButton(inputs.axis.button_camera_move_right))))
{
// check if the pivot is not in a boundary
if(!Moba_Camera_Boundaries.isPointInBoundary(requirements.pivot.position)) {
// Get the closet boundary to the pivot
Moba_Camera_Boundary boundary = Moba_Camera_Boundaries.GetClosestBoundary(requirements.pivot.position);
if(boundary != null) {
// set the pivot's position to the closet point on the boundary
requirements.pivot.position = Moba_Camera_Boundaries.GetClosestPointOnBoundary(boundary, requirements.pivot.position);
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Class functions
//////////////////////////////////////////////////////////////////////////////////////////
// Set Variables from outside script
public void SetTargetTransform(Transform t) {
if(transform != null) {
settings.lockTargetTransform = t;
}
}
public void SetCameraRotation(Vector2 rotation) {
currentCameraRotation = new Vector2(rotation.x, rotation.y);
}
public void SetCameraRotation(float x, float y) {
currentCameraRotation = new Vector2(x, y);
}
public void SetCameraZoom(float amount) {
currentZoomAmount = amount;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Get Variables from outside script
public Camera GetCamera() {
return requirements.camera;
}
}
| |
//---------------------------------------------------------------------
// This file is part of the CLR Managed Debugger (mdbg) Sample.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//---------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Threading;
using Microsoft.Samples.Tools.Mdbg;
using Microsoft.Samples.Debugging.MdbgEngine;
using Microsoft.Samples.Debugging.CorDebug;
using IronPython.Hosting;
using IronPython.Compiler;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Exceptions;
class ConsoleOptions : EngineOptions
{
internal static int AutoIndentSize = 0;
}
/// <summary>
/// Class controlling the MDbg python interactive command line.
/// </summary>
public class PythonCommandLine
{
private static StringBuilder b = new StringBuilder();
private PythonEngine engine;
private IConsole console;
public PythonCommandLine(PythonEngine pEngine)
{
engine = pEngine;
if (typeof(IMDbgIO3).IsAssignableFrom(CommandBase.Shell.IO.GetType()))
{
console = new MDbgSuperConsole(engine, false);
}
else
{
console = new MDbgBasicConsole();
}
}
// Act on single line of python interactive input.
public void Execute(string line)
{
if ((line == null) || (line == "exit"))
{
console.WriteLine("type pyout to exit python interactive mode", Style.Error);
return;
}
b.Append(line);
b.Append("\n");
bool allowIncompleteStatement = !TreatAsBlankLine(line, 4);
try
{
bool s = engine.ParseInteractiveInput(b.ToString(), allowIncompleteStatement);
if (s)
{
engine.ExecuteToConsole(b.ToString());
b = new StringBuilder();
}
}
catch (Exception e)
{
console.WriteLine(e.Message, Style.Error);
b = new StringBuilder();
}
}
// Run python interactive input loop.
public void RunInteractive()
{
string line = console.ReadLine(ConsoleOptions.AutoIndentSize);
while (line != "pyout")
{
Execute(line);
line = console.ReadLine(ConsoleOptions.AutoIndentSize);
}
}
private static bool TreatAsBlankLine(string line, int autoIndentSize)
{
if (line.Length == 0) return true;
if (autoIndentSize != 0 && line.Trim().Length == 0 && line.Length == autoIndentSize)
{
return true;
}
return false;
}
}
public interface IConsole
{
// Read a single line of interactive input
// AutoIndentSize is the indentation level to be used for the current suite of a compound statement.
// The console can ignore this argument if it does not want to support auto-indentation
string ReadLine(int autoIndentSize);
// Write text to console with no new line.
void Write(string text, Style style);
// Write text to console with new line.
void WriteLine(string text, Style style);
}
public enum Style
{
Prompt, Out, Error
}
/// <summary>
/// Basic console for interactive python input in MDbg. Does not support tab completion.
/// </summary>
public class MDbgBasicConsole : IConsole
{
private static bool dotPrompt = false;
// Read a single line of interactive input
// AutoIndentSize is the indentation level to be used for the current suite of a compound statement.
// The console can ignore this argument if it does not want to support auto-indentation
public string ReadLine(int autoIndentSize)
{
string text;
if (dotPrompt) Console.Write("... ");
else Console.Write(">>> ");
CommandBase.Shell.IO.ReadCommand(out text);
text = text.TrimEnd();
if (text.Length == 0)
{
dotPrompt = false;
}
else if (text[text.Length - 1] == ':')
{
dotPrompt = true;
}
return text;
}
public void Write(string text, Style style)
{
CommandBase.Write(GetMDbgWriteStyle(style), text);
}
public void WriteLine(string text, Style style)
{
// Call into MDbg
CommandBase.WriteOutput(GetMDbgWriteStyle(style), text);
}
// Map from IronPython.Hosting.Style --> Mdbg console.
// This determines how console output is formatted.
string GetMDbgWriteStyle(Style style)
{
if (style == Style.Error)
return MDbgOutputConstants.StdError;
else
return MDbgOutputConstants.StdOutput;
}
}
/// <summary>
/// Console for interactive Python input in MDbg. Supports tab completion.
/// </summary>
public class MDbgSuperConsole : IConsole
{
public ConsoleColor PromptColor = Console.ForegroundColor;
public ConsoleColor OutColor = Console.ForegroundColor;
public ConsoleColor ErrorColor = Console.ForegroundColor;
private static bool dotPrompt = false;
public void SetupColors()
{
PromptColor = ConsoleColor.DarkGray;
OutColor = ConsoleColor.DarkBlue;
ErrorColor = ConsoleColor.DarkRed;
}
/// <summary>
/// Class managing the command history.
/// </summary>
class History
{
protected ArrayList list = new ArrayList();
protected int current = 0;
public int Count
{
get
{
return list.Count;
}
}
public string Current
{
get
{
return current >= 0 && current < list.Count ? (string)list[current] : String.Empty;
}
}
public void Clear()
{
list.Clear();
current = -1;
}
public void Add(string line)
{
if (line != null && line.Length > 0)
{
list.Add(line);
}
}
public void AddLast(string line)
{
if (line != null && line.Length > 0)
{
current = list.Add(line) + 1;
}
}
public string First()
{
current = 0;
return Current;
}
public string Last()
{
current = list.Count - 1;
return Current;
}
public string Previous()
{
if (list.Count > 0)
{
current = ((current - 1) + list.Count) % list.Count;
}
return Current;
}
public string Next()
{
if (list.Count > 0)
{
current = (current + 1) % list.Count;
}
return Current;
}
}
/// <summary>
/// List of available options
/// </summary>
class SuperConsoleOptions : History
{
private string root;
public string Root
{
get
{
return root;
}
set
{
root = value;
}
}
}
/// <summary>
/// Cursor position management
/// </summary>
struct Cursor
{
/// <summary>
/// Beginning position of the cursor - top coordinate.
/// </summary>
private int anchorTop;
/// <summary>
/// Beginning position of the cursor - left coordinate.
/// </summary>
private int anchorLeft;
public int Top
{
get
{
return anchorTop;
}
}
public int Left
{
get
{
return anchorLeft;
}
}
public void Anchor()
{
anchorTop = Console.CursorTop;
anchorLeft = Console.CursorLeft;
}
public void Reset()
{
Console.CursorTop = anchorTop;
Console.CursorLeft = anchorLeft;
}
public void Place(int index)
{
Console.CursorLeft = (anchorLeft + index) % Console.BufferWidth;
int cursorTop = anchorTop + (anchorLeft + index) / Console.BufferWidth;
if (cursorTop >= Console.BufferHeight)
{
anchorTop -= cursorTop - Console.BufferHeight + 1;
cursorTop = Console.BufferHeight - 1;
}
Console.CursorTop = cursorTop;
}
public void Move(int delta)
{
int position = Console.CursorTop * Console.BufferWidth + Console.CursorLeft + delta;
Console.CursorLeft = position % Console.BufferWidth;
Console.CursorTop = position / Console.BufferWidth;
}
};
/// <summary>
/// The console input buffer.
/// </summary>
private StringBuilder input = new StringBuilder();
/// <summary>
/// Current position - index into the input buffer
/// </summary>
private int current = 0;
/// <summary>
/// The number of white-spaces displayed for the auto-indenation of the current line
/// </summary>
private int autoIndentSize = 0;
/// <summary>
/// Length of the output currently rendered on screen.
/// </summary>
private int rendered = 0;
/// <summary>
/// Input has changed.
/// </summary>
private bool changed = true;
/// <summary>
/// Command history
/// </summary>
private History history = new History();
/// <summary>
/// Tab options available in current context
/// </summary>
private SuperConsoleOptions options = new SuperConsoleOptions();
/// <summary>
/// Cursort anchor - position of cursor when the routine was called
/// </summary>
Cursor cursor;
/// <summary>
/// Python Engine reference. Used for the tab-completion lookup.
/// </summary>
private PythonEngine engine;
private AutoResetEvent ctrlCEvent;
private Thread MainEngineThread = Thread.CurrentThread;
public MDbgSuperConsole(PythonEngine engine, bool colorfulConsole)
{
this.engine = engine;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
ctrlCEvent = new AutoResetEvent(false);
if (colorfulConsole)
{
SetupColors();
}
}
void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
if (e.SpecialKey == ConsoleSpecialKey.ControlC)
{
e.Cancel = true;
ctrlCEvent.Set();
MainEngineThread.Abort(new PythonKeyboardInterruptException(""));
}
}
private bool GetOptions()
{
options.Clear();
int len;
for (len = input.Length; len > 0; len--)
{
char c = input[len - 1];
if (Char.IsLetterOrDigit(c))
{
continue;
}
else if (c == '.' || c == '_')
{
continue;
}
else
{
break;
}
}
string name = input.ToString(len, input.Length - len);
if (name.Trim().Length > 0)
{
int lastDot = name.LastIndexOf('.');
string attr, pref, root;
if (lastDot < 0)
{
attr = String.Empty;
pref = name;
root = input.ToString(0, len);
}
else
{
attr = name.Substring(0, lastDot);
pref = name.Substring(lastDot + 1);
root = input.ToString(0, len + lastDot + 1);
}
try
{
IEnumerable result = engine.Evaluate(String.Format("dir({0})", attr)) as IEnumerable;
options.Root = root;
foreach (string option in result)
{
if (option.StartsWith(pref, StringComparison.CurrentCultureIgnoreCase))
{
options.Add(option);
}
}
}
catch
{
options.Clear();
}
return true;
}
else
{
return false;
}
}
private void SetInput(string line)
{
input.Length = 0;
input.Append(line);
current = input.Length;
Render();
}
private void Initialize()
{
cursor.Anchor();
input.Length = 0;
current = 0;
rendered = 0;
changed = false;
}
// Check if the user is backspacing the auto-indentation. In that case, we go back all the way to
// the previous indentation level.
// Return true if we did backspace the auto-indenation.
private bool BackspaceAutoIndentation()
{
if (input.Length == 0 || input.Length > autoIndentSize) return false;
// Is the auto-indenation all white space, or has the user since edited the auto-indentation?
for (int i = 0; i < input.Length; i++)
{
if (input[i] != ' ') return false;
}
// Calculate the previous indentation level
int newLength = ((input.Length - 1) / ConsoleOptions.AutoIndentSize) * ConsoleOptions.AutoIndentSize;
int backspaceSize = input.Length - newLength;
input.Remove(newLength, backspaceSize);
current -= backspaceSize;
Render();
return true;
}
private void Backspace()
{
if (BackspaceAutoIndentation()) return;
if (input.Length > 0 && current > 0)
{
input.Remove(current - 1, 1);
current--;
Render();
}
}
private void Delete()
{
if (input.Length > 0 && current < input.Length)
{
input.Remove(current, 1);
Render();
}
}
private void Insert(ConsoleKeyInfo key)
{
char c;
if (key.Key == ConsoleKey.F6)
{
Debug.Assert(FinalLineText.Length == 1);
c = FinalLineText[0];
}
else
{
c = key.KeyChar;
}
Insert(c);
}
private void Insert(char c)
{
if (current == input.Length)
{
if (Char.IsControl(c))
{
string s = MapCharacter(c);
current++;
input.Append(c);
CommandBase.Write(s);
rendered += s.Length;
}
else
{
current++;
input.Append(c);
CommandBase.Write(new string(new char[] { c }));
rendered++;
}
}
else
{
input.Insert(current, c);
current++;
Render();
}
}
private string MapCharacter(char c)
{
if (c == 13) return "\r\n";
if (c <= 26) return "^" + ((char)(c + 'A' - 1)).ToString();
return "^?";
}
private int GetCharacterSize(char c)
{
if (Char.IsControl(c))
{
return MapCharacter(c).Length;
}
else
{
return 1;
}
}
private void Render()
{
cursor.Reset();
StringBuilder output = new StringBuilder();
int position = -1;
for (int i = 0; i < input.Length; i++)
{
if (i == current)
{
position = output.Length;
}
char c = input[i];
if (Char.IsControl(c))
{
output.Append(MapCharacter(c));
}
else
{
output.Append(c);
}
}
if (current == input.Length)
{
position = output.Length;
}
string text = output.ToString();
CommandBase.Write(text);
if (text.Length < rendered)
{
CommandBase.Write(new String(' ', rendered - text.Length));
}
rendered = text.Length;
cursor.Place(position);
}
private void MoveLeft(ConsoleModifiers keyModifiers)
{
if ((keyModifiers & ConsoleModifiers.Control) != 0)
{
// move back to the start of the previous word
if (input.Length > 0 && current != 0)
{
bool nonLetter = IsSeperator(input[current - 1]);
while (current > 0 && (current - 1 < input.Length))
{
MoveLeft();
if (IsSeperator(input[current]) != nonLetter)
{
if (!nonLetter)
{
MoveRight();
break;
}
nonLetter = false;
}
}
}
}
else
{
MoveLeft();
}
}
private bool IsSeperator(char ch)
{
return !Char.IsLetter(ch);
}
private void MoveRight(ConsoleModifiers keyModifiers)
{
if ((keyModifiers & ConsoleModifiers.Control) != 0)
{
// move to the next word
if (input.Length != 0 && current < input.Length)
{
bool nonLetter = IsSeperator(input[current]);
while (current < input.Length)
{
MoveRight();
if (current == input.Length) break;
if (IsSeperator(input[current]) != nonLetter)
{
if (nonLetter)
break;
nonLetter = true;
}
}
}
}
else
{
MoveRight();
}
}
private void MoveRight()
{
if (current < input.Length)
{
char c = input[current];
current++;
cursor.Move(GetCharacterSize(c));
}
}
private void MoveLeft()
{
if (current > 0 && (current - 1 < input.Length))
{
current--;
char c = input[current];
cursor.Move(-GetCharacterSize(c));
}
}
private const int TabSize = 4;
private void InsertTab()
{
for (int i = TabSize - (current % TabSize); i > 0; i--)
{
Insert(' ');
}
}
private void MoveHome()
{
current = 0;
cursor.Reset();
}
private void MoveEnd()
{
current = input.Length;
cursor.Place(rendered);
}
public string ReadLine(int autoIndentSizeInput)
{
if (dotPrompt)
{
CommandBase.Write("... ");
}
else
{
CommandBase.Write(">>> ");
}
Initialize();
autoIndentSize = autoIndentSizeInput;
for (int i = 0; i < autoIndentSize; i++)
Insert(' ');
int count = 0;
for (; ; )
{
ConsoleKeyInfo key;
key = (CommandBase.Shell.IO as IMDbgIO3).ReadKey(true);
switch (key.Key)
{
case ConsoleKey.Backspace:
Backspace();
break;
case ConsoleKey.Delete:
Delete();
break;
case ConsoleKey.Enter:
CommandBase.Write("\n");
string line = input.ToString();
if (line == FinalLineText) return null;
if (line.Length > 0)
{
history.AddLast(line);
}
if (count == 0)
{
dotPrompt = false;
}
options.Clear();
return line;
case ConsoleKey.Tab:
{
bool prefix = false;
if (changed)
{
prefix = GetOptions();
changed = false;
}
if (options.Count > 0)
{
string part = (key.Modifiers & ConsoleModifiers.Shift) != 0 ? options.Previous() : options.Next();
SetInput(options.Root + part);
}
else
{
InsertTab();
}
continue;
}
case ConsoleKey.UpArrow:
SetInput(history.Previous());
break;
case ConsoleKey.DownArrow:
SetInput(history.Next());
break;
case ConsoleKey.RightArrow:
MoveRight(key.Modifiers);
break;
case ConsoleKey.LeftArrow:
MoveLeft(key.Modifiers);
break;
case ConsoleKey.Escape:
SetInput(String.Empty);
break;
case ConsoleKey.Home:
MoveHome();
break;
case ConsoleKey.End:
MoveEnd();
break;
case ConsoleKey.LeftWindows:
case ConsoleKey.RightWindows:
// ignore these
break;
default:
if (key.KeyChar == '\x0D') goto case ConsoleKey.Enter; // Ctrl-M
if (key.KeyChar == '\x08') goto case ConsoleKey.Backspace; // Ctrl-H
Insert(key);
break;
}
if (key.KeyChar == ':')
{
dotPrompt = true;
}
changed = true;
count++;
}
}
string FinalLineText
{
get
{
return Environment.OSVersion.Platform != PlatformID.Unix ? "\x1A" : "\x04";
}
}
public void Write(string text, Style style)
{
switch (style)
{
case Style.Prompt: WriteColor(text, PromptColor); break;
case Style.Out: WriteColor(text, OutColor); break;
case Style.Error: WriteColor(text, ErrorColor); break;
}
}
public void WriteLine(string text, Style style)
{
Write(text + Environment.NewLine, style);
}
private void WriteColor(string s, ConsoleColor c)
{
ConsoleColor origColor = Console.ForegroundColor;
Console.ForegroundColor = c;
CommandBase.Write(s);
Console.ForegroundColor = origColor;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Threading;
using System.Transactions.Distributed;
namespace System.Transactions
{
public class TransactionEventArgs : EventArgs
{
internal Transaction _transaction;
public Transaction Transaction => _transaction;
}
public delegate void TransactionCompletedEventHandler(object sender, TransactionEventArgs e);
public enum IsolationLevel
{
Serializable = 0,
RepeatableRead = 1,
ReadCommitted = 2,
ReadUncommitted = 3,
Snapshot = 4,
Chaos = 5,
Unspecified = 6,
}
public enum TransactionStatus
{
Active = 0,
Committed = 1,
Aborted = 2,
InDoubt = 3
}
public enum DependentCloneOption
{
BlockCommitUntilComplete = 0,
RollbackIfNotComplete = 1,
}
[Flags]
public enum EnlistmentOptions
{
None = 0x0,
EnlistDuringPrepareRequired = 0x1,
}
// When we serialize a Transaction, we specify the type DistributedTransaction, so a Transaction never
// actually gets deserialized.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229", Justification = "Serialization not yet supported and will be done using DistributedTransaction")]
public class Transaction : IDisposable, ISerializable
{
// UseServiceDomain
//
// Property tells parts of system.transactions if it should use a
// service domain for current.
[System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
internal static bool UseServiceDomainForCurrent() => false;
// InteropMode
//
// This property figures out the current interop mode based on the
// top of the transaction scope stack as well as the default mode
// from config.
internal static EnterpriseServicesInteropOption InteropMode(TransactionScope currentScope)
{
if (currentScope != null)
{
return currentScope.InteropMode;
}
return EnterpriseServicesInteropOption.None;
}
internal static Transaction FastGetTransaction(TransactionScope currentScope, ContextData contextData, out Transaction contextTransaction)
{
Transaction current = null;
contextTransaction = null;
contextTransaction = contextData.CurrentTransaction;
switch (InteropMode(currentScope))
{
case EnterpriseServicesInteropOption.None:
current = contextTransaction;
// If there is a transaction in the execution context or if there is a current transaction scope
// then honer the transaction context.
if (current == null && currentScope == null)
{
// Otherwise check for an external current.
if (TransactionManager.s_currentDelegateSet)
{
current = TransactionManager.s_currentDelegate();
}
else
{
current = EnterpriseServices.GetContextTransaction(contextData);
}
}
break;
case EnterpriseServicesInteropOption.Full:
current = EnterpriseServices.GetContextTransaction(contextData);
break;
case EnterpriseServicesInteropOption.Automatic:
if (EnterpriseServices.UseServiceDomainForCurrent())
{
current = EnterpriseServices.GetContextTransaction(contextData);
}
else
{
current = contextData.CurrentTransaction;
}
break;
}
return current;
}
// GetCurrentTransactionAndScope
//
// Returns both the current transaction and scope. This is implemented for optimizations
// in TransactionScope because it is required to get both of them in several cases.
internal static void GetCurrentTransactionAndScope(
TxLookup defaultLookup,
out Transaction current,
out TransactionScope currentScope,
out Transaction contextTransaction)
{
current = null;
currentScope = null;
contextTransaction = null;
ContextData contextData = ContextData.LookupContextData(defaultLookup);
if (contextData != null)
{
currentScope = contextData.CurrentScope;
current = FastGetTransaction(currentScope, contextData, out contextTransaction);
}
}
public static Transaction Current
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "Transaction.get_Current");
}
Transaction current = null;
TransactionScope currentScope = null;
Transaction contextValue = null;
GetCurrentTransactionAndScope(TxLookup.Default, out current, out currentScope, out contextValue);
if (currentScope != null)
{
if (currentScope.ScopeComplete)
{
throw new InvalidOperationException(SR.TransactionScopeComplete);
}
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, "Transaction.get_Current");
}
return current;
}
set
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "Transaction.set_Current");
}
// Bring your own Transaction(BYOT) is supported only for legacy scenarios.
// This transaction won't be flown across thread continuations.
if (InteropMode(ContextData.TLSCurrentData.CurrentScope) != EnterpriseServicesInteropOption.None)
{
if (etwLog.IsEnabled())
{
etwLog.InvalidOperation("Transaction", "Transaction.set_Current");
}
throw new InvalidOperationException(SR.CannotSetCurrent);
}
// Support only legacy scenarios using TLS.
ContextData.TLSCurrentData.CurrentTransaction = value;
// Clear CallContext data.
CallContextCurrentData.ClearCurrentData(null, false);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, "Transaction.set_Current");
}
}
}
// Storage for the transaction isolation level
internal IsolationLevel _isoLevel;
// Storage for the consistent flag
internal bool _complete = false;
// Record an identifier for this clone
internal int _cloneId;
// Storage for a disposed flag
internal const int _disposedTrueValue = 1;
internal int _disposed = 0;
internal bool Disposed { get { return _disposed == Transaction._disposedTrueValue; } }
internal Guid DistributedTxId
{
get
{
Guid returnValue = Guid.Empty;
if (_internalTransaction != null)
{
returnValue = _internalTransaction.DistributedTxId;
}
return returnValue;
}
}
// Internal synchronization object for transactions. It is not safe to lock on the
// transaction object because it is public and users of the object may lock it for
// other purposes.
internal InternalTransaction _internalTransaction;
// The TransactionTraceIdentifier for the transaction instance.
internal TransactionTraceIdentifier _traceIdentifier;
// Not used by anyone
private Transaction() { }
// Create a transaction with the given settings
//
internal Transaction(IsolationLevel isoLevel, InternalTransaction internalTransaction)
{
TransactionManager.ValidateIsolationLevel(isoLevel);
_isoLevel = isoLevel;
// Never create a transaction with an IsolationLevel of Unspecified.
if (IsolationLevel.Unspecified == _isoLevel)
{
_isoLevel = TransactionManager.DefaultIsolationLevel;
}
if (internalTransaction != null)
{
_internalTransaction = internalTransaction;
_cloneId = Interlocked.Increment(ref _internalTransaction._cloneCount);
}
else
{
// Null is passed from the constructor of a CommittableTransaction. That
// constructor will fill in the traceIdentifier because it has allocated the
// internal transaction.
}
}
internal Transaction(DistributedTransaction distributedTransaction)
{
_isoLevel = distributedTransaction.IsolationLevel;
_internalTransaction = new InternalTransaction(this, distributedTransaction);
_cloneId = Interlocked.Increment(ref _internalTransaction._cloneCount);
}
internal Transaction(IsolationLevel isoLevel, ISimpleTransactionSuperior superior)
{
TransactionManager.ValidateIsolationLevel(isoLevel);
if (superior == null)
{
throw new ArgumentNullException(nameof(superior));
}
_isoLevel = isoLevel;
// Never create a transaction with an IsolationLevel of Unspecified.
if (IsolationLevel.Unspecified == _isoLevel)
{
_isoLevel = TransactionManager.DefaultIsolationLevel;
}
_internalTransaction = new InternalTransaction(this, superior);
// ISimpleTransactionSuperior is defined to also promote to MSDTC.
_internalTransaction.SetPromoterTypeToMSDTC();
_cloneId = 1;
}
#region System.Object Overrides
// Don't use the identifier for the hash code.
//
public override int GetHashCode()
{
return _internalTransaction.TransactionHash;
}
// Don't allow equals to get the identifier
//
public override bool Equals(object obj)
{
Transaction transaction = obj as Transaction;
// If we can't cast the object as a Transaction, it must not be equal
// to this, which is a Transaction.
if (null == transaction)
{
return false;
}
// Check the internal transaction object for equality.
return _internalTransaction.TransactionHash == transaction._internalTransaction.TransactionHash;
}
public static bool operator ==(Transaction x, Transaction y)
{
if (((object)x) != null)
{
return x.Equals(y);
}
return ((object)y) == null;
}
public static bool operator !=(Transaction x, Transaction y)
{
if (((object)x) != null)
{
return !x.Equals(y);
}
return ((object)y) != null;
}
#endregion
public TransactionInformation TransactionInformation
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
TransactionInformation txInfo = _internalTransaction._transactionInformation;
if (txInfo == null)
{
// A race would only result in an extra allocation
txInfo = new TransactionInformation(_internalTransaction);
_internalTransaction._transactionInformation = txInfo;
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return txInfo;
}
}
// Return the Isolation Level for the given transaction
//
public IsolationLevel IsolationLevel
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return _isoLevel;
}
}
/// <summary>
/// Gets the PromoterType value for the transaction.
/// </summary>
/// <value>
/// If the transaction has not yet been promoted and does not yet have a promotable single phase enlistment,
/// this property value will be Guid.Empty.
///
/// If the transaction has been promoted or has a promotable single phase enlistment, this will return the
/// promoter type specified by the transaction promoter.
///
/// If the transaction is, or will be, promoted to MSDTC, the value will be TransactionInterop.PromoterTypeDtc.
/// </value>
public Guid PromoterType
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
lock (_internalTransaction)
{
return _internalTransaction._promoterType;
}
}
}
/// <summary>
/// Gets the PromotedToken for the transaction.
///
/// If the transaction has not already been promoted, retrieving this value will cause promotion. Before retrieving the
/// PromotedToken, the Transaction.PromoterType value should be checked to see if it is a promoter type (Guid) that the
/// caller understands. If the caller does not recognize the PromoterType value, retreiving the PromotedToken doesn't
/// have much value because the caller doesn't know how to utilize it. But if the PromoterType is recognized, the
/// caller should know how to utilize the PromotedToken to communicate with the promoting distributed transaction
/// coordinator to enlist on the distributed transaction.
///
/// If the value of a transaction's PromoterType is TransactionInterop.PromoterTypeDtc, then that transaction's
/// PromotedToken will be an MSDTC-based TransmitterPropagationToken.
/// </summary>
/// <returns>
/// The byte[] that can be used to enlist with the distributed transaction coordinator used to promote the transaction.
/// The format of the byte[] depends upon the value of Transaction.PromoterType.
/// </returns>
public byte[] GetPromotedToken()
{
// We need to ask the current transaction state for the PromotedToken because depending on the state
// we may need to induce a promotion.
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
// We always make a copy of the promotedToken stored in the internal transaction.
byte[] internalPromotedToken;
lock (_internalTransaction)
{
internalPromotedToken = _internalTransaction.State.PromotedToken(_internalTransaction);
}
byte[] toReturn = new byte[internalPromotedToken.Length];
Array.Copy(internalPromotedToken, toReturn, toReturn.Length);
return toReturn;
}
public Enlistment EnlistDurable(
Guid resourceManagerIdentifier,
IEnlistmentNotification enlistmentNotification,
EnlistmentOptions enlistmentOptions)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (resourceManagerIdentifier == Guid.Empty)
{
throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier));
}
if (enlistmentNotification == null)
{
throw new ArgumentNullException(nameof(enlistmentNotification));
}
if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired)
{
throw new ArgumentOutOfRangeException(nameof(enlistmentOptions));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
Enlistment enlistment = _internalTransaction.State.EnlistDurable(_internalTransaction,
resourceManagerIdentifier, enlistmentNotification, enlistmentOptions, this);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return enlistment;
}
}
// Forward request to the state machine to take the appropriate action.
//
public Enlistment EnlistDurable(
Guid resourceManagerIdentifier,
ISinglePhaseNotification singlePhaseNotification,
EnlistmentOptions enlistmentOptions)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (resourceManagerIdentifier == Guid.Empty)
{
throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier));
}
if (singlePhaseNotification == null)
{
throw new ArgumentNullException(nameof(singlePhaseNotification));
}
if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired)
{
throw new ArgumentOutOfRangeException(nameof(enlistmentOptions));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
Enlistment enlistment = _internalTransaction.State.EnlistDurable(_internalTransaction,
resourceManagerIdentifier, singlePhaseNotification, enlistmentOptions, this);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return enlistment;
}
}
public void Rollback()
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
etwLog.TransactionRollback(this, "Transaction");
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
lock (_internalTransaction)
{
Debug.Assert(_internalTransaction.State != null);
_internalTransaction.State.Rollback(_internalTransaction, null);
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
}
public void Rollback(Exception e)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
etwLog.TransactionRollback(this, "Transaction");
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
lock (_internalTransaction)
{
Debug.Assert(_internalTransaction.State != null);
_internalTransaction.State.Rollback(_internalTransaction, e);
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
}
// Forward request to the state machine to take the appropriate action.
//
public Enlistment EnlistVolatile(IEnlistmentNotification enlistmentNotification, EnlistmentOptions enlistmentOptions)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (enlistmentNotification == null)
{
throw new ArgumentNullException(nameof(enlistmentNotification));
}
if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired)
{
throw new ArgumentOutOfRangeException(nameof(enlistmentOptions));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
Enlistment enlistment = _internalTransaction.State.EnlistVolatile(_internalTransaction,
enlistmentNotification, enlistmentOptions, this);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return enlistment;
}
}
// Forward request to the state machine to take the appropriate action.
//
public Enlistment EnlistVolatile(ISinglePhaseNotification singlePhaseNotification, EnlistmentOptions enlistmentOptions)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (singlePhaseNotification == null)
{
throw new ArgumentNullException(nameof(singlePhaseNotification));
}
if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired)
{
throw new ArgumentOutOfRangeException(nameof(enlistmentOptions));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
Enlistment enlistment = _internalTransaction.State.EnlistVolatile(_internalTransaction,
singlePhaseNotification, enlistmentOptions, this);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return enlistment;
}
}
// Create a clone of the transaction that forwards requests to this object.
//
public Transaction Clone()
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
Transaction clone = InternalClone();
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return clone;
}
internal Transaction InternalClone()
{
Transaction clone = new Transaction(_isoLevel, _internalTransaction);
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TransactionCloneCreate(clone, "Transaction");
}
return clone;
}
// Create a dependent clone of the transaction that forwards requests to this object.
//
public DependentTransaction DependentClone(
DependentCloneOption cloneOption
)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (cloneOption != DependentCloneOption.BlockCommitUntilComplete
&& cloneOption != DependentCloneOption.RollbackIfNotComplete)
{
throw new ArgumentOutOfRangeException(nameof(cloneOption));
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
DependentTransaction clone = new DependentTransaction(
_isoLevel, _internalTransaction, cloneOption == DependentCloneOption.BlockCommitUntilComplete);
if (etwLog.IsEnabled())
{
etwLog.TransactionCloneCreate(clone, "DependentTransaction");
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return clone;
}
internal TransactionTraceIdentifier TransactionTraceId
{
get
{
if (_traceIdentifier == TransactionTraceIdentifier.Empty)
{
lock (_internalTransaction)
{
if (_traceIdentifier == TransactionTraceIdentifier.Empty)
{
TransactionTraceIdentifier temp = new TransactionTraceIdentifier(
_internalTransaction.TransactionTraceId.TransactionIdentifier,
_cloneId);
Interlocked.MemoryBarrier();
_traceIdentifier = temp;
}
}
}
return _traceIdentifier;
}
}
// Forward request to the state machine to take the appropriate action.
//
public event TransactionCompletedEventHandler TransactionCompleted
{
add
{
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
lock (_internalTransaction)
{
// Register for completion with the inner transaction
_internalTransaction.State.AddOutcomeRegistrant(_internalTransaction, value);
}
}
remove
{
lock (_internalTransaction)
{
_internalTransaction._transactionCompletedDelegate = (TransactionCompletedEventHandler)
System.Delegate.Remove(_internalTransaction._transactionCompletedDelegate, value);
}
}
}
public void Dispose()
{
InternalDispose();
}
// Handle Transaction Disposal.
//
internal virtual void InternalDispose()
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Interlocked.Exchange(ref _disposed, Transaction._disposedTrueValue) == Transaction._disposedTrueValue)
{
return;
}
// Attempt to clean up the internal transaction
long remainingITx = Interlocked.Decrement(ref _internalTransaction._cloneCount);
if (remainingITx == 0)
{
_internalTransaction.Dispose();
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
}
// Ask the state machine for serialization info.
//
void ISerializable.GetObjectData(
SerializationInfo serializationInfo,
StreamingContext context)
{
//TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
//if (etwLog.IsEnabled())
//{
// etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
//}
//if (Disposed)
//{
// throw new ObjectDisposedException(nameof(Transaction));
//}
//if (serializationInfo == null)
//{
// throw new ArgumentNullException(nameof(serializationInfo));
//}
//if (_complete)
//{
// throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
//}
//lock (_internalTransaction)
//{
// _internalTransaction.State.GetObjectData(_internalTransaction, serializationInfo, context);
//}
//if (etwLog.IsEnabled())
//{
// etwLog.TransactionSerialized(this, "Transaction");
// etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
//}
throw new PlatformNotSupportedException();
}
/// <summary>
/// Create a promotable single phase enlistment that promotes to MSDTC.
/// </summary>
/// <param name="promotableSinglePhaseNotification">The object that implements the IPromotableSinglePhaseNotification interface.</param>
/// <returns>
/// True if the enlistment is successful.
///
/// False if the transaction already has a durable enlistment or promotable single phase enlistment or
/// if the transaction has already promoted. In this case, the caller will need to enlist in the transaction through other
/// means, such as Transaction.EnlistDurable or retreive the MSDTC export cookie or propagation token to enlist with MSDTC.
/// </returns>
// We apparently didn't spell Promotable like FXCop thinks it should be spelled.
public bool EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification)
{
return EnlistPromotableSinglePhase(promotableSinglePhaseNotification, TransactionInterop.PromoterTypeDtc);
}
/// <summary>
/// Create a promotable single phase enlistment that promotes to a distributed transaction manager other than MSDTC.
/// </summary>
/// <param name="promotableSinglePhaseNotification">The object that implements the IPromotableSinglePhaseNotification interface.</param>
/// <param name="promoterType">
/// The promoter type Guid that identifies the format of the byte[] that is returned by the ITransactionPromoter.Promote
/// call that is implemented by the IPromotableSinglePhaseNotificationObject, and thus the promoter of the transaction.
/// </param>
/// <returns>
/// True if the enlistment is successful.
///
/// False if the transaction already has a durable enlistment or promotable single phase enlistment or
/// if the transaction has already promoted. In this case, the caller will need to enlist in the transaction through other
/// means.
///
/// If the Transaction.PromoterType matches the promoter type supported by the caller, then the
/// Transaction.PromotedToken can be retrieved and used to enlist directly with the identified distributed transaction manager.
///
/// How the enlistment is created with the distributed transaction manager identified by the Transaction.PromoterType
/// is defined by that distributed transaction manager.
/// </returns>
public bool EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Guid promoterType)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (promotableSinglePhaseNotification == null)
{
throw new ArgumentNullException(nameof(promotableSinglePhaseNotification));
}
if (promoterType == Guid.Empty)
{
throw new ArgumentException(SR.PromoterTypeInvalid, nameof(promoterType));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
bool succeeded = false;
lock (_internalTransaction)
{
succeeded = _internalTransaction.State.EnlistPromotableSinglePhase(_internalTransaction, promotableSinglePhaseNotification, this, promoterType);
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return succeeded;
}
public Enlistment PromoteAndEnlistDurable(Guid resourceManagerIdentifier,
IPromotableSinglePhaseNotification promotableNotification,
ISinglePhaseNotification enlistmentNotification,
EnlistmentOptions enlistmentOptions)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceDistributed, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (resourceManagerIdentifier == Guid.Empty)
{
throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier));
}
if (promotableNotification == null)
{
throw new ArgumentNullException(nameof(promotableNotification));
}
if (enlistmentNotification == null)
{
throw new ArgumentNullException(nameof(enlistmentNotification));
}
if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired)
{
throw new ArgumentOutOfRangeException(nameof(enlistmentOptions));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
Enlistment enlistment = _internalTransaction.State.PromoteAndEnlistDurable(_internalTransaction,
resourceManagerIdentifier, promotableNotification, enlistmentNotification, enlistmentOptions, this);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceDistributed, this);
}
return enlistment;
}
}
public void SetDistributedTransactionIdentifier(IPromotableSinglePhaseNotification promotableNotification,
Guid distributedTransactionIdentifier)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (promotableNotification == null)
{
throw new ArgumentNullException(nameof(promotableNotification));
}
if (distributedTransactionIdentifier == Guid.Empty)
{
throw new ArgumentException(null, nameof(distributedTransactionIdentifier));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
_internalTransaction.State.SetDistributedTransactionId(_internalTransaction,
promotableNotification,
distributedTransactionIdentifier);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return;
}
}
internal DistributedTransaction Promote()
{
lock (_internalTransaction)
{
// This method is only called when we expect to be promoting to MSDTC.
_internalTransaction.ThrowIfPromoterTypeIsNotMSDTC();
_internalTransaction.State.Promote(_internalTransaction);
return _internalTransaction.PromotedTransaction;
}
}
}
//
// The following code & data is related to management of Transaction.Current
//
internal enum DefaultComContextState
{
Unknown = 0,
Unavailable = -1,
Available = 1
}
//
// The TxLookup enum is used internally to detect where the ambient context needs to be stored or looked up.
// Default - Used internally when looking up Transaction.Current.
// DefaultCallContext - Used when TransactionScope with async flow option is enabled. Internally we will use CallContext to store the ambient transaction.
// Default TLS - Used for legacy/syncronous TransactionScope. Internally we will use TLS to store the ambient transaction.
//
internal enum TxLookup
{
Default,
DefaultCallContext,
DefaultTLS,
}
//
// CallContextCurrentData holds the ambient transaction and uses CallContext and ConditionalWeakTable to track the ambient transaction.
// For async flow scenarios, we should not allow flowing of transaction across app domains. To prevent transaction from flowing across
// AppDomain/Remoting boundaries, we are using ConditionalWeakTable to hold the actual ambient transaction and store only a object reference
// in CallContext. When TransactionScope is used to invoke a call across AppDomain/Remoting boundaries, only the object reference will be sent
// across and not the actaul ambient transaction which is stashed away in the ConditionalWeakTable.
//
internal static class CallContextCurrentData
{
private static AsyncLocal<ContextKey> s_currentTransaction = new AsyncLocal<ContextKey>();
// ConditionalWeakTable is used to automatically remove the entries that are no longer referenced. This will help prevent leaks in async nested TransactionScope
// usage and when child nested scopes are not syncronized properly.
private static readonly ConditionalWeakTable<ContextKey, ContextData> s_contextDataTable = new ConditionalWeakTable<ContextKey, ContextData>();
//
// Set CallContext data with the given contextKey.
// return the ContextData if already present in contextDataTable, otherwise return the default value.
//
public static ContextData CreateOrGetCurrentData(ContextKey contextKey)
{
s_currentTransaction.Value = contextKey;
return s_contextDataTable.GetValue(contextKey, (env) => new ContextData(true));
}
public static void ClearCurrentData(ContextKey contextKey, bool removeContextData)
{
// Get the current ambient CallContext.
ContextKey key = s_currentTransaction.Value;
if (contextKey != null || key != null)
{
// removeContextData flag is used for perf optimization to avoid removing from the table in certain nested TransactionScope usage.
if (removeContextData)
{
// if context key is passed in remove that from the contextDataTable, otherwise remove the default context key.
s_contextDataTable.Remove(contextKey ?? key);
}
if (key != null)
{
s_currentTransaction.Value = null;
}
}
}
public static bool TryGetCurrentData(out ContextData currentData)
{
currentData = null;
ContextKey contextKey = s_currentTransaction.Value;
if (contextKey == null)
{
return false;
}
else
{
return s_contextDataTable.TryGetValue(contextKey, out currentData);
}
}
}
//
// MarshalByRefObject is needed for cross AppDomain scenarios where just using object will end up with a different reference when call is made across serialization boundary.
//
internal class ContextKey // : MarshalByRefObject
{
}
internal class ContextData
{
internal TransactionScope CurrentScope;
internal Transaction CurrentTransaction;
internal DefaultComContextState DefaultComContextState;
internal WeakReference WeakDefaultComContext;
internal bool _asyncFlow;
[ThreadStatic]
private static ContextData t_staticData;
internal ContextData(bool asyncFlow)
{
_asyncFlow = asyncFlow;
}
internal static ContextData TLSCurrentData
{
get
{
ContextData data = t_staticData;
if (data == null)
{
data = new ContextData(false);
t_staticData = data;
}
return data;
}
set
{
if (value == null && t_staticData != null)
{
// set each property to null to retain one TLS ContextData copy.
t_staticData.CurrentScope = null;
t_staticData.CurrentTransaction = null;
t_staticData.DefaultComContextState = DefaultComContextState.Unknown;
t_staticData.WeakDefaultComContext = null;
}
else
{
t_staticData = value;
}
}
}
internal static ContextData LookupContextData(TxLookup defaultLookup)
{
ContextData currentData = null;
if (CallContextCurrentData.TryGetCurrentData(out currentData))
{
if (currentData.CurrentScope == null && currentData.CurrentTransaction == null && defaultLookup != TxLookup.DefaultCallContext)
{
// Clear Call Context Data
CallContextCurrentData.ClearCurrentData(null, true);
return TLSCurrentData;
}
return currentData;
}
else
{
return TLSCurrentData;
}
}
}
}
| |
using Foundation;
using System;
using UIKit;
using Stripe.iOS;
using PassKit;
using CoreFoundation;
namespace Stripe.UIExamples
{
partial class BrowseViewController : UITableViewController, IAddCardViewControllerDelegate, IPaymentMethodsViewControllerDelegate, IShippingAddressViewControllerDelegate
{
ThemeViewController themeViewController = new ThemeViewController ();
MockCustomerContext customerContext = new MockCustomerContext ();
public BrowseViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
Title = "Stripe UI Examples";
TableView.TableFooterView = new UIView ();
TableView.RowHeight = 60;
NavigationController.NavigationBar.Translucent = false;
}
public override nint NumberOfSections (UITableView tableView)
{
return 1;
}
public override nint RowsInSection (UITableView tableView, nint section)
{
return Enum.GetValues (typeof (Demo)).Length;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
var cell = new UITableViewCell (UITableViewCellStyle.Subtitle, null);
Demo example = (Demo)indexPath.Row;
cell.TextLabel.Text = example.Title ();
cell.DetailTextLabel.Text = example.Detail ();
return cell;
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
UINavigationController navigationController;
PaymentConfiguration config;
tableView.DeselectRow (indexPath, true);
Demo example = (Demo)indexPath.Row;
var theme = themeViewController.Theme.GetStripeTheme ();
switch (example)
{
case Demo.PaymentCardTextField:
var cardFieldViewContoller = new CardFieldViewController ();
cardFieldViewContoller.Theme = theme;
navigationController = new UINavigationController (cardFieldViewContoller);
navigationController.NavigationBar.SetStripeTheme (theme);
PresentViewController (navigationController, true, null);
break;
case Demo.AddCardViewController:
config = new PaymentConfiguration ();
config.RequiredBillingAddressFields = BillingAddressFields.Full;
var viewController = new MockAddCardViewController (config, theme);
viewController.Delegate = this;
navigationController = new UINavigationController (viewController);
navigationController.NavigationBar.SetStripeTheme (theme);
PresentViewController (navigationController, true, null);
break;
case Demo.PaymentMethodsViewController:
config = new PaymentConfiguration ();
config.AdditionalPaymentMethods = PaymentMethodType.All;
config.RequiredBillingAddressFields = BillingAddressFields.None;
config.AppleMerchantIdentifier = "dummy-merchant-id";
var paymentMethodsViewController = new PaymentMethodsViewController (config, theme, customerContext, this);
navigationController = new UINavigationController (paymentMethodsViewController);
navigationController.NavigationBar.SetStripeTheme (theme);
PresentViewController (navigationController, true, null);
break;
case Demo.ShippingInfoViewController:
config = new PaymentConfiguration ();
config.RequiredShippingAddressFields = PKAddressField.PostalAddress;
var shippingAddressViewController = new ShippingAddressViewController (config, theme, "usd", null, null, null);
shippingAddressViewController.Delegate = this;
navigationController = new UINavigationController (shippingAddressViewController);
navigationController.NavigationBar.SetStripeTheme (theme);
PresentViewController (navigationController, true, null);
break;
case Demo.ChangeTheme:
navigationController = new UINavigationController (themeViewController);
PresentViewController (navigationController, true, null);
break;
default:
throw new NotImplementedException ();
}
}
public void AddCardViewControllerCancelled (AddCardViewController addCardViewController)
{
DismissViewController (true, null);
}
public void AddCardViewControllerCreatedToken (AddCardViewController addCardViewController, Token token, STPErrorBlock completion)
{
DismissViewController (true, null);
}
public void PaymentMethodsViewControllerFailedToLoad (PaymentMethodsViewController paymentMethodsViewController, NSError error)
{
DismissViewController (true, null);
}
public void PaymentMethodsViewControllerFinished (PaymentMethodsViewController paymentMethodsViewController)
{
paymentMethodsViewController.NavigationController.PopViewController (true);
}
public void PaymentMethodsViewControllerCancelled (PaymentMethodsViewController paymentMethodsViewController)
{
DismissViewController (true, null);
}
public void ShippingAddressViewControllerCancelled (ShippingAddressViewController addressViewController)
{
DismissViewController (true, null);
}
public void ShippingAddressViewControllerEnteredAddress (ShippingAddressViewController addressViewController, Address address, ShippingMethodsCompletionBlock completion)
{
var upsGround = new PKShippingMethod
{
Amount = new NSDecimalNumber (0),
Label = "UPS Ground",
Detail = "Arrives in 3-5 days",
Identifier = "ups_ground",
};
var upsWorldwide = new PKShippingMethod
{
Amount = new NSDecimalNumber (10.99),
Label = "UPS Worldwide Express",
Detail = "Arrives in 1-3 days",
Identifier = "ups_worldwide",
};
var fedEx = new PKShippingMethod
{
Amount = new NSDecimalNumber (5.99),
Label = "FedEx",
Detail = "Arrives tomorrow",
Identifier = "fedex",
};
DispatchQueue.MainQueue.DispatchAfter (new DispatchTime (DispatchTime.Now, new TimeSpan (0, 0, 0, 0, 600)), () =>
{
if (address.Country == null || address.Country == "US")
{
completion (ShippingStatus.Valid, null, new PKShippingMethod[] { upsGround, fedEx }, fedEx);
}
else if (address.Country == "AQ")
{
var error = new NSError (new NSString ("ShippingError"), 123,
new NSDictionary (NSError.LocalizedDescriptionKey, new NSString ("Invalid Shipping Address"),
NSError.LocalizedFailureReasonErrorKey, new NSString ("We can't ship to this country.")));
completion (ShippingStatus.Invalid, error, null, null);
}
else
{
fedEx.Amount = new NSDecimalNumber (20.99);
completion (ShippingStatus.Valid, null, new PKShippingMethod[] { upsWorldwide, fedEx }, fedEx);
}
});
}
public void ShippingAddressViewControllerFinished (ShippingAddressViewController addressViewController, Address address, PKShippingMethod method)
{
customerContext.UpdateCustomer (address, null);
DismissViewController (true, null);
}
}
enum Demo
{
PaymentCardTextField = 0,
AddCardViewController,
PaymentMethodsViewController,
ShippingInfoViewController,
ChangeTheme,
}
static class DemoExtensions
{
public static string Title (this Demo This)
{
switch (This)
{
case Demo.PaymentCardTextField:
return "Card Field";
case Demo.AddCardViewController:
return "Card Form with Billing Address";
case Demo.PaymentMethodsViewController:
return "Payment Method Picker";
case Demo.ShippingInfoViewController:
return "Shipping Info Form";
case Demo.ChangeTheme:
return "Change Theme";
default:
throw new NotImplementedException ();
}
}
public static string Detail (this Demo This)
{
switch (This)
{
case Demo.PaymentCardTextField:
return "STPPaymentCardTextField";
case Demo.AddCardViewController:
return "STPAddCardViewController";
case Demo.PaymentMethodsViewController:
return "STPPaymentMethodsViewController";
case Demo.ShippingInfoViewController:
return "STPShippingInfoViewController";
case Demo.ChangeTheme:
return "";
default:
throw new NotImplementedException ();
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ReplicationNetworkMappingsOperations operations.
/// </summary>
public partial interface IReplicationNetworkMappingsOperations
{
/// <summary>
/// Gets all the network mappings under a vault.
/// </summary>
/// <remarks>
/// Lists all ASR network mappings in the vault.
/// </remarks>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkMapping>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the network mappings under a network.
/// </summary>
/// <remarks>
/// Lists all ASR network mappings for the specified network.
/// </remarks>
/// <param name='fabricName'>
/// Primary fabric name.
/// </param>
/// <param name='networkName'>
/// Primary network name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkMapping>>> ListByReplicationNetworksWithHttpMessagesAsync(string fabricName, string networkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets network mapping by name.
/// </summary>
/// <remarks>
/// Gets the details of an ASR network mapping
/// </remarks>
/// <param name='fabricName'>
/// Primary fabric name.
/// </param>
/// <param name='networkName'>
/// Primary network name.
/// </param>
/// <param name='networkMappingName'>
/// Network mapping name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkMapping>> GetWithHttpMessagesAsync(string fabricName, string networkName, string networkMappingName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates network mapping.
/// </summary>
/// <remarks>
/// The operation to create an ASR network mapping.
/// </remarks>
/// <param name='fabricName'>
/// Primary fabric name.
/// </param>
/// <param name='networkName'>
/// Primary network name.
/// </param>
/// <param name='networkMappingName'>
/// Network mapping name.
/// </param>
/// <param name='input'>
/// Create network mapping input.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkMapping>> CreateWithHttpMessagesAsync(string fabricName, string networkName, string networkMappingName, CreateNetworkMappingInput input, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete network mapping.
/// </summary>
/// <remarks>
/// The operation to delete a network mapping.
/// </remarks>
/// <param name='fabricName'>
/// Primary fabric name.
/// </param>
/// <param name='networkName'>
/// Primary network name.
/// </param>
/// <param name='networkMappingName'>
/// ARM Resource Name for network mapping.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string fabricName, string networkName, string networkMappingName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates network mapping.
/// </summary>
/// <remarks>
/// The operation to update an ASR network mapping.
/// </remarks>
/// <param name='fabricName'>
/// Primary fabric name.
/// </param>
/// <param name='networkName'>
/// Primary network name.
/// </param>
/// <param name='networkMappingName'>
/// Network mapping name.
/// </param>
/// <param name='input'>
/// Update network mapping input.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkMapping>> UpdateWithHttpMessagesAsync(string fabricName, string networkName, string networkMappingName, UpdateNetworkMappingInput input, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates network mapping.
/// </summary>
/// <remarks>
/// The operation to create an ASR network mapping.
/// </remarks>
/// <param name='fabricName'>
/// Primary fabric name.
/// </param>
/// <param name='networkName'>
/// Primary network name.
/// </param>
/// <param name='networkMappingName'>
/// Network mapping name.
/// </param>
/// <param name='input'>
/// Create network mapping input.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkMapping>> BeginCreateWithHttpMessagesAsync(string fabricName, string networkName, string networkMappingName, CreateNetworkMappingInput input, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete network mapping.
/// </summary>
/// <remarks>
/// The operation to delete a network mapping.
/// </remarks>
/// <param name='fabricName'>
/// Primary fabric name.
/// </param>
/// <param name='networkName'>
/// Primary network name.
/// </param>
/// <param name='networkMappingName'>
/// ARM Resource Name for network mapping.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string fabricName, string networkName, string networkMappingName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates network mapping.
/// </summary>
/// <remarks>
/// The operation to update an ASR network mapping.
/// </remarks>
/// <param name='fabricName'>
/// Primary fabric name.
/// </param>
/// <param name='networkName'>
/// Primary network name.
/// </param>
/// <param name='networkMappingName'>
/// Network mapping name.
/// </param>
/// <param name='input'>
/// Update network mapping input.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkMapping>> BeginUpdateWithHttpMessagesAsync(string fabricName, string networkName, string networkMappingName, UpdateNetworkMappingInput input, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the network mappings under a vault.
/// </summary>
/// <remarks>
/// Lists all ASR network mappings in the vault.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkMapping>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the network mappings under a network.
/// </summary>
/// <remarks>
/// Lists all ASR network mappings for the specified network.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkMapping>>> ListByReplicationNetworksNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
namespace Domain.Data.Query
{
public partial class Node
{
public static ProductVendorNode ProductVendor { get { return new ProductVendorNode(); } }
}
public partial class ProductVendorNode : Blueprint41.Query.Node
{
protected override string GetNeo4jLabel()
{
return "ProductVendor";
}
internal ProductVendorNode() { }
internal ProductVendorNode(ProductVendorAlias alias, bool isReference = false)
{
NodeAlias = alias;
IsReference = isReference;
}
internal ProductVendorNode(RELATIONSHIP relationship, DirectionEnum direction, string neo4jLabel = null) : base(relationship, direction, neo4jLabel) { }
public ProductVendorNode Alias(out ProductVendorAlias alias)
{
alias = new ProductVendorAlias(this);
NodeAlias = alias;
return this;
}
public ProductVendorNode UseExistingAlias(AliasResult alias)
{
NodeAlias = alias;
return this;
}
public ProductVendorIn In { get { return new ProductVendorIn(this); } }
public class ProductVendorIn
{
private ProductVendorNode Parent;
internal ProductVendorIn(ProductVendorNode parent)
{
Parent = parent;
}
public IFromIn_PRODUCTVENDOR_HAS_PRODUCT_REL PRODUCTVENDOR_HAS_PRODUCT { get { return new PRODUCTVENDOR_HAS_PRODUCT_REL(Parent, DirectionEnum.In); } }
public IFromIn_PRODUCTVENDOR_HAS_UNITMEASURE_REL PRODUCTVENDOR_HAS_UNITMEASURE { get { return new PRODUCTVENDOR_HAS_UNITMEASURE_REL(Parent, DirectionEnum.In); } }
}
public ProductVendorOut Out { get { return new ProductVendorOut(this); } }
public class ProductVendorOut
{
private ProductVendorNode Parent;
internal ProductVendorOut(ProductVendorNode parent)
{
Parent = parent;
}
public IFromOut_VENDOR_BECOMES_PRODUCTVENDOR_REL VENDOR_BECOMES_PRODUCTVENDOR { get { return new VENDOR_BECOMES_PRODUCTVENDOR_REL(Parent, DirectionEnum.Out); } }
}
}
public class ProductVendorAlias : AliasResult
{
internal ProductVendorAlias(ProductVendorNode parent)
{
Node = parent;
}
public override IReadOnlyDictionary<string, FieldResult> AliasFields
{
get
{
if (m_AliasFields == null)
{
m_AliasFields = new Dictionary<string, FieldResult>()
{
{ "AverageLeadTime", new StringResult(this, "AverageLeadTime", Datastore.AdventureWorks.Model.Entities["ProductVendor"], Datastore.AdventureWorks.Model.Entities["ProductVendor"].Properties["AverageLeadTime"]) },
{ "StandardPrice", new StringResult(this, "StandardPrice", Datastore.AdventureWorks.Model.Entities["ProductVendor"], Datastore.AdventureWorks.Model.Entities["ProductVendor"].Properties["StandardPrice"]) },
{ "LastReceiptCost", new StringResult(this, "LastReceiptCost", Datastore.AdventureWorks.Model.Entities["ProductVendor"], Datastore.AdventureWorks.Model.Entities["ProductVendor"].Properties["LastReceiptCost"]) },
{ "LastReceiptDate", new DateTimeResult(this, "LastReceiptDate", Datastore.AdventureWorks.Model.Entities["ProductVendor"], Datastore.AdventureWorks.Model.Entities["ProductVendor"].Properties["LastReceiptDate"]) },
{ "MinOrderQty", new NumericResult(this, "MinOrderQty", Datastore.AdventureWorks.Model.Entities["ProductVendor"], Datastore.AdventureWorks.Model.Entities["ProductVendor"].Properties["MinOrderQty"]) },
{ "MaxOrderQty", new NumericResult(this, "MaxOrderQty", Datastore.AdventureWorks.Model.Entities["ProductVendor"], Datastore.AdventureWorks.Model.Entities["ProductVendor"].Properties["MaxOrderQty"]) },
{ "OnOrderQty", new NumericResult(this, "OnOrderQty", Datastore.AdventureWorks.Model.Entities["ProductVendor"], Datastore.AdventureWorks.Model.Entities["ProductVendor"].Properties["OnOrderQty"]) },
{ "UnitMeasureCode", new StringResult(this, "UnitMeasureCode", Datastore.AdventureWorks.Model.Entities["ProductVendor"], Datastore.AdventureWorks.Model.Entities["ProductVendor"].Properties["UnitMeasureCode"]) },
{ "ModifiedDate", new DateTimeResult(this, "ModifiedDate", Datastore.AdventureWorks.Model.Entities["ProductVendor"], Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"]) },
{ "Uid", new StringResult(this, "Uid", Datastore.AdventureWorks.Model.Entities["ProductVendor"], Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]) },
};
}
return m_AliasFields;
}
}
private IReadOnlyDictionary<string, FieldResult> m_AliasFields = null;
public ProductVendorNode.ProductVendorIn In { get { return new ProductVendorNode.ProductVendorIn(new ProductVendorNode(this, true)); } }
public ProductVendorNode.ProductVendorOut Out { get { return new ProductVendorNode.ProductVendorOut(new ProductVendorNode(this, true)); } }
public StringResult AverageLeadTime
{
get
{
if ((object)m_AverageLeadTime == null)
m_AverageLeadTime = (StringResult)AliasFields["AverageLeadTime"];
return m_AverageLeadTime;
}
}
private StringResult m_AverageLeadTime = null;
public StringResult StandardPrice
{
get
{
if ((object)m_StandardPrice == null)
m_StandardPrice = (StringResult)AliasFields["StandardPrice"];
return m_StandardPrice;
}
}
private StringResult m_StandardPrice = null;
public StringResult LastReceiptCost
{
get
{
if ((object)m_LastReceiptCost == null)
m_LastReceiptCost = (StringResult)AliasFields["LastReceiptCost"];
return m_LastReceiptCost;
}
}
private StringResult m_LastReceiptCost = null;
public DateTimeResult LastReceiptDate
{
get
{
if ((object)m_LastReceiptDate == null)
m_LastReceiptDate = (DateTimeResult)AliasFields["LastReceiptDate"];
return m_LastReceiptDate;
}
}
private DateTimeResult m_LastReceiptDate = null;
public NumericResult MinOrderQty
{
get
{
if ((object)m_MinOrderQty == null)
m_MinOrderQty = (NumericResult)AliasFields["MinOrderQty"];
return m_MinOrderQty;
}
}
private NumericResult m_MinOrderQty = null;
public NumericResult MaxOrderQty
{
get
{
if ((object)m_MaxOrderQty == null)
m_MaxOrderQty = (NumericResult)AliasFields["MaxOrderQty"];
return m_MaxOrderQty;
}
}
private NumericResult m_MaxOrderQty = null;
public NumericResult OnOrderQty
{
get
{
if ((object)m_OnOrderQty == null)
m_OnOrderQty = (NumericResult)AliasFields["OnOrderQty"];
return m_OnOrderQty;
}
}
private NumericResult m_OnOrderQty = null;
public StringResult UnitMeasureCode
{
get
{
if ((object)m_UnitMeasureCode == null)
m_UnitMeasureCode = (StringResult)AliasFields["UnitMeasureCode"];
return m_UnitMeasureCode;
}
}
private StringResult m_UnitMeasureCode = null;
public DateTimeResult ModifiedDate
{
get
{
if ((object)m_ModifiedDate == null)
m_ModifiedDate = (DateTimeResult)AliasFields["ModifiedDate"];
return m_ModifiedDate;
}
}
private DateTimeResult m_ModifiedDate = null;
public StringResult Uid
{
get
{
if ((object)m_Uid == null)
m_Uid = (StringResult)AliasFields["Uid"];
return m_Uid;
}
}
private StringResult m_Uid = null;
}
}
| |
using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Collections.Generic;
namespace NavHardwareControl
{
/// <summary>
/// UPDATE FOR NAV CONTROLLER:
/// This is more or less a direct copy of SHC, addapted to our needs.
///
///
/// HOW TO ADD A CHANNEL:
/// 1. add channel + calibration to hardware file
/// 2. add to controller
/// 3. add to controller window
/// 4. add controller window component to list of DOCheckBoxes or AOTextBoxes (found in ControllerWindow()).
///
///
/// OLD:
/// Front panel for the sympathetic hardware controller. Everything is just stuffed in there. No particularly
/// clever structure. This class just hands everything straight off to the controller. It has a few
/// thread safe wrappers so that remote calls can safely manipulate the front panel.
/// </summary>
public class ControlWindow : System.Windows.Forms.Form
{
#region Setup
public Controller controller;
private Dictionary<string, TextBox> AOTextBoxes = new Dictionary<string, TextBox>();
private Dictionary<string, CheckBox> DOCheckBoxes = new Dictionary<string, CheckBox>();
private Dictionary<string, CheckBox> DOHSCheckBoxes = new Dictionary<string, CheckBox>();
public ControlWindow()
{
InitializeComponent();
AOTextBoxes["motCoil"] = motCoilCurrent;
AOTextBoxes["aom1freq"] = AOM1;
AOTextBoxes["motShutter"] = motShutterTextBox;
AOTextBoxes["imagingShutter"] = imageShutterTextBox;
AOTextBoxes["rfSwitch"] = rfSwitch;
AOTextBoxes["rfAtten"] = rfAttenBox;
DOCheckBoxes["testDigitalChannel"] = testChannel;
DOHSCheckBoxes["do00"] = do00;
DOHSCheckBoxes["do01"] = do01;
}
private void WindowClosing(object sender, FormClosingEventArgs e)
{
controller.ControllerStopping();
}
private void WindowLoaded(object sender, EventArgs e)
{
try
{
controller.ControllerLoaded();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.shcTabs = new System.Windows.Forms.TabControl();
this.tabCamera = new System.Windows.Forms.TabPage();
this.stopStreamButton = new System.Windows.Forms.Button();
this.streamButton = new System.Windows.Forms.Button();
this.snapshotButton = new System.Windows.Forms.Button();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.testChannel = new System.Windows.Forms.CheckBox();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.label6 = new System.Windows.Forms.Label();
this.rfAttenBox = new System.Windows.Forms.TextBox();
this.rfSwitch = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.imageShutterTextBox = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.motShutterTextBox = new System.Windows.Forms.TextBox();
this.coil0GroupBox = new System.Windows.Forms.GroupBox();
this.AOM1 = new System.Windows.Forms.TextBox();
this.coil0Label0 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.motCoilCurrent = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadParametersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveParametersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.saveImageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.windowsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openImageViewerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.label1 = new System.Windows.Forms.Label();
this.updateHardwareButton = new System.Windows.Forms.Button();
this.consoleRichTextBox = new System.Windows.Forms.RichTextBox();
this.do00 = new System.Windows.Forms.CheckBox();
this.do01 = new System.Windows.Forms.CheckBox();
this.shcTabs.SuspendLayout();
this.tabCamera.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.coil0GroupBox.SuspendLayout();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// shcTabs
//
this.shcTabs.AllowDrop = true;
this.shcTabs.Controls.Add(this.tabCamera);
this.shcTabs.Controls.Add(this.tabPage1);
this.shcTabs.Controls.Add(this.tabPage2);
this.shcTabs.Location = new System.Drawing.Point(3, 27);
this.shcTabs.Name = "shcTabs";
this.shcTabs.SelectedIndex = 0;
this.shcTabs.Size = new System.Drawing.Size(666, 235);
this.shcTabs.TabIndex = 0;
//
// tabCamera
//
this.tabCamera.Controls.Add(this.stopStreamButton);
this.tabCamera.Controls.Add(this.streamButton);
this.tabCamera.Controls.Add(this.snapshotButton);
this.tabCamera.Location = new System.Drawing.Point(4, 22);
this.tabCamera.Name = "tabCamera";
this.tabCamera.Padding = new System.Windows.Forms.Padding(3);
this.tabCamera.Size = new System.Drawing.Size(658, 209);
this.tabCamera.TabIndex = 0;
this.tabCamera.Text = "Camera Control";
this.tabCamera.UseVisualStyleBackColor = true;
//
// stopStreamButton
//
this.stopStreamButton.Location = new System.Drawing.Point(168, 6);
this.stopStreamButton.Name = "stopStreamButton";
this.stopStreamButton.Size = new System.Drawing.Size(75, 23);
this.stopStreamButton.TabIndex = 18;
this.stopStreamButton.Text = "Stop";
this.stopStreamButton.UseVisualStyleBackColor = true;
this.stopStreamButton.Click += new System.EventHandler(this.stopStreamButton_Click);
//
// streamButton
//
this.streamButton.Location = new System.Drawing.Point(87, 6);
this.streamButton.Name = "streamButton";
this.streamButton.Size = new System.Drawing.Size(75, 23);
this.streamButton.TabIndex = 17;
this.streamButton.Text = "Stream";
this.streamButton.UseVisualStyleBackColor = true;
this.streamButton.Click += new System.EventHandler(this.streamButton_Click);
//
// snapshotButton
//
this.snapshotButton.Location = new System.Drawing.Point(6, 6);
this.snapshotButton.Name = "snapshotButton";
this.snapshotButton.Size = new System.Drawing.Size(75, 23);
this.snapshotButton.TabIndex = 15;
this.snapshotButton.Text = "Snapshot";
this.snapshotButton.UseVisualStyleBackColor = true;
this.snapshotButton.Click += new System.EventHandler(this.snapshotButton_Click);
//
// tabPage1
//
this.tabPage1.Controls.Add(this.do01);
this.tabPage1.Controls.Add(this.do00);
this.tabPage1.Controls.Add(this.testChannel);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(658, 209);
this.tabPage1.TabIndex = 1;
this.tabPage1.Text = "Digital Line";
this.tabPage1.UseVisualStyleBackColor = true;
//
// testChannel
//
this.testChannel.AutoSize = true;
this.testChannel.Location = new System.Drawing.Point(19, 18);
this.testChannel.Name = "testChannel";
this.testChannel.Size = new System.Drawing.Size(89, 17);
this.testChannel.TabIndex = 0;
this.testChannel.Text = "Test Channel";
this.testChannel.UseVisualStyleBackColor = true;
//
// tabPage2
//
this.tabPage2.Controls.Add(this.label6);
this.tabPage2.Controls.Add(this.rfAttenBox);
this.tabPage2.Controls.Add(this.rfSwitch);
this.tabPage2.Controls.Add(this.label5);
this.tabPage2.Controls.Add(this.imageShutterTextBox);
this.tabPage2.Controls.Add(this.label4);
this.tabPage2.Controls.Add(this.label3);
this.tabPage2.Controls.Add(this.motShutterTextBox);
this.tabPage2.Controls.Add(this.coil0GroupBox);
this.tabPage2.Controls.Add(this.label2);
this.tabPage2.Controls.Add(this.motCoilCurrent);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(658, 209);
this.tabPage2.TabIndex = 2;
this.tabPage2.Text = "Analog Lines";
this.tabPage2.UseVisualStyleBackColor = true;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(20, 171);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(70, 13);
this.label6.TabIndex = 22;
this.label6.Text = "rf Attenuation";
//
// rfAttenBox
//
this.rfAttenBox.Location = new System.Drawing.Point(107, 168);
this.rfAttenBox.Name = "rfAttenBox";
this.rfAttenBox.Size = new System.Drawing.Size(100, 20);
this.rfAttenBox.TabIndex = 21;
//
// rfSwitch
//
this.rfSwitch.Location = new System.Drawing.Point(107, 130);
this.rfSwitch.Name = "rfSwitch";
this.rfSwitch.Size = new System.Drawing.Size(100, 20);
this.rfSwitch.TabIndex = 20;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(20, 133);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(48, 13);
this.label5.TabIndex = 19;
this.label5.Text = "rf Switch";
//
// imageShutterTextBox
//
this.imageShutterTextBox.Location = new System.Drawing.Point(107, 91);
this.imageShutterTextBox.Name = "imageShutterTextBox";
this.imageShutterTextBox.Size = new System.Drawing.Size(100, 20);
this.imageShutterTextBox.TabIndex = 18;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(20, 94);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(81, 13);
this.label4.TabIndex = 17;
this.label4.Text = "Imaging Shutter";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(39, 55);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(62, 13);
this.label3.TabIndex = 16;
this.label3.Text = "Mot Shutter";
//
// motShutterTextBox
//
this.motShutterTextBox.Location = new System.Drawing.Point(107, 52);
this.motShutterTextBox.Name = "motShutterTextBox";
this.motShutterTextBox.Size = new System.Drawing.Size(100, 20);
this.motShutterTextBox.TabIndex = 15;
//
// coil0GroupBox
//
this.coil0GroupBox.Controls.Add(this.AOM1);
this.coil0GroupBox.Controls.Add(this.coil0Label0);
this.coil0GroupBox.Location = new System.Drawing.Point(263, 18);
this.coil0GroupBox.Name = "coil0GroupBox";
this.coil0GroupBox.Size = new System.Drawing.Size(225, 45);
this.coil0GroupBox.TabIndex = 14;
this.coil0GroupBox.TabStop = false;
this.coil0GroupBox.Text = "AOM 1";
//
// AOM1
//
this.AOM1.Location = new System.Drawing.Point(99, 17);
this.AOM1.Name = "AOM1";
this.AOM1.Size = new System.Drawing.Size(100, 20);
this.AOM1.TabIndex = 8;
this.AOM1.Text = "0";
//
// coil0Label0
//
this.coil0Label0.AutoSize = true;
this.coil0Label0.Location = new System.Drawing.Point(40, 20);
this.coil0Label0.Name = "coil0Label0";
this.coil0Label0.Size = new System.Drawing.Size(50, 13);
this.coil0Label0.TabIndex = 7;
this.coil0Label0.Text = "Freq (Hz)";
this.coil0Label0.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(3, 18);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(98, 13);
this.label2.TabIndex = 1;
this.label2.Text = "Mot Coil Current (A)";
//
// motCoilCurrent
//
this.motCoilCurrent.Location = new System.Drawing.Point(107, 15);
this.motCoilCurrent.Name = "motCoilCurrent";
this.motCoilCurrent.Size = new System.Drawing.Size(100, 20);
this.motCoilCurrent.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(0, 0);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
//
// checkBox1
//
this.checkBox1.Location = new System.Drawing.Point(0, 0);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(104, 24);
this.checkBox1.TabIndex = 0;
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(0, 0);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 20);
this.textBox1.TabIndex = 0;
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(0, 0);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(100, 20);
this.textBox2.TabIndex = 0;
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.windowsToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(794, 24);
this.menuStrip.TabIndex = 15;
this.menuStrip.Text = "menuStrip";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.loadParametersToolStripMenuItem,
this.saveParametersToolStripMenuItem,
this.toolStripSeparator1,
this.saveImageToolStripMenuItem,
this.toolStripSeparator2,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20);
this.fileToolStripMenuItem.Text = "File";
//
// loadParametersToolStripMenuItem
//
this.loadParametersToolStripMenuItem.Name = "loadParametersToolStripMenuItem";
this.loadParametersToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
this.loadParametersToolStripMenuItem.Text = "Load parameters";
this.loadParametersToolStripMenuItem.Click += new System.EventHandler(this.loadParametersToolStripMenuItem_Click);
//
// saveParametersToolStripMenuItem
//
this.saveParametersToolStripMenuItem.Name = "saveParametersToolStripMenuItem";
this.saveParametersToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
this.saveParametersToolStripMenuItem.Text = "Save parameters on UI";
this.saveParametersToolStripMenuItem.Click += new System.EventHandler(this.saveParametersToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(182, 6);
//
// saveImageToolStripMenuItem
//
this.saveImageToolStripMenuItem.Name = "saveImageToolStripMenuItem";
this.saveImageToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
this.saveImageToolStripMenuItem.Text = "Save image";
this.saveImageToolStripMenuItem.Click += new System.EventHandler(this.saveImageToolStripMenuItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(182, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
this.exitToolStripMenuItem.Text = "Exit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// windowsToolStripMenuItem
//
this.windowsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openImageViewerToolStripMenuItem});
this.windowsToolStripMenuItem.Name = "windowsToolStripMenuItem";
this.windowsToolStripMenuItem.Size = new System.Drawing.Size(62, 20);
this.windowsToolStripMenuItem.Text = "Windows";
//
// openImageViewerToolStripMenuItem
//
this.openImageViewerToolStripMenuItem.Name = "openImageViewerToolStripMenuItem";
this.openImageViewerToolStripMenuItem.Size = new System.Drawing.Size(250, 22);
this.openImageViewerToolStripMenuItem.Text = "Start camera and open image viewer";
this.openImageViewerToolStripMenuItem.Click += new System.EventHandler(this.openImageViewerToolStripMenuItem_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(675, 36);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 13);
this.label1.TabIndex = 18;
this.label1.Text = "Remote Control";
//
// updateHardwareButton
//
this.updateHardwareButton.Location = new System.Drawing.Point(678, 62);
this.updateHardwareButton.Name = "updateHardwareButton";
this.updateHardwareButton.Size = new System.Drawing.Size(102, 23);
this.updateHardwareButton.TabIndex = 21;
this.updateHardwareButton.Text = "Update hardware";
this.updateHardwareButton.UseVisualStyleBackColor = true;
this.updateHardwareButton.Click += new System.EventHandler(this.updateHardwareButton_Click);
//
// consoleRichTextBox
//
this.consoleRichTextBox.BackColor = System.Drawing.Color.Black;
this.consoleRichTextBox.ForeColor = System.Drawing.Color.Lime;
this.consoleRichTextBox.Location = new System.Drawing.Point(3, 264);
this.consoleRichTextBox.Name = "consoleRichTextBox";
this.consoleRichTextBox.ReadOnly = true;
this.consoleRichTextBox.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Vertical;
this.consoleRichTextBox.Size = new System.Drawing.Size(791, 154);
this.consoleRichTextBox.TabIndex = 23;
this.consoleRichTextBox.Text = "";
//
// do00
//
this.do00.AutoSize = true;
this.do00.Location = new System.Drawing.Point(19, 52);
this.do00.Name = "do00";
this.do00.Size = new System.Drawing.Size(50, 17);
this.do00.TabIndex = 1;
this.do00.Text = "do00";
this.do00.UseVisualStyleBackColor = true;
//
// do01
//
this.do01.AutoSize = true;
this.do01.Location = new System.Drawing.Point(19, 85);
this.do01.Name = "do01";
this.do01.Size = new System.Drawing.Size(50, 17);
this.do01.TabIndex = 2;
this.do01.Text = "do01";
this.do01.UseVisualStyleBackColor = true;
//
// ControlWindow
//
this.ClientSize = new System.Drawing.Size(794, 419);
this.Controls.Add(this.consoleRichTextBox);
this.Controls.Add(this.updateHardwareButton);
this.Controls.Add(this.label1);
this.Controls.Add(this.shcTabs);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "ControlWindow";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Navigator Hardware Control";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.WindowClosing);
this.Load += new System.EventHandler(this.WindowLoaded);
this.shcTabs.ResumeLayout(false);
this.tabCamera.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage1.PerformLayout();
this.tabPage2.ResumeLayout(false);
this.tabPage2.PerformLayout();
this.coil0GroupBox.ResumeLayout(false);
this.coil0GroupBox.PerformLayout();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
#region ThreadSafe wrappers
private void setCheckBox(CheckBox box, bool state)
{
box.Invoke(new setCheckDelegate(setCheckHelper), new object[] { box, state });
}
private delegate void setCheckDelegate(CheckBox box, bool state);
private void setCheckHelper(CheckBox box, bool state)
{
box.Checked = state;
}
private void setTabEnable(TabControl box, bool state)
{
box.Invoke(new setTabEnableDelegate(setTabEnableHelper), new object[] { box, state });
}
private delegate void setTabEnableDelegate(TabControl box, bool state);
private void setTabEnableHelper(TabControl box, bool state)
{
box.Enabled = state;
}
private void setTextBox(TextBox box, string text)
{
box.Invoke(new setTextDelegate(setTextHelper), new object[] { box, text });
}
private delegate void setTextDelegate(TextBox box, string text);
private void setTextHelper(TextBox box, string text)
{
box.Text = text;
}
private void setRichTextBox(RichTextBox box, string text)
{
box.Invoke(new setRichTextDelegate(setRichTextHelper), new object[] { box, text });
}
private delegate void setRichTextDelegate(RichTextBox box, string text);
private void setRichTextHelper(RichTextBox box, string text)
{
box.AppendText(text);
consoleRichTextBox.ScrollToCaret();
}
#endregion
#region Declarations
//Declare stuff here
public TabControl shcTabs;
public TabPage tabCamera;
private Button button1;
public CheckBox checkBox1;
public TextBox textBox1;
public TextBox textBox2;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem loadParametersToolStripMenuItem;
private ToolStripMenuItem saveParametersToolStripMenuItem;
private ToolStripMenuItem saveImageToolStripMenuItem;
private ToolStripMenuItem exitToolStripMenuItem;
private ToolStripSeparator toolStripSeparator1;
private ToolStripSeparator toolStripSeparator2;
private Button snapshotButton;
private Label label1;
private Button updateHardwareButton;
private ToolStripMenuItem windowsToolStripMenuItem;
private RichTextBox consoleRichTextBox;
private ToolStripMenuItem openImageViewerToolStripMenuItem;
private Button streamButton;
private Button stopStreamButton;
private TabPage tabPage1;
private CheckBox testChannel;
private TabPage tabPage2;
private Label label2;
private TextBox motCoilCurrent;
private GroupBox coil0GroupBox;
public TextBox AOM1;
private Label coil0Label0;
#endregion
#region Click Handlers
private void saveParametersToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.SaveParametersWithDialog();
}
private void saveImageToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.SaveImageWithDialog();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void updateHardwareButton_Click(object sender, EventArgs e)
{
controller.UpdateHardware();
}
private void loadParametersToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.LoadParametersWithDialog();
}
#endregion
#region Public properties for controlling UI.
//This gets/sets the values on the GUI panel
public void WriteToConsole(string text)
{
setRichTextBox(consoleRichTextBox, ">> " + text + "\n");
}
public double ReadAnalog(string channelName)
{
return double.Parse(AOTextBoxes[channelName].Text);
}
public void SetAnalog(string channelName, double value)
{
setTextBox(AOTextBoxes[channelName], Convert.ToString(value));
}
public bool ReadDigital(string channelName)
{
return DOCheckBoxes[channelName].Checked;
}
public void SetDigital(string channelName, bool value)
{
setCheckBox(DOCheckBoxes[channelName], value);
}
public bool ReadHSDigital(string channelName)
{
return DOHSCheckBoxes[channelName].Checked;
}
public void SetHSDigital(string channelName, bool value)
{
setCheckBox(DOHSCheckBoxes[channelName], value);
}
#endregion
#region Camera Control
private void snapshotButton_Click(object sender, EventArgs e)
{
controller.CameraSnapshot();
}
private void streamButton_Click(object sender, EventArgs e)
{
controller.CameraStream();
}
private void stopStreamButton_Click(object sender, EventArgs e)
{
controller.StopCameraStream();
}
#endregion
#region UI state
public void UpdateUIState(Controller.HCUIControlState state)
{
switch (state)
{
case Controller.HCUIControlState.OFF:
setTabEnable(shcTabs, true);
break;
case Controller.HCUIControlState.LOCAL:
setTabEnable(shcTabs, true);
break;
case Controller.HCUIControlState.REMOTE:
setTabEnable(shcTabs, false) ;
break;
}
}
#endregion
#region Other Windows
private void openImageViewerToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.StartCameraControl();
}
#endregion
private Label label3;
private TextBox motShutterTextBox;
private TextBox imageShutterTextBox;
private Label label4;
private TextBox rfSwitch;
private Label label5;
private Label label6;
private TextBox rfAttenBox;
private CheckBox do01;
private CheckBox do00;
}
}
| |
/*
* Qa full api
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: all
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace HostMe.Sdk.Model
{
/// <summary>
/// RestaurantContactInfo
/// </summary>
[DataContract]
public partial class RestaurantContactInfo : IEquatable<RestaurantContactInfo>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="RestaurantContactInfo" /> class.
/// </summary>
/// <param name="Id">Id.</param>
/// <param name="Name">Name.</param>
/// <param name="Address">Address.</param>
/// <param name="ImageUrl">ImageUrl.</param>
/// <param name="WebsiteUrl">WebsiteUrl.</param>
/// <param name="Phone">Phone.</param>
/// <param name="TimeZone">TimeZone.</param>
public RestaurantContactInfo(int? Id = null, string Name = null, string Address = null, string ImageUrl = null, string WebsiteUrl = null, string Phone = null, string TimeZone = null)
{
this.Id = Id;
this.Name = Name;
this.Address = Address;
this.ImageUrl = ImageUrl;
this.WebsiteUrl = WebsiteUrl;
this.Phone = Phone;
this.TimeZone = TimeZone;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=true)]
public int? Id { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=true)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets Address
/// </summary>
[DataMember(Name="address", EmitDefaultValue=true)]
public string Address { get; set; }
/// <summary>
/// Gets or Sets ImageUrl
/// </summary>
[DataMember(Name="imageUrl", EmitDefaultValue=true)]
public string ImageUrl { get; set; }
/// <summary>
/// Gets or Sets WebsiteUrl
/// </summary>
[DataMember(Name="websiteUrl", EmitDefaultValue=true)]
public string WebsiteUrl { get; set; }
/// <summary>
/// Gets or Sets Phone
/// </summary>
[DataMember(Name="phone", EmitDefaultValue=true)]
public string Phone { get; set; }
/// <summary>
/// Gets or Sets TimeZone
/// </summary>
[DataMember(Name="timeZone", EmitDefaultValue=true)]
public string TimeZone { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class RestaurantContactInfo {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Address: ").Append(Address).Append("\n");
sb.Append(" ImageUrl: ").Append(ImageUrl).Append("\n");
sb.Append(" WebsiteUrl: ").Append(WebsiteUrl).Append("\n");
sb.Append(" Phone: ").Append(Phone).Append("\n");
sb.Append(" TimeZone: ").Append(TimeZone).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as RestaurantContactInfo);
}
/// <summary>
/// Returns true if RestaurantContactInfo instances are equal
/// </summary>
/// <param name="other">Instance of RestaurantContactInfo to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(RestaurantContactInfo other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Address == other.Address ||
this.Address != null &&
this.Address.Equals(other.Address)
) &&
(
this.ImageUrl == other.ImageUrl ||
this.ImageUrl != null &&
this.ImageUrl.Equals(other.ImageUrl)
) &&
(
this.WebsiteUrl == other.WebsiteUrl ||
this.WebsiteUrl != null &&
this.WebsiteUrl.Equals(other.WebsiteUrl)
) &&
(
this.Phone == other.Phone ||
this.Phone != null &&
this.Phone.Equals(other.Phone)
) &&
(
this.TimeZone == other.TimeZone ||
this.TimeZone != null &&
this.TimeZone.Equals(other.TimeZone)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Address != null)
hash = hash * 59 + this.Address.GetHashCode();
if (this.ImageUrl != null)
hash = hash * 59 + this.ImageUrl.GetHashCode();
if (this.WebsiteUrl != null)
hash = hash * 59 + this.WebsiteUrl.GetHashCode();
if (this.Phone != null)
hash = hash * 59 + this.Phone.GetHashCode();
if (this.TimeZone != null)
hash = hash * 59 + this.TimeZone.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System.Text;
using Bridge.Contract;
using Bridge.Contract.Constants;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.Semantics;
namespace Bridge.Translator
{
public abstract partial class AbstractEmitterBlock : IAbstractEmitterBlock
{
private AstNode previousNode;
public AbstractEmitterBlock(IEmitter emitter, AstNode node)
{
this.Emitter = emitter;
this.previousNode = this.Emitter.Translator.EmitNode;
this.Emitter.Translator.EmitNode = node;
}
protected abstract void DoEmit();
public AstNode PreviousNode
{
get
{
return this.previousNode;
}
}
public IEmitter Emitter
{
get;
set;
}
public virtual void Emit()
{
this.BeginEmit();
this.DoEmit();
this.EndEmit();
}
private int startPos;
private int checkPos;
private StringBuilder checkedOutput;
protected virtual void BeginEmit()
{
if (this.NeedSequencePoint())
{
this.startPos = this.Emitter.Output.Length;
this.WriteSequencePoint(this.Emitter.Translator.EmitNode.Region);
this.checkPos = this.Emitter.Output.Length;
this.checkedOutput = this.Emitter.Output;
}
}
protected virtual void EndEmit()
{
if (this.NeedSequencePoint() && this.checkPos == this.Emitter.Output.Length && this.checkedOutput == this.Emitter.Output)
{
this.Emitter.Output.Length = this.startPos;
}
this.Emitter.Translator.EmitNode = this.previousNode;
}
protected bool NeedSequencePoint()
{
if (this.Emitter.Translator.EmitNode != null && !this.Emitter.Translator.EmitNode.Region.IsEmpty)
{
if (this.Emitter.Translator.EmitNode is EntityDeclaration ||
this.Emitter.Translator.EmitNode is BlockStatement ||
this.Emitter.Translator.EmitNode is ArrayInitializerExpression ||
this.Emitter.Translator.EmitNode is PrimitiveExpression ||
this.Emitter.Translator.EmitNode is Comment)
{
return false;
}
return true;
}
return false;
}
public virtual void EmitBlockOrIndentedLine(AstNode node)
{
bool block = node is BlockStatement;
var ifStatement = node.Parent as IfElseStatement;
if (!block && node is IfElseStatement && ifStatement != null && ifStatement.FalseStatement == node)
{
block = true;
}
if (!block)
{
this.WriteNewLine();
this.Indent();
}
else
{
this.WriteSpace();
}
node.AcceptVisitor(this.Emitter);
if (!block)
{
this.Outdent();
}
}
public bool NoValueableSiblings(AstNode node)
{
while (node.NextSibling != null)
{
var sibling = node.NextSibling;
if (sibling is NewLineNode || sibling is CSharpTokenNode || sibling is Comment)
{
node = sibling;
}
else
{
return false;
}
}
return true;
}
protected AstNode[] GetAwaiters(AstNode node)
{
var awaitSearch = new AwaitSearchVisitor(this.Emitter);
node.AcceptVisitor(awaitSearch);
return awaitSearch.GetAwaitExpressions().ToArray();
}
protected bool IsDirectAsyncBlockChild(AstNode node)
{
var block = node.GetParent<BlockStatement>();
if (block != null && (block.Parent is MethodDeclaration || block.Parent is AnonymousMethodExpression || block.Parent is LambdaExpression))
{
return true;
}
return false;
}
protected IAsyncStep WriteAwaiter(AstNode node)
{
var index = System.Array.IndexOf(this.Emitter.AsyncBlock.AwaitExpressions, node) + 1;
if (node is ConditionalExpression)
{
new ConditionalBlock(this.Emitter, (ConditionalExpression)node).WriteAsyncConditionalExpression(index);
return null;
}
if (node is BinaryOperatorExpression)
{
var binaryOperatorExpression = (BinaryOperatorExpression)node;
if (binaryOperatorExpression.Operator == BinaryOperatorType.BitwiseAnd ||
binaryOperatorExpression.Operator == BinaryOperatorType.BitwiseOr ||
binaryOperatorExpression.Operator == BinaryOperatorType.ConditionalOr ||
binaryOperatorExpression.Operator == BinaryOperatorType.ConditionalAnd)
{
new BinaryOperatorBlock(this.Emitter, binaryOperatorExpression).WriteAsyncBinaryExpression(index);
return null;
}
}
if (this.Emitter.AsyncBlock.WrittenAwaitExpressions.Contains(node))
{
return null;
}
this.Emitter.AsyncBlock.WrittenAwaitExpressions.Add(node);
this.Write(JS.Vars.ASYNC_TASK + index + " = ");
bool customAwaiter = false;
var oldValue = this.Emitter.ReplaceAwaiterByVar;
this.Emitter.ReplaceAwaiterByVar = true;
var unaryExpr = node.Parent as UnaryOperatorExpression;
if (unaryExpr != null && unaryExpr.Operator == UnaryOperatorType.Await)
{
var rr = this.Emitter.Resolver.ResolveNode(unaryExpr, this.Emitter) as AwaitResolveResult;
if (rr != null)
{
var awaiterMethod = rr.GetAwaiterInvocation as InvocationResolveResult;
if (awaiterMethod != null && awaiterMethod.Member.FullName != "System.Threading.Tasks.Task.GetAwaiter")
{
this.WriteCustomAwaiter(node, awaiterMethod);
customAwaiter = true;
}
}
}
if (!customAwaiter)
{
node.AcceptVisitor(this.Emitter);
}
this.Emitter.ReplaceAwaiterByVar = oldValue;
this.WriteSemiColon();
this.WriteNewLine();
this.Write(JS.Vars.ASYNC_STEP + " = " + this.Emitter.AsyncBlock.Step + ";");
this.WriteNewLine();
this.WriteIf();
this.WriteOpenParentheses();
this.Write(JS.Vars.ASYNC_TASK + index + ".isCompleted()");
this.WriteCloseParentheses();
this.WriteSpace();
this.WriteBlock("continue;");
this.Write(JS.Vars.ASYNC_TASK + index + "." + JS.Funcs.CONTINUE_WITH + "(" + JS.Funcs.ASYNC_BODY + ");");
this.WriteNewLine();
if (this.Emitter.WrapRestCounter > 0)
{
this.EndBlock();
this.Write("));");
this.WriteNewLine();
this.Emitter.WrapRestCounter--;
}
this.Write("return;");
var asyncStep = this.Emitter.AsyncBlock.AddAsyncStep(index);
if (this.Emitter.AsyncBlock.EmittedAsyncSteps != null)
{
this.Emitter.AsyncBlock.EmittedAsyncSteps.Add(asyncStep);
}
return asyncStep;
}
private void WriteCustomAwaiter(AstNode node, InvocationResolveResult awaiterMethod)
{
var method = awaiterMethod.Member;
var inline = this.Emitter.GetInline(method);
if (!string.IsNullOrWhiteSpace(inline))
{
var argsInfo = new ArgumentsInfo(this.Emitter, node as Expression, awaiterMethod);
new InlineArgumentsBlock(this.Emitter, argsInfo, inline).Emit();
}
else
{
if (method.IsStatic)
{
this.Write(BridgeTypes.ToJsName(method.DeclaringType, this.Emitter));
this.WriteDot();
this.Write(OverloadsCollection.Create(this.Emitter, method).GetOverloadName());
this.WriteOpenParentheses();
new ExpressionListBlock(this.Emitter, new Expression[] { (Expression)node }, null, null, 0).Emit();
this.WriteCloseParentheses();
}
else
{
node.AcceptVisitor(this.Emitter);
this.WriteDot();
var name = OverloadsCollection.Create(this.Emitter, method).GetOverloadName();
this.Write(name);
this.WriteOpenParentheses();
this.WriteCloseParentheses();
}
}
}
protected void WriteAwaiters(AstNode node)
{
var awaiters = this.Emitter.IsAsync && !node.IsNull ? this.GetAwaiters(node) : null;
if (awaiters != null && awaiters.Length > 0)
{
var oldValue = this.Emitter.AsyncExpressionHandling;
this.Emitter.AsyncExpressionHandling = true;
foreach (var awaiter in awaiters)
{
this.WriteAwaiter(awaiter);
}
this.Emitter.AsyncExpressionHandling = oldValue;
}
}
public AstNode GetParentFinallyBlock(AstNode node, bool stopOnLoops)
{
var insideTryFinally = false;
var target = node.GetParent(n =>
{
if (n is LambdaExpression || n is AnonymousMethodExpression || n is MethodDeclaration)
{
return true;
}
if (stopOnLoops && (n is WhileStatement || n is ForeachStatement || n is ForStatement || n is DoWhileStatement))
{
return true;
}
if (n is TryCatchStatement && !((TryCatchStatement)n).FinallyBlock.IsNull)
{
insideTryFinally = true;
return true;
}
return false;
});
return insideTryFinally ? ((TryCatchStatement)target).FinallyBlock : null;
}
public CatchClause GetParentCatchBlock(AstNode node, bool stopOnLoops)
{
var insideCatch = false;
var target = node.GetParent(n =>
{
if (n is LambdaExpression || n is AnonymousMethodExpression || n is MethodDeclaration)
{
return true;
}
if (stopOnLoops && (n is WhileStatement || n is ForeachStatement || n is ForStatement || n is DoWhileStatement))
{
return true;
}
if (n is CatchClause)
{
insideCatch = true;
return true;
}
return false;
});
return insideCatch ? (CatchClause)target : null;
}
public void WriteIdentifier(string name, bool script = true, bool colon = false)
{
var isValid = Helpers.IsValidIdentifier(name);
if (isValid)
{
this.Write(name);
}
else
{
if (colon)
{
this.WriteScript(name);
}
else if (this.Emitter.Output[this.Emitter.Output.Length - 1] == '.')
{
--this.Emitter.Output.Length;
this.Write("[");
if (script)
{
this.WriteScript(name);
}
else
{
this.Write(name);
}
this.Write("]");
}
}
}
}
}
| |
using RefactoringEssentials.CSharp.CodeRefactorings;
using Xunit;
namespace RefactoringEssentials.Tests.CSharp.CodeRefactorings
{
public class LinqFluentToQueryTests : CSharpCodeRefactoringTestBase
{
[Fact(Skip="Not implemented!")]
public void TestBasicCase()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].$Select (t => t);
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from t in new int[0]
select t;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestAddedParenthesis()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].$Select (t => t) + 1;
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = (from t in new int[0]
select t) + 1;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestCast()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].$Cast<int> ();
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from int _1 in new int[0]
select _1;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestLet()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].Select (w => new { w, two = w * 2 }).$Select (_ => _.two);
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from w in new int[0]
let two = w * 2
select two;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestLet2()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].Select (w => new { two = w * 2, w }).$Select (_ => _.two);
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from w in new int[0]
let two = w * 2
select two;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestLongLetChain()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].Select (w => new { w, two = w * 2 })
.Select (h => new { h, three = h.w * 3 })
.Select (k => new { k, four = k.h.w * 4 })
.$Select (_ => _.k.h.w + _.k.h.two + _.k.three + _.four)
.Select (sum => sum * 2);
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from w in new int[0]
let two = w * 2
let three = w * 3
let four = w * 4
select w + two + three + four into sum
select sum * 2;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestLongLetChain2()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].Select (w => new { two = w * 2, w })
.Select (h => new { three = h.w * 3, h })
.Select (k => new { four = k.h.w * 4, k })
.$Select (_ => _.k.h.w + _.k.h.two + _.k.three + _.four)
.Select (sum => sum * 2);
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from w in new int[0]
let two = w * 2
let three = w * 3
let four = w * 4
select w + two + three + four into sum
select sum * 2;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestSelectMany()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].$SelectMany (elem => new int[0], (elem1, elem2) => elem1 + elem2);
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from elem1 in new int[0]
from elem2 in new int[0]
select elem1 + elem2;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestSelectManyLet()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].$SelectMany (elem => new int[0], (elem1, elem2) => new { elem1, elem2 }).Select(i => new { i, sum = i.elem1 + i.elem2 })
.Select(j => j.i.elem1 + j.i.elem2 + j.sum);
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from elem1 in new int[0]
from elem2 in new int[0]
let sum = elem1 + elem2
select elem1 + elem2 + sum;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestSelectManyLet2()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].$SelectMany (elem => new int[0], (elem1, elem2) => new { elem1, elem2 = elem2 + 1 }).Select(i => new { i, sum = i.elem1 + i.elem2 })
.Select(j => j.i.elem1 + j.i.elem2 + j.sum);
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from elem1 in new int[0]
from elem2 in new int[0]
select new {
elem1,
elem2 = elem2 + 1
} into i
let sum = i.elem1 + i.elem2
select i.elem1 + i.elem2 + sum;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestCastSelect()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].$Cast<int> ().Select (t => t * 2);
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from int t in new int[0]
select t * 2;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestSelectWhere()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].$Where (t => t > 0).Select (t => t * 2);
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from t in new int[0]
where t > 0
select t * 2;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestSorting()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].$OrderBy (t => t).ThenByDescending (t => t);
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from t in new int[0]
orderby t, t descending
select t;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestDegenerateWhere()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].$Where (t => t > 0);
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from t in new int[0]
where t > 0
select t;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestChain()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].Where (t => t > 0).$Where (u => u > 0);
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from t in new int[0]
where t > 0
select t into u
where u > 0
select u;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestJoin()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].Cast<char> ().$Join(new int[0].Cast<float> (), a => a * 2, b => b, (l, r) => l * r);
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from char a in new int[0]
join float b in new int[0] on a * 2 equals b
select a * b;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestGroupJoin()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].Cast<char> ().$GroupJoin(new int[0].Cast<float> (), a => a * 2, b => b, (l, r) => l * r [0]);
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from char a in new int[0]
join float b in new int[0] on a * 2 equals b into r
select a * r [0];
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestNonRecursive()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = Enumerable.Empty<int[]> ().$Select (t => t.Select (v => v));
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from t in Enumerable.Empty<int[]> ()
select t.Select (v => v);
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestNonRecursiveCombineQueries()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = Enumerable.Empty<int[]> ().$Select (t => (from g in t select g));
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from t in Enumerable.Empty<int[]> ()
select (from g in t
select g);
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestGroupBy()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].$GroupBy (t => t, t => new int[0]);
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from t in new int[0]
group new int[0] by t;
}
}");
}
[Fact(Skip="Not implemented!")]
public void Test_1AlreadyUsed()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
int _1;
var x = new int[0].$Cast<float> ();
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
int _1;
var x = from float _2 in new int[0]
select _2;
}
}");
}
[Fact(Skip="Not implemented!")]
public void TestDoubleCasts()
{
Test<LinqFluentToQueryAction>(@"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = new int[0].$Cast<float> ().Cast<int> ();
}
}", @"
using System.Linq;
class TestClass
{
void TestMethod ()
{
var x = from int _1 in
from float _2 in new int[0]
select _2
select _1;
}
}");
}
}
}
| |
/* See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Esri Inc. licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
namespace com.esri.gpt.csw { /// <summary>
/// Maintains information of CSW Catalog
/// </summary>
/// <remarks>
/// The catalogs contain all the information like url, profile information
/// credentials and capabilities.
/// </remarks>
///
public class CswCatalog:IComparable
{
private static int IDCounter = 1 ;
private string id;
private string name;
private bool locking;
private string url;
private string baseurl;
private CswProfile profile;
private CswCatalogCapabilities capabilities;
private bool isConnect;
#region "Properties"
/// <summary>
/// Name parameter
/// </summary>
public string Name {
set {
if (value.Length > 0)
name = value;
else
name = url;
}
get {
return name;
}
}
/// <summary>
/// URL parameter
/// </summary>
public string URL {
set {
url = value;
}
get {
return url;
}
}
/// <summary>
/// BaseURL parameter
/// </summary>
public string BaseURL {
set {
baseurl = value;
}
get {
return baseurl;
}
}
/// <summary>
/// Profile parameter
/// </summary>
public CswProfile Profile {
set {
profile = value;
}
get {
return profile;
}
}
/// <summary>
/// HashKey parameter
/// </summary>
public int HashKey {
get {
return url.GetHashCode();
}
}
/// <summary>
/// ID parameter
/// </summary>
public string ID {
get {
return id;
}
}
/// <summary>
/// Locking parameter
/// </summary>
public bool Locking {
set {
locking = value;
}
get {
return locking;
}
}
/// <summary>
/// Capabilities parameter
/// </summary>
internal CswCatalogCapabilities Capabilities
{
get
{
return capabilities;
}
}
#endregion
# region constructor definition
/// <summary>
/// Constructor
/// </summary>
public CswCatalog() {
id = "catalog"+ IDCounter.ToString();
IDCounter++;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="surl"></param>
/// <param name="sname"></param>
/// <param name="oprofile"></param>
public CswCatalog(String surl, String sname, CswProfile oprofile) {
id = "catalog" + IDCounter.ToString();
IDCounter++;
URL = surl;
Profile = oprofile;
Name = sname;
Locking = false;
}
#endregion
#region "PrivateFunction"
/// <summary>
/// To retrieve informations about the CSW service.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="param1">capabilities baseurl</param>
/// <returns>Response the get capabilities url</returns>
private string GetCapabilities(string capabilitiesurl) {
try {
CswClient client = new CswClient();
Utils.logger.writeLog("GetCapabilities url : " + capabilitiesurl);
string response = client.SubmitHttpRequest("GET", capabilitiesurl, "");
Utils.logger.writeLog("GetCapabilities response : " + response);
//Console.WriteLine()
XmlDocument xmlDoc = new XmlDocument();
if (response == null)
return null ;
xmlDoc.LoadXml(response);
XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(xmlDoc.NameTable);
if (this.Profile.CswNamespace.Length <= 0) {
this.Profile.CswNamespace = CswProfiles.DEFAULT_CSW_NAMESPACE;
}
xmlnsManager.AddNamespace("ows", "http://www.opengis.net/ows");
xmlnsManager.AddNamespace("csw", this.Profile.CswNamespace);
xmlnsManager.AddNamespace("wrs10", "http://www.opengis.net/cat/wrs/1.0");
xmlnsManager.AddNamespace("wrs", "http://www.opengis.net/cat/wrs");
xmlnsManager.AddNamespace("xlink", "http://www.w3.org/1999/xlink");
xmlnsManager.AddNamespace("wcs", "http://www.opengis.net/wcs");
if (xmlDoc.SelectSingleNode("/csw:Capabilities|/wrs:Capabilities| /wrs10:Capabilities | /wcs:WCS_Capabilities", xmlnsManager) != null)
return response;
else
return null;
}
catch (Exception ex) {
Utils.logger.writeLog(ex.StackTrace);
throw ex;
}
}
/// <summary>
/// To retrieve informations about the CSW service.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="param1">capabilitiesxml details </param>
private bool ParseCapabilities(string capabilitiesxml) {
try {
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(capabilitiesxml);
XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(xmlDoc.NameTable);
if (this.Profile.CswNamespace.Length <= 0) {
this.Profile.CswNamespace = CswProfiles.DEFAULT_CSW_NAMESPACE;
}
xmlnsManager.AddNamespace("ows", "http://www.opengis.net/ows");
xmlnsManager.AddNamespace("csw", this.Profile.CswNamespace);
xmlnsManager.AddNamespace("wrs", "http://www.opengis.net/cat/wrs");
xmlnsManager.AddNamespace("wrs10", "http://www.opengis.net/cat/wrs/1.0");
xmlnsManager.AddNamespace("xlink", "http://www.w3.org/1999/xlink");
xmlnsManager.AddNamespace("wcs", "http://www.opengis.net/wcs");
//setting capabilities
if (capabilities == null) capabilities = new CswCatalogCapabilities();
if (isWCSService(capabilitiesxml))
{
capabilities.GetRecordByID_GetURL = xmlDoc.SelectSingleNode("/wcs:WCS_Capabilities/wcs:Capability/wcs:Request/wcs:GetCoverage/wcs:DCPType/wcs:HTTP/wcs:Get/wcs:OnlineResource", xmlnsManager).Attributes["xlink:href"].Value;
if (capabilities.GetRecordByID_GetURL == null || capabilities.GetRecordByID_GetURL.Trim().Length == 0)
{
Utils.logger.writeLog(Resources.NoValidCoverageUrl);
throw new Exception(Resources.NoValidCoverageUrl);
}
}
else
{
// XmlNodeList parentNodeList = xmlDoc.SelectNodes("//ows:OperationsMetadata/ows:Operation[@name='GetRecords']/ows:DCP/ows:HTTP/ows:Post", xmlnsManager);
capabilities.GetRecords_PostURL = xmlDoc.SelectSingleNode("//ows:OperationsMetadata/ows:Operation[@name='GetRecords']/ows:DCP/ows:HTTP/ows:Post", xmlnsManager).Attributes["xlink:href"].Value;
/* if (parentNodeList.Count > 1)
{
XmlNodeList nodeList = xmlDoc.SelectNodes("//ows:OperationsMetadata/ows:Operation[@name='GetRecords']/ows:DCP/ows:HTTP/ows:Post/ows:Constraint/ows:Value", xmlnsManager);
if (nodeList != null && nodeList.Count >0 && (nodeList.Item(0).InnerText.Equals("SOAP") || nodeList.Item(0).InnerText.Equals("soap")))
{
capabilities.GetRecords_IsSoapEndPoint = true;
}
else if(capabilities.GetRecords_PostURL.ToLower().Contains("soap"))
{
capabilities.GetRecords_IsSoapEndPoint = true;
}
// capabilities.GetRecords_PostURL = xmlDoc.SelectSingleNode("//ows:OperationsMetadata/ows:Operation[@name='GetRecords']/ows:DCP/ows:HTTP/ows:Post", xmlnsManager).Attributes["xlink:href"].Value;
}*/
XmlNodeList nodeList = xmlDoc.SelectNodes("//ows:OperationsMetadata/ows:Operation[@name='GetRecords']/ows:DCP/ows:HTTP/ows:Post/ows:Constraint/ows:Value", xmlnsManager);
for (int iter = 0; iter < nodeList.Count; iter++)
{
capabilities.GetRecords_PostURL = nodeList.Item(iter).ParentNode.ParentNode.Attributes["xlink:href"].Value;
if (this.profile.Name == "INSPIRE CSW 2.0.2 AP ISO")
{
if (nodeList.Item(iter).InnerText.Equals("SOAP") || nodeList.Item(iter).InnerText.Equals("soap") || capabilities.GetRecords_PostURL.ToLower().Contains("soap"))
{
capabilities.GetRecords_IsSoapEndPoint = true;
break;
}
}
else
{
if (nodeList.Item(iter).InnerText.Equals("XML") || nodeList.Item(iter).InnerText.Equals("xml"))
{
break;
}
}
}
if (capabilities.GetRecords_PostURL == null || capabilities.GetRecords_PostURL.Trim().Length == 0)
{
Utils.logger.writeLog(Resources.NoValidPostUrl);
throw new Exception(Resources.NoValidPostUrl);
}
// capabilities.GetRecords_PostURL = xmlDoc.SelectSingleNode("//ows:OperationsMetadata/ows:Operation[@name='GetRecords']/ows:DCP/ows:HTTP/ows:Post", xmlnsManager).Attributes["xlink:href"].Value;
capabilities.GetRecordByID_GetURL = xmlDoc.SelectSingleNode("//ows:OperationsMetadata/ows:Operation[@name='GetRecordById']/ows:DCP/ows:HTTP/ows:Get", xmlnsManager).Attributes["xlink:href"].Value;
}
return true;
}
catch (Exception e) {
Utils.logger.writeLog(e.StackTrace);
return false;
}
}
private Boolean isWCSService(String capabilitiesXml)
{
return capabilitiesXml.IndexOf("WCS_Capabilities") > -1 ? true : false;
}
#endregion
#region "PublicFunction"
/// <summary>
/// To connect to a catalog service.
/// The capabilties details are populated based on the service.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>true if connection can be made to the csw service</returns>
public bool Connect() {
StringBuilder sb = new StringBuilder();
sb.AppendLine(DateTime.Now + " Sending GetCapabilities request to URL : " + URL);
string capabilitesxml = GetCapabilities(URL);
if (capabilitesxml != null){
sb.AppendLine(DateTime.Now + " GetCapabilitiesResponse xml : " + capabilitesxml);
ParseCapabilities(capabilitesxml);
sb.AppendLine(DateTime.Now + " Parsed GetCapabilitiesResponse xml...");
isConnect = true;
Utils.logger.writeLog(sb.ToString());
return true;
}
else {
sb.AppendLine(DateTime.Now + " Failed to connect to GetCapabilities endpoint.");
Utils.logger.writeLog(sb.ToString());
isConnect = false;
return false;
}
}
/// <summary>
/// To test if already connected to a catalog service.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>true if connection has already been made to the csw service else false</returns>
public bool IsConnected() {
return isConnect;
}
/// <summary>
/// Resets catalog connection
/// </summary>
public void resetConnection()
{
isConnect = false;
}
/// <summary>
/// Compares CswCatalog objects by name
/// </summary>
public int CompareTo(object obj)
{
if (obj is CswCatalog)
{
CswCatalog catalog = (CswCatalog)obj;
return this.Name.CompareTo(catalog.Name);
}
throw new ArgumentException("object is not a CswCatalog");
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Services.Client;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Runtime.Versioning;
using System.Windows;
using NuGet.Resources;
namespace NuGet
{
public class DataServicePackageRepository :
PackageRepositoryBase,
IHttpClientEvents,
IServiceBasedRepository,
ICloneableRepository,
ICultureAwareRepository,
IOperationAwareRepository,
IPackageLookup,
ILatestPackageLookup,
IWeakEventListener
{
private const string FindPackagesByIdSvcMethod = "FindPackagesById";
private const string PackageServiceEntitySetName = "Packages";
private const string SearchSvcMethod = "Search";
private const string GetUpdatesSvcMethod = "GetUpdates";
private IDataServiceContext _context;
private readonly IHttpClient _httpClient;
private readonly PackageDownloader _packageDownloader;
private CultureInfo _culture;
private Tuple<string, string, string> _currentOperation;
private event EventHandler<WebRequestEventArgs> _sendingRequest;
public DataServicePackageRepository(Uri serviceRoot)
: this(new HttpClient(serviceRoot))
{
}
public DataServicePackageRepository(IHttpClient client)
: this(client, new PackageDownloader())
{
}
public DataServicePackageRepository(IHttpClient client, PackageDownloader packageDownloader)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
if (packageDownloader == null)
{
throw new ArgumentNullException("packageDownloader");
}
_httpClient = client;
_httpClient.AcceptCompression = true;
_packageDownloader = packageDownloader;
if (EnvironmentUtility.RunningFromCommandLine)
{
_packageDownloader.SendingRequest += OnPackageDownloaderSendingRequest;
}
else
{
// weak event pattern
SendingRequestEventManager.AddListener(_packageDownloader, this);
}
}
private void OnPackageDownloaderSendingRequest(object sender, WebRequestEventArgs e)
{
if (_currentOperation != null)
{
string operation = _currentOperation.Item1;
string mainPackageId = _currentOperation.Item2;
string mainPackageVersion = _currentOperation.Item3;
if (!String.IsNullOrEmpty(mainPackageId) && !String.IsNullOrEmpty(_packageDownloader.CurrentDownloadPackageId))
{
if (!mainPackageId.Equals(_packageDownloader.CurrentDownloadPackageId, StringComparison.OrdinalIgnoreCase))
{
operation = operation + "-Dependency";
}
}
e.Request.Headers[RepositoryOperationNames.OperationHeaderName] = operation;
if (!operation.Equals(_currentOperation.Item1, StringComparison.OrdinalIgnoreCase))
{
e.Request.Headers[RepositoryOperationNames.DependentPackageHeaderName] = mainPackageId;
if (!String.IsNullOrEmpty(mainPackageVersion))
{
e.Request.Headers[RepositoryOperationNames.DependentPackageVersionHeaderName] = mainPackageVersion;
}
}
RaiseSendingRequest(e);
}
}
// Just forward calls to the package downloader
public event EventHandler<ProgressEventArgs> ProgressAvailable
{
add
{
_packageDownloader.ProgressAvailable += value;
}
remove
{
_packageDownloader.ProgressAvailable -= value;
}
}
public event EventHandler<WebRequestEventArgs> SendingRequest
{
add
{
_packageDownloader.SendingRequest += value;
_httpClient.SendingRequest += value;
_sendingRequest += value;
}
remove
{
_packageDownloader.SendingRequest -= value;
_httpClient.SendingRequest -= value;
_sendingRequest -= value;
}
}
public CultureInfo Culture
{
get
{
if (_culture == null)
{
// TODO: Technically, if this is a remote server, we have to return the culture of the server
// instead of invariant culture. However, there is no trivial way to retrieve the server's culture,
// So temporarily use Invariant culture here.
_culture = _httpClient.Uri.IsLoopback ? CultureInfo.CurrentCulture : CultureInfo.InvariantCulture;
}
return _culture;
}
}
// Do NOT delete this property. It is used by the functional test.
public PackageDownloader PackageDownloader
{
get { return _packageDownloader; }
}
public override string Source
{
get
{
return _httpClient.Uri.OriginalString;
}
}
public override bool SupportsPrereleasePackages
{
get
{
return Context.SupportsProperty("IsAbsoluteLatestVersion");
}
}
// Don't initialize the Context at the constructor time so that
// we don't make a web request if we are not going to actually use it
// since getting the Uri property of the RedirectedHttpClient will
// trigger that functionality.
internal IDataServiceContext Context
{
private get
{
if (_context == null)
{
_context = new DataServiceContextWrapper(_httpClient.Uri);
_context.SendingRequest += OnSendingRequest;
_context.ReadingEntity += OnReadingEntity;
_context.IgnoreMissingProperties = true;
}
return _context;
}
set
{
_context = value;
}
}
private void OnReadingEntity(object sender, ReadingWritingEntityEventArgs e)
{
var package = (DataServicePackage)e.Entity;
// REVIEW: This is the only way (I know) to download the package on demand
// GetReadStreamUri cannot be evaluated inside of OnReadingEntity. Lazily evaluate it inside DownloadPackage
package.Context = Context;
package.Downloader = _packageDownloader;
}
private void OnSendingRequest(object sender, SendingRequestEventArgs e)
{
// Initialize the request
_httpClient.InitializeRequest(e.Request);
RaiseSendingRequest(new WebRequestEventArgs(e.Request));
}
private void RaiseSendingRequest(WebRequestEventArgs e)
{
if (_sendingRequest != null)
{
_sendingRequest(this, e);
}
}
public override IQueryable<IPackage> GetPackages()
{
// REVIEW: Is it ok to assume that the package entity set is called packages?
return new SmartDataServiceQuery<DataServicePackage>(Context, PackageServiceEntitySetName);
}
public IQueryable<IPackage> Search(string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions)
{
if (!Context.SupportsServiceMethod(SearchSvcMethod))
{
// If there's no search method then we can't filter by target framework
return GetPackages().Find(searchTerm)
.FilterByPrerelease(allowPrereleaseVersions)
.AsQueryable();
}
// Convert the list of framework names into short names
var shortFrameworkNames = targetFrameworks.Select(name => new FrameworkName(name))
.Select(VersionUtility.GetShortFrameworkName);
// Create a '|' separated string of framework names
string targetFrameworkString = String.Join("|", shortFrameworkNames);
var searchParameters = new Dictionary<string, object> {
{ "searchTerm", "'" + UrlEncodeOdataParameter(searchTerm) + "'" },
{ "targetFramework", "'" + UrlEncodeOdataParameter(targetFrameworkString) + "'" },
};
if (SupportsPrereleasePackages)
{
searchParameters.Add("includePrerelease", ToLowerCaseString(allowPrereleaseVersions));
}
// Create a query for the search service method
var query = Context.CreateQuery<DataServicePackage>(SearchSvcMethod, searchParameters);
return new SmartDataServiceQuery<DataServicePackage>(Context, query);
}
public bool Exists(string packageId, SemanticVersion version)
{
IQueryable<DataServicePackage> query = Context.CreateQuery<DataServicePackage>(PackageServiceEntitySetName).AsQueryable();
foreach (string versionString in version.GetComparableVersionStrings())
{
try
{
var packages = query.Where(p => p.Id == packageId && p.Version == versionString)
.Select(p => p.Id) // since we only want to check for existence, no need to get all attributes
.ToArray();
if (packages.Length == 1)
{
return true;
}
}
catch (DataServiceQueryException)
{
// DataServiceQuery exception will occur when the (id, version)
// combination doesn't exist.
}
}
return false;
}
public IPackage FindPackage(string packageId, SemanticVersion version)
{
IQueryable<DataServicePackage> query = Context.CreateQuery<DataServicePackage>(PackageServiceEntitySetName).AsQueryable();
foreach (string versionString in version.GetComparableVersionStrings())
{
try
{
var packages = query.Where(p => p.Id == packageId && p.Version == versionString).ToArray();
Debug.Assert(packages == null || packages.Length <= 1);
if (packages.Length != 0)
{
return packages[0];
}
}
catch (DataServiceQueryException)
{
// DataServiceQuery exception will occur when the (id, version)
// combination doesn't exist.
}
}
return null;
}
public IEnumerable<IPackage> FindPackagesById(string packageId)
{
try
{
if (!Context.SupportsServiceMethod(FindPackagesByIdSvcMethod))
{
// If there's no search method then we can't filter by target framework
return PackageRepositoryExtensions.FindPackagesByIdCore(this, packageId);
}
var serviceParameters = new Dictionary<string, object> {
{ "id", "'" + UrlEncodeOdataParameter(packageId) + "'" }
};
// Create a query for the search service method
var query = Context.CreateQuery<DataServicePackage>(FindPackagesByIdSvcMethod, serviceParameters);
return new SmartDataServiceQuery<DataServicePackage>(Context, query);
}
catch (Exception ex)
{
var message = string.Format(
CultureInfo.CurrentCulture,
NuGetResources.ErrorLoadingPackages,
_httpClient.OriginalUri,
ex.Message);
throw new InvalidOperationException(message, ex);
}
}
public IEnumerable<IPackage> GetUpdates(
IEnumerable<IPackageName> packages,
bool includePrerelease,
bool includeAllVersions,
IEnumerable<FrameworkName> targetFrameworks,
IEnumerable<IVersionSpec> versionConstraints)
{
if (!Context.SupportsServiceMethod(GetUpdatesSvcMethod))
{
// If there's no search method then we can't filter by target framework
return PackageRepositoryExtensions.GetUpdatesCore(this, packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints);
}
// Pipe all the things!
string ids = String.Join("|", packages.Select(p => p.Id));
string versions = String.Join("|", packages.Select(p => p.Version.ToString()));
string targetFrameworksValue = targetFrameworks.IsEmpty() ? "" : String.Join("|", targetFrameworks.Select(VersionUtility.GetShortFrameworkName));
string versionConstraintsValue = versionConstraints.IsEmpty() ? "" : String.Join("|", versionConstraints.Select(v => v == null ? "" : v.ToString()));
var serviceParameters = new Dictionary<string, object> {
{ "packageIds", "'" + ids + "'" },
{ "versions", "'" + versions + "'" },
{ "includePrerelease", ToLowerCaseString(includePrerelease) },
{ "includeAllVersions", ToLowerCaseString(includeAllVersions) },
{ "targetFrameworks", "'" + UrlEncodeOdataParameter(targetFrameworksValue) + "'" },
{ "versionConstraints", "'" + UrlEncodeOdataParameter(versionConstraintsValue) + "'" }
};
var query = Context.CreateQuery<DataServicePackage>(GetUpdatesSvcMethod, serviceParameters);
return new SmartDataServiceQuery<DataServicePackage>(Context, query);
}
public IPackageRepository Clone()
{
return new DataServicePackageRepository(_httpClient, _packageDownloader);
}
public IDisposable StartOperation(string operation, string mainPackageId, string mainPackageVersion)
{
Tuple<string, string, string> oldOperation = _currentOperation;
_currentOperation = Tuple.Create(operation, mainPackageId, mainPackageVersion);
return new DisposableAction(() =>
{
_currentOperation = oldOperation;
});
}
public bool TryFindLatestPackageById(string id, out SemanticVersion latestVersion)
{
latestVersion = null;
try
{
var serviceParameters = new Dictionary<string, object> {
{ "id", "'" + UrlEncodeOdataParameter(id) + "'" }
};
// Create a query for the search service method
var query = Context.CreateQuery<DataServicePackage>(FindPackagesByIdSvcMethod, serviceParameters);
var packages = (IQueryable<DataServicePackage>)query.AsQueryable();
var latestPackage = packages.Where(p => p.IsLatestVersion)
.Select(p => new { p.Id, p.Version })
.FirstOrDefault();
if (latestPackage != null)
{
latestVersion = new SemanticVersion(latestPackage.Version);
return true;
}
}
catch (DataServiceQueryException)
{
}
return false;
}
public bool TryFindLatestPackageById(string id, bool includePrerelease, out IPackage package)
{
try
{
var serviceParameters = new Dictionary<string, object> {
{ "id", "'" + UrlEncodeOdataParameter(id) + "'" }
};
// Create a query for the search service method
var query = Context.CreateQuery<DataServicePackage>(FindPackagesByIdSvcMethod, serviceParameters);
var packages = (IQueryable<DataServicePackage>)query.AsQueryable();
if (includePrerelease)
{
package = packages.Where(p => p.IsAbsoluteLatestVersion).OrderByDescending(p => p.Version).FirstOrDefault();
}
else
{
package = packages.Where(p => p.IsLatestVersion).OrderByDescending(p => p.Version).FirstOrDefault();
}
return package != null;
}
catch (DataServiceQueryException)
{
package = null;
return false;
}
}
private static string UrlEncodeOdataParameter(string value)
{
if (!String.IsNullOrEmpty(value))
{
// OData requires that a single quote MUST be escaped as 2 single quotes.
// In .NET 4.5, Uri.EscapeDataString() escapes single quote as %27. Thus we must replace %27 with 2 single quotes.
// In .NET 4.0, Uri.EscapeDataString() doesn't escape single quote. Thus we must replace it with 2 single quotes.
return Uri.EscapeDataString(value).Replace("'", "''").Replace("%27", "''");
}
return value;
}
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "OData expects a lower case value.")]
private static string ToLowerCaseString(bool value)
{
return value.ToString().ToLowerInvariant();
}
public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
if (managerType == typeof(SendingRequestEventManager))
{
OnPackageDownloaderSendingRequest(sender, (WebRequestEventArgs)e);
return true;
}
else
{
return false;
}
}
}
}
| |
/*============================================================================*
* Title : Artsy (Social Application w/ Art Auction)
* Description : "Artsy" is a social application idea that would provide artists
a place to showcase their artworks and offer them the chance
to make a profit from it.
* Filename : Profile.cs
* Version : v1.0
* Author : Gensaya, Carl Jerwin F.
* Yr&Sec&Uni : BSCS 3-3 PUP Main
* Subject : Advance Programming
*============================================================================*/
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Threading;
using System.Timers;
using System.Windows.Forms;
namespace Artsy {
public class Profile : Panel {
public Profile() {
__DisplayProfile();
}
/*============================================================================*
* Function : __DisplayProfile
* Params : None
* Returns : Void
* Description: The panel that displays the profile of the Artsy user.
*=============================================================================*/
void __DisplayProfile() {
BackColor = ColorTranslator.FromHtml("#212121");
AutoSize = true;
_SideContainer = new Label() {
Size = new Size(220, 700),
Location = new Point(10, 10),
Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom,
BackColor = ColorTranslator.FromHtml("#333333")
};
this.Controls.Add(_SideContainer);
var path = new GraphicsPath();
path.AddEllipse(0, 0, 160, 160);
_UserImage = new PictureBox() {
Size = new Size(160, 160),
Location = new Point(28, 10),
Image = Image.FromFile("res/log1.jpg"),
SizeMode = PictureBoxSizeMode.StretchImage,
Region = new Region(path)
};
_SideContainer.Controls.Add(_UserImage);
_Username = new Label() {
Size = new Size(210, 30),
Location = new Point(5, 170),
BackColor = ColorTranslator.FromHtml("#651a1a"),
ForeColor = ColorTranslator.FromHtml("#E0E0E0"),
Text = "JinMer",
TextAlign = ContentAlignment.MiddleCenter,
Font = new Font("Segoe UI", 12)
};
_SideContainer.Controls.Add(_Username);
_FollowButton = new PictureBox() {
Size = new Size(50, 50),
Location = new Point(28, 205),
SizeMode = PictureBoxSizeMode.StretchImage,
BackColor = Color.Transparent,
Image = Image.FromFile("res/Icons/user-1.png"),
Font = new Font("Segoe UI Light", 12)
};
_SideContainer.Controls.Add(_FollowButton);
_CollabButton = new PictureBox() {
Size = new Size(50, 50),
Location = new Point(83, 205),
SizeMode = PictureBoxSizeMode.StretchImage,
BackColor = Color.Transparent,
Image = Image.FromFile("res/Icons/pencil.png")
};
_SideContainer.Controls.Add(_CollabButton);
_MessageButton = new PictureBox() {
Size = new Size(50, 50),
Location = new Point(138, 205),
SizeMode = PictureBoxSizeMode.StretchImage,
BackColor = Color.Transparent,
Image = Image.FromFile("res/Icons/mail.png")
};
_SideContainer.Controls.Add(_MessageButton);
_Followers = new Label() {
Size = new Size(90, 20),
Location = new Point(5, 275),
BackColor = ColorTranslator.FromHtml("#212121"),
ForeColor = ColorTranslator.FromHtml("#E0E0E0"),
Text = "FOLLOWERS",
TextAlign = ContentAlignment.MiddleCenter,
Font = new Font("Segoe UI", 10)
};
_SideContainer.Controls.Add(_Followers);
_FollowersCount = new Label() {
Size = new Size(120, 24),
Location = new Point(95, 270),
BackColor = ColorTranslator.FromHtml("#954535"),
ForeColor = ColorTranslator.FromHtml("#E0E0E0"),
Text = _intFollowersCount.ToString(),
Font = new Font("Segoe UI", 11),
TextAlign = ContentAlignment.MiddleCenter
};
_SideContainer.Controls.Add(_FollowersCount);
_Following = new Label() {
Size = new Size(90, 20),
Location = new Point(5, 315),
BackColor = ColorTranslator.FromHtml("#212121"),
ForeColor = ColorTranslator.FromHtml("#E0E0E0"),
Text = "FOLLOWING",
TextAlign = ContentAlignment.MiddleCenter,
Font = new Font("Segoe UI", 10)
};
_SideContainer.Controls.Add(_Following);
_FollowingCount = new Label() {
Size = new Size(120, 24),
Location = new Point(95, 310),
BackColor = ColorTranslator.FromHtml("#954535"),
ForeColor = ColorTranslator.FromHtml("#E0E0E0"),
Text = _intFollowingCount.ToString(),
Font = new Font("Segoe UI", 11),
TextAlign = ContentAlignment.MiddleCenter
};
_SideContainer.Controls.Add(_FollowingCount);
_Arts = new Label() {
Size = new Size(90, 20),
Location = new Point(5, 355),
BackColor = ColorTranslator.FromHtml("#212121"),
ForeColor = ColorTranslator.FromHtml("#E0E0E0"),
Text = "ARTS",
TextAlign = ContentAlignment.MiddleCenter,
Font = new Font("Segoe UI", 10)
};
_SideContainer.Controls.Add(_Arts);
_ArtsCount = new Label() {
Size = new Size(120, 24),
Location = new Point(95, 350),
BackColor = ColorTranslator.FromHtml("#954535"),
ForeColor = ColorTranslator.FromHtml("#E0E0E0"),
Text = _intArtsCount.ToString(),
Font = new Font("Segoe UI", 11),
TextAlign = ContentAlignment.MiddleCenter
};
_SideContainer.Controls.Add(_ArtsCount);
_Auctions = new Label() {
Size = new Size(90, 20),
Location = new Point(5, 395),
BackColor = ColorTranslator.FromHtml("#212121"),
ForeColor = ColorTranslator.FromHtml("#E0E0E0"),
Text = "AUCTIONS",
TextAlign = ContentAlignment.MiddleCenter,
Font = new Font("Segoe UI", 10)
};
_SideContainer.Controls.Add(_Auctions);
_AuctionsCount = new Label() {
Size = new Size(120, 24),
Location = new Point(95, 390),
BackColor = ColorTranslator.FromHtml("#954535"),
ForeColor = ColorTranslator.FromHtml("#E0E0E0"),
Text = _intAuctionsCount.ToString(),
Font = new Font("Segoe UI", 11),
TextAlign = ContentAlignment.MiddleCenter
};
_SideContainer.Controls.Add(_AuctionsCount);
_PostContainer = new Label() {
Size = new Size(220, 600),
Location = new Point(0, 490),
BackColor = Color.Gray
};
_SideContainer.Controls.Add(_PostContainer);
_UserPosts[0] = new Label() {
Size = new Size(180, 180),
Location = new Point(20, 10),
BackColor = ColorTranslator.FromHtml("#E0E0E0"),
Text = "Thumbnails ng mga post ni user",
Font = new Font("Segoe UI Light", 12),
TextAlign = ContentAlignment.MiddleCenter
};
_PostContainer.Controls.Add(_UserPosts[0]);
_MainContainer = new Label() {
Size = new Size(630, 700),
Location = new Point(230, 10)
};
this.Controls.Add(_MainContainer);
_FeaturedArtsContainer = new Label() {
Tag = "Art",
Size = new Size(300, 300),
Location = new Point(10, 0),
BackColor = ColorTranslator.FromHtml("#737373")
};
_MainContainer.Controls.Add(_FeaturedArtsContainer);
_FeaturedArtsLabel = new Label() {
Size = new Size(300, 30),
Location = new Point(0, 0),
BackColor = ColorTranslator.FromHtml("#264040"),
ForeColor = ColorTranslator.FromHtml("#e6e6e6"),
Text = "FEATURED ARTS",
Font = new Font("Segoe UI ", 15),
TextAlign = ContentAlignment.MiddleCenter
};
_FeaturedArtsContainer.Controls.Add(_FeaturedArtsLabel);
_AuctionsContainer = new Label() {
Tag = "Auction",
Size = new Size(300, 300),
Location = new Point(320, 0),
BackColor = ColorTranslator.FromHtml("#737373")
};
_MainContainer.Controls.Add(_AuctionsContainer);
_AuctionsLabel = new Label() {
Size = new Size(300, 30),
Location = new Point(0, 0),
BackColor = ColorTranslator.FromHtml("#264040"),
ForeColor = ColorTranslator.FromHtml("#e6e6e6"),
Text = "AUCTIONS",
Font = new Font("Segoe UI ", 15),
TextAlign = ContentAlignment.MiddleCenter
};
_AuctionsContainer.Controls.Add(_AuctionsLabel);
_TempContainer1 = new Label() {
Tag = "Follow",
Size = new Size(300, 300),
Location = new Point(10, 320),
BackColor = ColorTranslator.FromHtml("#737373")
};
_MainContainer.Controls.Add(_TempContainer1);
_TempLabel1 = new Label() {
Size = new Size(300, 30),
Location = new Point(0, 0),
BackColor = ColorTranslator.FromHtml("#264040"),
ForeColor = ColorTranslator.FromHtml("#e6e6e6"),
Text = "FOLLOWING",
Font = new Font("Segoe UI ", 15),
TextAlign = ContentAlignment.MiddleCenter
};
_TempContainer1.Controls.Add(_TempLabel1);
_TempContainer2 = new Label() {
Tag = "Followr",
Size = new Size(300, 300),
Location = new Point(320, 320),
BackColor = ColorTranslator.FromHtml("#737373")
};
_MainContainer.Controls.Add(_TempContainer2);
_TempLabel2 = new Label() {
Size = new Size(300, 30),
Location = new Point(0, 0),
BackColor = ColorTranslator.FromHtml("#264040"),
ForeColor = ColorTranslator.FromHtml("#e6e6e6"),
Text = "FOLLOWERS",
Font = new Font("Segoe UI ", 15),
TextAlign = ContentAlignment.MiddleCenter
};
_TempContainer2.Controls.Add(_TempLabel2);
}
/*============================================================================*
* Function : __MouseLeave
* Params : object source - Component that triggered the event.
EventArgs mla - Event Argument
* Returns : Void
* Description: Show animation for the panel components.
*=============================================================================*/
void __MouseEnter(object source, EventArgs mea) {
var sender = source as Label;
if(sender.Tag.ToString() == "Art" && _ArtFlag == 0) {
new Thread(() => {
for(int loop = 0; loop <= 270; loop += 10) {
try {
_FeaturedArtsLabel.Size = new Size(300 - loop, 30);
Thread.Sleep(1);
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
}
for(int loop = 0; loop <= 270; loop+=10) {
try {
_FeaturedArtsLabel.Location = new Point(0, 0 + loop);
Thread.Sleep(1);
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
}
for(int loop = 0; loop <= 270; loop +=10) {
_FeaturedArtsLabel.Size = new Size(30 + loop, 30);
Thread.Sleep(1);
}
}).Start(); _ArtFlag = 1;
} else if(sender.Tag.ToString() == "Auction" && _AucFlag == 0) {
new Thread(() => {
for(int loop = 0; loop <= 270; loop += 10) {
try {
_AuctionsLabel.Size = new Size(300 - loop, 30);
Thread.Sleep(1);
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
}
for(int loop = 0; loop <= 270; loop+=10) {
try {
_AuctionsLabel.Location = new Point(0, 0 + loop);
Thread.Sleep(1);
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
}
for(int loop = 0; loop <= 270; loop +=10) {
_AuctionsLabel.Size = new Size(30 + loop, 30);
Thread.Sleep(1);
}
}).Start(); _AucFlag = 1;
} else if(sender.Tag.ToString() == "Follow" && _FlwFlag == 0) {
new Thread(() => {
for(int loop = 0; loop <= 270; loop += 10) {
try {
_TempLabel1.Size = new Size(300 - loop, 30);
Thread.Sleep(1);
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
}
for(int loop = 0; loop <= 270; loop+=10) {
try {
_TempLabel1.Location = new Point(0, 0 + loop);
Thread.Sleep(1);
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
}
for(int loop = 0; loop <= 270; loop +=10) {
_TempLabel1.Size = new Size(30 + loop, 30);
Thread.Sleep(1);
}
}).Start(); _FlwFlag = 1;
} else if(sender.Tag.ToString() == "Followr" && _FlrFlag == 0) {
new Thread(() => {
for(int loop = 0; loop <= 270; loop += 10) {
try {
_TempLabel2.Size = new Size(300 - loop, 30);
Thread.Sleep(1);
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
}
for(int loop = 0; loop <= 270; loop+=10) {
try {
_TempLabel2.Location = new Point(0, 0 + loop);
Thread.Sleep(1);
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
}
for(int loop = 0; loop <= 270; loop +=10) {
_TempLabel2.Size = new Size(30 + loop, 30);
Thread.Sleep(1);
}
}).Start(); _FlrFlag = 1;
}
}
/*============================================================================*
* Function : __MouseLeave
* Params : object source - Component that triggered the event.
EventArgs mla - Event Argument
* Returns : Void
* Description: Hide animation for the panel components.
*=============================================================================*/
void __MouseLeave(object source, EventArgs mla) {
var sender = source as Label;
if(sender.Tag.ToString() == "Art" && _ArtFlag == 1) {
new Thread(() => {
for(int loop = 0; loop <= 270; loop+=10) {
try {
_FeaturedArtsLabel.Location = new Point(0, 270 - loop);
Thread.Sleep(1);
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
}
for(int loop = 0; loop <= 270; loop +=10) {
_FeaturedArtsLabel.Size = new Size(30 + loop, 30);
Thread.Sleep(1);
}
}).Start(); _ArtFlag = 0;
} else if(sender.Tag.ToString() == "Auction" && _AucFlag == 1) {
new Thread(() => {
for(int loop = 0; loop <= 270; loop+=10) {
try {
_AuctionsLabel.Location = new Point(0, 270 - loop);
Thread.Sleep(1);
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
}
for(int loop = 0; loop <= 270; loop +=10) {
_AuctionsLabel.Size = new Size(30 + loop, 30);
Thread.Sleep(1);
}
}).Start(); _AucFlag = 0;
} else if(sender.Tag.ToString() == "Follow" && _FlwFlag == 1) {
new Thread(() => {
for(int loop = 0; loop <= 270; loop+=10) {
try {
_TempLabel1.Location = new Point(0, 270 - loop);
Thread.Sleep(1);
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
}
for(int loop = 0; loop <= 270; loop +=10) {
_TempLabel1.Size = new Size(30 + loop, 30);
Thread.Sleep(1);
}
}).Start(); _FlwFlag = 0;
} else if(sender.Tag.ToString() == "Followr" && _FlrFlag == 1) {
new Thread(() => {
for(int loop = 0; loop <= 270; loop+=10) {
try {
_TempLabel2.Location = new Point(0, 270 - loop);
Thread.Sleep(1);
} catch(Exception ex) {
Console.WriteLine(ex.ToString());
}
}
for(int loop = 0; loop <= 270; loop +=10) {
_TempLabel2.Size = new Size(30 + loop, 30);
Thread.Sleep(1);
}
}).Start(); _FlrFlag = 0;
}
}
/*==============================INITIALIZATION==============================*/
Label _MainContainer;
Label _FeaturedArtsContainer;
Label _FeaturedArtsLabel;
Label _AuctionsContainer;
Label _AuctionsLabel;
Label _TempContainer1;
Label _TempLabel1;
Label _TempContainer2;
Label _TempLabel2;
Label _SideContainer;
Label _Username;
Label _Followers;
Label _FollowersCount;
Label _Following;
Label _FollowingCount;
PictureBox _FollowButton;
PictureBox _CollabButton;
PictureBox _MessageButton;
Label _Arts;
Label _ArtsCount;
Label _Auctions;
Label _AuctionsCount;
Label _PostContainer;
Label[] _UserPosts = new Label[1];
PictureBox _UserImage;
int _intFollowersCount = 653;
int _intFollowingCount = 110;
int _intArtsCount = 50;
int _intAuctionsCount = 2;
static int _ArtFlag = 0;
static int _AucFlag = 0;
static int _FlwFlag = 0;
static int _FlrFlag = 0;
}
}
| |
/*
* BottomNavigationBar for Xamarin Forms
* Copyright (c) 2016 Thrive GmbH and others (http://github.com/thrive-now).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using System.Linq;
using BottomBar.XamarinForms;
using BottomNavigationBar;
using BottomNavigationBar.Listeners;
using Android.Views;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms.Platform.Android.AppCompat;
using BottomBar.Droid.Renderers;
using BottomBar.Droid.Utils;
using System.Collections.Generic;
[assembly: ExportRenderer (typeof (BottomBarPage), typeof (BottomBarPageRenderer))]
namespace BottomBar.Droid.Renderers
{
public class BottomBarPageRenderer : VisualElementRenderer<BottomBarPage>, IOnTabClickListener
{
bool _disposed;
BottomNavigationBar.BottomBar _bottomBar;
FrameLayout _frameLayout;
IPageController _pageController;
HashSet<int> _alreadyMappedTabs;
UpdatableBottomBarTab[] _currentTabs;
public BottomBarPageRenderer ()
{
AutoPackage = false;
}
#region IOnTabClickListener
public void OnTabSelected (int position)
{
//Do we need this call? It's also done in OnElementPropertyChanged
SwitchContent(Element.Children [position]);
var bottomBarPage = Element as BottomBarPage;
bottomBarPage.CurrentPage = Element.Children[position];
//bottomBarPage.RaiseCurrentPageChanged();
}
public void OnTabReSelected (int position)
{
}
#endregion
public void RefreshTabIcons()
{
for (int i = 0; i < Element.Children.Count; ++i) {
Page page = Element.Children[i];
var pageTab = _currentTabs?.FirstOrDefault(t => t.PageId == page.Id);
if (pageTab != null) {
var tabIconId = ResourceManagerEx.IdFromTitle(page.Icon, ResourceManager.DrawableClass);
pageTab.SetIconResource(tabIconId);
}
}
if (_currentTabs?.Length > 0) {
_bottomBar.SetItems(_currentTabs);
}
}
protected override void Dispose (bool disposing)
{
if (disposing && !_disposed) {
_disposed = true;
RemoveAllViews ();
foreach (Page pageToRemove in Element.Children) {
IVisualElementRenderer pageRenderer = Platform.GetRenderer (pageToRemove);
if (pageRenderer != null) {
pageRenderer.ViewGroup.RemoveFromParent ();
pageRenderer.Dispose ();
}
// pageToRemove.ClearValue (Platform.RendererProperty);
}
if (_bottomBar != null) {
_bottomBar.SetOnTabClickListener (null);
_bottomBar.Dispose ();
_bottomBar = null;
}
if (_frameLayout != null) {
_frameLayout.Dispose ();
_frameLayout = null;
}
/*if (Element != null) {
PageController.InternalChildren.CollectionChanged -= OnChildrenCollectionChanged;
}*/
}
base.Dispose (disposing);
}
protected override void OnAttachedToWindow ()
{
base.OnAttachedToWindow ();
_pageController.SendAppearing ();
}
protected override void OnDetachedFromWindow ()
{
base.OnDetachedFromWindow ();
_pageController.SendDisappearing ();
}
protected override void OnElementChanged (ElementChangedEventArgs<BottomBarPage> e)
{
base.OnElementChanged (e);
if (e.OldElement != null) {
BottomBarPage oldBottomBarPage = e.OldElement;
oldBottomBarPage.ChildAdded -= BottomBarPage_ChildAdded;
oldBottomBarPage.ChildRemoved -= BottomBarPage_ChildRemoved;
oldBottomBarPage.ChildrenReordered -= BottomBarPage_ChildrenReordered;
}
if (e.NewElement != null) {
BottomBarPage bottomBarPage = e.NewElement;
if (_bottomBar == null) {
_pageController = PageController.Create (bottomBarPage);
// create a view which will act as container for Page's
_frameLayout = new FrameLayout (Forms.Context);
_frameLayout.LayoutParameters = new FrameLayout.LayoutParams (LayoutParams.MatchParent, LayoutParams.MatchParent, GravityFlags.Fill);
AddView (_frameLayout, 0);
// create bottomBar control
_bottomBar = BottomNavigationBar.BottomBar.Attach (_frameLayout, null);
_bottomBar.NoTabletGoodness ();
if (bottomBarPage.FixedMode)
{
_bottomBar.UseFixedMode();
}
switch (bottomBarPage.BarTheme)
{
case BottomBarPage.BarThemeTypes.Light:
break;
case BottomBarPage.BarThemeTypes.DarkWithAlpha:
_bottomBar.UseDarkThemeWithAlpha(true);
break;
case BottomBarPage.BarThemeTypes.DarkWithoutAlpha:
_bottomBar.UseDarkThemeWithAlpha(false);
break;
default:
throw new ArgumentOutOfRangeException();
}
_bottomBar.LayoutParameters = new LayoutParams (LayoutParams.MatchParent, LayoutParams.MatchParent);
_bottomBar.SetOnTabClickListener (this);
UpdateTabs ();
UpdateBarBackgroundColor ();
UpdateBarTextColor ();
}
if (bottomBarPage.CurrentPage != null) {
SwitchContent (bottomBarPage.CurrentPage);
}
bottomBarPage.ChildAdded += BottomBarPage_ChildAdded;
bottomBarPage.ChildRemoved += BottomBarPage_ChildRemoved;
bottomBarPage.ChildrenReordered += BottomBarPage_ChildrenReordered;
}
}
protected override void OnElementPropertyChanged (object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged (sender, e);
if (e.PropertyName == nameof (TabbedPage.CurrentPage)) {
SwitchContent (Element.CurrentPage);
RefreshTabIcons();
} else if (e.PropertyName == NavigationPage.BarBackgroundColorProperty.PropertyName) {
UpdateBarBackgroundColor ();
} else if (e.PropertyName == NavigationPage.BarTextColorProperty.PropertyName) {
UpdateBarTextColor ();
}
}
protected virtual void SwitchContent (Page view)
{
Context.HideKeyboard (this);
_frameLayout.RemoveAllViews ();
if (view == null) {
return;
}
if (Platform.GetRenderer (view) == null) {
Platform.SetRenderer (view, Platform.CreateRenderer (view));
}
_frameLayout.AddView (Platform.GetRenderer (view).ViewGroup);
}
protected override void OnLayout (bool changed, int l, int t, int r, int b)
{
int width = r - l;
int height = b - t;
var context = Context;
_bottomBar.Measure (MeasureSpecFactory.MakeMeasureSpec (width, MeasureSpecMode.Exactly), MeasureSpecFactory.MakeMeasureSpec (height, MeasureSpecMode.AtMost));
int tabsHeight = Math.Min (height, Math.Max (_bottomBar.MeasuredHeight, _bottomBar.MinimumHeight));
if (width > 0 && height > 0) {
_pageController.ContainerArea = new Rectangle(0, 0, context.FromPixels(width), context.FromPixels(_frameLayout.Height));
ObservableCollection<Element> internalChildren = _pageController.InternalChildren;
for (var i = 0; i < internalChildren.Count; i++) {
var child = internalChildren [i] as VisualElement;
if (child == null) {
continue;
}
IVisualElementRenderer renderer = Platform.GetRenderer (child);
var navigationRenderer = renderer as NavigationPageRenderer;
if (navigationRenderer != null) {
// navigationRenderer.ContainerPadding = tabsHeight;
}
}
_bottomBar.Measure (MeasureSpecFactory.MakeMeasureSpec (width, MeasureSpecMode.Exactly), MeasureSpecFactory.MakeMeasureSpec (tabsHeight, MeasureSpecMode.Exactly));
_bottomBar.Layout (0, 0, width, tabsHeight);
}
base.OnLayout (changed, l, t, r, b);
}
void UpdateBarBackgroundColor ()
{
if (_disposed || _bottomBar == null) {
return;
}
_bottomBar.SetBackgroundColor (Element.BarBackgroundColor.ToAndroid ());
}
void UpdateBarTextColor ()
{
if (_disposed || _bottomBar == null) {
return;
}
_bottomBar.SetActiveTabColor(Element.BarTextColor.ToAndroid());
// The problem SetActiveTabColor does only work in fiexed mode // haven't found yet how to set text color for tab items on_bottomBar, doesn't seem to have a direct way
}
void UpdateTabs ()
{
// create tab items
SetTabItems ();
// set tab colors
SetTabColors ();
}
void SetTabItems ()
{
UpdatableBottomBarTab[] tabs = Element.Children.Select(page => {
var tabIconId = ResourceManagerEx.IdFromTitle(page.Icon, ResourceManager.DrawableClass);
return new UpdatableBottomBarTab(tabIconId, page.Title, page.Id);
}).ToArray();
if (tabs.Length > 0) {
_bottomBar.SetItems(tabs);
}
_currentTabs = tabs;
}
void SetTabColors ()
{
for (int i = 0; i < Element.Children.Count; ++i) {
Page page = Element.Children [i];
Color? tabColor = page.GetTabColor ();
if (tabColor != null) {
if (_alreadyMappedTabs == null) {
_alreadyMappedTabs = new HashSet<int>();
}
// Workaround for exception on BottomNavigationBar.
// The issue should be fixed on the base library but we are patching it here for now.
if (!_alreadyMappedTabs.Contains(i)) {
_bottomBar.MapColorForTab(i, tabColor.Value.ToAndroid());
_alreadyMappedTabs.Add(i);
}
}
}
}
void BottomBarPage_ChildAdded(object sender, ElementEventArgs e)
{
UpdateTabs();
}
void BottomBarPage_ChildrenReordered(object sender, EventArgs e)
{
UpdateTabs();
}
void BottomBarPage_ChildRemoved(object sender, ElementEventArgs e)
{
UpdateTabs();
}
private class UpdatableBottomBarTab : BottomBarTab
{
public Guid PageId { get; private set; }
public UpdatableBottomBarTab(int iconResource, string title, Guid pageId) : base(iconResource, title)
{
PageId = pageId;
}
public void SetIconResource(int iconResource)
{
_iconResource = iconResource;
}
public int GetIconResource()
{
return _iconResource;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
#if FEATURE_PERFTRACING
namespace System.Diagnostics.Tracing
{
[StructLayout(LayoutKind.Sequential)]
internal struct EventPipeEventInstanceData
{
internal IntPtr ProviderID;
internal uint EventID;
internal uint ThreadID;
internal long TimeStamp;
internal Guid ActivityId;
internal Guid ChildActivityId;
internal IntPtr Payload;
internal uint PayloadLength;
}
[StructLayout(LayoutKind.Sequential)]
internal struct EventPipeSessionInfo
{
internal long StartTimeAsUTCFileTime;
internal long StartTimeStamp;
internal long TimeStampFrequency;
}
[StructLayout(LayoutKind.Sequential)]
internal struct EventPipeProviderConfiguration
{
[MarshalAs(UnmanagedType.LPWStr)]
private readonly string m_providerName;
private readonly ulong m_keywords;
private readonly uint m_loggingLevel;
[MarshalAs(UnmanagedType.LPWStr)]
private readonly string? m_filterData;
internal EventPipeProviderConfiguration(
string providerName,
ulong keywords,
uint loggingLevel,
string? filterData)
{
if (string.IsNullOrEmpty(providerName))
{
throw new ArgumentNullException(nameof(providerName));
}
if (loggingLevel > 5) // 5 == Verbose, the highest value in EventPipeLoggingLevel.
{
throw new ArgumentOutOfRangeException(nameof(loggingLevel));
}
m_providerName = providerName;
m_keywords = keywords;
m_loggingLevel = loggingLevel;
m_filterData = filterData;
}
internal string ProviderName
{
get { return m_providerName; }
}
internal ulong Keywords
{
get { return m_keywords; }
}
internal uint LoggingLevel
{
get { return m_loggingLevel; }
}
internal string? FilterData => m_filterData;
}
internal enum EventPipeSerializationFormat
{
NetPerf,
NetTrace
}
internal sealed class EventPipeWaitHandle : WaitHandle
{
}
internal sealed class EventPipeConfiguration
{
private readonly string m_outputFile;
private readonly EventPipeSerializationFormat m_format;
private readonly uint m_circularBufferSizeInMB;
private readonly List<EventPipeProviderConfiguration> m_providers;
private TimeSpan m_minTimeBetweenSamples = TimeSpan.FromMilliseconds(1);
internal EventPipeConfiguration(
string outputFile,
EventPipeSerializationFormat format,
uint circularBufferSizeInMB)
{
if (string.IsNullOrEmpty(outputFile))
{
throw new ArgumentNullException(nameof(outputFile));
}
if (circularBufferSizeInMB == 0)
{
throw new ArgumentOutOfRangeException(nameof(circularBufferSizeInMB));
}
m_outputFile = outputFile;
m_format = format;
m_circularBufferSizeInMB = circularBufferSizeInMB;
m_providers = new List<EventPipeProviderConfiguration>();
}
internal string OutputFile
{
get { return m_outputFile; }
}
internal EventPipeSerializationFormat Format
{
get { return m_format; }
}
internal uint CircularBufferSizeInMB
{
get { return m_circularBufferSizeInMB; }
}
internal EventPipeProviderConfiguration[] Providers
{
get { return m_providers.ToArray(); }
}
internal void EnableProvider(string providerName, ulong keywords, uint loggingLevel)
{
EnableProviderWithFilter(providerName, keywords, loggingLevel, null);
}
internal void EnableProviderWithFilter(string providerName, ulong keywords, uint loggingLevel, string? filterData)
{
m_providers.Add(new EventPipeProviderConfiguration(
providerName,
keywords,
loggingLevel,
filterData));
}
private void EnableProviderConfiguration(EventPipeProviderConfiguration providerConfig)
{
m_providers.Add(providerConfig);
}
internal void EnableProviderRange(EventPipeProviderConfiguration[] providerConfigs)
{
foreach (EventPipeProviderConfiguration config in providerConfigs)
{
EnableProviderConfiguration(config);
}
}
internal void SetProfilerSamplingRate(TimeSpan minTimeBetweenSamples)
{
if (minTimeBetweenSamples.Ticks <= 0)
{
throw new ArgumentOutOfRangeException(nameof(minTimeBetweenSamples));
}
m_minTimeBetweenSamples = minTimeBetweenSamples;
}
}
internal static class EventPipe
{
private static ulong s_sessionID = 0;
internal static void Enable(EventPipeConfiguration configuration)
{
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
if (configuration.Providers == null)
{
throw new ArgumentNullException(nameof(configuration.Providers));
}
EventPipeProviderConfiguration[] providers = configuration.Providers;
s_sessionID = EventPipeInternal.Enable(
configuration.OutputFile,
configuration.Format,
configuration.CircularBufferSizeInMB,
providers);
}
internal static void Disable()
{
EventPipeInternal.Disable(s_sessionID);
}
}
internal static class EventPipeInternal
{
private unsafe struct EventPipeProviderConfigurationNative
{
private char* m_pProviderName;
private ulong m_keywords;
private uint m_loggingLevel;
private char* m_pFilterData;
internal static void MarshalToNative(EventPipeProviderConfiguration managed, ref EventPipeProviderConfigurationNative native)
{
native.m_pProviderName = (char*)Marshal.StringToCoTaskMemUni(managed.ProviderName);
native.m_keywords = managed.Keywords;
native.m_loggingLevel = managed.LoggingLevel;
native.m_pFilterData = (char*)Marshal.StringToCoTaskMemUni(managed.FilterData);
}
internal void Release()
{
if (m_pProviderName != null)
{
Marshal.FreeCoTaskMem((IntPtr)m_pProviderName);
}
if (m_pFilterData != null)
{
Marshal.FreeCoTaskMem((IntPtr)m_pFilterData);
}
}
}
//
// These PInvokes are used by the configuration APIs to interact with EventPipe.
//
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static unsafe extern ulong Enable(
char* outputFile,
EventPipeSerializationFormat format,
uint circularBufferSizeInMB,
EventPipeProviderConfigurationNative* providers,
uint numProviders);
internal static unsafe ulong Enable(
string? outputFile,
EventPipeSerializationFormat format,
uint circularBufferSizeInMB,
EventPipeProviderConfiguration[] providers)
{
Span<EventPipeProviderConfigurationNative> providersNative = new Span<EventPipeProviderConfigurationNative>((void*)Marshal.AllocCoTaskMem(sizeof(EventPipeProviderConfigurationNative) * providers.Length), providers.Length);
providersNative.Clear();
try
{
for (int i = 0; i < providers.Length; i++)
{
EventPipeProviderConfigurationNative.MarshalToNative(providers[i], ref providersNative[i]);
}
fixed (char* outputFilePath = outputFile)
fixed (EventPipeProviderConfigurationNative* providersNativePointer = providersNative)
{
return Enable(outputFilePath, format, circularBufferSizeInMB, providersNativePointer, (uint)providersNative.Length);
}
}
finally
{
for (int i = 0; i < providers.Length; i++)
{
providersNative[i].Release();
}
fixed (EventPipeProviderConfigurationNative* providersNativePointer = providersNative)
{
Marshal.FreeCoTaskMem((IntPtr)providersNativePointer);
}
}
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern void Disable(ulong sessionID);
//
// These PInvokes are used by EventSource to interact with the EventPipe.
//
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern IntPtr CreateProvider(string providerName, Interop.Advapi32.EtwEnableCallback callbackFunc);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern unsafe IntPtr DefineEvent(IntPtr provHandle, uint eventID, long keywords, uint eventVersion, uint level, void* pMetadata, uint metadataLength);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern IntPtr GetProvider(string providerName);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern void DeleteProvider(IntPtr provHandle);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern int EventActivityIdControl(uint controlCode, ref Guid activityId);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern unsafe void WriteEvent(IntPtr eventHandle, uint eventID, void* pData, uint length, Guid* activityId, Guid* relatedActivityId);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern unsafe void WriteEventData(IntPtr eventHandle, uint eventID, EventProvider.EventData* pEventData, uint dataCount, Guid* activityId, Guid* relatedActivityId);
//
// These PInvokes are used as part of the EventPipeEventDispatcher.
//
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern unsafe bool GetSessionInfo(ulong sessionID, EventPipeSessionInfo* pSessionInfo);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern unsafe bool GetNextEvent(ulong sessionID, EventPipeEventInstanceData* pInstance);
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern unsafe IntPtr GetWaitHandle(ulong sessionID);
}
}
#endif // FEATURE_PERFTRACING
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using Windows.Devices.SmartCards;
using static NfcSample.NfcUtils;
using Windows.Storage;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace NfcSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class ManageCardScenario : Page
{
private MainPage rootPage;
public ManageCardScenario()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
// Clear the messages
rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
if (!ApplicationData.Current.RoamingSettings.Values.ContainsKey("DenyIfPhoneLocked"))
{
ApplicationData.Current.RoamingSettings.Values["DenyIfPhoneLocked"] = false;
}
if (!ApplicationData.Current.RoamingSettings.Values.ContainsKey("LaunchAboveLock"))
{
ApplicationData.Current.RoamingSettings.Values["LaunchAboveLock"] = false;
}
chkDenyIfPhoneLocked.IsChecked = (bool)ApplicationData.Current.RoamingSettings.Values["DenyIfPhoneLocked"];
chkLaunchAboveLock.IsChecked = (bool)ApplicationData.Current.RoamingSettings.Values["LaunchAboveLock"];
if (!(await CheckHceSupport()))
{
// No HCE support on this device
btnRegisterBgTask.IsEnabled = false;
btnAddCard.IsEnabled = false;
}
else
{
lstCards.ItemsSource = await SmartCardEmulator.GetAppletIdGroupRegistrationsAsync();
}
}
private async void ShowDialog(string msg)
{
var msgbox = new Windows.UI.Popups.MessageDialog(msg);
msgbox.Commands.Add(new Windows.UI.Popups.UICommand("OK"));
await msgbox.ShowAsync();
}
private async void btnRegisterBgTask_Click(object sender, RoutedEventArgs e)
{
// Clear the messages
rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
// First check if the device supports NFC/HCE at all
if (!(await NfcUtils.CheckHceSupport()))
{
// HCE not supported
return;
}
// Register the background task which gets launched to handle and respond to incoming APDUs
await NfcUtils.GetOrRegisterHceBackgroundTask("NFC HCE Sample - Activated", "NfcHceBackgroundTask.BgTask", SmartCardTriggerType.EmulatorHostApplicationActivated);
// Register the background task which gets launched when our registration state changes (for example the user changes which card is the payment default in the control panel, or another app causes us to be disabled due to an AID conflict)
await NfcUtils.GetOrRegisterHceBackgroundTask("NFC HCE Sample - Registration Changed", "NfcHceBackgroundTask.BgTask", SmartCardTriggerType.EmulatorAppletIdGroupRegistrationChanged);
// Register for UICC transaction event
await NfcUtils.GetOrRegisterHceBackgroundTask("NFC HCE Sample - Transaction", "NfcHceBackgroundTask.BgTask", SmartCardTriggerType.EmulatorTransaction);
}
private async void btnRegisterSamplePaymentCard_Click(object sender, RoutedEventArgs e)
{
// Clear the messages
rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
// First check if the device supports NFC/HCE at all
if (!(await NfcUtils.CheckHceSupport()))
{
// HCE not supported
return;
}
// Next check if NFC card emualtion is turned on in the settings control panel
if ((await SmartCardEmulator.GetDefaultAsync()).EnablementPolicy == SmartCardEmulatorEnablementPolicy.Never)
{
ShowDialog("Your NFC tap+pay setting is turned off, you will be taken to the NFC control panel to turn it on");
// This URI will navigate the user to the NFC tap+pay control panel
NfcUtils.LaunchNfcPaymentsSettingsPage();
return;
}
this.Frame.Navigate(typeof(SetCardDataScenario));
}
private async void btnEnableCard_Click(object sender, RoutedEventArgs e)
{
// Clear the messages
rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
var reg = (SmartCardAppletIdGroupRegistration)lstCards.SelectedItem;
if (reg == null)
{
LogMessage("No card selected, must select from listbox", NotifyType.ErrorMessage);
return;
}
await NfcUtils.SetCardActivationPolicy(
reg,
SmartCardAppletIdGroupActivationPolicy.Enabled);
// Refresh the listbox
lstCards.ItemsSource = await SmartCardEmulator.GetAppletIdGroupRegistrationsAsync();
}
private async void btnDisableCard_Click(object sender, RoutedEventArgs e)
{
// Clear the messages
rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
var reg = (SmartCardAppletIdGroupRegistration)lstCards.SelectedItem;
if (reg == null)
{
LogMessage("No card selected, must select from listbox", NotifyType.ErrorMessage);
return;
}
await NfcUtils.SetCardActivationPolicy(reg, SmartCardAppletIdGroupActivationPolicy.Disabled);
// Refresh the listbox
lstCards.ItemsSource = await SmartCardEmulator.GetAppletIdGroupRegistrationsAsync();
}
private async void btnForegroundOverrideCard_Click(object sender, RoutedEventArgs e)
{
// Clear the messages
rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
var reg = (SmartCardAppletIdGroupRegistration)lstCards.SelectedItem;
if (reg == null)
{
LogMessage("No card selected, must select from listbox", NotifyType.ErrorMessage);
return;
}
await NfcUtils.SetCardActivationPolicy(reg, SmartCardAppletIdGroupActivationPolicy.ForegroundOverride);
// Refresh the listbox
lstCards.ItemsSource = await SmartCardEmulator.GetAppletIdGroupRegistrationsAsync();
}
private async void btnUnregisterCard_Click(object sender, RoutedEventArgs e)
{
// Clear the messages
rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
var reg = (SmartCardAppletIdGroupRegistration)lstCards.SelectedItem;
if (reg == null)
{
LogMessage("No card selected, must select from listbox", NotifyType.ErrorMessage);
return;
}
// Unregister the card
await SmartCardEmulator.UnregisterAppletIdGroupAsync(reg);
if (reg.AppletIdGroup.SmartCardEmulationCategory == SmartCardEmulationCategory.Payment
&& reg.AppletIdGroup.SmartCardEmulationType == SmartCardEmulationType.Host)
{
// Delete the data file for the card
await (await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("ReadRecordResponse-" + reg.Id.ToString("B") + ".dat")).DeleteAsync();
}
// Refresh the listbox
lstCards.ItemsSource = await SmartCardEmulator.GetAppletIdGroupRegistrationsAsync();
LogMessage("AID group successfully unregistered");
}
private void chkDenyIfPhoneLocked_Checked(object sender, RoutedEventArgs e)
{
ApplicationData.Current.RoamingSettings.Values["DenyIfPhoneLocked"] = true;
}
private void chkDenyIfPhoneLocked_Unchecked(object sender, RoutedEventArgs e)
{
ApplicationData.Current.RoamingSettings.Values["DenyIfPhoneLocked"] = false;
}
private void chkLaunchAboveLock_Checked(object sender, RoutedEventArgs e)
{
ApplicationData.Current.RoamingSettings.Values["LaunchAboveLock"] = true;
}
private void chkLaunchAboveLock_Unchecked(object sender, RoutedEventArgs e)
{
ApplicationData.Current.RoamingSettings.Values["LaunchAboveLock"] = false;
}
private void lstCards_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var reg = (SmartCardAppletIdGroupRegistration)lstCards.SelectedItem;
if (reg != null)
{
// Clear the messages
rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
LogMessage("Selected card is: " + reg.ActivationPolicy.ToString());
}
}
private async void btnDebugLog_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
var debugLogFile = (StorageFile)(await Windows.Storage.ApplicationData.Current.LocalFolder.TryGetItemAsync("DebugLog.txt"));
if (debugLogFile != null)
{
if (txtDebugLog.Visibility == Windows.UI.Xaml.Visibility.Visible)
{
// Log was already displayed, clear it
await debugLogFile.DeleteAsync();
txtDebugLog.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
btnDebugLog.Content = "Debug Log";
}
else
{
// Display the log
txtDebugLog.Text = await FileIO.ReadTextAsync(debugLogFile);
txtDebugLog.Visibility = Windows.UI.Xaml.Visibility.Visible;
btnDebugLog.Content = "Clear Debug Log";
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using WngCodingTask.Areas.HelpPage.ModelDescriptions;
using WngCodingTask.Areas.HelpPage.Models;
namespace WngCodingTask.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Agent.Sdk.Knob;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Linq;
using System.Collections.Generic;
namespace Microsoft.VisualStudio.Services.Agent.Worker
{
[ServiceLocator(Default = typeof(WorkerCommandManager))]
public interface IWorkerCommandManager : IAgentService
{
void EnablePluginInternalCommand(bool enable);
bool TryProcessCommand(IExecutionContext context, string input);
}
public sealed class WorkerCommandManager : AgentService, IWorkerCommandManager
{
private readonly Dictionary<string, IWorkerCommandExtension> _commandExtensions = new Dictionary<string, IWorkerCommandExtension>(StringComparer.OrdinalIgnoreCase);
private IWorkerCommandExtension _pluginInternalCommandExtensions;
private readonly object _commandSerializeLock = new object();
private bool _invokePluginInternalCommand = false;
public override void Initialize(IHostContext hostContext)
{
ArgUtil.NotNull(hostContext, nameof(hostContext));
base.Initialize(hostContext);
// Register all command extensions
var extensionManager = hostContext.GetService<IExtensionManager>();
foreach (var commandExt in extensionManager.GetExtensions<IWorkerCommandExtension>() ?? new List<IWorkerCommandExtension>())
{
Trace.Info($"Register command extension for area {commandExt.CommandArea}");
if (!string.Equals(commandExt.CommandArea, "plugininternal", StringComparison.OrdinalIgnoreCase))
{
_commandExtensions[commandExt.CommandArea] = commandExt;
}
else
{
_pluginInternalCommandExtensions = commandExt;
}
}
}
public void EnablePluginInternalCommand(bool enable)
{
if (enable)
{
Trace.Info($"Enable plugin internal command extension.");
_invokePluginInternalCommand = true;
}
else
{
Trace.Info($"Disable plugin internal command extension.");
_invokePluginInternalCommand = false;
}
}
public bool TryProcessCommand(IExecutionContext context, string input)
{
ArgUtil.NotNull(context, nameof(context));
if (string.IsNullOrEmpty(input))
{
return false;
}
// TryParse input to Command
Command command;
var unescapePercents = AgentKnobs.DecodePercents.GetValue(context).AsBoolean();
if (!Command.TryParse(input, unescapePercents, out command))
{
// if parse fail but input contains ##vso, print warning with DOC link
if (input.IndexOf("##vso") >= 0)
{
context.Warning(StringUtil.Loc("CommandKeywordDetected", input));
}
return false;
}
IWorkerCommandExtension extension = null;
if (_invokePluginInternalCommand && string.Equals(command.Area, _pluginInternalCommandExtensions.CommandArea, StringComparison.OrdinalIgnoreCase))
{
extension = _pluginInternalCommandExtensions;
}
if (extension != null || _commandExtensions.TryGetValue(command.Area, out extension))
{
if (!extension.SupportedHostTypes.HasFlag(context.Variables.System_HostType))
{
context.Error(StringUtil.Loc("CommandNotSupported", command.Area, context.Variables.System_HostType));
context.CommandResult = TaskResult.Failed;
return false;
}
// process logging command in serialize oreder.
lock (_commandSerializeLock)
{
try
{
extension.ProcessCommand(context, command);
}
catch (Exception ex)
{
context.Error(StringUtil.Loc("CommandProcessFailed", input));
context.Error(ex);
context.CommandResult = TaskResult.Failed;
}
finally
{
// trace the ##vso command as long as the command is not a ##vso[task.debug] command.
if (!(string.Equals(command.Area, "task", StringComparison.OrdinalIgnoreCase) &&
string.Equals(command.Event, "debug", StringComparison.OrdinalIgnoreCase)))
{
context.Debug($"Processed: {input}");
}
}
}
}
else
{
context.Warning(StringUtil.Loc("CommandNotFound", command.Area));
}
// Only if we've successfully parsed do we show this warning
if (AgentKnobs.DecodePercents.GetValue(context).AsString() == "" && input.Contains("%AZP25"))
{
context.Warning("%AZP25 detected in ##vso command. In March 2021, the agent command parser will be updated to unescape this to %. To opt out of this behavior, set a job level variable DECODE_PERCENTS to false. Setting to true will force this behavior immediately. More information can be found at https://github.com/microsoft/azure-pipelines-agent/blob/master/docs/design/percentEncoding.md");
}
return true;
}
}
public interface IWorkerCommandExtension : IExtension
{
string CommandArea { get; }
HostTypes SupportedHostTypes { get; }
void ProcessCommand(IExecutionContext context, Command command);
}
public interface IWorkerCommand
{
string Name { get; }
List<string> Aliases { get; }
void Execute(IExecutionContext context, Command command);
}
public abstract class BaseWorkerCommandExtension: AgentService, IWorkerCommandExtension
{
public string CommandArea { get; protected set; }
public HostTypes SupportedHostTypes { get; protected set; }
public Type ExtensionType => typeof(IWorkerCommandExtension);
private Dictionary<string, IWorkerCommand> _commands = new Dictionary<string, IWorkerCommand>(StringComparer.OrdinalIgnoreCase);
protected void InstallWorkerCommand(IWorkerCommand commandExecutor)
{
ArgUtil.NotNull(commandExecutor, nameof(commandExecutor));
if (_commands.ContainsKey(commandExecutor.Name))
{
throw new Exception(StringUtil.Loc("CommandDuplicateDetected", commandExecutor.Name, CommandArea.ToLowerInvariant()));
}
_commands[commandExecutor.Name] = commandExecutor;
var aliasList = commandExecutor.Aliases;
if (aliasList != null)
{
foreach (var alias in commandExecutor.Aliases)
{
if (_commands.ContainsKey(alias))
{
throw new Exception(StringUtil.Loc("CommandDuplicateDetected", alias, CommandArea.ToLowerInvariant()));
}
_commands[alias] = commandExecutor;
}
}
}
public IWorkerCommand GetWorkerCommand(String name)
{
_commands.TryGetValue(name, out var commandExecutor);
return commandExecutor;
}
public void ProcessCommand(IExecutionContext context, Command command)
{
ArgUtil.NotNull(context, nameof(context));
ArgUtil.NotNull(command, nameof(command));
var commandExecutor = GetWorkerCommand(command.Event);
if (commandExecutor == null)
{
throw new Exception(StringUtil.Loc("CommandNotFound2", CommandArea.ToLowerInvariant(), command.Event, CommandArea));
}
var checker = context.GetHostContext().GetService<ITaskRestrictionsChecker>();
if (checker.CheckCommand(context, commandExecutor, command))
{
commandExecutor.Execute(context, command);
}
}
}
[Flags]
public enum HostTypes
{
None = 0,
Build = 1,
Deployment = 2,
PoolMaintenance = 4,
Release = 8,
All = Build | Deployment | PoolMaintenance | Release,
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.SolutionSize;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Storage
{
/// <summary>
/// A service that enables storing and retrieving of information associated with solutions,
/// projects or documents across runtime sessions.
/// </summary>
internal abstract partial class AbstractPersistentStorageService : IPersistentStorageService2
{
protected readonly IOptionService OptionService;
private readonly SolutionSizeTracker _solutionSizeTracker;
private readonly object _lookupAccessLock;
private readonly Dictionary<string, AbstractPersistentStorage> _lookup;
private readonly bool _testing;
private string _lastSolutionPath;
private SolutionId _primarySolutionId;
private AbstractPersistentStorage _primarySolutionStorage;
protected AbstractPersistentStorageService(
IOptionService optionService,
SolutionSizeTracker solutionSizeTracker)
{
OptionService = optionService;
_solutionSizeTracker = solutionSizeTracker;
_lookupAccessLock = new object();
_lookup = new Dictionary<string, AbstractPersistentStorage>();
_lastSolutionPath = null;
_primarySolutionId = null;
_primarySolutionStorage = null;
}
protected AbstractPersistentStorageService(IOptionService optionService, bool testing)
: this(optionService, solutionSizeTracker: null)
{
_testing = true;
}
protected abstract string GetDatabaseFilePath(string workingFolderPath);
protected abstract AbstractPersistentStorage OpenDatabase(Solution solution, string workingFolderPath, string databaseFilePath);
protected abstract bool ShouldDeleteDatabase(Exception exception);
public IPersistentStorage GetStorage(Solution solution)
=> GetStorage(solution, checkBranchId: true);
public IPersistentStorage GetStorage(Solution solution, bool checkBranchId)
{
if (!ShouldUseDatabase(solution, checkBranchId))
{
return NoOpPersistentStorage.Instance;
}
// can't use cached information
if (!string.Equals(solution.FilePath, _lastSolutionPath, StringComparison.OrdinalIgnoreCase))
{
// check whether the solution actually exist on disk
if (!File.Exists(solution.FilePath))
{
return NoOpPersistentStorage.Instance;
}
}
// cache current result.
_lastSolutionPath = solution.FilePath;
// get working folder path
var workingFolderPath = GetWorkingFolderPath(solution);
if (workingFolderPath == null)
{
// we don't have place to save db file. don't use db
return NoOpPersistentStorage.Instance;
}
return GetStorage(solution, workingFolderPath);
}
private IPersistentStorage GetStorage(Solution solution, string workingFolderPath)
{
lock (_lookupAccessLock)
{
// see whether we have something we can use
if (_lookup.TryGetValue(solution.FilePath, out var storage))
{
// previous attempt to create db storage failed.
if (storage == null && !SolutionSizeAboveThreshold(solution))
{
return NoOpPersistentStorage.Instance;
}
// everything seems right, use what we have
if (storage?.WorkingFolderPath == workingFolderPath)
{
storage.AddRefUnsafe();
return storage;
}
}
// either this is the first time, or working folder path has changed.
// remove existing one
_lookup.Remove(solution.FilePath);
var dbFile = GetDatabaseFilePath(workingFolderPath);
if (!File.Exists(dbFile) && !SolutionSizeAboveThreshold(solution))
{
_lookup.Add(solution.FilePath, storage);
return NoOpPersistentStorage.Instance;
}
// try create new one
storage = TryCreatePersistentStorage(solution, workingFolderPath);
_lookup.Add(solution.FilePath, storage);
if (storage != null)
{
RegisterPrimarySolutionStorageIfNeeded(solution, storage);
storage.AddRefUnsafe();
return storage;
}
return NoOpPersistentStorage.Instance;
}
}
private bool ShouldUseDatabase(Solution solution, bool checkBranchId)
{
if (_testing)
{
return true;
}
if (solution.FilePath == null)
{
return false;
}
if (checkBranchId && solution.BranchId != solution.Workspace.PrimaryBranchId)
{
// we only use database for primary solution. (Ex, forked solution will not use database)
return false;
}
return true;
}
private bool SolutionSizeAboveThreshold(Solution solution)
{
if (_testing)
{
return true;
}
var workspace = solution.Workspace;
if (workspace.Kind == WorkspaceKind.RemoteWorkspace ||
workspace.Kind == WorkspaceKind.RemoteTemporaryWorkspace)
{
// Storage is always available in the remote server.
return true;
}
if (_solutionSizeTracker == null)
{
return false;
}
var size = _solutionSizeTracker.GetSolutionSize(solution.Workspace, solution.Id);
var threshold = this.OptionService.GetOption(StorageOptions.SolutionSizeThreshold);
return size >= threshold;
}
private void RegisterPrimarySolutionStorageIfNeeded(Solution solution, AbstractPersistentStorage storage)
{
if (_primarySolutionStorage != null || solution.Id != _primarySolutionId)
{
return;
}
// hold onto the primary solution when it is used the first time.
_primarySolutionStorage = storage;
storage.AddRefUnsafe();
}
private string GetWorkingFolderPath(Solution solution)
{
if (_testing)
{
return Path.Combine(Path.GetDirectoryName(solution.FilePath), ".vs", Path.GetFileNameWithoutExtension(solution.FilePath));
}
var locationService = solution.Workspace.Services.GetService<IPersistentStorageLocationService>();
return locationService?.GetStorageLocation(solution);
}
private AbstractPersistentStorage TryCreatePersistentStorage(Solution solution, string workingFolderPath)
{
// Attempt to create the database up to two times. The first time we may encounter
// some sort of issue (like DB corruption). We'll then try to delete the DB and can
// try to create it again. If we can't create it the second time, then there's nothing
// we can do and we have to store things in memory.
if (TryCreatePersistentStorage(solution, workingFolderPath, out var persistentStorage) ||
TryCreatePersistentStorage(solution, workingFolderPath, out persistentStorage))
{
return persistentStorage;
}
// okay, can't recover, then use no op persistent service
// so that things works old way (cache everything in memory)
return null;
}
private bool TryCreatePersistentStorage(
Solution solution, string workingFolderPath,
out AbstractPersistentStorage persistentStorage)
{
persistentStorage = null;
AbstractPersistentStorage database = null;
var databaseFilePath = GetDatabaseFilePath(workingFolderPath);
try
{
database = OpenDatabase(solution, workingFolderPath, databaseFilePath);
database.Initialize(solution);
persistentStorage = database;
return true;
}
catch (Exception ex)
{
StorageDatabaseLogger.LogException(ex);
if (database != null)
{
database.Close();
}
if (ShouldDeleteDatabase(ex))
{
// this was not a normal exception that we expected during DB open.
// Report this so we can try to address whatever is causing this.
FatalError.ReportWithoutCrash(ex);
IOUtilities.PerformIO(() => Directory.Delete(Path.GetDirectoryName(databaseFilePath), recursive: true));
}
return false;
}
}
protected void Release(AbstractPersistentStorage storage)
{
lock (_lookupAccessLock)
{
if (storage.ReleaseRefUnsafe())
{
_lookup.Remove(storage.SolutionFilePath);
storage.Close();
}
}
}
public void RegisterPrimarySolution(SolutionId solutionId)
{
// don't create database storage file right away. it will be
// created when first C#/VB project is added
lock (_lookupAccessLock)
{
Contract.ThrowIfTrue(_primarySolutionStorage != null);
// just reset solutionId as long as there is no storage has created.
_primarySolutionId = solutionId;
}
}
public void UnregisterPrimarySolution(SolutionId solutionId, bool synchronousShutdown)
{
AbstractPersistentStorage storage = null;
lock (_lookupAccessLock)
{
if (_primarySolutionId == null)
{
// primary solution is never registered or already unregistered
Contract.ThrowIfTrue(_primarySolutionStorage != null);
return;
}
Contract.ThrowIfFalse(_primarySolutionId == solutionId);
_primarySolutionId = null;
if (_primarySolutionStorage == null)
{
// primary solution is registered but no C#/VB project was added
return;
}
storage = _primarySolutionStorage;
_primarySolutionStorage = null;
}
if (storage != null)
{
if (synchronousShutdown)
{
// dispose storage outside of the lock
storage.Dispose();
}
else
{
// make it to shutdown asynchronously
Task.Run(() => storage.Dispose());
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.DirectoryServices
{
using System;
using System.Runtime.InteropServices;
using System.Collections;
using System.Diagnostics;
using System.DirectoryServices.Interop;
using System.Security.Permissions;
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection"]/*' />
/// <devdoc>
/// <para>Holds a collection of values for a multi-valued property.</para>
/// </devdoc>
public class PropertyValueCollection : CollectionBase
{
internal enum UpdateType
{
Add = 0,
Delete = 1,
Update = 2,
None = 3
}
private DirectoryEntry _entry;
private string _propertyName;
private UpdateType _updateType = UpdateType.None;
private ArrayList _changeList = null;
private bool _allowMultipleChange = false;
private bool _needNewBehavior = false;
internal PropertyValueCollection(DirectoryEntry entry, string propertyName)
{
_entry = entry;
_propertyName = propertyName;
PopulateList();
ArrayList tempList = new ArrayList();
_changeList = ArrayList.Synchronized(tempList);
_allowMultipleChange = entry.allowMultipleChange;
string tempPath = entry.Path;
if (tempPath == null || tempPath.Length == 0)
{
// user does not specify path, so we bind to default naming context using LDAP provider.
_needNewBehavior = true;
}
else
{
if (tempPath.StartsWith("LDAP:", StringComparison.Ordinal))
_needNewBehavior = true;
}
}
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.this"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object this[int index]
{
get
{
return List[index];
}
set
{
if (_needNewBehavior && !_allowMultipleChange)
throw new NotSupportedException();
else
{
List[index] = value;
}
}
}
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.PropertyName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string PropertyName
{
get
{
return _propertyName;
}
}
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.Value"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Value
{
get
{
if (this.Count == 0)
return null;
else if (this.Count == 1)
return List[0];
else
{
object[] objectArray = new object[this.Count];
List.CopyTo(objectArray, 0);
return objectArray;
}
}
set
{
try
{
this.Clear();
}
catch (System.Runtime.InteropServices.COMException e)
{
if (e.ErrorCode != unchecked((int)0x80004005) || (value == null))
// WinNT provider throws E_FAIL when null value is specified though actually ADS_PROPERTY_CLEAR option is used, need to catch exception
// here. But at the same time we don't want to catch the exception if user explicitly sets the value to null.
throw;
}
if (value == null)
return;
// we could not do Clear and Add, we have to bypass the existing collection cache
_changeList.Clear();
if (value is Array)
{
// byte[] is a special case, we will follow what ADSI is doing, it must be an octet string. So treat it as a single valued attribute
if (value is byte[])
_changeList.Add(value);
else if (value is object[])
_changeList.AddRange((object[])value);
else
{
//Need to box value type array elements.
object[] objArray = new object[((Array)value).Length];
((Array)value).CopyTo(objArray, 0);
_changeList.AddRange((object[])objArray);
}
}
else
_changeList.Add(value);
object[] allValues = new object[_changeList.Count];
_changeList.CopyTo(allValues, 0);
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, _propertyName, allValues);
_entry.CommitIfNotCaching();
// populate the new context
PopulateList();
}
}
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.Add"]/*' />
/// <devdoc>
/// <para>Appends the value to the set of values for this property.</para>
/// </devdoc>
public int Add(object value)
{
return List.Add(value);
}
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.AddRange"]/*' />
/// <devdoc>
/// <para>Appends the values to the set of values for this property.</para>
/// </devdoc>
public void AddRange(object[] value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
for (int i = 0; ((i) < (value.Length)); i = ((i) + (1)))
{
this.Add(value[i]);
}
}
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.AddRange1"]/*' />
/// <devdoc>
/// <para>Appends the values to the set of values for this property.</para>
/// </devdoc>
public void AddRange(PropertyValueCollection value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
int currentCount = value.Count;
for (int i = 0; i < currentCount; i = ((i) + (1)))
{
this.Add(value[i]);
}
}
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.Contains"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool Contains(object value)
{
return List.Contains(value);
}
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.CopyTo"]/*' />
/// <devdoc>
/// <para>Copies the elements of this instance into an <see cref='System.Array'/>,
/// starting at a particular index
/// into the given <paramref name="array"/>.</para>
/// </devdoc>
public void CopyTo(object[] array, int index)
{
List.CopyTo(array, index);
}
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.IndexOf"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int IndexOf(object value)
{
return List.IndexOf(value);
}
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.Insert"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Insert(int index, object value)
{
List.Insert(index, value);
}
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.PopulateList"]/*' />
///<internalonly/>
private void PopulateList()
{
//No need to fill the cache here, when GetEx is calles, an implicit
//call to GetInfo will be called against an uninitialized property
//cache. Which is exactly what FillCache does.
//entry.FillCache(propertyName);
object var;
int unmanagedResult = _entry.AdsObject.GetEx(_propertyName, out var);
if (unmanagedResult != 0)
{
// property not found (IIS provider returns 0x80005006, other provides return 0x8000500D).
if ((unmanagedResult == unchecked((int)0x8000500D)) || (unmanagedResult == unchecked((int)0x80005006)))
{
return;
}
else
{
throw COMExceptionHelper.CreateFormattedComException(unmanagedResult);
}
}
if (var is ICollection)
InnerList.AddRange((ICollection)var);
else
InnerList.Add(var);
}
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.Remove"]/*' />
/// <devdoc>
/// <para>Removes the value from the collection.</para>
/// </devdoc>
public void Remove(object value)
{
if (_needNewBehavior)
{
try
{
List.Remove(value);
}
catch (ArgumentException)
{
// exception is thrown because value does not exist in the current cache, but it actually might do exist just because it is a very
// large multivalued attribute, the value has not been downloaded yet.
OnRemoveComplete(0, value);
}
}
else
List.Remove(value);
}
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.OnClear"]/*' />
///<internalonly/>
protected override void OnClearComplete()
{
if (_needNewBehavior && !_allowMultipleChange && _updateType != UpdateType.None && _updateType != UpdateType.Update)
{
throw new InvalidOperationException(SR.DSPropertyValueSupportOneOperation);
}
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Clear, _propertyName, null);
_updateType = UpdateType.Update;
try
{
_entry.CommitIfNotCaching();
}
catch (System.Runtime.InteropServices.COMException e)
{
// On ADSI 2.5 if property has not been assigned any value before,
// then IAds::SetInfo() in CommitIfNotCaching returns bad HREsult 0x8007200A, which we ignore.
if (e.ErrorCode != unchecked((int)0x8007200A)) // ERROR_DS_NO_ATTRIBUTE_OR_VALUE
throw;
}
}
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.OnInsert"]/*' />
///<internalonly/>
protected override void OnInsertComplete(int index, object value)
{
if (_needNewBehavior)
{
if (!_allowMultipleChange)
{
if (_updateType != UpdateType.None && _updateType != UpdateType.Add)
{
throw new InvalidOperationException(SR.DSPropertyValueSupportOneOperation);
}
_changeList.Add(value);
object[] allValues = new object[_changeList.Count];
_changeList.CopyTo(allValues, 0);
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Append, _propertyName, allValues);
_updateType = UpdateType.Add;
}
else
{
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Append, _propertyName, new object[] { value });
}
}
else
{
object[] allValues = new object[InnerList.Count];
InnerList.CopyTo(allValues, 0);
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, _propertyName, allValues);
}
_entry.CommitIfNotCaching();
}
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.OnRemove"]/*' />
///<internalonly/>
protected override void OnRemoveComplete(int index, object value)
{
if (_needNewBehavior)
{
if (!_allowMultipleChange)
{
if (_updateType != UpdateType.None && _updateType != UpdateType.Delete)
{
throw new InvalidOperationException(SR.DSPropertyValueSupportOneOperation);
}
_changeList.Add(value);
object[] allValues = new object[_changeList.Count];
_changeList.CopyTo(allValues, 0);
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Delete, _propertyName, allValues);
_updateType = UpdateType.Delete;
}
else
{
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Delete, _propertyName, new object[] { value });
}
}
else
{
object[] allValues = new object[InnerList.Count];
InnerList.CopyTo(allValues, 0);
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, _propertyName, allValues);
}
_entry.CommitIfNotCaching();
}
/// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.OnSet"]/*' />
///<internalonly/>
protected override void OnSetComplete(int index, object oldValue, object newValue)
{
// no need to consider the not allowing accumulative change case as it does not support Set
if (Count <= 1)
{
_entry.AdsObject.Put(_propertyName, newValue);
}
else
{
if (_needNewBehavior)
{
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Delete, _propertyName, new object[] { oldValue });
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Append, _propertyName, new object[] { newValue });
}
else
{
object[] allValues = new object[InnerList.Count];
InnerList.CopyTo(allValues, 0);
_entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, _propertyName, allValues);
}
}
_entry.CommitIfNotCaching();
}
}
}
| |
// Copyright (c) 2013 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Icu.Collation
{
/// <summary>
/// The Collator class performs locale-sensitive string comparison.
/// You use this class to build searching and sorting routines for natural
/// language text.
/// </summary>
public abstract class Collator : IComparer<string>, ICloneable, IDisposable
{
/// <summary>
/// Gets or sets the minimum strength that will be used in comparison
/// or transformation.
/// </summary>
public abstract CollationStrength Strength{ get; set; }
/// <summary>
/// Gets or sets the NormalizationMode
/// </summary>
public abstract NormalizationMode NormalizationMode{ get; set; }
/// <summary>
/// Gets or sets the FrenchCollation. Attribute for direction of
/// secondary weights - used in Canadian French.
/// </summary>
public abstract FrenchCollation FrenchCollation{ get; set; }
/// <summary>
/// Gets or sets the CaseLevel mode. Controls whether an extra case
/// level (positioned before the third level) is generated or not.
/// </summary>
/// <remarks></remarks>
public abstract CaseLevel CaseLevel{ get; set; }
/// <summary>
/// Gets or sets HiraganaQuaternary mode. When turned on, this attribute
/// positions Hiragana before all non-ignorables on quaternary level
/// This is a sneaky way to produce JIS sort order.
/// </summary>
[Obsolete("ICU 50 Implementation detail, cannot be set via API, was removed from implementation.")]
public abstract HiraganaQuaternary HiraganaQuaternary{ get; set; }
/// <summary>
/// Gets or sets NumericCollation mode. When turned on, this attribute
/// makes substrings of digits sort according to their numeric values.
/// </summary>
public abstract NumericCollation NumericCollation{ get; set; }
/// <summary>
/// Controls the ordering of upper and lower case letters.
/// </summary>
public abstract CaseFirst CaseFirst{ get; set; }
/// <summary>
/// Gets or sets attribute for handling variable elements.
/// </summary>
public abstract AlternateHandling AlternateHandling{ get; set; }
/// <summary>
/// Get a sort key for a string from the collator.
/// </summary>
/// <param name="source">The text</param>
public abstract SortKey GetSortKey(string source);
/// <summary>
/// Compare two strings.
/// </summary>
/// <param name="source">The source string</param>
/// <param name="target">The target string</param>
/// <returns>The result of comparing the strings; 0 if source == target;
/// 1 if source > target; -1 source < target</returns>
public abstract int Compare(string source, string target);
/// <summary>
/// Thread safe cloning operation.
/// </summary>
/// <returns>The result is a clone of a given collator.</returns>
public abstract object Clone();
/// <summary>
/// Specifies whether locale fallback is allowed.
/// For more information, see: http://userguide.icu-project.org/locale#TOC-Fallback
/// </summary>
public enum Fallback
{
/// <summary>Do not use Locale fallback</summary>
NoFallback,
/// <summary>Use locale fallback algorithm</summary>
FallbackAllowed
}
/// <summary>
/// Creates a collator with the current culture. Does not allow
/// locale fallback.
/// </summary>
public static Collator Create()
{
return Create(CultureInfo.CurrentCulture);
}
/// <summary>
/// Creates a collator with the specified locale. Does not allow
/// locale fallback.
/// </summary>
/// <param name="localeId">Locale to use</param>
public static Collator Create(string localeId)
{
return Create(localeId, Fallback.NoFallback);
}
/// <summary>
/// Creates a collator with the given locale and whether to use locale
/// fallback when creating collator.
/// </summary>
/// <param name="localeId">The locale</param>
/// <param name="fallback">Whether to use locale fallback or not.</param>
public static Collator Create(string localeId, Fallback fallback)
{
if (localeId == null)
{
throw new ArgumentNullException();
}
return RuleBasedCollator.Create(localeId, fallback);
}
/// <summary>
/// Creates a collator with the given CultureInfo
/// </summary>
/// <param name="cultureInfo">Culture to use.</param>
public static Collator Create(CultureInfo cultureInfo)
{
return Create(cultureInfo, Fallback.NoFallback);
}
/// <summary>
/// Creates a collator with the given CultureInfo and fallback
/// </summary>
/// <param name="cultureInfo">Culture to use</param>
/// <param name="fallback">Whether to use locale fallback or not.</param>
public static Collator Create(CultureInfo cultureInfo, Fallback fallback)
{
if (cultureInfo == null)
{
throw new ArgumentNullException();
}
return Create(cultureInfo.IetfLanguageTag, fallback);
}
/// <summary>
/// Creates a SortKey with the given string and keyData
/// </summary>
/// <param name="originalString">String to use</param>
/// <param name="keyData">Data of the SortKey</param>
static public SortKey CreateSortKey(string originalString, byte[] keyData)
{
if (keyData == null)
{
throw new ArgumentNullException("keyData");
}
return CreateSortKey(originalString, keyData, keyData.Length);
}
/// <summary>
/// Creates a SortKey with the given string and keyData
/// </summary>
/// <param name="originalString">String to use</param>
/// <param name="keyData">Data of the SortKey</param>
/// <param name="keyDataLength">Length to use from keyData</param>
static public SortKey CreateSortKey(string originalString, byte[] keyData, int keyDataLength)
{
if (originalString == null)
{
throw new ArgumentNullException("originalString");
}
if (keyData == null)
{
throw new ArgumentNullException("keyData");
}
if (0 > keyDataLength || keyDataLength > keyData.Length)
{
throw new ArgumentOutOfRangeException("keyDataLength");
}
SortKey sortKey = CultureInfo.InvariantCulture.CompareInfo.GetSortKey(string.Empty);
SetInternalOriginalStringField(sortKey, originalString);
SetInternalKeyDataField(sortKey, keyData, keyDataLength);
return sortKey;
}
private static void SetInternalKeyDataField(SortKey sortKey, byte[] keyData, int keyDataLength)
{
byte[] keyDataCopy = new byte[keyDataLength];
Array.Copy(keyData, keyDataCopy, keyDataLength);
string propertyName = "SortKey.KeyData";
string monoInternalFieldName = "key";
string netInternalFieldName = "m_KeyData";
SetInternalFieldForPublicProperty(sortKey,
propertyName,
netInternalFieldName,
monoInternalFieldName,
keyDataCopy);
}
private static void SetInternalOriginalStringField(SortKey sortKey, string originalString)
{
string propertyName = "SortKey.OriginalString";
string monoInternalFieldName = "source";
string netInternalFieldName = "m_String";
SetInternalFieldForPublicProperty(sortKey,
propertyName,
netInternalFieldName,
monoInternalFieldName,
originalString);
}
private static void SetInternalFieldForPublicProperty<T,P>(
T instance,
string propertyName,
string netInternalFieldName,
string monoInternalFieldName,
P value)
{
Type type = instance.GetType();
FieldInfo fieldInfo;
if (IsRunningOnMono())
{
fieldInfo = type.GetField(monoInternalFieldName,
BindingFlags.Instance
| BindingFlags.NonPublic);
}
else //Is Running On .Net
{
fieldInfo = type.GetField(netInternalFieldName,
BindingFlags.Instance
| BindingFlags.NonPublic);
}
Debug.Assert(fieldInfo != null,
"Unsupported runtime",
"Could not figure out an internal field for" + propertyName);
if (fieldInfo == null)
{
throw new NotImplementedException("Not implemented for this runtime");
}
fieldInfo.SetValue(instance, value);
}
private static bool IsRunningOnMono()
{
return Type.GetType("Mono.Runtime") != null;
}
/// <summary>
/// Simple class to allow passing collation error info back to the caller of CheckRules.
/// </summary>
public class CollationRuleErrorInfo
{
/// <summary>Line number (1-based) containing the error</summary>
public int Line;
/// <summary>Character offset (1-based) on Line where the error was detected</summary>
public int Offset;
/// <summary>Characters preceding the the error</summary>
public String PreContext;
/// <summary>Characters following the the error</summary>
public String PostContext;
}
// REVIEW: We might want to integrate the methods below in a better way.
/// <summary>
/// Test collation rules and return an object with error information if it fails.
/// </summary>
/// <param name="rules">String containing the collation rules to check</param>
/// <returns>A CollationRuleErrorInfo object with error information; or <c>null</c> if
/// no errors are found.</returns>
public static CollationRuleErrorInfo CheckRules(string rules)
{
if (rules == null)
return null;
ErrorCode err;
var parseError = new ParseError();
using (NativeMethods.ucol_openRules(rules, rules.Length, NormalizationMode.Default,
CollationStrength.Default, ref parseError, out err))
{
if (err == ErrorCode.NoErrors)
return null;
return new CollationRuleErrorInfo
{
Line = parseError.Line + 1,
Offset = parseError.Offset + 1,
PreContext = parseError.PreContext,
PostContext = parseError.PostContext
};
}
}
/// <summary>
/// Gets the collation rules for the specified locale.
/// </summary>
/// <param name="locale">The locale.</param>
/// <param name="collatorRuleOption">UColRuleOption to use. Default is UColRuleOption.UCOL_TAILORING_ONLY</param>
public static string GetCollationRules(string locale, UColRuleOption collatorRuleOption = UColRuleOption.UCOL_TAILORING_ONLY)
{
return GetCollationRules(new Locale(locale), collatorRuleOption);
}
/// <summary>
/// Gets the collation rules for the specified locale.
/// </summary>
/// <param name="locale">The locale.</param>
/// <param name="collatorRuleOption">UColRuleOption to use. Default is UColRuleOption.UCOL_TAILORING_ONLY</param>
public static string GetCollationRules(Locale locale, UColRuleOption collatorRuleOption = UColRuleOption.UCOL_TAILORING_ONLY)
{
ErrorCode err;
using (RuleBasedCollator.SafeRuleBasedCollatorHandle coll = NativeMethods.ucol_open(locale.Id, out err))
{
if (coll.IsInvalid || err.IsFailure())
return null;
const int len = 1000;
IntPtr buffer = Marshal.AllocCoTaskMem(len * 2);
try
{
int actualLen = NativeMethods.ucol_getRulesEx(coll, collatorRuleOption, buffer, len);
if (actualLen > len)
{
Marshal.FreeCoTaskMem(buffer);
buffer = Marshal.AllocCoTaskMem(actualLen * 2);
NativeMethods.ucol_getRulesEx(coll, collatorRuleOption, buffer, actualLen);
}
return Marshal.PtrToStringUni(buffer, actualLen);
}
finally
{
Marshal.FreeCoTaskMem(buffer);
}
}
}
/// <summary>
/// Produces a bound for a given sort key.
/// </summary>
/// <param name="sortKey">The sort key.</param>
/// <param name="boundType">Type of the bound.</param>
/// <param name="result">The result.</param>
public static void GetSortKeyBound(byte[] sortKey, UColBoundMode boundType, ref byte[] result)
{
ErrorCode err;
int size = NativeMethods.ucol_getBound(sortKey, sortKey.Length, boundType, 1, result, result.Length, out err);
if (err > 0 && err != ErrorCode.BUFFER_OVERFLOW_ERROR)
throw new Exception("Collator.GetSortKeyBound() failed with code " + err);
if (size > result.Length)
{
result = new byte[size + 1];
NativeMethods.ucol_getBound(sortKey, sortKey.Length, boundType, 1, result, result.Length, out err);
if (err != ErrorCode.NoErrors)
throw new Exception("Collator.GetSortKeyBound() failed with code " + err);
}
}
#region IDisposable Support
/// <summary>
/// Dispose of managed/unmanaged resources.
/// Allow any inheriting classes to dispose of manage
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the resources used by Collator.
/// </summary>
/// <param name="disposing">true to release managed and unmanaged
/// resources; false to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing) { }
#endregion
}
}
| |
/*
* REST API Documentation for Schoolbus
*
* API Sample
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SchoolBusAPI.Models;
using Microsoft.EntityFrameworkCore;
namespace SchoolBusAPI.Services.Impl
{
/// <summary>
///
/// </summary>
public class SchoolBusApiService : ISchoolBusApiService
{
private readonly DbAppContext _context;
/// <summary>
/// Create a service and set the database context
/// </summary>
public SchoolBusApiService (DbAppContext context)
{
_context = context;
}
/// <summary>
/// Creates a new school bus
/// </summary>
/// <remarks>The Location response-header field is used to redirect the recipient to a location other than the Request-URI for completion of the request or identification of a new resource. For 201 (Created) responses, the Location is that of the new resource which was created by the request. The field value consists of a single absolute URI. </remarks>
/// <param name="item"></param>
/// <response code="201">SchoolBus created</response>
public virtual IActionResult AddBusAsync (SchoolBus item)
{
// adjust school bus owner
if (item.SchoolBusOwner != null)
{
int school_bus_owner_id = item.SchoolBusOwner.Id;
bool school_bus_owner_exists = _context.SchoolBusOwners.Any(a => a.Id == school_bus_owner_id);
if (school_bus_owner_exists)
{
SchoolBusOwner school_bus_owner = _context.SchoolBusOwners.First(a => a.Id == school_bus_owner_id);
item.SchoolBusOwner = school_bus_owner;
}
}
// adjust service area.
if (item.ServiceArea != null)
{
int service_area_id = item.ServiceArea.Id;
bool service_area_exists = _context.ServiceAreas.Any(a => a.Id == service_area_id);
if (service_area_exists)
{
ServiceArea service_area = _context.ServiceAreas.First(a => a.Id == service_area_id);
item.ServiceArea = service_area;
}
}
// adjust school district
if (item.SchoolBusDistrict != null)
{
int schoolbus_district_id = item.SchoolBusDistrict.Id;
bool schoolbus_district_exists = _context.SchoolDistricts.Any(a => a.Id == schoolbus_district_id);
if (schoolbus_district_exists)
{
SchoolDistrict school_district = _context.SchoolDistricts.First(a => a.Id == schoolbus_district_id);
item.SchoolBusDistrict = school_district;
}
}
// adjust home city
if (item.HomeTerminalCity != null)
{
int city_id = item.HomeTerminalCity.Id;
bool city_exists = _context.Cities.Any(a => a.Id == city_id);
if (city_exists)
{
City city = _context.Cities.First(a => a.Id == city_id);
item.HomeTerminalCity = city;
}
}
_context.SchoolBuss.Add(item);
_context.SaveChanges();
return new ObjectResult(item);
}
/// <summary>
/// Creates several school buses
/// </summary>
/// <remarks>Used for bulk creation of schoolbus records.</remarks>
/// <param name="body"></param>
/// <response code="201">SchoolBus items created</response>
public virtual IActionResult AddSchoolBusBulkAsync (SchoolBus[] items)
{
if (items == null)
{
return new BadRequestResult();
}
foreach (SchoolBus item in items)
{
// adjust school bus owner
if (item.SchoolBusOwner != null)
{
int school_bus_owner_id = item.SchoolBusOwner.Id;
bool school_bus_owner_exists = _context.SchoolBusOwners.Any(a => a.Id == school_bus_owner_id);
if (school_bus_owner_exists)
{
SchoolBusOwner school_bus_owner = _context.SchoolBusOwners.First(a => a.Id == school_bus_owner_id);
item.SchoolBusOwner = school_bus_owner;
}
}
// adjust service area.
if (item.ServiceArea != null)
{
int service_area_id = item.ServiceArea.Id;
bool service_area_exists = _context.ServiceAreas.Any(a => a.Id == service_area_id);
if (service_area_exists)
{
ServiceArea service_area = _context.ServiceAreas.First(a => a.Id == service_area_id);
item.ServiceArea = service_area;
}
}
// adjust school district
if (item.SchoolBusDistrict != null)
{
int schoolbus_district_id = item.SchoolBusDistrict.Id;
bool schoolbus_district_exists = _context.SchoolDistricts.Any(a => a.Id == schoolbus_district_id);
if (schoolbus_district_exists)
{
SchoolDistrict school_district = _context.SchoolDistricts.First(a => a.Id == schoolbus_district_id);
item.SchoolBusDistrict = school_district;
}
}
// adjust home city
if (item.HomeTerminalCity != null)
{
int city_id = item.HomeTerminalCity.Id;
bool city_exists = _context.Cities.Any(a => a.Id == city_id);
if (city_exists)
{
City city = _context.Cities.First(a => a.Id == city_id);
item.HomeTerminalCity = city;
}
}
var exists = _context.SchoolBuss.Any(a => a.Id == item.Id);
if (exists)
{
_context.SchoolBuss.Update(item);
}
else
{
_context.SchoolBuss.Add(item);
}
}
// Save the changes
_context.SaveChanges();
return new NoContentResult();
}
/// <summary>
/// Returns a single school bus object
/// </summary>
/// <remarks></remarks>
/// <param name="id">Id of SchoolBus to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">Not Found</response>
public virtual IActionResult FindBusByIdAsync (int id)
{
var exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists)
{
var result = _context.SchoolBuss.First(a => a.Id == id);
return new ObjectResult(result);
}
else
{
return new StatusCodeResult(404);
}
}
/// <summary>
/// Returns a collection of school buses
/// </summary>
/// <remarks></remarks>
/// <response code="200">OK</response>
public virtual IActionResult GetAllBusesAsync ()
{
var result = _context.SchoolBuss
.Include (x => x.HomeTerminalCity)
.Include(x => x.SchoolBusDistrict)
.Include(x => x.SchoolBusOwner)
.Include(x => x.ServiceArea)
.ToList();
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns attachments for a particular SchoolBus</remarks>
/// <param name="id">id of SchoolBus to fetch attachments for</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
public virtual IActionResult SchoolbusesIdAttachmentsGetAsync (int id)
{
var exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists)
{
var result = _context.SchoolBusAttachments.Where(a => a.SchoolBus.Id == id);
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <remarks>Returns CCWData for a particular Schoolbus</remarks>
/// <param name="id">id of SchoolBus to fetch CCWData for</param>
/// <response code="200">OK</response>
public virtual IActionResult SchoolbusesIdCcwdataGetAsync (int id)
{
// TODO: need to fix the model for CCWData
var result = "";
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of SchoolBus to delete</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
public virtual IActionResult SchoolbusesIdDeletePostAsync (int id)
{
var exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists)
{
var item = _context.SchoolBuss.First(a => a.Id == id);
if (item != null)
{
_context.SchoolBuss.Remove(item);
// Save the changes
_context.SaveChanges();
}
return new ObjectResult(item);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <remarks>Returns History for a particular SchoolBus</remarks>
/// <param name="id">id of SchoolBus to fetch SchoolBusHistory for</param>
/// <response code="200">OK</response>
public virtual IActionResult SchoolbusesIdHistoryGetAsync (int id)
{
var exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists)
{
var result = _context.SchoolBusHistorys.Where(a => a.SchoolBus.Id == id);
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <remarks>Returns notes for a particular SchoolBus.</remarks>
/// <param name="id">id of SchoolBus to fetch notes for</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
public virtual IActionResult SchoolbusesIdNotesGetAsync (int id)
{
var exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists)
{
var result = _context.SchoolBusNotes.Where(a => a.SchoolBus.Id == id);
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
/// Updates a single school bus object
/// </summary>
/// <remarks></remarks>
/// <param name="id">Id of SchoolBus to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">Not Found</response>
public virtual IActionResult SchoolbusesIdPutAsync (int id, SchoolBus body)
{
var exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists && id == body.Id)
{
_context.SchoolBuss.Update(body);
// Save the changes
_context.SaveChanges();
return new ObjectResult(body);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <param name="id">id of SchoolBus to fetch Inspections for</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
public virtual IActionResult SchoolbusesIdInspectionsGetAsync(int id)
{
var exists = _context.SchoolBuss.Any(a => a.Id == id);
if (exists)
{
var items = _context.Inspections.Where(a => a.SchoolBus.Id == id);
return new ObjectResult(items);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
/// Searches school buses
/// </summary>
/// <remarks>Used for the search schoolbus page.</remarks>
/// <param name="serviceareas">Service areas (array of id numbers)</param>
/// <param name="inspectors">Assigned School Bus Inspectors (array of id numbers)</param>
/// <param name="cities">Cities (array of id numbers)</param>
/// <param name="schooldistricts">School Districts (array of id numbers)</param>
/// <param name="owner"></param>
/// <param name="regi">ICBC Regi Number</param>
/// <param name="vin">VIN</param>
/// <param name="plate">License Plate String</param>
/// <param name="includeInactive">True if Inactive schoolbuses will be returned</param>
/// <param name="onlyReInspections">If true, only buses that need a re-inspection will be returned</param>
/// <param name="startDate">Inspection start date</param>
/// <param name="endDate">Inspection end date</param>
/// <response code="200">OK</response>
public IActionResult SchoolbusesSearchGetAsync(int?[] serviceareas, int?[] inspectors, int?[] cities, int?[] schooldistricts, int? owner, string regi, string vin, string plate, bool? includeInactive, bool? onlyReInspections, DateTime? startDate, DateTime? endDate)
{
// Eager loading of related data
var data = _context.SchoolBuss
.Include(x => x.HomeTerminalCity)
.Include(x => x.SchoolBusDistrict)
.Include(x => x.SchoolBusOwner)
.Include(x => x.ServiceArea)
.Select(x => x);
bool keySearch = false;
// do key search fields first.
if (regi != null)
{
data = data.Where(x => x.Regi == regi);
keySearch = true;
}
if (vin != null)
{
data = data.Where(x => x.VIN == vin);
keySearch = true;
}
if (plate != null)
{
data = data.Where(x => x.Plate == plate);
keySearch = true;
}
// only search other fields if a key search was not done.
if (!keySearch)
{
if (serviceareas != null)
{
foreach (int? servicearea in serviceareas)
{
if (servicearea != null)
{
data = data.Where(x => x.ServiceArea.Id == servicearea);
}
}
}
if (inspectors != null)
{
// no inspectors yet.
}
if (cities != null)
{
foreach (int? city in cities)
{
if (city != null)
{
data = data.Where(x => x.HomeTerminalCity.Id == city);
}
}
}
if (schooldistricts != null)
{
foreach (int? schooldistrict in schooldistricts)
{
if (schooldistrict != null)
{
data = data.Where(x => x.SchoolBusDistrict.Id == schooldistrict);
}
}
}
if (owner != null)
{
data = data.Where(x => x.SchoolBusOwner.Id == owner);
}
if (includeInactive == null)
{
data = data.Where(x => x.Status == "Active");
}
if (includeInactive == null || (includeInactive != null && includeInactive == false))
{
data = data.Where(x => x.Status == "Active");
}
if (onlyReInspections != null && onlyReInspections == true)
{
data = data.Where(x => x.NextInspectionType == "Re-inspection");
}
if (startDate != null)
{
data = data.Where(x => x.NextInspectionDate >= startDate);
}
if (endDate != null)
{
data = data.Where(x => x.NextInspectionDate <= endDate);
}
}
var result = data.ToList();
return new ObjectResult(result);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using ILCompiler.DependencyAnalysisFramework;
using Internal.TypeSystem;
using Internal.Runtime;
using Internal.IL;
namespace ILCompiler.DependencyAnalysis
{
public abstract class NodeFactory
{
private TargetDetails _target;
private CompilerTypeSystemContext _context;
private CompilationModuleGroup _compilationModuleGroup;
public NodeFactory(CompilerTypeSystemContext context, CompilationModuleGroup compilationModuleGroup)
{
_target = context.Target;
_context = context;
_compilationModuleGroup = compilationModuleGroup;
CreateNodeCaches();
MetadataManager = new MetadataGeneration();
}
public TargetDetails Target
{
get
{
return _target;
}
}
public CompilationModuleGroup CompilationModuleGroup
{
get
{
return _compilationModuleGroup;
}
}
public CompilerTypeSystemContext TypeSystemContext
{
get
{
return _context;
}
}
public MetadataGeneration MetadataManager
{
get; private set;
}
private struct NodeCache<TKey, TValue>
{
private Func<TKey, TValue> _creator;
private Dictionary<TKey, TValue> _cache;
public NodeCache(Func<TKey, TValue> creator, IEqualityComparer<TKey> comparer)
{
_creator = creator;
_cache = new Dictionary<TKey, TValue>(comparer);
}
public NodeCache(Func<TKey, TValue> creator)
{
_creator = creator;
_cache = new Dictionary<TKey, TValue>();
}
public TValue GetOrAdd(TKey key)
{
TValue result;
if (!_cache.TryGetValue(key, out result))
{
result = _creator(key);
_cache.Add(key, result);
}
return result;
}
}
private void CreateNodeCaches()
{
_typeSymbols = new NodeCache<TypeDesc, IEETypeNode>((TypeDesc type) =>
{
if (_compilationModuleGroup.ContainsType(type))
{
if (type.IsGenericDefinition)
{
return new GenericDefinitionEETypeNode(type);
}
else
{
return new EETypeNode(type);
}
}
else
{
return new ExternEETypeSymbolNode(type);
}
});
_constructedTypeSymbols = new NodeCache<TypeDesc, IEETypeNode>((TypeDesc type) =>
{
if (_compilationModuleGroup.ContainsType(type))
{
return new ConstructedEETypeNode(type);
}
else
{
return new ExternEETypeSymbolNode(type);
}
});
_nonGCStatics = new NodeCache<MetadataType, NonGCStaticsNode>((MetadataType type) =>
{
return new NonGCStaticsNode(type, this);
});
_GCStatics = new NodeCache<MetadataType, GCStaticsNode>((MetadataType type) =>
{
return new GCStaticsNode(type);
});
_GCStaticIndirectionNodes = new NodeCache<MetadataType, EmbeddedObjectNode>((MetadataType type) =>
{
ISymbolNode gcStaticsNode = TypeGCStaticsSymbol(type);
Debug.Assert(gcStaticsNode is GCStaticsNode);
return GCStaticsRegion.NewNode((GCStaticsNode)gcStaticsNode);
});
_threadStatics = new NodeCache<MetadataType, ThreadStaticsNode>((MetadataType type) =>
{
return new ThreadStaticsNode(type, this);
});
_GCStaticEETypes = new NodeCache<GCPointerMap, GCStaticEETypeNode>((GCPointerMap gcMap) =>
{
return new GCStaticEETypeNode(Target, gcMap);
});
_readOnlyDataBlobs = new NodeCache<Tuple<string, byte[], int>, BlobNode>((Tuple<string, byte[], int> key) =>
{
return new BlobNode(key.Item1, ObjectNodeSection.ReadOnlyDataSection, key.Item2, key.Item3);
}, new BlobTupleEqualityComparer());
_externSymbols = new NodeCache<string, ExternSymbolNode>((string name) =>
{
return new ExternSymbolNode(name);
});
_pInvokeModuleFixups = new NodeCache<string, PInvokeModuleFixupNode>((string name) =>
{
return new PInvokeModuleFixupNode(name);
});
_pInvokeMethodFixups = new NodeCache<Tuple<string, string>, PInvokeMethodFixupNode>((Tuple<string, string> key) =>
{
return new PInvokeMethodFixupNode(key.Item1, key.Item2);
});
_internalSymbols = new NodeCache<Tuple<ObjectNode, int, string>, ObjectAndOffsetSymbolNode>(
(Tuple<ObjectNode, int, string> key) =>
{
return new ObjectAndOffsetSymbolNode(key.Item1, key.Item2, key.Item3);
});
_methodEntrypoints = new NodeCache<MethodDesc, IMethodNode>(CreateMethodEntrypointNode);
_unboxingStubs = new NodeCache<MethodDesc, IMethodNode>(CreateUnboxingStubNode);
_virtMethods = new NodeCache<MethodDesc, VirtualMethodUseNode>((MethodDesc method) =>
{
return new VirtualMethodUseNode(method);
});
_readyToRunHelpers = new NodeCache<Tuple<ReadyToRunHelperId, Object>, ISymbolNode>(CreateReadyToRunHelperNode);
_stringDataNodes = new NodeCache<string, StringDataNode>((string data) =>
{
return new StringDataNode(data);
});
_stringIndirectionNodes = new NodeCache<string, StringIndirectionNode>((string data) =>
{
return new StringIndirectionNode(data);
});
_typeOptionalFields = new NodeCache<EETypeOptionalFieldsBuilder, EETypeOptionalFieldsNode>((EETypeOptionalFieldsBuilder fieldBuilder) =>
{
return new EETypeOptionalFieldsNode(fieldBuilder, this.Target);
});
_interfaceDispatchCells = new NodeCache<MethodDesc, InterfaceDispatchCellNode>((MethodDesc method) =>
{
return new InterfaceDispatchCellNode(method);
});
_interfaceDispatchMaps = new NodeCache<TypeDesc, InterfaceDispatchMapNode>((TypeDesc type) =>
{
return new InterfaceDispatchMapNode(type);
});
_interfaceDispatchMapIndirectionNodes = new NodeCache<TypeDesc, EmbeddedObjectNode>((TypeDesc type) =>
{
var dispatchMap = InterfaceDispatchMap(type);
return DispatchMapTable.NewNodeWithSymbol(dispatchMap, (indirectionNode) =>
{
dispatchMap.SetDispatchMapIndex(this, DispatchMapTable.IndexOfEmbeddedObject(indirectionNode));
});
});
_genericCompositions = new NodeCache<GenericCompositionDetails, GenericCompositionNode>((GenericCompositionDetails details) =>
{
return new GenericCompositionNode(details);
});
_eagerCctorIndirectionNodes = new NodeCache<MethodDesc, EmbeddedObjectNode>((MethodDesc method) =>
{
Debug.Assert(method.IsStaticConstructor);
Debug.Assert(TypeSystemContext.HasEagerStaticConstructor((MetadataType)method.OwningType));
return EagerCctorTable.NewNode(MethodEntrypoint(method));
});
_vTableNodes = new NodeCache<TypeDesc, VTableSliceNode>((TypeDesc type ) =>
{
if (CompilationModuleGroup.ShouldProduceFullType(type))
return new EagerlyBuiltVTableSliceNode(type);
else
return new LazilyBuiltVTableSliceNode(type);
});
}
protected abstract IMethodNode CreateMethodEntrypointNode(MethodDesc method);
protected abstract IMethodNode CreateUnboxingStubNode(MethodDesc method);
protected abstract ISymbolNode CreateReadyToRunHelperNode(Tuple<ReadyToRunHelperId, Object> helperCall);
private NodeCache<TypeDesc, IEETypeNode> _typeSymbols;
public IEETypeNode NecessaryTypeSymbol(TypeDesc type)
{
return _typeSymbols.GetOrAdd(type);
}
private NodeCache<TypeDesc, IEETypeNode> _constructedTypeSymbols;
public IEETypeNode ConstructedTypeSymbol(TypeDesc type)
{
return _constructedTypeSymbols.GetOrAdd(type);
}
private NodeCache<MetadataType, NonGCStaticsNode> _nonGCStatics;
public ISymbolNode TypeNonGCStaticsSymbol(MetadataType type)
{
if (_compilationModuleGroup.ContainsType(type))
{
return _nonGCStatics.GetOrAdd(type);
}
else
{
return ExternSymbol("__NonGCStaticBase_" + NodeFactory.NameMangler.GetMangledTypeName(type));
}
}
private NodeCache<MetadataType, GCStaticsNode> _GCStatics;
public ISymbolNode TypeGCStaticsSymbol(MetadataType type)
{
if (_compilationModuleGroup.ContainsType(type))
{
return _GCStatics.GetOrAdd(type);
}
else
{
return ExternSymbol("__GCStaticBase_" + NodeFactory.NameMangler.GetMangledTypeName(type));
}
}
private NodeCache<MetadataType, EmbeddedObjectNode> _GCStaticIndirectionNodes;
public EmbeddedObjectNode GCStaticIndirection(MetadataType type)
{
return _GCStaticIndirectionNodes.GetOrAdd(type);
}
private NodeCache<MetadataType, ThreadStaticsNode> _threadStatics;
public ISymbolNode TypeThreadStaticsSymbol(MetadataType type)
{
if (_compilationModuleGroup.ContainsType(type))
{
return _threadStatics.GetOrAdd(type);
}
else
{
return ExternSymbol("__ThreadStaticBase_" + NodeFactory.NameMangler.GetMangledTypeName(type));
}
}
private NodeCache<MethodDesc, InterfaceDispatchCellNode> _interfaceDispatchCells;
internal InterfaceDispatchCellNode InterfaceDispatchCell(MethodDesc method)
{
return _interfaceDispatchCells.GetOrAdd(method);
}
private class BlobTupleEqualityComparer : IEqualityComparer<Tuple<string, byte[], int>>
{
bool IEqualityComparer<Tuple<string, byte[], int>>.Equals(Tuple<string, byte[], int> x, Tuple<string, byte[], int> y)
{
return x.Item1.Equals(y.Item1);
}
int IEqualityComparer<Tuple<string, byte[], int>>.GetHashCode(Tuple<string, byte[], int> obj)
{
return obj.Item1.GetHashCode();
}
}
private NodeCache<GCPointerMap, GCStaticEETypeNode> _GCStaticEETypes;
public ISymbolNode GCStaticEEType(GCPointerMap gcMap)
{
return _GCStaticEETypes.GetOrAdd(gcMap);
}
private NodeCache<Tuple<string, byte[], int>, BlobNode> _readOnlyDataBlobs;
public BlobNode ReadOnlyDataBlob(string name, byte[] blobData, int alignment)
{
return _readOnlyDataBlobs.GetOrAdd(new Tuple<string, byte[], int>(name, blobData, alignment));
}
private NodeCache<EETypeOptionalFieldsBuilder, EETypeOptionalFieldsNode> _typeOptionalFields;
internal EETypeOptionalFieldsNode EETypeOptionalFields(EETypeOptionalFieldsBuilder fieldBuilder)
{
return _typeOptionalFields.GetOrAdd(fieldBuilder);
}
private NodeCache<TypeDesc, InterfaceDispatchMapNode> _interfaceDispatchMaps;
internal InterfaceDispatchMapNode InterfaceDispatchMap(TypeDesc type)
{
return _interfaceDispatchMaps.GetOrAdd(type);
}
private NodeCache<TypeDesc, EmbeddedObjectNode> _interfaceDispatchMapIndirectionNodes;
public EmbeddedObjectNode InterfaceDispatchMapIndirection(TypeDesc type)
{
return _interfaceDispatchMapIndirectionNodes.GetOrAdd(type);
}
private NodeCache<GenericCompositionDetails, GenericCompositionNode> _genericCompositions;
internal ISymbolNode GenericComposition(GenericCompositionDetails details)
{
return _genericCompositions.GetOrAdd(details);
}
private NodeCache<string, ExternSymbolNode> _externSymbols;
public ISymbolNode ExternSymbol(string name)
{
return _externSymbols.GetOrAdd(name);
}
private NodeCache<string, PInvokeModuleFixupNode> _pInvokeModuleFixups;
public ISymbolNode PInvokeModuleFixup(string moduleName)
{
return _pInvokeModuleFixups.GetOrAdd(moduleName);
}
private NodeCache<Tuple<string, string>, PInvokeMethodFixupNode> _pInvokeMethodFixups;
public PInvokeMethodFixupNode PInvokeMethodFixup(string moduleName, string entryPointName)
{
return _pInvokeMethodFixups.GetOrAdd(new Tuple<string, string>(moduleName, entryPointName));
}
private NodeCache<Tuple<ObjectNode, int, string>, ObjectAndOffsetSymbolNode> _internalSymbols;
public ISymbolNode ObjectAndOffset(ObjectNode obj, int offset, string name)
{
return _internalSymbols.GetOrAdd(new Tuple<ObjectNode, int, string>(obj, offset, name));
}
private NodeCache<TypeDesc, VTableSliceNode> _vTableNodes;
internal VTableSliceNode VTable(TypeDesc type)
{
return _vTableNodes.GetOrAdd(type);
}
private NodeCache<MethodDesc, IMethodNode> _methodEntrypoints;
private NodeCache<MethodDesc, IMethodNode> _unboxingStubs;
public IMethodNode MethodEntrypoint(MethodDesc method, bool unboxingStub = false)
{
if (unboxingStub)
{
return _unboxingStubs.GetOrAdd(method);
}
return _methodEntrypoints.GetOrAdd(method);
}
private static readonly string[][] s_helperEntrypointNames = new string[][] {
new string[] { "System.Runtime.CompilerServices", "ClassConstructorRunner", "CheckStaticClassConstructionReturnGCStaticBase" },
new string[] { "System.Runtime.CompilerServices", "ClassConstructorRunner", "CheckStaticClassConstructionReturnNonGCStaticBase" }
};
private ISymbolNode[] _helperEntrypointSymbols;
public ISymbolNode HelperEntrypoint(HelperEntrypoint entrypoint)
{
if (_helperEntrypointSymbols == null)
_helperEntrypointSymbols = new ISymbolNode[s_helperEntrypointNames.Length];
int index = (int)entrypoint;
ISymbolNode symbol = _helperEntrypointSymbols[index];
if (symbol == null)
{
var entry = s_helperEntrypointNames[index];
var type = _context.SystemModule.GetKnownType(entry[0], entry[1]);
var method = type.GetKnownMethod(entry[2], null);
symbol = MethodEntrypoint(method);
_helperEntrypointSymbols[index] = symbol;
}
return symbol;
}
private MetadataType _systemArrayOfTClass;
public MetadataType ArrayOfTClass
{
get
{
if (_systemArrayOfTClass == null)
{
_systemArrayOfTClass = _context.SystemModule.GetKnownType("System", "Array`1");
}
return _systemArrayOfTClass;
}
}
private TypeDesc _systemArrayOfTEnumeratorType;
public TypeDesc ArrayOfTEnumeratorType
{
get
{
if (_systemArrayOfTEnumeratorType == null)
{
_systemArrayOfTEnumeratorType = ArrayOfTClass.GetNestedType("ArrayEnumerator");
}
return _systemArrayOfTEnumeratorType;
}
}
private TypeDesc _systemICastableType;
public TypeDesc ICastableInterface
{
get
{
if (_systemICastableType == null)
{
_systemICastableType = _context.SystemModule.GetKnownType("System.Runtime.CompilerServices", "ICastable");
}
return _systemICastableType;
}
}
private NodeCache<MethodDesc, VirtualMethodUseNode> _virtMethods;
public DependencyNode VirtualMethodUse(MethodDesc decl)
{
return _virtMethods.GetOrAdd(decl);
}
private NodeCache<Tuple<ReadyToRunHelperId, Object>, ISymbolNode> _readyToRunHelpers;
public ISymbolNode ReadyToRunHelper(ReadyToRunHelperId id, Object target)
{
return _readyToRunHelpers.GetOrAdd(new Tuple<ReadyToRunHelperId, object>(id, target));
}
private NodeCache<string, StringDataNode> _stringDataNodes;
public StringDataNode StringData(string data)
{
return _stringDataNodes.GetOrAdd(data);
}
private NodeCache<string, StringIndirectionNode> _stringIndirectionNodes;
public StringIndirectionNode StringIndirection(string data)
{
return _stringIndirectionNodes.GetOrAdd(data);
}
private NodeCache<MethodDesc, EmbeddedObjectNode> _eagerCctorIndirectionNodes;
public EmbeddedObjectNode EagerCctorIndirection(MethodDesc cctorMethod)
{
return _eagerCctorIndirectionNodes.GetOrAdd(cctorMethod);
}
/// <summary>
/// Returns alternative symbol name that object writer should produce for given symbols
/// in addition to the regular one.
/// </summary>
public string GetSymbolAlternateName(ISymbolNode node)
{
string value;
if (!NodeAliases.TryGetValue(node, out value))
return null;
return value;
}
public ArrayOfEmbeddedPointersNode<GCStaticsNode> GCStaticsRegion = new ArrayOfEmbeddedPointersNode<GCStaticsNode>(
CompilationUnitPrefix + "__GCStaticRegionStart",
CompilationUnitPrefix + "__GCStaticRegionEnd",
null);
public ArrayOfEmbeddedDataNode ThreadStaticsRegion = new ArrayOfEmbeddedDataNode(
CompilationUnitPrefix + "__ThreadStaticRegionStart",
CompilationUnitPrefix + "__ThreadStaticRegionEnd",
null);
public ArrayOfEmbeddedDataNode StringTable = new ArrayOfEmbeddedDataNode(
CompilationUnitPrefix + "__StringTableStart",
CompilationUnitPrefix + "__StringTableEnd",
null);
public ArrayOfEmbeddedPointersNode<IMethodNode> EagerCctorTable = new ArrayOfEmbeddedPointersNode<IMethodNode>(
CompilationUnitPrefix + "__EagerCctorStart",
CompilationUnitPrefix + "__EagerCctorEnd",
new EagerConstructorComparer());
public ArrayOfEmbeddedPointersNode<InterfaceDispatchMapNode> DispatchMapTable = new ArrayOfEmbeddedPointersNode<InterfaceDispatchMapNode>(
CompilationUnitPrefix + "__DispatchMapTableStart",
CompilationUnitPrefix + "__DispatchMapTableEnd",
null);
public ReadyToRunHeaderNode ReadyToRunHeader;
public Dictionary<ISymbolNode, string> NodeAliases = new Dictionary<ISymbolNode, string>();
internal ModuleManagerIndirectionNode ModuleManagerIndirection = new ModuleManagerIndirectionNode();
public static NameMangler NameMangler;
public static string CompilationUnitPrefix;
public void AttachToDependencyGraph(DependencyAnalysisFramework.DependencyAnalyzerBase<NodeFactory> graph)
{
ReadyToRunHeader = new ReadyToRunHeaderNode(Target);
graph.AddRoot(ReadyToRunHeader, "ReadyToRunHeader is always generated");
graph.AddRoot(new ModulesSectionNode(Target), "ModulesSection is always generated");
graph.AddRoot(GCStaticsRegion, "GC StaticsRegion is always generated");
graph.AddRoot(ThreadStaticsRegion, "ThreadStaticsRegion is always generated");
graph.AddRoot(StringTable, "StringTable is always generated");
graph.AddRoot(EagerCctorTable, "EagerCctorTable is always generated");
graph.AddRoot(ModuleManagerIndirection, "ModuleManagerIndirection is always generated");
graph.AddRoot(DispatchMapTable, "DispatchMapTable is always generated");
ReadyToRunHeader.Add(ReadyToRunSectionType.GCStaticRegion, GCStaticsRegion, GCStaticsRegion.StartSymbol, GCStaticsRegion.EndSymbol);
ReadyToRunHeader.Add(ReadyToRunSectionType.ThreadStaticRegion, ThreadStaticsRegion, ThreadStaticsRegion.StartSymbol, ThreadStaticsRegion.EndSymbol);
ReadyToRunHeader.Add(ReadyToRunSectionType.StringTable, StringTable, StringTable.StartSymbol, StringTable.EndSymbol);
ReadyToRunHeader.Add(ReadyToRunSectionType.EagerCctor, EagerCctorTable, EagerCctorTable.StartSymbol, EagerCctorTable.EndSymbol);
ReadyToRunHeader.Add(ReadyToRunSectionType.ModuleManagerIndirection, ModuleManagerIndirection, ModuleManagerIndirection);
ReadyToRunHeader.Add(ReadyToRunSectionType.InterfaceDispatchTable, DispatchMapTable, DispatchMapTable.StartSymbol);
MetadataManager.AddToReadyToRunHeader(ReadyToRunHeader);
MetadataManager.AttachToDependencyGraph(graph);
_compilationModuleGroup.AddCompilationRoots(new RootingServiceProvider(graph, this));
}
private class RootingServiceProvider : IRootingServiceProvider
{
private DependencyAnalyzerBase<NodeFactory> _graph;
private NodeFactory _factory;
public RootingServiceProvider(DependencyAnalyzerBase<NodeFactory> graph, NodeFactory factory)
{
_graph = graph;
_factory = factory;
}
public void AddCompilationRoot(MethodDesc method, string reason, string exportName = null)
{
var methodEntryPoint = _factory.MethodEntrypoint(method);
_graph.AddRoot(methodEntryPoint, reason);
if (exportName != null)
_factory.NodeAliases.Add(methodEntryPoint, exportName);
}
public void AddCompilationRoot(TypeDesc type, string reason)
{
_graph.AddRoot(_factory.ConstructedTypeSymbol(type), reason);
}
}
}
public enum HelperEntrypoint
{
EnsureClassConstructorRunAndReturnGCStaticBase,
EnsureClassConstructorRunAndReturnNonGCStaticBase,
}
}
| |
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk)
//
// This file is part of SharpMap.
// SharpMap is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// SharpMap is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public License
// along with SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Net.Mime;
using System.Runtime.CompilerServices;
using Common.Logging;
using SharpMap.Rendering.Thematics;
namespace SharpMap.Styles
{
/// <summary>
/// Defines a style used for rendering labels
/// </summary>
[Serializable]
public class LabelStyle : Style, ICloneable
{
private static readonly ILog _logger = LogManager.GetLogger(typeof (LabelStyle));
#region HorizontalAlignmentEnum enum
/// <summary>
/// Label text alignment
/// </summary>
public enum HorizontalAlignmentEnum : short
{
/// <summary>
/// Left oriented
/// </summary>
Left = 0,
/// <summary>
/// Right oriented
/// </summary>
Right = 2,
/// <summary>
/// Centered
/// </summary>
Center = 1
}
#endregion
#region VerticalAlignmentEnum enum
/// <summary>
/// Label text alignment
/// </summary>
public enum VerticalAlignmentEnum : short
{
/// <summary>
/// Left oriented
/// </summary>
Bottom = 0,
/// <summary>
/// Right oriented
/// </summary>
Top = 2,
/// <summary>
/// Centered
/// </summary>
Middle = 1
}
#endregion
Brush _BackColor;
SizeF _CollisionBuffer;
bool _CollisionDetection;
Font _Font;
Color _ForeColor;
Pen _Halo;
HorizontalAlignmentEnum _HorizontalAlignment;
PointF _Offset;
VerticalAlignmentEnum _VerticalAlignment;
float _rotation;
bool _ignoreLength;
bool _isTextOnPath = false;
/// <summary>
/// get or set label on path
/// </summary>
public bool IsTextOnPath
{
get { return _isTextOnPath; }
set { _isTextOnPath = value; }
}
/// <summary>
/// Initializes a new LabelStyle
/// </summary>
public LabelStyle()
{
_Font = new Font(FontFamily.GenericSerif, 12f);
_Offset = new PointF(0, 0);
_CollisionDetection = false;
_CollisionBuffer = new Size(0, 0);
_ForeColor = Color.Black;
_HorizontalAlignment = HorizontalAlignmentEnum.Center;
_VerticalAlignment = VerticalAlignmentEnum.Middle;
}
/// <summary>
/// Releases managed resources
/// </summary>
protected override void ReleaseManagedResources()
{
if (IsDisposed)
return;
if (_Font != null) _Font.Dispose();
if (_Halo != null) _Halo.Dispose();
if (_BackColor != null) _BackColor.Dispose();
base.ReleaseManagedResources();
}
/// <summary>
/// Method to create a deep copy of this <see cref="LabelStyle"/>
/// </summary>
/// <returns>A LabelStyle resembling this instance.</returns>
public LabelStyle Clone()
{
var res = (LabelStyle) MemberwiseClone();
lock (this)
{
if (_Font != null)
res.Font = (Font)_Font.Clone();
if (_Halo != null)
res._Halo = (Pen)_Halo.Clone();
if (_BackColor != null)
res._BackColor = (Brush) _BackColor.Clone();
}
return res;
}
object ICloneable.Clone()
{
return Clone();
}
/// <summary>
/// Function to get a <see cref="StringFormat"/> with <see cref="StringFormat.Alignment"/> and <see cref="StringFormat.LineAlignment"/> properties according to
/// <see cref="HorizontalAlignment"/> and <see cref="VerticalAlignment"/>
/// </summary>
/// <returns>A <see cref="StringFormat"/></returns>
internal StringFormat GetStringFormat()
{
var r = (StringFormat)StringFormat.GenericTypographic.Clone();
switch (HorizontalAlignment)
{
case HorizontalAlignmentEnum.Center:
r.Alignment = StringAlignment.Center;
break;
case HorizontalAlignmentEnum.Left:
r.Alignment = StringAlignment.Near;
break;
case HorizontalAlignmentEnum.Right:
r.Alignment = StringAlignment.Far;
break;
}
switch (VerticalAlignment)
{
case VerticalAlignmentEnum.Middle:
r.LineAlignment = StringAlignment.Center;
break;
case VerticalAlignmentEnum.Top:
r.LineAlignment = StringAlignment.Near;
break;
case VerticalAlignmentEnum.Bottom:
r.LineAlignment = StringAlignment.Far;
break;
}
return r;
}
/// <summary>
/// Label Font
/// </summary>
public Font Font
{
get
{
return _Font;
}
set
{
if (value.Unit != GraphicsUnit.Point)
_logger.Error( fmh => fmh("Only assign fonts with size in Points"));
_Font = value;
// we can't dispose the previous font
// because it could still be used by
// the rendering engine, so we just let it be GC'ed.
_cachedFontForGraphics = null;
}
}
[NonSerialized]
private float _cachedDpiY = 0f;
[NonSerialized]
private Font _cachedFontForGraphics = null;
/// <summary>
/// Method to create a font that ca
/// </summary>
/// <param name="g"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public Font GetFontForGraphics(Graphics g)
{
if (_cachedFontForGraphics == null || g.DpiY != _cachedDpiY)
{
_cachedDpiY = g.DpiY;
if (_cachedFontForGraphics != null) _cachedFontForGraphics.Dispose();
_cachedFontForGraphics = new Font(_Font.FontFamily, _Font.GetHeight(g), _Font.Style, GraphicsUnit.Pixel);
/*
var textHeight = _Font.Size;
switch (_Font.Unit)
{
case GraphicsUnit.Display:
textHeight *= g.DpiY / 75;
break;
case GraphicsUnit.Document:
textHeight *= g.DpiY / 300;
break;
case GraphicsUnit.Inch:
textHeight *= g.DpiY;
break;
case GraphicsUnit.Millimeter:
textHeight /= 25.4f * g.DpiY;
break;
case GraphicsUnit.Pixel:
//do nothing
break;
case GraphicsUnit.Point:
textHeight *= g.DpiY / 72;
break;
}
_cachedFontForGraphics = new Font(_Font.FontFamily, textHeight, _Font.Style, GraphicsUnit.Pixel);
*/
}
return _cachedFontForGraphics;
}
/// <summary>
/// Font color
/// </summary>
public Color ForeColor
{
get { return _ForeColor; }
set { _ForeColor = value; }
}
/// <summary>
/// The background color of the label. Set to transparent brush or null if background isn't needed
/// </summary>
public Brush BackColor
{
get { return _BackColor; }
set { _BackColor = value; }
}
/// <summary>
/// Creates a halo around the text
/// </summary>
[System.ComponentModel.Category("Uneditable")]
[System.ComponentModel.Editor()]
public Pen Halo
{
get { return _Halo; }
set
{
_Halo = value;
//if (_Halo != null)
// _Halo.LineJoin = LineJoin.Round;
}
}
/// <summary>
/// Specifies relative position of labels with respect to objects label point
/// </summary>
[System.ComponentModel.Category("Uneditable")]
public PointF Offset
{
get { return _Offset; }
set { _Offset = value; }
}
/// <summary>
/// Gets or sets whether Collision Detection is enabled for the labels.
/// If set to true, label collision will be tested.
/// </summary>
/// <remarks>Just setting this property in a <see cref="ITheme.GetStyle"/> method does not lead to the desired result. You must set it to for the whole layer using the default Style.</remarks>
[System.ComponentModel.Category("Collision Detection")]
public bool CollisionDetection
{
get { return _CollisionDetection; }
set { _CollisionDetection = value; }
}
/// <summary>
/// Distance around label where collision buffer is active
/// </summary>
[System.ComponentModel.Category("Collision Detection")]
public SizeF CollisionBuffer
{
get { return _CollisionBuffer; }
set { _CollisionBuffer = value; }
}
/// <summary>
/// The horizontal alignment of the text in relation to the labelpoint
/// </summary>
[System.ComponentModel.Category("Alignment")]
public HorizontalAlignmentEnum HorizontalAlignment
{
get { return _HorizontalAlignment; }
set { _HorizontalAlignment = value; }
}
/// <summary>
/// The horizontal alignment of the text in relation to the labelpoint
/// </summary>
[System.ComponentModel.Category("Alignment")]
public VerticalAlignmentEnum VerticalAlignment
{
get { return _VerticalAlignment; }
set { _VerticalAlignment = value; }
}
/// <summary>
/// The Rotation of the text
/// </summary>
[System.ComponentModel.Category("Alignment")]
public float Rotation
{
get { return _rotation; }
set { _rotation = value % 360f; }
}
/// <summary>
/// Gets or sets if length of linestring should be ignored
/// </summary>
[System.ComponentModel.Category("Alignment")]
public bool IgnoreLength
{
get { return _ignoreLength; }
set { _ignoreLength = value; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class LambdaModuloNullableTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableDecimalTest(bool useInterpreter)
{
decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableDecimal(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableDoubleTest(bool useInterpreter)
{
double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableDouble(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableFloatTest(bool useInterpreter)
{
float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableFloat(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableIntTest(bool useInterpreter)
{
int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableInt(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableLongTest(bool useInterpreter)
{
long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableLong(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableShortTest(bool useInterpreter)
{
short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableShort(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableUIntTest(bool useInterpreter)
{
uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableUInt(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableULongTest(bool useInterpreter)
{
ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableULong(values[i], values[j], useInterpreter);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513
[ClassData(typeof(CompilationTypes))]
public static void LambdaModuloNullableUShortTest(bool useInterpreter)
{
ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyModuloNullableUShort(values[i], values[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private enum ResultType
{
Success,
DivideByZero,
Overflow
}
#region Verify decimal?
private static void VerifyModuloNullableDecimal(decimal? a, decimal? b, bool useInterpreter)
{
bool divideByZero;
decimal? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(decimal?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(decimal?), "p1");
// verify with parameters supplied
Expression<Func<decimal?>> e1 =
Expression.Lambda<Func<decimal?>>(
Expression.Invoke(
Expression.Lambda<Func<decimal?, decimal?, decimal?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?))
}),
Enumerable.Empty<ParameterExpression>());
Func<decimal?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<decimal?, decimal?, Func<decimal?>>> e2 =
Expression.Lambda<Func<decimal?, decimal?, Func<decimal?>>>(
Expression.Lambda<Func<decimal?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<decimal?, decimal?, Func<decimal?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<decimal?, decimal?, decimal?>>> e3 =
Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?, decimal?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<decimal?, decimal?, decimal?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<decimal?, decimal?, decimal?>>> e4 =
Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?, decimal?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<decimal?, decimal?, decimal?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<decimal?, Func<decimal?, decimal?>>> e5 =
Expression.Lambda<Func<decimal?, Func<decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<decimal?, Func<decimal?, decimal?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<decimal?, decimal?>>> e6 =
Expression.Lambda<Func<Func<decimal?, decimal?>>>(
Expression.Invoke(
Expression.Lambda<Func<decimal?, Func<decimal?, decimal?>>>(
Expression.Lambda<Func<decimal?, decimal?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(decimal?)) }),
Enumerable.Empty<ParameterExpression>());
Func<decimal?, decimal?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify double?
private static void VerifyModuloNullableDouble(double? a, double? b, bool useInterpreter)
{
double? expected = a % b;
ParameterExpression p0 = Expression.Parameter(typeof(double?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(double?), "p1");
// verify with parameters supplied
Expression<Func<double?>> e1 =
Expression.Lambda<Func<double?>>(
Expression.Invoke(
Expression.Lambda<Func<double?, double?, double?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?))
}),
Enumerable.Empty<ParameterExpression>());
Func<double?> f1 = e1.Compile(useInterpreter);
Assert.Equal(expected, f1());
// verify with values passed to make parameters
Expression<Func<double?, double?, Func<double?>>> e2 =
Expression.Lambda<Func<double?, double?, Func<double?>>>(
Expression.Lambda<Func<double?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<double?, double?, Func<double?>> f2 = e2.Compile(useInterpreter);
Assert.Equal(expected, f2(a, b)());
// verify with values directly passed
Expression<Func<Func<double?, double?, double?>>> e3 =
Expression.Lambda<Func<Func<double?, double?, double?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<double?, double?, double?>>>(
Expression.Lambda<Func<double?, double?, double?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<double?, double?, double?> f3 = e3.Compile(useInterpreter)();
Assert.Equal(expected, f3(a, b));
// verify as a function generator
Expression<Func<Func<double?, double?, double?>>> e4 =
Expression.Lambda<Func<Func<double?, double?, double?>>>(
Expression.Lambda<Func<double?, double?, double?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<double?, double?, double?>> f4 = e4.Compile(useInterpreter);
Assert.Equal(expected, f4()(a, b));
// verify with currying
Expression<Func<double?, Func<double?, double?>>> e5 =
Expression.Lambda<Func<double?, Func<double?, double?>>>(
Expression.Lambda<Func<double?, double?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<double?, Func<double?, double?>> f5 = e5.Compile(useInterpreter);
Assert.Equal(expected, f5(a)(b));
// verify with one parameter
Expression<Func<Func<double?, double?>>> e6 =
Expression.Lambda<Func<Func<double?, double?>>>(
Expression.Invoke(
Expression.Lambda<Func<double?, Func<double?, double?>>>(
Expression.Lambda<Func<double?, double?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(double?)) }),
Enumerable.Empty<ParameterExpression>());
Func<double?, double?> f6 = e6.Compile(useInterpreter)();
Assert.Equal(expected, f6(b));
}
#endregion
#region Verify float?
private static void VerifyModuloNullableFloat(float? a, float? b, bool useInterpreter)
{
float? expected = a % b;
ParameterExpression p0 = Expression.Parameter(typeof(float?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(float?), "p1");
// verify with parameters supplied
Expression<Func<float?>> e1 =
Expression.Lambda<Func<float?>>(
Expression.Invoke(
Expression.Lambda<Func<float?, float?, float?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?))
}),
Enumerable.Empty<ParameterExpression>());
Func<float?> f1 = e1.Compile(useInterpreter);
Assert.Equal(expected, f1());
// verify with values passed to make parameters
Expression<Func<float?, float?, Func<float?>>> e2 =
Expression.Lambda<Func<float?, float?, Func<float?>>>(
Expression.Lambda<Func<float?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<float?, float?, Func<float?>> f2 = e2.Compile(useInterpreter);
Assert.Equal(expected, f2(a, b)());
// verify with values directly passed
Expression<Func<Func<float?, float?, float?>>> e3 =
Expression.Lambda<Func<Func<float?, float?, float?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<float?, float?, float?>>>(
Expression.Lambda<Func<float?, float?, float?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<float?, float?, float?> f3 = e3.Compile(useInterpreter)();
Assert.Equal(expected, f3(a, b));
// verify as a function generator
Expression<Func<Func<float?, float?, float?>>> e4 =
Expression.Lambda<Func<Func<float?, float?, float?>>>(
Expression.Lambda<Func<float?, float?, float?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<float?, float?, float?>> f4 = e4.Compile(useInterpreter);
Assert.Equal(expected, f4()(a, b));
// verify with currying
Expression<Func<float?, Func<float?, float?>>> e5 =
Expression.Lambda<Func<float?, Func<float?, float?>>>(
Expression.Lambda<Func<float?, float?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<float?, Func<float?, float?>> f5 = e5.Compile(useInterpreter);
Assert.Equal(expected, f5(a)(b));
// verify with one parameter
Expression<Func<Func<float?, float?>>> e6 =
Expression.Lambda<Func<Func<float?, float?>>>(
Expression.Invoke(
Expression.Lambda<Func<float?, Func<float?, float?>>>(
Expression.Lambda<Func<float?, float?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(float?)) }),
Enumerable.Empty<ParameterExpression>());
Func<float?, float?> f6 = e6.Compile(useInterpreter)();
Assert.Equal(expected, f6(b));
}
#endregion
#region Verify int?
private static void VerifyModuloNullableInt(int? a, int? b, bool useInterpreter)
{
ResultType outcome;
int? expected = null;
if (a.HasValue && b == 0)
{
outcome = ResultType.DivideByZero;
}
else if (a == int.MinValue && b == -1)
{
outcome = ResultType.Overflow;
}
else
{
expected = a % b;
outcome = ResultType.Success;
}
ParameterExpression p0 = Expression.Parameter(typeof(int?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(int?), "p1");
// verify with parameters supplied
Expression<Func<int?>> e1 =
Expression.Lambda<Func<int?>>(
Expression.Invoke(
Expression.Lambda<Func<int?, int?, int?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?))
}),
Enumerable.Empty<ParameterExpression>());
Func<int?> f1 = e1.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f1());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f1());
break;
default:
Assert.Equal(expected, f1());
break;
}
// verify with values passed to make parameters
Expression<Func<int?, int?, Func<int?>>> e2 =
Expression.Lambda<Func<int?, int?, Func<int?>>>(
Expression.Lambda<Func<int?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<int?, int?, Func<int?>> f2 = e2.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f2(a, b)());
break;
default:
Assert.Equal(expected, f2(a, b)());
break;
}
// verify with values directly passed
Expression<Func<Func<int?, int?, int?>>> e3 =
Expression.Lambda<Func<Func<int?, int?, int?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<int?, int?, int?>>>(
Expression.Lambda<Func<int?, int?, int?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<int?, int?, int?> f3 = e3.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f3(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f3(a, b));
break;
default:
Assert.Equal(expected, f3(a, b));
break;
}
// verify as a function generator
Expression<Func<Func<int?, int?, int?>>> e4 =
Expression.Lambda<Func<Func<int?, int?, int?>>>(
Expression.Lambda<Func<int?, int?, int?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<int?, int?, int?>> f4 = e4.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f4()(a, b));
break;
default:
Assert.Equal(expected, f4()(a, b));
break;
}
// verify with currying
Expression<Func<int?, Func<int?, int?>>> e5 =
Expression.Lambda<Func<int?, Func<int?, int?>>>(
Expression.Lambda<Func<int?, int?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<int?, Func<int?, int?>> f5 = e5.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f5(a)(b));
break;
default:
Assert.Equal(expected, f5(a)(b));
break;
}
// verify with one parameter
Expression<Func<Func<int?, int?>>> e6 =
Expression.Lambda<Func<Func<int?, int?>>>(
Expression.Invoke(
Expression.Lambda<Func<int?, Func<int?, int?>>>(
Expression.Lambda<Func<int?, int?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(int?)) }),
Enumerable.Empty<ParameterExpression>());
Func<int?, int?> f6 = e6.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f6(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f6(b));
break;
default:
Assert.Equal(expected, f6(b));
break;
}
}
#endregion
#region Verify long?
private static void VerifyModuloNullableLong(long? a, long? b, bool useInterpreter)
{
ResultType outcome;
long? expected = null;
if (a.HasValue && b == 0)
{
outcome = ResultType.DivideByZero;
}
else if (a == long.MinValue && b == -1)
{
outcome = ResultType.Overflow;
}
else
{
expected = a % b;
outcome = ResultType.Success;
}
ParameterExpression p0 = Expression.Parameter(typeof(long?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(long?), "p1");
// verify with parameters supplied
Expression<Func<long?>> e1 =
Expression.Lambda<Func<long?>>(
Expression.Invoke(
Expression.Lambda<Func<long?, long?, long?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?))
}),
Enumerable.Empty<ParameterExpression>());
Func<long?> f1 = e1.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f1());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f1());
break;
default:
Assert.Equal(expected, f1());
break;
}
// verify with values passed to make parameters
Expression<Func<long?, long?, Func<long?>>> e2 =
Expression.Lambda<Func<long?, long?, Func<long?>>>(
Expression.Lambda<Func<long?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<long?, long?, Func<long?>> f2 = e2.Compile(useInterpreter);
long? f2Result = default(long?);
Exception f2Ex = null;
try
{
f2Result = f2(a, b)();
}
catch (Exception ex)
{
f2Ex = ex;
}
// verify with values directly passed
Expression<Func<Func<long?, long?, long?>>> e3 =
Expression.Lambda<Func<Func<long?, long?, long?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<long?, long?, long?>>>(
Expression.Lambda<Func<long?, long?, long?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<long?, long?, long?> f3 = e3.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f2(a, b)());
break;
default:
Assert.Equal(expected, f2(a, b)());
break;
}
// verify as a function generator
Expression<Func<Func<long?, long?, long?>>> e4 =
Expression.Lambda<Func<Func<long?, long?, long?>>>(
Expression.Lambda<Func<long?, long?, long?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<long?, long?, long?>> f4 = e4.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f3(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f3(a, b));
break;
default:
Assert.Equal(expected, f3(a, b));
break;
}
// verify with currying
Expression<Func<long?, Func<long?, long?>>> e5 =
Expression.Lambda<Func<long?, Func<long?, long?>>>(
Expression.Lambda<Func<long?, long?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<long?, Func<long?, long?>> f5 = e5.Compile(useInterpreter);
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f4()(a, b));
break;
default:
Assert.Equal(expected, f4()(a, b));
break;
}
// verify with one parameter
Expression<Func<Func<long?, long?>>> e6 =
Expression.Lambda<Func<Func<long?, long?>>>(
Expression.Invoke(
Expression.Lambda<Func<long?, Func<long?, long?>>>(
Expression.Lambda<Func<long?, long?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(long?)) }),
Enumerable.Empty<ParameterExpression>());
Func<long?, long?> f6 = e6.Compile(useInterpreter)();
switch (outcome)
{
case ResultType.DivideByZero:
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
break;
case ResultType.Overflow:
Assert.Throws<OverflowException>(() => f5(a)(b));
break;
default:
Assert.Equal(expected, f5(a)(b));
break;
}
}
#endregion
#region Verify short?
private static void VerifyModuloNullableShort(short? a, short? b, bool useInterpreter)
{
bool divideByZero;
short? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = (short?)(a % b);
}
ParameterExpression p0 = Expression.Parameter(typeof(short?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(short?), "p1");
// verify with parameters supplied
Expression<Func<short?>> e1 =
Expression.Lambda<Func<short?>>(
Expression.Invoke(
Expression.Lambda<Func<short?, short?, short?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?))
}),
Enumerable.Empty<ParameterExpression>());
Func<short?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<short?, short?, Func<short?>>> e2 =
Expression.Lambda<Func<short?, short?, Func<short?>>>(
Expression.Lambda<Func<short?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<short?, short?, Func<short?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<short?, short?, short?>>> e3 =
Expression.Lambda<Func<Func<short?, short?, short?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<short?, short?, short?>>>(
Expression.Lambda<Func<short?, short?, short?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<short?, short?, short?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<short?, short?, short?>>> e4 =
Expression.Lambda<Func<Func<short?, short?, short?>>>(
Expression.Lambda<Func<short?, short?, short?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<short?, short?, short?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<short?, Func<short?, short?>>> e5 =
Expression.Lambda<Func<short?, Func<short?, short?>>>(
Expression.Lambda<Func<short?, short?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<short?, Func<short?, short?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<short?, short?>>> e6 =
Expression.Lambda<Func<Func<short?, short?>>>(
Expression.Invoke(
Expression.Lambda<Func<short?, Func<short?, short?>>>(
Expression.Lambda<Func<short?, short?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(short?)) }),
Enumerable.Empty<ParameterExpression>());
Func<short?, short?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify uint?
private static void VerifyModuloNullableUInt(uint? a, uint? b, bool useInterpreter)
{
bool divideByZero;
uint? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(uint?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(uint?), "p1");
// verify with parameters supplied
Expression<Func<uint?>> e1 =
Expression.Lambda<Func<uint?>>(
Expression.Invoke(
Expression.Lambda<Func<uint?, uint?, uint?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?))
}),
Enumerable.Empty<ParameterExpression>());
Func<uint?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<uint?, uint?, Func<uint?>>> e2 =
Expression.Lambda<Func<uint?, uint?, Func<uint?>>>(
Expression.Lambda<Func<uint?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<uint?, uint?, Func<uint?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<uint?, uint?, uint?>>> e3 =
Expression.Lambda<Func<Func<uint?, uint?, uint?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<uint?, uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?, uint?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<uint?, uint?, uint?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<uint?, uint?, uint?>>> e4 =
Expression.Lambda<Func<Func<uint?, uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?, uint?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<uint?, uint?, uint?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<uint?, Func<uint?, uint?>>> e5 =
Expression.Lambda<Func<uint?, Func<uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<uint?, Func<uint?, uint?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<uint?, uint?>>> e6 =
Expression.Lambda<Func<Func<uint?, uint?>>>(
Expression.Invoke(
Expression.Lambda<Func<uint?, Func<uint?, uint?>>>(
Expression.Lambda<Func<uint?, uint?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(uint?)) }),
Enumerable.Empty<ParameterExpression>());
Func<uint?, uint?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify ulong?
private static void VerifyModuloNullableULong(ulong? a, ulong? b, bool useInterpreter)
{
bool divideByZero;
ulong? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = a % b;
}
ParameterExpression p0 = Expression.Parameter(typeof(ulong?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ulong?), "p1");
// verify with parameters supplied
Expression<Func<ulong?>> e1 =
Expression.Lambda<Func<ulong?>>(
Expression.Invoke(
Expression.Lambda<Func<ulong?, ulong?, ulong?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?))
}),
Enumerable.Empty<ParameterExpression>());
Func<ulong?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<ulong?, ulong?, Func<ulong?>>> e2 =
Expression.Lambda<Func<ulong?, ulong?, Func<ulong?>>>(
Expression.Lambda<Func<ulong?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ulong?, ulong?, Func<ulong?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<ulong?, ulong?, ulong?>>> e3 =
Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?, ulong?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ulong?, ulong?, ulong?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<ulong?, ulong?, ulong?>>> e4 =
Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?, ulong?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ulong?, ulong?, ulong?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<ulong?, Func<ulong?, ulong?>>> e5 =
Expression.Lambda<Func<ulong?, Func<ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ulong?, Func<ulong?, ulong?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<ulong?, ulong?>>> e6 =
Expression.Lambda<Func<Func<ulong?, ulong?>>>(
Expression.Invoke(
Expression.Lambda<Func<ulong?, Func<ulong?, ulong?>>>(
Expression.Lambda<Func<ulong?, ulong?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ulong?)) }),
Enumerable.Empty<ParameterExpression>());
Func<ulong?, ulong?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#region Verify ushort?
private static void VerifyModuloNullableUShort(ushort? a, ushort? b, bool useInterpreter)
{
bool divideByZero;
ushort? expected;
if (a.HasValue && b == 0)
{
divideByZero = true;
expected = null;
}
else
{
divideByZero = false;
expected = (ushort?)(a % b);
}
ParameterExpression p0 = Expression.Parameter(typeof(ushort?), "p0");
ParameterExpression p1 = Expression.Parameter(typeof(ushort?), "p1");
// verify with parameters supplied
Expression<Func<ushort?>> e1 =
Expression.Lambda<Func<ushort?>>(
Expression.Invoke(
Expression.Lambda<Func<ushort?, ushort?, ushort?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
new Expression[]
{
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?))
}),
Enumerable.Empty<ParameterExpression>());
Func<ushort?> f1 = e1.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f1());
}
else
{
Assert.Equal(expected, f1());
}
// verify with values passed to make parameters
Expression<Func<ushort?, ushort?, Func<ushort?>>> e2 =
Expression.Lambda<Func<ushort?, ushort?, Func<ushort?>>>(
Expression.Lambda<Func<ushort?>>(
Expression.Modulo(p0, p1),
Enumerable.Empty<ParameterExpression>()),
new ParameterExpression[] { p0, p1 });
Func<ushort?, ushort?, Func<ushort?>> f2 = e2.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f2(a, b)());
}
else
{
Assert.Equal(expected, f2(a, b)());
}
// verify with values directly passed
Expression<Func<Func<ushort?, ushort?, ushort?>>> e3 =
Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>(
Expression.Invoke(
Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?, ushort?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>()),
Enumerable.Empty<Expression>()),
Enumerable.Empty<ParameterExpression>());
Func<ushort?, ushort?, ushort?> f3 = e3.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f3(a, b));
}
else
{
Assert.Equal(expected, f3(a, b));
}
// verify as a function generator
Expression<Func<Func<ushort?, ushort?, ushort?>>> e4 =
Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?, ushort?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p0, p1 }),
Enumerable.Empty<ParameterExpression>());
Func<Func<ushort?, ushort?, ushort?>> f4 = e4.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f4()(a, b));
}
else
{
Assert.Equal(expected, f4()(a, b));
}
// verify with currying
Expression<Func<ushort?, Func<ushort?, ushort?>>> e5 =
Expression.Lambda<Func<ushort?, Func<ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 });
Func<ushort?, Func<ushort?, ushort?>> f5 = e5.Compile(useInterpreter);
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f5(a)(b));
}
else
{
Assert.Equal(expected, f5(a)(b));
}
// verify with one parameter
Expression<Func<Func<ushort?, ushort?>>> e6 =
Expression.Lambda<Func<Func<ushort?, ushort?>>>(
Expression.Invoke(
Expression.Lambda<Func<ushort?, Func<ushort?, ushort?>>>(
Expression.Lambda<Func<ushort?, ushort?>>(
Expression.Modulo(p0, p1),
new ParameterExpression[] { p1 }),
new ParameterExpression[] { p0 }),
new Expression[] { Expression.Constant(a, typeof(ushort?)) }),
Enumerable.Empty<ParameterExpression>());
Func<ushort?, ushort?> f6 = e6.Compile(useInterpreter)();
if (divideByZero)
{
Assert.Throws<DivideByZeroException>(() => f6(b));
}
else
{
Assert.Equal(expected, f6(b));
}
}
#endregion
#endregion
}
}
| |
//
// LunarConsole.cs
//
// Lunar Unity Mobile Console
// https://github.com/SpaceMadness/lunar-unity-console
//
// Copyright 2017 Alex Lementuev, SpaceMadness.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#define LUNAR_CONSOLE_ENABLED
#define LUNAR_CONSOLE_FREE
#if UNITY_IOS || UNITY_IPHONE || UNITY_ANDROID || UNITY_EDITOR
#define LUNAR_CONSOLE_PLATFORM_SUPPORTED
#endif
#if LUNAR_CONSOLE_ENABLED && !LUNAR_CONSOLE_ANALYTICS_DISABLED
#define LUNAR_CONSOLE_ANALYTICS_ENABLED
#endif
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using System.Runtime.CompilerServices;
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Text;
using System.IO;
using LunarConsolePlugin;
using LunarConsolePluginInternal;
#if UNITY_EDITOR
[assembly: InternalsVisibleTo("Test")]
#endif
namespace LunarConsolePlugin
{
public enum Gesture
{
None,
SwipeDown
}
delegate void LunarConsoleNativeMessageCallback(string message);
delegate void LunarConsoleNativeMessageHandler(IDictionary<string, string> data);
[Serializable]
public class LunarConsoleSettings
{
public bool exceptionWarning = true;
#if LUNAR_CONSOLE_FREE
[HideInInspector]
#endif
public bool transparentLogOverlay = false;
#if LUNAR_CONSOLE_FREE
[HideInInspector]
#endif
public bool sortActions = true;
#if LUNAR_CONSOLE_FREE
[HideInInspector]
#endif
public bool sortVariables = true;
[SerializeField]
public string[] emails;
}
public sealed class LunarConsole : MonoBehaviour
{
#pragma warning disable 0649
#pragma warning disable 0414
[SerializeField]
LunarConsoleSettings m_settings = new LunarConsoleSettings();
[Range(128, 65536)]
[Tooltip("Logs will be trimmed to the capacity")]
[SerializeField]
int m_capacity = 4096;
[Range(128, 65536)]
[Tooltip("How many logs will be trimmed when console overflows")]
[SerializeField]
int m_trim = 512;
[Tooltip("Gesture type to open the console")]
[SerializeField]
Gesture m_gesture = Gesture.SwipeDown;
[Tooltip("If checked - removes <color>, <b> and <i> rich text tags from the output (may cause performance overhead)")]
[SerializeField]
bool m_removeRichTextTags;
static LunarConsole s_instance;
CRegistry m_registry;
bool m_variablesDirty;
#pragma warning restore 0649
#pragma warning restore 0414
#if LUNAR_CONSOLE_ENABLED
IPlatform m_platform;
IDictionary<string, LunarConsoleNativeMessageHandler> m_nativeHandlerLookup;
#region Life cycle
void Awake()
{
InitInstance();
}
void OnEnable()
{
EnablePlatform();
}
void OnDisable()
{
DisablePlatform();
}
void Update()
{
if (m_platform != null)
{
m_platform.Update();
}
if (m_variablesDirty)
{
m_variablesDirty = false;
SaveVariables();
}
}
void OnDestroy()
{
DestroyInstance();
}
#endregion
#region Plugin Lifecycle
void InitInstance()
{
if (s_instance == null)
{
if (IsPlatformSupported())
{
s_instance = this;
DontDestroyOnLoad(gameObject);
Log.dev("Instance created...");
}
else
{
Destroy(gameObject);
Log.dev("Platform not supported. Destroying object...");
}
}
else if (s_instance != this)
{
Destroy(gameObject);
Log.dev("Another instance exists. Destroying object...");
}
}
void EnablePlatform()
{
if (s_instance != null)
{
bool succeed = InitPlatform(m_capacity, m_trim, m_settings);
Log.dev("Platform initialized successfully: {0}", succeed.ToString());
}
}
void DisablePlatform()
{
if (s_instance != null)
{
bool succeed = DestroyPlatform();
Log.dev("Platform destroyed successfully: {0}", succeed.ToString());
}
}
static bool IsPlatformSupported()
{
#if UNITY_EDITOR
return true;
#elif UNITY_IOS || UNITY_IPHONE
return Application.platform == RuntimePlatform.IPhonePlayer;
#elif UNITY_ANDROID
return Application.platform == RuntimePlatform.Android;
#else
return false;
#endif
}
#endregion
#region Platforms
bool InitPlatform(int capacity, int trim, LunarConsoleSettings settings)
{
try
{
if (m_platform == null)
{
trim = Math.Min(trim, capacity); // can't trim more that we have
m_platform = CreatePlatform(capacity, trim, settings);
if (m_platform != null)
{
m_registry = new CRegistry();
m_registry.registryDelegate = m_platform;
Application.logMessageReceivedThreaded += OnLogMessageReceived;
ResolveVariables();
LoadVariables();
return true;
}
}
}
catch (Exception e)
{
Log.e(e, "Can't init platform");
}
return false;
}
bool DestroyPlatform()
{
if (m_platform != null)
{
Application.logMessageReceivedThreaded -= OnLogMessageReceived;
if (m_registry != null)
{
m_registry.Destroy();
m_registry = null;
}
m_platform.Destroy();
m_platform = null;
return true;
}
return false;
}
IPlatform CreatePlatform(int capacity, int trim, LunarConsoleSettings settings)
{
#if UNITY_IOS || UNITY_IPHONE
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
LunarConsoleNativeMessageCallback callback = NativeMessageCallback;
return new PlatformIOS(gameObject.name, callback.Method.Name, Constants.Version, capacity, trim, GetGestureName(m_gesture), settings);
}
#elif UNITY_ANDROID
if (Application.platform == RuntimePlatform.Android)
{
LunarConsoleNativeMessageCallback callback = NativeMessageCallback;
return new PlatformAndroid(gameObject.name, callback.Method.Name, Constants.Version, capacity, trim, GetGestureName(m_gesture), settings);
}
#endif
#if UNITY_EDITOR
return new PlatformEditor();
#else
return null;
#endif
}
void DestroyInstance()
{
if (s_instance == this)
{
DestroyPlatform();
s_instance = null;
}
}
static string GetGestureName(Gesture gesture)
{
return gesture.ToString();
}
interface IPlatform : ICRegistryDelegate
{
void Update();
void OnLogMessageReceived(string message, string stackTrace, LogType type);
bool ShowConsole();
bool HideConsole();
void ClearConsole();
void Destroy();
}
#region CVar resolver
private void ResolveVariables()
{
try
{
var assembly = GetType().Assembly;
var containerTypes = ReflectionUtils.FindAttributeTypes<CVarContainerAttribute>(assembly);
foreach (var type in containerTypes)
{
RegisterVariables(type);
}
}
catch (Exception e)
{
Debug.LogError("Unable to resolve variables: " + e.Message);
}
}
private void RegisterVariables(Type type)
{
try
{
var fields = type.GetFields(BindingFlags.Static|BindingFlags.Public|BindingFlags.NonPublic);
if (fields != null && fields.Length > 0)
{
foreach (var field in fields)
{
if (!field.FieldType.IsAssignableFrom(typeof(CVar)))
{
continue;
}
var cvar = field.GetValue(null) as CVar;
if (cvar == null)
{
Log.w("Unable to register variable {0}.{0}", type.Name, field.Name);
continue;
}
var variableRange = ResolveVariableRange(field);
if (variableRange.IsValid)
{
if (cvar.Type == CVarType.Float)
{
cvar.Range = variableRange;
}
else
{
Log.w("'{0}' attribute is only available with 'float' variables", typeof(CVarRangeAttribute).Name);
}
}
m_registry.Register(cvar);
}
}
}
catch (Exception e)
{
Log.e(e, "Unable to initialize cvar container: {0}", type);
}
}
static CVarValueRange ResolveVariableRange(FieldInfo field)
{
try
{
var attributes = field.GetCustomAttributes(typeof(CVarRangeAttribute), true);
if (attributes != null && attributes.Length > 0)
{
var rangeAttribute = attributes[0] as CVarRangeAttribute;
if (rangeAttribute != null)
{
var min = rangeAttribute.min;
var max = rangeAttribute.max;
if (max - min < 0.00001f)
{
Log.w("Invalid range [{0}, {1}] for variable '{2}'", min.ToString(), max.ToString(), field.Name);
return CVarValueRange.Undefined;
}
return new CVarValueRange(min, max);
}
}
}
catch (Exception e)
{
Log.e(e, "Exception while resolving variable's range: {0}", field.Name);
}
return CVarValueRange.Undefined;
}
void LoadVariables()
{
try
{
var configPath = Path.Combine(Application.persistentDataPath, "lunar-mobile-console-variables.bin");
if (File.Exists(configPath))
{
Log.dev("Loading variables from file {0}", configPath);
using (var stream = File.OpenRead(configPath))
{
using (var reader = new BinaryReader(stream))
{
int count = reader.ReadInt32();
for (int i = 0; i < count; ++i)
{
var name = reader.ReadString();
var value = reader.ReadString();
var cvar = m_registry.FindVariable(name);
if (cvar == null)
{
Log.w("Ignoring variable '%s'", name);
continue;
}
cvar.Value = value;
m_platform.OnVariableRegistered(m_registry, cvar);
}
}
}
}
else
{
Log.dev("Missing variables file {0}", configPath);
}
}
catch (Exception e)
{
Log.e(e, "Error while loading variables");
}
}
void SaveVariables()
{
try
{
var configPath = Path.Combine(Application.persistentDataPath, "lunar-mobile-console-variables.bin");
Log.dev("Saving variables to file {0}", configPath);
using (var stream = File.OpenWrite(configPath))
{
using (var writer = new BinaryWriter(stream))
{
var cvars = m_registry.cvars;
int count = 0;
foreach (var cvar in cvars)
{
if (ShouldSaveVar(cvar))
{
++count;
}
}
writer.Write(count);
foreach (var cvar in cvars)
{
if (ShouldSaveVar(cvar))
{
writer.Write(cvar.Name);
writer.Write(cvar.Value);
}
}
}
}
}
catch (Exception e)
{
Log.e(e, "Error while saving variables");
}
}
bool ShouldSaveVar(CVar cvar)
{
return !cvar.IsDefault && !cvar.HasFlag(CFlags.NoArchive);
}
#endregion
#region Messages
void OnLogMessageReceived(string message, string stackTrace, LogType type)
{
message = m_removeRichTextTags ? StringUtils.RemoveRichTextTags(message) : message;
m_platform.OnLogMessageReceived(message, stackTrace, type);
}
#endregion
#if UNITY_IOS || UNITY_IPHONE
class PlatformIOS : IPlatform
{
[DllImport("__Internal")]
private static extern void __lunar_console_initialize(string targetName, string methodName, string version, int capacity, int trim, string gesture, string settingsJson);
[DllImport("__Internal")]
private static extern void __lunar_console_log_message(string message, string stackTrace, int type);
[DllImport("__Internal")]
private static extern void __lunar_console_show();
[DllImport("__Internal")]
private static extern void __lunar_console_hide();
[DllImport("__Internal")]
private static extern void __lunar_console_clear();
[DllImport("__Internal")]
private static extern void __lunar_console_action_register(int actionId, string name);
[DllImport("__Internal")]
private static extern void __lunar_console_action_unregister(int actionId);
[DllImport("__Internal")]
private static extern void __lunar_console_cvar_register(int variableId, string name, string type, string value, string defaultValue, int flags, bool hasRange, float min, float max);
[DllImport("__Internal")]
private static extern void __lunar_console_cvar_update(int variableId, string value);
[DllImport("__Internal")]
private static extern void __lunar_console_destroy();
/// <summary>
/// Initializes a new instance of the iOS platform class.
/// </summary>
/// <param name="targetName">The name of the game object which will receive native callbacks</param>
/// <param name="methodName">The method of the game object which will be called from the native code</param>
/// <param name="version">Plugin version</param>
/// <param name="capacity">Console capacity (elements over this amount will be trimmed)</param>
/// <param name="trim">Console trim amount (how many elements will be trimmed on the overflow)</param>
/// <param name="gesture">Gesture name to activate the console</param>
public PlatformIOS(string targetName, string methodName, string version, int capacity, int trim, string gesture, LunarConsoleSettings settings)
{
var settingsData = JsonUtility.ToJson(settings);
__lunar_console_initialize(targetName, methodName, version, capacity, trim, gesture, settingsData);
}
public void Update()
{
}
public void OnLogMessageReceived(string message, string stackTrace, LogType type)
{
// Suppress "stale touch" warning.
// See: https://github.com/SpaceMadness/lunar-unity-console/issues/70
if (type == LogType.Error && message == "Stale touch detected!")
{
return;
}
__lunar_console_log_message(message, stackTrace, (int)type);
}
public bool ShowConsole()
{
__lunar_console_show();
return true;
}
public bool HideConsole()
{
__lunar_console_hide();
return true;
}
public void ClearConsole()
{
__lunar_console_clear();
}
public void OnActionRegistered(CRegistry registry, CAction action)
{
__lunar_console_action_register(action.Id, action.Name);
}
public void OnActionUnregistered(CRegistry registry, CAction action)
{
__lunar_console_action_unregister(action.Id);
}
public void OnVariableRegistered(CRegistry registry, CVar cvar)
{
__lunar_console_cvar_register(cvar.Id, cvar.Name, cvar.Type.ToString(), cvar.Value, cvar.DefaultValue, (int)cvar.Flags, cvar.HasRange, cvar.Range.min, cvar.Range.max);
}
public void Destroy()
{
__lunar_console_destroy();
}
}
#elif UNITY_ANDROID
class PlatformAndroid : IPlatform
{
private readonly int m_mainThreadId;
private readonly jvalue[] m_args0 = new jvalue[0];
private readonly jvalue[] m_args1 = new jvalue[1];
private readonly jvalue[] m_args2 = new jvalue[2];
private readonly jvalue[] m_args3 = new jvalue[3];
private readonly jvalue[] m_args9 = new jvalue[9];
private static readonly string kPluginClassName = "spacemadness.com.lunarconsole.console.ConsolePlugin";
private readonly AndroidJavaClass m_pluginClass;
private readonly IntPtr m_pluginClassRaw;
private readonly IntPtr m_methodLogMessage;
private readonly IntPtr m_methodShowConsole;
private readonly IntPtr m_methodHideConsole;
private readonly IntPtr m_methodClearConsole;
private readonly IntPtr m_methodRegisterAction;
private readonly IntPtr m_methodUnregisterAction;
private readonly IntPtr m_methodRegisterVariable;
private readonly IntPtr m_methodDestroy;
private readonly Queue<LogMessageEntry> m_messageQueue;
/// <summary>
/// Initializes a new instance of the Android platform class.
/// </summary>
/// <param name="targetName">The name of the game object which will receive native callbacks</param>
/// <param name="methodName">The method of the game object which will be called from the native code</param>
/// <param name="version">Plugin version</param>
/// <param name="capacity">Console capacity (elements over this amount will be trimmed)</param>
/// <param name="trim">Console trim amount (how many elements will be trimmed on the overflow)</param>
/// <param name="gesture">Gesture name to activate the console</param>
public PlatformAndroid(string targetName, string methodName, string version, int capacity, int trim, string gesture, LunarConsoleSettings settings)
{
var settingsData = JsonUtility.ToJson(settings);
m_mainThreadId = Thread.CurrentThread.ManagedThreadId;
m_pluginClass = new AndroidJavaClass(kPluginClassName);
m_pluginClassRaw = m_pluginClass.GetRawClass();
IntPtr methodInit = GetStaticMethod(m_pluginClassRaw, "init", "(Ljava.lang.String;Ljava.lang.String;Ljava.lang.String;IILjava.lang.String;Ljava.lang.String;)V");
var methodInitParams = new jvalue[] {
jval(targetName),
jval(methodName),
jval(version),
jval(capacity),
jval(trim),
jval(gesture),
jval(settingsData)
};
CallStaticVoidMethod(methodInit, methodInitParams);
AndroidJNI.DeleteLocalRef(methodInitParams[0].l);
AndroidJNI.DeleteLocalRef(methodInitParams[1].l);
AndroidJNI.DeleteLocalRef(methodInitParams[2].l);
AndroidJNI.DeleteLocalRef(methodInitParams[5].l);
m_methodLogMessage = GetStaticMethod(m_pluginClassRaw, "logMessage", "(Ljava.lang.String;Ljava.lang.String;I)V");
m_methodShowConsole = GetStaticMethod(m_pluginClassRaw, "show", "()V");
m_methodHideConsole = GetStaticMethod(m_pluginClassRaw, "hide", "()V");
m_methodClearConsole = GetStaticMethod(m_pluginClassRaw, "clear", "()V");
m_methodRegisterAction = GetStaticMethod(m_pluginClassRaw, "registerAction", "(ILjava.lang.String;)V");
m_methodUnregisterAction = GetStaticMethod(m_pluginClassRaw, "unregisterAction", "(I)V");
m_methodRegisterVariable = GetStaticMethod(m_pluginClassRaw, "registerVariable", "(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZFF)V");
m_methodDestroy = GetStaticMethod(m_pluginClassRaw, "destroyInstance", "()V");
m_messageQueue = new Queue<LogMessageEntry>();
}
~PlatformAndroid()
{
m_pluginClass.Dispose();
}
#region IPlatform implementation
public void Update()
{
lock (m_messageQueue)
{
while (m_messageQueue.Count > 0)
{
var entry = m_messageQueue.Dequeue();
OnLogMessageReceived(entry.message, entry.stackTrace, entry.type);
}
}
}
public void OnLogMessageReceived(string message, string stackTrace, LogType type)
{
if (Thread.CurrentThread.ManagedThreadId == m_mainThreadId)
{
m_args3[0] = jval(message);
m_args3[1] = jval(stackTrace);
m_args3[2] = jval((int)type);
CallStaticVoidMethod(m_methodLogMessage, m_args3);
AndroidJNI.DeleteLocalRef(m_args3[0].l);
AndroidJNI.DeleteLocalRef(m_args3[1].l);
}
else
{
lock (m_messageQueue)
{
m_messageQueue.Enqueue(new LogMessageEntry(message, stackTrace, type));
}
}
}
public bool ShowConsole()
{
try
{
CallStaticVoidMethod(m_methodShowConsole, m_args0);
return true;
}
catch (Exception e)
{
Debug.LogError("Exception while calling 'LunarConsole.ShowConsole': " + e.Message);
return false;
}
}
public bool HideConsole()
{
try
{
CallStaticVoidMethod(m_methodHideConsole, m_args0);
return true;
}
catch (Exception e)
{
Debug.LogError("Exception while calling 'LunarConsole.HideConsole': " + e.Message);
return false;
}
}
public void ClearConsole()
{
try
{
CallStaticVoidMethod(m_methodClearConsole, m_args0);
}
catch (Exception e)
{
Debug.LogError("Exception while calling 'LunarConsole.ClearConsole': " + e.Message);
}
}
public void Destroy()
{
try
{
CallStaticVoidMethod(m_methodDestroy, m_args0);
}
catch (Exception e)
{
Debug.LogError("Exception while destroying platform: " + e.Message);
}
}
public void OnActionRegistered(CRegistry registry, CAction action)
{
try
{
m_args2[0] = jval(action.Id);
m_args2[1] = jval(action.Name);
CallStaticVoidMethod(m_methodRegisterAction, m_args2);
AndroidJNI.DeleteLocalRef(m_args2[1].l);
}
catch (Exception e)
{
Debug.LogError("Exception while calling 'LunarConsole.OnActionRegistered': " + e.Message);
}
}
public void OnActionUnregistered(CRegistry registry, CAction action)
{
try
{
m_args1[0] = jval(action.Id);
CallStaticVoidMethod(m_methodUnregisterAction, m_args1);
}
catch (Exception e)
{
Debug.LogError("Exception while calling 'LunarConsole.OnActionUnregistered': " + e.Message);
}
}
public void OnVariableRegistered(CRegistry registry, CVar cvar)
{
try
{
m_args9[0] = jval(cvar.Id);
m_args9[1] = jval(cvar.Name);
m_args9[2] = jval(cvar.Type.ToString());
m_args9[3] = jval(cvar.Value);
m_args9[4] = jval(cvar.DefaultValue);
m_args9[5] = jval((int)cvar.Flags);
m_args9[6] = jval(cvar.HasRange);
m_args9[7] = jval(cvar.Range.min);
m_args9[8] = jval(cvar.Range.max);
CallStaticVoidMethod(m_methodRegisterVariable, m_args9);
AndroidJNI.DeleteLocalRef(m_args9[1].l);
AndroidJNI.DeleteLocalRef(m_args9[2].l);
AndroidJNI.DeleteLocalRef(m_args9[3].l);
AndroidJNI.DeleteLocalRef(m_args9[4].l);
}
catch (Exception e)
{
Debug.LogError("Exception while calling 'LunarConsole.OnVariableRegistered': " + e.Message);
}
}
#endregion
#region Helpers
private static IntPtr GetStaticMethod(IntPtr classRaw, string name, string signature)
{
return AndroidJNIHelper.GetMethodID(classRaw, name, signature, true);
}
private void CallStaticVoidMethod(IntPtr method, jvalue[] args)
{
AndroidJNI.CallStaticVoidMethod(m_pluginClassRaw, method, args);
}
private bool CallStaticBoolMethod(IntPtr method, jvalue[] args)
{
return AndroidJNI.CallStaticBooleanMethod(m_pluginClassRaw, method, args);
}
private jvalue jval(string value)
{
jvalue val = new jvalue();
val.l = AndroidJNI.NewStringUTF(value);
return val;
}
private jvalue jval(bool value)
{
jvalue val = new jvalue();
val.z = value;
return val;
}
private jvalue jval(int value)
{
jvalue val = new jvalue();
val.i = value;
return val;
}
private jvalue jval(float value)
{
jvalue val = new jvalue();
val.f = value;
return val;
}
#endregion
}
struct LogMessageEntry
{
public readonly string message;
public readonly string stackTrace;
public readonly LogType type;
public LogMessageEntry(string message, string stackTrace, LogType type)
{
this.message = message;
this.stackTrace = stackTrace;
this.type = type;
}
}
#endif // UNITY_ANDROID
#if UNITY_EDITOR
class PlatformEditor : IPlatform
{
public void Update()
{
}
public void OnLogMessageReceived(string message, string stackTrace, LogType type)
{
}
public bool ShowConsole()
{
return false;
}
public bool HideConsole()
{
return false;
}
public void ClearConsole()
{
}
public void Destroy()
{
}
public void OnActionRegistered(CRegistry registry, CAction action)
{
}
public void OnActionUnregistered(CRegistry registry, CAction action)
{
}
public void OnVariableRegistered(CRegistry registry, CVar cvar)
{
}
}
#endif // UNITY_ANDROID
#endregion
#region Native callback
void NativeMessageCallback(string param)
{
IDictionary<string, string> data = StringUtils.DeserializeString(param);
string name = data["name"];
if (string.IsNullOrEmpty(name))
{
Log.w("Can't handle native callback: 'name' is undefined");
return;
}
LunarConsoleNativeMessageHandler handler;
if (!nativeHandlerLookup.TryGetValue(name, out handler))
{
Log.w("Can't handle native callback: handler not found '" + name + "'");
return;
}
try
{
handler(data);
}
catch (Exception e)
{
Log.e(e, "Exception while handling native callback '{0}'", name);
}
}
IDictionary<string, LunarConsoleNativeMessageHandler> nativeHandlerLookup
{
get
{
if (m_nativeHandlerLookup == null)
{
m_nativeHandlerLookup = new Dictionary<string, LunarConsoleNativeMessageHandler>();
m_nativeHandlerLookup["console_open"] = ConsoleOpenHandler;
m_nativeHandlerLookup["console_close"] = ConsoleCloseHandler;
m_nativeHandlerLookup["console_action"] = ConsoleActionHandler;
m_nativeHandlerLookup["console_variable_set"] = ConsoleVariableSetHandler;
m_nativeHandlerLookup["track_event"] = TrackEventHandler;
}
return m_nativeHandlerLookup;
}
}
void ConsoleOpenHandler(IDictionary<string, string> data)
{
if (onConsoleOpened != null)
{
onConsoleOpened();
}
TrackEvent("Console", "console_open");
}
void ConsoleCloseHandler(IDictionary<string, string> data)
{
if (onConsoleClosed != null)
{
onConsoleClosed();
}
TrackEvent("Console", "console_close");
}
void ConsoleActionHandler(IDictionary<string, string> data)
{
string actionIdStr;
if (!data.TryGetValue("id", out actionIdStr))
{
Log.w("Can't run action: data is not properly formatted");
return;
}
int actionId;
if (!int.TryParse(actionIdStr, out actionId))
{
Log.w("Can't run action: invalid ID " + actionIdStr);
return;
}
if (m_registry == null)
{
Log.w("Can't run action: registry is not property initialized");
return;
}
var action = m_registry.FindAction(actionId);
if (action == null)
{
Log.w("Can't run action: ID not found " + actionIdStr);
return;
}
try
{
action.Execute();
}
catch (Exception e)
{
Log.e(e, "Can't run action {0}", action.Name);
}
}
void ConsoleVariableSetHandler(IDictionary<string, string> data)
{
string variableIdStr;
if (!data.TryGetValue("id", out variableIdStr))
{
Log.w("Can't set variable: missing 'id' property");
return;
}
string value;
if (!data.TryGetValue("value", out value))
{
Log.w("Can't set variable: missing 'value' property");
return;
}
int variableId;
if (!int.TryParse(variableIdStr, out variableId))
{
Log.w("Can't set variable: invalid ID " + variableIdStr);
return;
}
if (m_registry == null)
{
Log.w("Can't set variable: registry is not property initialized");
return;
}
var variable = m_registry.FindVariable(variableId);
if (variable == null)
{
Log.w("Can't set variable: ID not found " + variableIdStr);
return;
}
try
{
switch(variable.Type)
{
case CVarType.Boolean:
{
int intValue;
if (int.TryParse(value, out intValue) && (intValue == 0 || intValue == 1))
{
variable.BoolValue = intValue == 1;
m_variablesDirty = true;
}
else
{
Log.e("Invalid boolean value: '{0}'", value);
}
break;
}
case CVarType.Integer:
{
int intValue;
if (int.TryParse(value, out intValue))
{
variable.IntValue = intValue;
m_variablesDirty = true;
}
else
{
Log.e("Invalid integer value: '{0}'", value);
}
break;
}
case CVarType.Float:
{
float floatValue;
if (float.TryParse(value, out floatValue))
{
variable.FloatValue = floatValue;
m_variablesDirty = true;
}
else
{
Log.e("Invalid float value: '{0}'", value);
}
break;
}
case CVarType.String:
{
variable.Value = value;
m_variablesDirty = true;
break;
}
default:
{
Log.e("Unexpected variable type: {0}", variable.Type);
break;
}
}
}
catch (Exception e)
{
Log.e(e, "Exception while trying to set variable '{0}'", variable.Name);
}
}
void TrackEventHandler(IDictionary<string, string> data)
{
#if LUNAR_CONSOLE_ANALYTICS_ENABLED
string category;
if (!data.TryGetValue("category", out category) || category.Length == 0)
{
Log.w("Can't track event: missing 'category' parameter");
return;
}
string action;
if (!data.TryGetValue("action", out action) || action.Length == 0)
{
Log.w("Can't track event: missing 'action' parameter");
return;
}
int value = LunarConsoleAnalytics.kUndefinedValue;;
string valueStr;
if (data.TryGetValue("value", out valueStr))
{
if (!int.TryParse(valueStr, out value))
{
Log.w("Can't track event: invalid 'value' parameter: {0}", valueStr);
return;
}
}
LunarConsoleAnalytics.TrackEvent(category, action, value);
#endif // LUNAR_CONSOLE_ANALYTICS_ENABLED
}
#region Analytics
void TrackEvent(string category, string action, int value = LunarConsoleAnalytics.kUndefinedValue)
{
#if LUNAR_CONSOLE_ANALYTICS_ENABLED
StartCoroutine(LunarConsoleAnalytics.TrackEvent(category, action, value));
#endif // LUNAR_CONSOLE_ANALYTICS_ENABLED
}
#endregion
#endregion
#endif // LUNAR_CONSOLE_ENABLED
#region Public API
/// <summary>
/// Shows the console on top of everything. Does nothing if current platform is not supported or if the plugin is not initialized.
/// </summary>
public static void Show()
{
#if LUNAR_CONSOLE_PLATFORM_SUPPORTED
#if LUNAR_CONSOLE_ENABLED
if (s_instance != null)
{
s_instance.ShowConsole();
}
else
{
Log.w("Can't show console: instance is not initialized. Make sure you've installed it correctly");
}
#else
Log.w("Can't show console: plugin is disabled");
#endif
#else
Log.w("Can't show console: current platform is not supported");
#endif
}
/// <summary>
/// Hides the console. Does nothing if platform is not supported or if plugin is not initialized.
/// </summary>
public static void Hide()
{
#if LUNAR_CONSOLE_PLATFORM_SUPPORTED
#if LUNAR_CONSOLE_ENABLED
if (s_instance != null)
{
s_instance.HideConsole();
}
else
{
Log.w("Can't hide console: instance is not initialized. Make sure you've installed it correctly");
}
#else
Log.w("Can't hide console: plugin is disabled");
#endif
#else
Log.w("Can't hide console: current platform is not supported");
#endif
}
/// <summary>
/// Clears log messages. Does nothing if platform is not supported or if plugin is not initialized.
/// </summary>
public static void Clear()
{
#if LUNAR_CONSOLE_PLATFORM_SUPPORTED
#if LUNAR_CONSOLE_ENABLED
if (s_instance != null)
{
s_instance.ClearConsole();
}
else
{
Log.w("Can't clear console: instance is not initialized. Make sure you've installed it correctly");
}
#else
Log.w("Can't clear console: plugin is disabled");
#endif
#else
Log.w("Can't clear console: current platform is not supported");
#endif
}
/// <summary>
/// Registers a user-defined action with a specific name and callback.
/// Does nothing if platform is not supported or if plugin is not initialized.
/// </summary>
/// <param name="name">Display name</param>
/// <param name="action">Callback delegate</param>
public static void RegisterAction(string name, Action action)
{
#if LUNAR_CONSOLE_PLATFORM_SUPPORTED
#if LUNAR_CONSOLE_FULL
#if LUNAR_CONSOLE_ENABLED
if (s_instance != null)
{
s_instance.RegisterConsoleAction(name, action);
}
else
{
Log.w("Can't register action: instance is not initialized. Make sure you've installed it correctly");
}
#else // LUNAR_CONSOLE_ENABLED
Log.w("Can't register action: plugin is disabled");
#endif // LUNAR_CONSOLE_ENABLED
#else // LUNAR_CONSOLE_FULL
Log.w("Can't register action: feature is not available in FREE version. Learn more about PRO version: https://goo.gl/TLInmD");
#endif // LUNAR_CONSOLE_FULL
#endif // LUNAR_CONSOLE_PLATFORM_SUPPORTED
}
/// <summary>
/// Un-registers a user-defined action with a specific callback.
/// Does nothing if platform is not supported or if plugin is not initialized.
/// </summary>
public static void UnregisterAction(Action action)
{
#if LUNAR_CONSOLE_PLATFORM_SUPPORTED
#if LUNAR_CONSOLE_FULL
#if LUNAR_CONSOLE_ENABLED
if (s_instance != null)
{
s_instance.UnregisterConsoleAction(action);
}
#endif // LUNAR_CONSOLE_ENABLED
#endif // LUNAR_CONSOLE_FULL
#endif // LUNAR_CONSOLE_PLATFORM_SUPPORTED
}
/// <summary>
/// Un-registers a user-defined action with a specific name.
/// Does nothing if platform is not supported or if plugin is not initialized.
/// </summary>
public static void UnregisterAction(string name)
{
#if LUNAR_CONSOLE_PLATFORM_SUPPORTED
#if LUNAR_CONSOLE_FULL
#if LUNAR_CONSOLE_ENABLED
if (s_instance != null)
{
s_instance.UnregisterConsoleAction(name);
}
#endif // LUNAR_CONSOLE_ENABLED
#endif // LUNAR_CONSOLE_FULL
#endif // LUNAR_CONSOLE_PLATFORM_SUPPORTED
}
/// <summary>
/// Un-registers all user-defined actions with a specific target
/// (the object of the class which contains callback methods).
/// Does nothing if platform is not supported or if plugin is not initialized.
/// </summary>
public static void UnregisterAllActions(object target)
{
#if LUNAR_CONSOLE_PLATFORM_SUPPORTED
#if LUNAR_CONSOLE_FULL
#if LUNAR_CONSOLE_ENABLED
if (s_instance != null)
{
s_instance.UnregisterAllConsoleActions(target);
}
#endif // LUNAR_CONSOLE_ENABLED
#endif // LUNAR_CONSOLE_FULL
#endif // LUNAR_CONSOLE_PLATFORM_SUPPORTED
}
/// <summary>
/// Sets console enabled or disabled.
/// Disabled console cannot be opened by user or API calls and does not collect logs.
/// Does nothing if platform is not supported or if plugin is not initialized.
/// </summary>
public static void SetConsoleEnabled(bool enabled)
{
#if LUNAR_CONSOLE_PLATFORM_SUPPORTED
#if LUNAR_CONSOLE_FULL
#if LUNAR_CONSOLE_ENABLED
if (s_instance != null)
{
s_instance.SetConsoleInstanceEnabled(enabled);
}
#endif // LUNAR_CONSOLE_ENABLED
#endif // LUNAR_CONSOLE_FULL
#endif // LUNAR_CONSOLE_PLATFORM_SUPPORTED
}
/// <summary>
/// Force variables to be written to a file
/// </summary>
public void MarkVariablesDirty()
{
m_variablesDirty = true;
}
/// <summary>
/// Callback method to be called when the console is opened. You can pause your game here.
/// </summary>
public static Action onConsoleOpened { get; set; }
/// <summary>
/// Callback method to be called when the console is closed. You can un-pause your game here.
/// </summary>
public static Action onConsoleClosed { get; set; }
#if LUNAR_CONSOLE_ENABLED
void ShowConsole()
{
if (m_platform != null)
{
m_platform.ShowConsole();
}
}
void HideConsole()
{
if (m_platform != null)
{
m_platform.HideConsole();
}
}
void ClearConsole()
{
if (m_platform != null)
{
m_platform.ClearConsole();
}
}
void RegisterConsoleAction(string name, Action actionDelegate)
{
if (m_registry != null)
{
m_registry.RegisterAction(name, actionDelegate);
}
else
{
Log.w("Can't register action '{0}': registry is not property initialized", name);
}
}
void UnregisterConsoleAction(Action actionDelegate)
{
if (m_registry != null)
{
m_registry.Unregister(actionDelegate);
}
else
{
Log.w("Can't unregister action '{0}': registry is not property initialized", actionDelegate);
}
}
void UnregisterConsoleAction(string name)
{
if (m_registry != null)
{
m_registry.Unregister(name);
}
else
{
Log.w("Can't unregister action '{0}': registry is not property initialized", name);
}
}
void UnregisterAllConsoleActions(object target)
{
if (m_registry != null)
{
m_registry.UnregisterAll(target);
}
else
{
Log.w("Can't unregister actions for target '{0}': registry is not property initialized", target);
}
}
void SetConsoleInstanceEnabled(bool enabled)
{
this.enabled = enabled;
}
#endif // LUNAR_CONSOLE_ENABLED
public static LunarConsole instance
{
get { return s_instance; }
}
public CRegistry registry
{
get { return m_registry; }
}
#endregion
}
}
namespace LunarConsolePluginInternal
{
public static class LunarConsoleConfig
{
public static readonly bool consoleEnabled;
public static readonly bool consoleSupported;
public static readonly bool freeVersion;
public static readonly bool fullVersion;
static LunarConsoleConfig()
{
#if LUNAR_CONSOLE_ENABLED
consoleEnabled = true;
#else
consoleEnabled = false;
#endif
#if LUNAR_CONSOLE_PLATFORM_SUPPORTED
consoleSupported = true;
#else
consoleSupported = false;
#endif
#if LUNAR_CONSOLE_FULL
freeVersion = false;
fullVersion = true;
#else
freeVersion = true;
fullVersion = false;
#endif
}
public static bool actionsEnabled
{
get
{
if (consoleSupported && consoleEnabled)
{
#if UNITY_EDITOR
return true;
#elif UNITY_IOS || UNITY_IPHONE
return Application.platform == RuntimePlatform.IPhonePlayer;
#elif UNITY_ANDROID
return Application.platform == RuntimePlatform.Android;
#endif
}
return false;
}
}
}
#if UNITY_EDITOR
public static class LunarConsolePluginEditorHelper
{
#if LUNAR_CONSOLE_ENABLED
[UnityEditor.MenuItem("Window/Lunar Mobile Console/Disable")]
static void Disable()
{
SetLunarConsoleEnabled(false);
}
#else
[UnityEditor.MenuItem("Window/Lunar Mobile Console/Enable")]
static void Enable()
{
SetLunarConsoleEnabled(true);
}
#endif // LUNAR_CONSOLE_ENABLED
#if LUNAR_CONSOLE_FREE
[UnityEditor.MenuItem("Window/Lunar Mobile Console/Get PRO version...")]
static void GetProVersion()
{
Application.OpenURL("https://goo.gl/aJbTsx");
}
#endif
public static void SetLunarConsoleEnabled(bool enabled)
{
string pluginFile = ResolvePluginFile();
if (pluginFile == null)
{
PrintError(enabled, "can't resolve plugin file");
return;
}
string sourceCode = File.ReadAllText(pluginFile);
string oldToken = "#define " + (enabled ? "LUNAR_CONSOLE_DISABLED" : "LUNAR_CONSOLE_ENABLED");
string newToken = "#define " + (enabled ? "LUNAR_CONSOLE_ENABLED" : "LUNAR_CONSOLE_DISABLED");
string newSourceCode = sourceCode.Replace(oldToken, newToken);
if (newSourceCode == sourceCode)
{
PrintError(enabled, "can't find '" + oldToken + "' token");
return;
}
File.WriteAllText(pluginFile, newSourceCode);
// re-import asset to apply changes
AssetDatabase.ImportAsset(FileUtils.GetAssetPath(pluginFile));
}
static string ResolvePluginFile()
{
try
{
string currentFile = new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileName();
if (currentFile != null && File.Exists(currentFile))
{
return currentFile;
}
}
catch (Exception e)
{
Log.e(e, "Exception while resolving plugin files location");
}
return null;
}
static void PrintError(bool flag, string message)
{
Debug.LogError("Can't " + (flag ? "enable" : "disable") + " Lunar Console: " + message);
}
}
#endif // UNITY_EDITOR
/// <summary>
/// Class for collecting anonymous usage statistics
/// </summary>
public static class LunarConsoleAnalytics
{
public static readonly string TrackingURL = "https://www.google-analytics.com/collect";
public const int kUndefinedValue = int.MinValue;
#if LUNAR_CONSOLE_ANALYTICS_ENABLED
private static readonly string DefaultPayload;
static LunarConsoleAnalytics()
{
// tracking id
#if LUNAR_CONSOLE_FULL
var trackingId = "UA-91768505-1";
#else
var trackingId = "UA-91747018-1";
#endif
StringBuilder payload = new StringBuilder("v=1&t=event");
payload.AppendFormat("&tid={0}", trackingId);
payload.AppendFormat("&cid={0}", WWW.EscapeURL(SystemInfo.deviceUniqueIdentifier));
payload.AppendFormat("&ua={0}", WWW.EscapeURL(SystemInfo.operatingSystem));
payload.AppendFormat("&av={0}", WWW.EscapeURL(Constants.Version));
#if UNITY_EDITOR
payload.AppendFormat("&ds={0}", "editor");
#else
payload.AppendFormat("&ds={0}", "player");
#endif
if (!string.IsNullOrEmpty(Application.productName))
{
var productName = WWW.EscapeURL(Application.productName);
if (productName.Length <= 100)
{
payload.AppendFormat("&an={0}", productName);
}
}
#if UNITY_5_6_OR_NEWER
var identifier = Application.identifier;
#else
var identifier = Application.bundleIdentifier;
#endif
if (!string.IsNullOrEmpty(identifier))
{
var bundleIdentifier = WWW.EscapeURL(identifier);
if (bundleIdentifier.Length <= 150)
{
payload.AppendFormat("&aid={0}", bundleIdentifier);
}
}
if (!string.IsNullOrEmpty(Application.companyName))
{
var companyName = WWW.EscapeURL(Application.companyName);
if (companyName.Length <= 150)
{
payload.AppendFormat("&aiid={0}", companyName);
}
}
DefaultPayload = payload.ToString();
}
internal static IEnumerator TrackEvent(string category, string action, int value = kUndefinedValue)
{
var payload = CreatePayload(category, action, value);
var www = new WWW(TrackingURL, System.Text.Encoding.UTF8.GetBytes(payload));
yield return www;
}
#endif // LUNAR_CONSOLE_ANALYTICS_ENABLED
public static string CreatePayload(string category, string action, int value)
{
#if LUNAR_CONSOLE_ANALYTICS_ENABLED
var payload = new StringBuilder(DefaultPayload);
payload.AppendFormat("&ec={0}", WWW.EscapeURL(category));
payload.AppendFormat("&ea={0}", WWW.EscapeURL(action));
if (value != kUndefinedValue)
{
payload.AppendFormat("&ev={0}", value.ToString());
}
return payload.ToString();
#else
return null;
#endif // LUNAR_CONSOLE_ANALYTICS_ENABLED
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
public class CSharpCommandLineParser : CommandLineParser
{
public static CSharpCommandLineParser Default { get; } = new CSharpCommandLineParser();
public static CSharpCommandLineParser Interactive { get; } = new CSharpCommandLineParser(isInteractive: true);
internal CSharpCommandLineParser(bool isInteractive = false)
: base(CSharp.MessageProvider.Instance, isInteractive)
{
}
protected override string RegularFileExtension { get { return ".cs"; } }
protected override string ScriptFileExtension { get { return ".csx"; } }
internal sealed override CommandLineArguments CommonParse(IEnumerable<string> args, string baseDirectory, string sdkDirectoryOpt, string additionalReferenceDirectories)
{
return Parse(args, baseDirectory, sdkDirectoryOpt, additionalReferenceDirectories);
}
/// <summary>
/// Parses a command line.
/// </summary>
/// <param name="args">A collection of strings representing the command line arguments.</param>
/// <param name="baseDirectory">The base directory used for qualifying file locations.</param>
/// <param name="sdkDirectory">The directory to search for mscorlib, or null if not available.</param>
/// <param name="additionalReferenceDirectories">A string representing additional reference paths.</param>
/// <returns>a commandlinearguments object representing the parsed command line.</returns>
public new CSharpCommandLineArguments Parse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories = null)
{
List<Diagnostic> diagnostics = new List<Diagnostic>();
List<string> flattenedArgs = new List<string>();
List<string> scriptArgs = IsInteractive ? new List<string>() : null;
FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory);
string appConfigPath = null;
bool displayLogo = true;
bool displayHelp = false;
bool optimize = false;
bool checkOverflow = false;
bool allowUnsafe = false;
bool concurrentBuild = true;
bool emitPdb = false;
bool debugPlus = false;
string pdbPath = null;
bool noStdLib = false;
string outputDirectory = baseDirectory;
string outputFileName = null;
string documentationPath = null;
string errorLogPath = null;
bool parseDocumentationComments = false; //Don't just null check documentationFileName because we want to do this even if the file name is invalid.
bool utf8output = false;
OutputKind outputKind = OutputKind.ConsoleApplication;
SubsystemVersion subsystemVersion = SubsystemVersion.None;
LanguageVersion languageVersion = CSharpParseOptions.Default.LanguageVersion;
string mainTypeName = null;
string win32ManifestFile = null;
string win32ResourceFile = null;
string win32IconFile = null;
bool noWin32Manifest = false;
Platform platform = Platform.AnyCpu;
ulong baseAddress = 0;
int fileAlignment = 0;
bool? delaySignSetting = null;
string keyFileSetting = null;
string keyContainerSetting = null;
List<ResourceDescription> managedResources = new List<ResourceDescription>();
List<CommandLineSourceFile> sourceFiles = new List<CommandLineSourceFile>();
List<CommandLineSourceFile> additionalFiles = new List<CommandLineSourceFile>();
bool sourceFilesSpecified = false;
bool resourcesOrModulesSpecified = false;
Encoding codepage = null;
var checksumAlgorithm = SourceHashAlgorithm.Sha1;
var defines = ArrayBuilder<string>.GetInstance();
List<CommandLineReference> metadataReferences = new List<CommandLineReference>();
List<CommandLineAnalyzerReference> analyzers = new List<CommandLineAnalyzerReference>();
List<string> libPaths = new List<string>();
List<string> keyFileSearchPaths = new List<string>();
List<string> usings = new List<string>();
var generalDiagnosticOption = ReportDiagnostic.Default;
var diagnosticOptions = new Dictionary<string, ReportDiagnostic>();
var noWarns = new Dictionary<string, ReportDiagnostic>();
var warnAsErrors = new Dictionary<string, ReportDiagnostic>();
int warningLevel = 4;
bool highEntropyVA = false;
bool printFullPaths = false;
string moduleAssemblyName = null;
string moduleName = null;
List<string> features = new List<string>();
string runtimeMetadataVersion = null;
bool errorEndLocation = false;
bool reportAnalyzer = false;
CultureInfo preferredUILang = null;
string touchedFilesPath = null;
var sqmSessionGuid = Guid.Empty;
// Process ruleset files first so that diagnostic severity settings specified on the command line via
// /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file.
if (!IsInteractive)
{
foreach (string arg in flattenedArgs)
{
string name, value;
if (TryParseOption(arg, out name, out value) && (name == "ruleset"))
{
var unquoted = RemoveAllQuotes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
}
else
{
generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, diagnostics, unquoted, baseDirectory);
}
}
}
}
foreach (string arg in flattenedArgs)
{
Debug.Assert(!arg.StartsWith("@", StringComparison.Ordinal));
string name, value;
if (!TryParseOption(arg, out name, out value))
{
sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics));
if (sourceFiles.Count > 0)
{
sourceFilesSpecified = true;
}
continue;
}
switch (name)
{
case "?":
case "help":
displayHelp = true;
continue;
case "r":
case "reference":
metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false));
continue;
case "a":
case "analyzer":
analyzers.AddRange(ParseAnalyzers(arg, value, diagnostics));
continue;
case "d":
case "define":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg);
continue;
}
IEnumerable<Diagnostic> defineDiagnostics;
defines.AddRange(ParseConditionalCompilationSymbols(value, out defineDiagnostics));
diagnostics.AddRange(defineDiagnostics);
continue;
case "codepage":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
continue;
}
var encoding = TryParseEncodingName(value);
if (encoding == null)
{
AddDiagnostic(diagnostics, ErrorCode.FTL_BadCodepage, value);
continue;
}
codepage = encoding;
continue;
case "checksumalgorithm":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
continue;
}
var newChecksumAlgorithm = TryParseHashAlgorithmName(value);
if (newChecksumAlgorithm == SourceHashAlgorithm.None)
{
AddDiagnostic(diagnostics, ErrorCode.FTL_BadChecksumAlgorithm, value);
continue;
}
checksumAlgorithm = newChecksumAlgorithm;
continue;
case "checked":
case "checked+":
if (value != null)
{
break;
}
checkOverflow = true;
continue;
case "checked-":
if (value != null)
break;
checkOverflow = false;
continue;
case "features":
if (value == null)
{
features.Clear();
}
else
{
features.Add(value);
}
continue;
case "noconfig":
// It is already handled (see CommonCommandLineCompiler.cs).
continue;
case "sqmsessionguid":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_MissingGuidForOption, "<text>", name);
}
else
{
if (!Guid.TryParse(value, out sqmSessionGuid))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFormatForGuidForOption, value, name);
}
}
continue;
case "preferreduilang":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg);
continue;
}
try
{
preferredUILang = new CultureInfo(value);
if (CorLightup.Desktop.IsUserCustomCulture(preferredUILang) ?? false)
{
// Do not use user custom cultures.
preferredUILang = null;
}
}
catch (CultureNotFoundException)
{
}
if (preferredUILang == null)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_BadUILang, value);
}
continue;
#if DEBUG
case "attachdebugger":
Debugger.Launch();
continue;
#endif
}
if (IsInteractive)
{
switch (name)
{
// interactive:
case "rp":
case "referencepath":
// TODO: should it really go to libPaths?
ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_REFERENCEPATH_OPTION, diagnostics);
continue;
case "u":
case "using":
usings.AddRange(ParseUsings(arg, value, diagnostics));
continue;
}
}
else
{
switch (name)
{
case "out":
if (string.IsNullOrWhiteSpace(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory);
}
continue;
case "t":
case "target":
if (value == null)
{
break; // force 'unrecognized option'
}
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget);
}
else
{
outputKind = ParseTarget(value, diagnostics);
}
continue;
case "moduleassemblyname":
value = value != null ? value.Unquote() : null;
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg);
}
else if (!MetadataHelpers.IsValidAssemblyOrModuleName(value))
{
// Dev11 C# doesn't check the name (VB does)
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidAssemblyName, "<text>", arg);
}
else
{
moduleAssemblyName = value;
}
continue;
case "modulename":
var unquotedModuleName = RemoveAllQuotes(value);
if (string.IsNullOrEmpty(unquotedModuleName))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename");
continue;
}
else
{
moduleName = unquotedModuleName;
}
continue;
case "platform":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<string>", arg);
}
else
{
platform = ParsePlatform(value, diagnostics);
}
continue;
case "recurse":
if (value == null)
{
break; // force 'unrecognized option'
}
else if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
int before = sourceFiles.Count;
sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics));
if (sourceFiles.Count > before)
{
sourceFilesSpecified = true;
}
}
continue;
case "doc":
parseDocumentationComments = true;
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
continue;
}
string unquoted = RemoveAllQuotes(value);
if (string.IsNullOrEmpty(unquoted))
{
// CONSIDER: This diagnostic exactly matches dev11, but it would be simpler (and more consistent with /out)
// if we just let the next case handle /doc:"".
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); // Different argument.
}
else
{
documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory);
}
continue;
case "addmodule":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:");
}
else if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
// NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory.
// Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory.
// An error will be reported by the assembly manager anyways.
metadataReferences.AddRange(ParseSeparatedPaths(value).Select(path => new CommandLineReference(path, MetadataReferenceProperties.Module)));
resourcesOrModulesSpecified = true;
}
continue;
case "l":
case "link":
metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: true));
continue;
case "win32res":
win32ResourceFile = GetWin32Setting(arg, value, diagnostics);
continue;
case "win32icon":
win32IconFile = GetWin32Setting(arg, value, diagnostics);
continue;
case "win32manifest":
win32ManifestFile = GetWin32Setting(arg, value, diagnostics);
noWin32Manifest = false;
continue;
case "nowin32manifest":
noWin32Manifest = true;
win32ManifestFile = null;
continue;
case "res":
case "resource":
if (value == null)
{
break; // Dev11 reports unrecognized option
}
var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true);
if (embeddedResource != null)
{
managedResources.Add(embeddedResource);
resourcesOrModulesSpecified = true;
}
continue;
case "linkres":
case "linkresource":
if (value == null)
{
break; // Dev11 reports unrecognized option
}
var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false);
if (linkedResource != null)
{
managedResources.Add(linkedResource);
resourcesOrModulesSpecified = true;
}
continue;
case "debug":
emitPdb = true;
// unused, parsed for backward compat only
if (value != null)
{
if (value.IsEmpty())
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), name);
}
else if (!string.Equals(value, "full", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(value, "pdbonly", StringComparison.OrdinalIgnoreCase))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value);
}
}
continue;
case "debug+":
//guard against "debug+:xx"
if (value != null)
break;
emitPdb = true;
debugPlus = true;
continue;
case "debug-":
if (value != null)
break;
emitPdb = false;
debugPlus = false;
continue;
case "o":
case "optimize":
case "o+":
case "optimize+":
if (value != null)
break;
optimize = true;
continue;
case "o-":
case "optimize-":
if (value != null)
break;
optimize = false;
continue;
case "p":
case "parallel":
case "p+":
case "parallel+":
if (value != null)
break;
concurrentBuild = true;
continue;
case "p-":
case "parallel-":
if (value != null)
break;
concurrentBuild = false;
continue;
case "warnaserror":
case "warnaserror+":
if (value == null)
{
generalDiagnosticOption = ReportDiagnostic.Error;
// Reset specific warnaserror options (since last /warnaserror flag on the command line always wins),
// and bump warnings to errors.
warnAsErrors.Clear();
foreach (var key in diagnosticOptions.Keys)
{
if (diagnosticOptions[key] == ReportDiagnostic.Warn)
{
warnAsErrors[key] = ReportDiagnostic.Error;
}
}
continue;
}
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else
{
AddWarnings(warnAsErrors, ReportDiagnostic.Error, ParseWarnings(value));
}
continue;
case "warnaserror-":
if (value == null)
{
generalDiagnosticOption = ReportDiagnostic.Default;
// Clear specific warnaserror options (since last /warnaserror flag on the command line always wins).
warnAsErrors.Clear();
continue;
}
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else
{
foreach (var id in ParseWarnings(value))
{
ReportDiagnostic ruleSetValue;
if (diagnosticOptions.TryGetValue(id, out ruleSetValue))
{
warnAsErrors[id] = ruleSetValue;
}
else
{
warnAsErrors[id] = ReportDiagnostic.Default;
}
}
}
continue;
case "w":
case "warn":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
continue;
}
int newWarningLevel;
if (string.IsNullOrEmpty(value) ||
!int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out newWarningLevel))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else if (newWarningLevel < 0 || newWarningLevel > 4)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadWarningLevel, name);
}
else
{
warningLevel = newWarningLevel;
}
continue;
case "nowarn":
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
continue;
}
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else
{
AddWarnings(noWarns, ReportDiagnostic.Suppress, ParseWarnings(value));
}
continue;
case "unsafe":
case "unsafe+":
if (value != null)
break;
allowUnsafe = true;
continue;
case "unsafe-":
if (value != null)
break;
allowUnsafe = false;
continue;
case "langversion":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:");
}
else if (!TryParseLanguageVersion(value, CSharpParseOptions.Default.LanguageVersion, out languageVersion))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value);
}
continue;
case "delaysign":
case "delaysign+":
if (value != null)
{
break;
}
delaySignSetting = true;
continue;
case "delaysign-":
if (value != null)
{
break;
}
delaySignSetting = false;
continue;
case "keyfile":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile");
}
else
{
keyFileSetting = RemoveAllQuotes(value);
}
// NOTE: Dev11/VB also clears "keycontainer", see also:
//
// MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by
// MSDN: custom attribute) in the same compilation, the compiler will first try the key container.
// MSDN: If that succeeds, then the assembly is signed with the information in the key container.
// MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile.
// MSDN: If that succeeds, the assembly is signed with the information in the key file and the key
// MSDN: information will be installed in the key container (similar to sn -i) so that on the next
// MSDN: compilation, the key container will be valid.
continue;
case "keycontainer":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer");
}
else
{
keyContainerSetting = value;
}
// NOTE: Dev11/VB also clears "keyfile", see also:
//
// MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by
// MSDN: custom attribute) in the same compilation, the compiler will first try the key container.
// MSDN: If that succeeds, then the assembly is signed with the information in the key container.
// MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile.
// MSDN: If that succeeds, the assembly is signed with the information in the key file and the key
// MSDN: information will be installed in the key container (similar to sn -i) so that on the next
// MSDN: compilation, the key container will be valid.
continue;
case "highentropyva":
case "highentropyva+":
if (value != null)
break;
highEntropyVA = true;
continue;
case "highentropyva-":
if (value != null)
break;
highEntropyVA = false;
continue;
case "nologo":
displayLogo = false;
continue;
case "baseaddress":
ulong newBaseAddress;
if (string.IsNullOrEmpty(value) || !TryParseUInt64(value, out newBaseAddress))
{
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, value);
}
}
else
{
baseAddress = newBaseAddress;
}
continue;
case "subsystemversion":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion");
continue;
}
// It seems VS 2012 just silently corrects invalid values and suppresses the error message
SubsystemVersion version = SubsystemVersion.None;
if (SubsystemVersion.TryParse(value, out version))
{
subsystemVersion = version;
}
else
{
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidSubsystemVersion, value);
}
continue;
case "touchedfiles":
unquoted = RemoveAllQuotes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles");
continue;
}
else
{
touchedFilesPath = unquoted;
}
continue;
case "bugreport":
UnimplementedSwitch(diagnostics, name);
continue;
case "utf8output":
if (value != null)
break;
utf8output = true;
continue;
case "m":
case "main":
// Remove any quotes for consistent behavior as MSBuild can return quoted or
// unquoted main.
unquoted = RemoveAllQuotes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
continue;
}
mainTypeName = unquoted;
continue;
case "fullpaths":
if (value != null)
break;
printFullPaths = true;
continue;
case "filealign":
ushort newAlignment;
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name);
}
else if (!TryParseUInt16(value, out newAlignment))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value);
}
else if (!CompilationOptions.IsValidFileAlignment(newAlignment))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value);
}
else
{
fileAlignment = newAlignment;
}
continue;
case "pdb":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
pdbPath = ParsePdbPath(value, diagnostics, baseDirectory);
}
continue;
case "errorendlocation":
errorEndLocation = true;
continue;
case "reportanalyzer":
reportAnalyzer = true;
continue;
case "nostdlib":
case "nostdlib+":
if (value != null)
break;
noStdLib = true;
continue;
case "lib":
ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_LIB_OPTION, diagnostics);
continue;
case "nostdlib-":
if (value != null)
break;
noStdLib = false;
continue;
case "errorreport":
continue;
case "errorlog":
unquoted = RemoveAllQuotes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<file>", RemoveAllQuotes(arg));
}
else
{
errorLogPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory);
}
continue;
case "appconfig":
unquoted = RemoveAllQuotes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<text>", RemoveAllQuotes(arg));
}
else
{
appConfigPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory);
}
continue;
case "runtimemetadataversion":
unquoted = RemoveAllQuotes(value);
if (string.IsNullOrEmpty(unquoted))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name);
continue;
}
runtimeMetadataVersion = unquoted;
continue;
case "ruleset":
// The ruleset arg has already been processed in a separate pass above.
continue;
case "additionalfile":
if (string.IsNullOrEmpty(value))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<file list>", name);
continue;
}
additionalFiles.AddRange(ParseAdditionalFileArgument(value, baseDirectory, diagnostics));
continue;
}
}
AddDiagnostic(diagnostics, ErrorCode.ERR_BadSwitch, arg);
}
foreach (var o in warnAsErrors)
{
diagnosticOptions[o.Key] = o.Value;
}
// Specific nowarn options always override specific warnaserror options.
foreach (var o in noWarns)
{
diagnosticOptions[o.Key] = o.Value;
}
if (!IsInteractive && !sourceFilesSpecified && (outputKind.IsNetModule() || !resourcesOrModulesSpecified))
{
AddDiagnostic(diagnostics, diagnosticOptions, ErrorCode.WRN_NoSources);
}
if (!noStdLib && sdkDirectory != null)
{
metadataReferences.Insert(0, new CommandLineReference(Path.Combine(sdkDirectory, "mscorlib.dll"), MetadataReferenceProperties.Assembly));
}
if (!platform.Requires64Bit())
{
if (baseAddress > uint.MaxValue - 0x8000)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, string.Format("0x{0:X}", baseAddress));
baseAddress = 0;
}
}
// add additional reference paths if specified
if (!string.IsNullOrWhiteSpace(additionalReferenceDirectories))
{
ParseAndResolveReferencePaths(null, additionalReferenceDirectories, baseDirectory, libPaths, MessageID.IDS_LIB_ENV, diagnostics);
}
ImmutableArray<string> referencePaths = BuildSearchPaths(sdkDirectory, libPaths);
ValidateWin32Settings(win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics);
// Dev11 searches for the key file in the current directory and assembly output directory.
// We always look to base directory and then examine the search paths.
keyFileSearchPaths.Add(baseDirectory);
if (baseDirectory != outputDirectory)
{
keyFileSearchPaths.Add(outputDirectory);
}
var parsedFeatures = CompilerOptionParseUtilities.ParseFeatures(features);
var debugInfoFormat = DebugInformationFormat.Pdb;
string pdbFormatStr;
if (emitPdb && parsedFeatures.TryGetValue("pdb", out pdbFormatStr))
{
if (pdbFormatStr == "portable")
{
debugInfoFormat = DebugInformationFormat.PortablePdb;
}
else if (pdbFormatStr == "embedded")
{
debugInfoFormat = DebugInformationFormat.Embedded;
emitPdb = false;
}
}
string compilationName;
GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFilesSpecified, moduleAssemblyName, ref outputFileName, ref moduleName, out compilationName);
var parseOptions = new CSharpParseOptions
(
languageVersion: languageVersion,
preprocessorSymbols: defines.ToImmutableAndFree(),
documentationMode: parseDocumentationComments ? DocumentationMode.Diagnose : DocumentationMode.None,
kind: SourceCodeKind.Regular,
features: parsedFeatures
);
var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script);
// We want to report diagnostics with source suppression in the error log file.
// However, these diagnostics won't be reported on the command line.
var reportSuppressedDiagnostics = errorLogPath != null;
var options = new CSharpCompilationOptions
(
outputKind: outputKind,
moduleName: moduleName,
mainTypeName: mainTypeName,
scriptClassName: WellKnownMemberNames.DefaultScriptClassName,
usings: usings,
optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug,
checkOverflow: checkOverflow,
allowUnsafe: allowUnsafe,
concurrentBuild: concurrentBuild,
cryptoKeyContainer: keyContainerSetting,
cryptoKeyFile: keyFileSetting,
delaySign: delaySignSetting,
platform: platform,
generalDiagnosticOption: generalDiagnosticOption,
warningLevel: warningLevel,
specificDiagnosticOptions: diagnosticOptions,
reportSuppressedDiagnostics: reportSuppressedDiagnostics
);
if (debugPlus)
{
options = options.WithDebugPlusMode(debugPlus);
}
var emitOptions = new EmitOptions
(
metadataOnly: false,
debugInformationFormat: debugInfoFormat,
pdbFilePath: null, // to be determined later
outputNameOverride: null, // to be determined later
baseAddress: baseAddress,
highEntropyVirtualAddressSpace: highEntropyVA,
fileAlignment: fileAlignment,
subsystemVersion: subsystemVersion,
runtimeMetadataVersion: runtimeMetadataVersion
);
// add option incompatibility errors if any
diagnostics.AddRange(options.Errors);
return new CSharpCommandLineArguments
{
IsInteractive = IsInteractive,
BaseDirectory = baseDirectory,
Errors = diagnostics.AsImmutable(),
Utf8Output = utf8output,
CompilationName = compilationName,
OutputFileName = outputFileName,
PdbPath = pdbPath,
EmitPdb = emitPdb,
OutputDirectory = outputDirectory,
DocumentationPath = documentationPath,
ErrorLogPath = errorLogPath,
AppConfigPath = appConfigPath,
SourceFiles = sourceFiles.AsImmutable(),
Encoding = codepage,
ChecksumAlgorithm = checksumAlgorithm,
MetadataReferences = metadataReferences.AsImmutable(),
AnalyzerReferences = analyzers.AsImmutable(),
AdditionalFiles = additionalFiles.AsImmutable(),
ReferencePaths = referencePaths,
KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(),
Win32ResourceFile = win32ResourceFile,
Win32Icon = win32IconFile,
Win32Manifest = win32ManifestFile,
NoWin32Manifest = noWin32Manifest,
DisplayLogo = displayLogo,
DisplayHelp = displayHelp,
ManifestResources = managedResources.AsImmutable(),
CompilationOptions = options,
ParseOptions = IsInteractive ? scriptParseOptions : parseOptions,
EmitOptions = emitOptions,
ScriptArguments = scriptArgs.AsImmutableOrEmpty(),
TouchedFilesPath = touchedFilesPath,
PrintFullPaths = printFullPaths,
ShouldIncludeErrorEndLocation = errorEndLocation,
PreferredUILang = preferredUILang,
SqmSessionGuid = sqmSessionGuid,
ReportAnalyzer = reportAnalyzer
};
}
private static void ParseAndResolveReferencePaths(string switchName, string switchValue, string baseDirectory, List<string> builder, MessageID origin, List<Diagnostic> diagnostics)
{
if (string.IsNullOrEmpty(switchValue))
{
Debug.Assert(!string.IsNullOrEmpty(switchName));
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName);
return;
}
foreach (string path in ParseSeparatedPaths(switchValue))
{
string resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory);
if (resolvedPath == null)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize());
}
else if (!PortableShim.Directory.Exists(resolvedPath))
{
AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize());
}
else
{
builder.Add(resolvedPath);
}
}
}
private static string GetWin32Setting(string arg, string value, List<Diagnostic> diagnostics)
{
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
string noQuotes = RemoveAllQuotes(value);
if (string.IsNullOrWhiteSpace(noQuotes))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
}
else
{
return noQuotes;
}
}
return null;
}
private void GetCompilationAndModuleNames(
List<Diagnostic> diagnostics,
OutputKind outputKind,
List<CommandLineSourceFile> sourceFiles,
bool sourceFilesSpecified,
string moduleAssemblyName,
ref string outputFileName,
ref string moduleName,
out string compilationName)
{
string simpleName;
if (outputFileName == null)
{
// In C#, if the output file name isn't specified explicitly, then executables take their
// names from the files containing their entrypoints and libraries derive their names from
// their first input files.
if (!IsInteractive && !sourceFilesSpecified)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName);
simpleName = null;
}
else if (outputKind.IsApplication())
{
simpleName = null;
}
else
{
simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(sourceFiles.FirstOrDefault().Path));
outputFileName = simpleName + outputKind.GetDefaultExtension();
if (simpleName.Length == 0 && !outputKind.IsNetModule())
{
AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName);
outputFileName = simpleName = null;
}
}
}
else
{
simpleName = PathUtilities.RemoveExtension(outputFileName);
if (simpleName.Length == 0)
{
AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName);
outputFileName = simpleName = null;
}
}
if (outputKind.IsNetModule())
{
Debug.Assert(!IsInteractive);
compilationName = moduleAssemblyName;
}
else
{
if (moduleAssemblyName != null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule);
}
compilationName = simpleName;
}
if (moduleName == null)
{
moduleName = outputFileName;
}
}
private static ImmutableArray<string> BuildSearchPaths(string sdkDirectoryOpt, List<string> libPaths)
{
var builder = ArrayBuilder<string>.GetInstance();
// Match how Dev11 builds the list of search paths
// see PCWSTR LangCompiler::GetSearchPath()
// current folder first -- base directory is searched by default
// Add SDK directory if it is available
if (sdkDirectoryOpt != null)
{
builder.Add(sdkDirectoryOpt);
}
// libpath
builder.AddRange(libPaths);
return builder.ToImmutableAndFree();
}
public static IEnumerable<string> ParseConditionalCompilationSymbols(string value, out IEnumerable<Diagnostic> diagnostics)
{
Diagnostic myDiagnostic = null;
value = value.TrimEnd(null);
// Allow a trailing semicolon or comma in the options
if (!value.IsEmpty() &&
(value.Last() == ';' || value.Last() == ','))
{
value = value.Substring(0, value.Length - 1);
}
string[] values = value.Split(new char[] { ';', ',' } /*, StringSplitOptions.RemoveEmptyEntries*/);
var defines = new ArrayBuilder<string>(values.Length);
foreach (string id in values)
{
string trimmedId = id.Trim();
if (SyntaxFacts.IsValidIdentifier(trimmedId))
{
defines.Add(trimmedId);
}
else if (myDiagnostic == null)
{
myDiagnostic = Diagnostic.Create(CSharp.MessageProvider.Instance, (int)ErrorCode.WRN_DefineIdentifierRequired, trimmedId);
}
}
diagnostics = myDiagnostic == null ? SpecializedCollections.EmptyEnumerable<Diagnostic>()
: SpecializedCollections.SingletonEnumerable(myDiagnostic);
return defines.AsEnumerable();
}
private static Platform ParsePlatform(string value, IList<Diagnostic> diagnostics)
{
switch (value.ToLowerInvariant())
{
case "x86":
return Platform.X86;
case "x64":
return Platform.X64;
case "itanium":
return Platform.Itanium;
case "anycpu":
return Platform.AnyCpu;
case "anycpu32bitpreferred":
return Platform.AnyCpu32BitPreferred;
case "arm":
return Platform.Arm;
default:
AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value);
return Platform.AnyCpu;
}
}
private static OutputKind ParseTarget(string value, IList<Diagnostic> diagnostics)
{
switch (value.ToLowerInvariant())
{
case "exe":
return OutputKind.ConsoleApplication;
case "winexe":
return OutputKind.WindowsApplication;
case "library":
return OutputKind.DynamicallyLinkedLibrary;
case "module":
return OutputKind.NetModule;
case "appcontainerexe":
return OutputKind.WindowsRuntimeApplication;
case "winmdobj":
return OutputKind.WindowsRuntimeMetadata;
default:
AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget);
return OutputKind.ConsoleApplication;
}
}
private static IEnumerable<string> ParseUsings(string arg, string value, IList<Diagnostic> diagnostics)
{
if (value.Length == 0)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg);
yield break;
}
foreach (var u in value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
yield return u;
}
}
private IEnumerable<CommandLineAnalyzerReference> ParseAnalyzers(string arg, string value, List<Diagnostic> diagnostics)
{
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
yield break;
}
else if (value.Length == 0)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
yield break;
}
List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList();
foreach (string path in paths)
{
yield return new CommandLineAnalyzerReference(path);
}
}
private IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes)
{
if (value == null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg);
yield break;
}
else if (value.Length == 0)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
yield break;
}
// /r:"reference"
// /r:alias=reference
// /r:alias="reference"
// /r:reference;reference
// /r:"path;containing;semicolons"
// /r:"unterminated_quotes
// /r:"quotes"in"the"middle
// /r:alias=reference;reference ... error 2034
// /r:nonidf=reference ... error 1679
int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' });
string alias;
if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=')
{
alias = value.Substring(0, eqlOrQuote);
value = value.Substring(eqlOrQuote + 1);
if (!SyntaxFacts.IsValidIdentifier(alias))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias);
yield break;
}
}
else
{
alias = null;
}
List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList();
if (alias != null)
{
if (paths.Count > 1)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value);
yield break;
}
if (paths.Count == 0)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias);
yield break;
}
}
foreach (string path in paths)
{
// NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory.
// Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory.
var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty;
var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes);
yield return new CommandLineReference(path, properties);
}
}
private static void ValidateWin32Settings(string win32ResourceFile, string win32IconResourceFile, string win32ManifestFile, OutputKind outputKind, IList<Diagnostic> diagnostics)
{
if (win32ResourceFile != null)
{
if (win32IconResourceFile != null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon);
}
if (win32ManifestFile != null)
{
AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest);
}
}
if (outputKind.IsNetModule() && win32ManifestFile != null)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule);
}
}
internal static ResourceDescription ParseResourceDescription(
string arg,
string resourceDescriptor,
string baseDirectory,
IList<Diagnostic> diagnostics,
bool embedded)
{
string filePath;
string fullPath;
string fileName;
string resourceName;
string accessibility;
ParseResourceDescription(
resourceDescriptor,
baseDirectory,
false,
out filePath,
out fullPath,
out fileName,
out resourceName,
out accessibility);
bool isPublic;
if (accessibility == null)
{
// If no accessibility is given, we default to "public".
// NOTE: Dev10 distinguishes between null and empty/whitespace-only.
isPublic = true;
}
else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase))
{
isPublic = true;
}
else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase))
{
isPublic = false;
}
else
{
AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility);
return null;
}
if (string.IsNullOrEmpty(filePath))
{
AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg);
return null;
}
if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
{
AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath);
return null;
}
Func<Stream> dataProvider = () =>
{
// Use FileShare.ReadWrite because the file could be opened by the current process.
// For example, it is an XML doc file produced by the build.
return PortableShim.FileStream.Create(fullPath, PortableShim.FileMode.Open, PortableShim.FileAccess.Read, PortableShim.FileShare.ReadWrite);
};
return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false);
}
private static bool TryParseLanguageVersion(string str, LanguageVersion defaultVersion, out LanguageVersion version)
{
if (str == null)
{
version = defaultVersion;
return true;
}
switch (str.ToLowerInvariant())
{
case "iso-1":
version = LanguageVersion.CSharp1;
return true;
case "iso-2":
version = LanguageVersion.CSharp2;
return true;
case "default":
version = defaultVersion;
return true;
default:
int versionNumber;
if (int.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out versionNumber) && ((LanguageVersion)versionNumber).IsValid())
{
version = (LanguageVersion)versionNumber;
return true;
}
version = defaultVersion;
return false;
}
}
private static IEnumerable<string> ParseWarnings(string value)
{
value = value.Unquote();
string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string id in values)
{
ushort number;
if (ushort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) &&
ErrorFacts.IsWarning((ErrorCode)number))
{
// The id refers to a compiler warning.
yield return CSharp.MessageProvider.Instance.GetIdForErrorCode(number);
}
else
{
// Previous versions of the compiler used to report a warning (CS1691)
// whenever an unrecognized warning code was supplied in /nowarn or
// /warnaserror. We no longer generate a warning in such cases.
// Instead we assume that the unrecognized id refers to a custom diagnostic.
yield return id;
}
}
}
private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items)
{
foreach (var id in items)
{
ReportDiagnostic existing;
if (d.TryGetValue(id, out existing))
{
// Rewrite the existing value with the latest one unless it is for /nowarn.
if (existing != ReportDiagnostic.Suppress)
d[id] = kind;
}
else
{
d.Add(id, kind);
}
}
}
private static void UnimplementedSwitch(IList<Diagnostic> diagnostics, string switchName)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName);
}
private static void UnimplementedSwitchValue(IList<Diagnostic> diagnostics, string switchName, string value)
{
AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName + ":" + value);
}
internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList<Diagnostic> diagnostics)
{
// no error in csc.exe
}
private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode)
{
diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode));
}
private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments)
{
diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode, arguments));
}
/// <summary>
/// Diagnostic for the errorCode added if the warningOptions does not mention suppressed for the errorCode.
/// </summary>
private static void AddDiagnostic(IList<Diagnostic> diagnostics, Dictionary<string, ReportDiagnostic> warningOptions, ErrorCode errorCode, params object[] arguments)
{
int code = (int)errorCode;
ReportDiagnostic value;
warningOptions.TryGetValue(CSharp.MessageProvider.Instance.GetIdForErrorCode(code), out value);
if (value != ReportDiagnostic.Suppress)
{
AddDiagnostic(diagnostics, errorCode, arguments);
}
}
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: DocClassEditColl
// ObjectType: DocClassEditColl
// CSLAType: EditableRootCollection
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
using UsingLibrary;
namespace DocStore.Business
{
/// <summary>
/// DocClassEditColl (editable root list).<br/>
/// This is a generated <see cref="DocClassEditColl"/> business object.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="DocClassEdit"/> objects.
/// </remarks>
[Serializable]
#if WINFORMS
public partial class DocClassEditColl : MyBusinessBindingListBase<DocClassEditColl, DocClassEdit>, IHaveInterface, IHaveGenericInterface<DocClassEditColl>
#else
public partial class DocClassEditColl : MyBusinessListBase<DocClassEditColl, DocClassEdit>, IHaveInterface, IHaveGenericInterface<DocClassEditColl>
#endif
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="DocClassEdit"/> item from the collection.
/// </summary>
/// <param name="docClassID">The DocClassID of the item to be removed.</param>
public void Remove(int docClassID)
{
foreach (var docClassEdit in this)
{
if (docClassEdit.DocClassID == docClassID)
{
Remove(docClassEdit);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="DocClassEdit"/> item is in the collection.
/// </summary>
/// <param name="docClassID">The DocClassID of the item to search for.</param>
/// <returns><c>true</c> if the DocClassEdit is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int docClassID)
{
foreach (var docClassEdit in this)
{
if (docClassEdit.DocClassID == docClassID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="DocClassEdit"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="docClassID">The DocClassID of the item to search for.</param>
/// <returns><c>true</c> if the DocClassEdit is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int docClassID)
{
foreach (var docClassEdit in DeletedList)
{
if (docClassEdit.DocClassID == docClassID)
{
return true;
}
}
return false;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="DocClassEditColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="DocClassEditColl"/> collection.</returns>
public static DocClassEditColl NewDocClassEditColl()
{
return DataPortal.Create<DocClassEditColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="DocClassEditColl"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="DocClassEditColl"/> collection.</returns>
public static DocClassEditColl GetDocClassEditColl()
{
return DataPortal.Fetch<DocClassEditColl>();
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="DocClassEditColl"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void NewDocClassEditColl(EventHandler<DataPortalResult<DocClassEditColl>> callback)
{
DocClassEditCollGetter.NewDocClassEditCollGetter((o, e) =>
{
callback(o, new DataPortalResult<DocClassEditColl>(e.Object.DocClassEditColl, e.Error, null));
});
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="DocClassEditColl"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void GetDocClassEditColl(EventHandler<DataPortalResult<DocClassEditColl>> callback)
{
DocClassEditCollGetter.GetDocClassEditCollGetter((o, e) =>
{
callback(o, new DataPortalResult<DocClassEditColl>(e.Object.DocClassEditColl, e.Error, null));
});
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DocClassEditColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public DocClassEditColl()
{
// Use factory methods and do not use direct creation.
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="DocClassEditColl"/> collection from the database.
/// </summary>
protected void DataPortal_Fetch()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("GetDocClassEditColl", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
var args = new DataPortalHookArgs(cmd);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="DocClassEditColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(DocClassEdit.GetDocClassEdit(dr));
}
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Updates in the database all changes made to the <see cref="DocClassEditColl"/> object.
/// </summary>
protected override void DataPortal_Update()
{
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
base.Child_Update();
ctx.Commit();
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
|