context stringlengths 2.52k 185k | gt stringclasses 1
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 System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Reflection.Metadata;
using System.Threading;
using System.Collections.Generic;
using Internal.TypeSystem;
namespace Internal.TypeSystem.Ecma
{
public sealed partial class EcmaMethod : MethodDesc, EcmaModule.IEntityHandleObject
{
private static class MethodFlags
{
public const int BasicMetadataCache = 0x0001;
public const int Virtual = 0x0002;
public const int NewSlot = 0x0004;
public const int Abstract = 0x0008;
public const int Final = 0x0010;
public const int NoInlining = 0x0020;
public const int AggressiveInlining = 0x0040;
public const int RuntimeImplemented = 0x0080;
public const int InternalCall = 0x0100;
public const int Synchronized = 0x0200;
public const int AttributeMetadataCache = 0x1000;
public const int Intrinsic = 0x2000;
public const int NativeCallable = 0x4000;
public const int RuntimeExport = 0x8000;
};
private EcmaType _type;
private MethodDefinitionHandle _handle;
// Cached values
private ThreadSafeFlags _methodFlags;
private MethodSignature _signature;
private string _name;
private TypeDesc[] _genericParameters; // TODO: Optional field?
internal EcmaMethod(EcmaType type, MethodDefinitionHandle handle)
{
_type = type;
_handle = handle;
#if DEBUG
// Initialize name eagerly in debug builds for convenience
this.ToString();
#endif
}
EntityHandle EcmaModule.IEntityHandleObject.Handle
{
get
{
return _handle;
}
}
public override TypeSystemContext Context
{
get
{
return _type.Module.Context;
}
}
public override TypeDesc OwningType
{
get
{
return _type;
}
}
private MethodSignature InitializeSignature()
{
var metadataReader = MetadataReader;
BlobReader signatureReader = metadataReader.GetBlobReader(metadataReader.GetMethodDefinition(_handle).Signature);
EcmaSignatureParser parser = new EcmaSignatureParser(Module, signatureReader);
var signature = parser.ParseMethodSignature();
return (_signature = signature);
}
public override MethodSignature Signature
{
get
{
if (_signature == null)
return InitializeSignature();
return _signature;
}
}
public EcmaModule Module
{
get
{
return _type.EcmaModule;
}
}
public MetadataReader MetadataReader
{
get
{
return _type.MetadataReader;
}
}
public MethodDefinitionHandle Handle
{
get
{
return _handle;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private int InitializeMethodFlags(int mask)
{
int flags = 0;
if ((mask & MethodFlags.BasicMetadataCache) != 0)
{
var methodAttributes = Attributes;
var methodImplAttributes = ImplAttributes;
if ((methodAttributes & MethodAttributes.Virtual) != 0)
flags |= MethodFlags.Virtual;
if ((methodAttributes & MethodAttributes.NewSlot) != 0)
flags |= MethodFlags.NewSlot;
if ((methodAttributes & MethodAttributes.Abstract) != 0)
flags |= MethodFlags.Abstract;
if ((methodAttributes & MethodAttributes.Final) != 0)
flags |= MethodFlags.Final;
if ((methodImplAttributes & MethodImplAttributes.NoInlining) != 0)
flags |= MethodFlags.NoInlining;
if ((methodImplAttributes & MethodImplAttributes.AggressiveInlining) != 0)
flags |= MethodFlags.AggressiveInlining;
if ((methodImplAttributes & MethodImplAttributes.Runtime) != 0)
flags |= MethodFlags.RuntimeImplemented;
if ((methodImplAttributes & MethodImplAttributes.InternalCall) != 0)
flags |= MethodFlags.InternalCall;
if ((methodImplAttributes & MethodImplAttributes.Synchronized) != 0)
flags |= MethodFlags.Synchronized;
flags |= MethodFlags.BasicMetadataCache;
}
// Fetching custom attribute based properties is more expensive, so keep that under
// a separate cache that might not be accessed very frequently.
if ((mask & MethodFlags.AttributeMetadataCache) != 0)
{
var metadataReader = this.MetadataReader;
var methodDefinition = metadataReader.GetMethodDefinition(_handle);
foreach (var attributeHandle in methodDefinition.GetCustomAttributes())
{
StringHandle namespaceHandle, nameHandle;
if (!metadataReader.GetAttributeNamespaceAndName(attributeHandle, out namespaceHandle, out nameHandle))
continue;
if (metadataReader.StringComparer.Equals(namespaceHandle, "System.Runtime.CompilerServices"))
{
if (metadataReader.StringComparer.Equals(nameHandle, "IntrinsicAttribute"))
{
flags |= MethodFlags.Intrinsic;
}
}
else
if (metadataReader.StringComparer.Equals(namespaceHandle, "System.Runtime.InteropServices"))
{
if (metadataReader.StringComparer.Equals(nameHandle, "NativeCallableAttribute"))
{
flags |= MethodFlags.NativeCallable;
}
}
else
if (metadataReader.StringComparer.Equals(namespaceHandle, "System.Runtime"))
{
if (metadataReader.StringComparer.Equals(nameHandle, "RuntimeExportAttribute"))
{
flags |= MethodFlags.RuntimeExport;
}
}
}
flags |= MethodFlags.AttributeMetadataCache;
}
Debug.Assert((flags & mask) != 0);
_methodFlags.AddFlags(flags);
return flags & mask;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int GetMethodFlags(int mask)
{
int flags = _methodFlags.Value & mask;
if (flags != 0)
return flags;
return InitializeMethodFlags(mask);
}
public override bool IsVirtual
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Virtual) & MethodFlags.Virtual) != 0;
}
}
public override bool IsNewSlot
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.NewSlot) & MethodFlags.NewSlot) != 0;
}
}
public override bool IsAbstract
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Abstract) & MethodFlags.Abstract) != 0;
}
}
public override bool IsFinal
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Final) & MethodFlags.Final) != 0;
}
}
public override bool IsNoInlining
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.NoInlining) & MethodFlags.NoInlining) != 0;
}
}
public override bool IsAggressiveInlining
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.AggressiveInlining) & MethodFlags.AggressiveInlining) != 0;
}
}
public override bool IsRuntimeImplemented
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.RuntimeImplemented) & MethodFlags.RuntimeImplemented) != 0;
}
}
public override bool IsIntrinsic
{
get
{
return (GetMethodFlags(MethodFlags.AttributeMetadataCache | MethodFlags.Intrinsic) & MethodFlags.Intrinsic) != 0;
}
}
public override bool IsInternalCall
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.InternalCall) & MethodFlags.InternalCall) != 0;
}
}
public override bool IsSynchronized
{
get
{
return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Synchronized) & MethodFlags.Synchronized) != 0;
}
}
public override bool IsNativeCallable
{
get
{
return (GetMethodFlags(MethodFlags.AttributeMetadataCache | MethodFlags.NativeCallable) & MethodFlags.NativeCallable) != 0;
}
}
public override bool IsRuntimeExport
{
get
{
return (GetMethodFlags(MethodFlags.AttributeMetadataCache | MethodFlags.RuntimeExport) & MethodFlags.RuntimeExport) != 0;
}
}
public override bool IsDefaultConstructor
{
get
{
MethodAttributes attributes = Attributes;
return attributes.IsRuntimeSpecialName()
&& attributes.IsPublic()
&& Signature.Length == 0
&& Name == ".ctor"
&& !_type.IsAbstract;
}
}
public MethodAttributes Attributes
{
get
{
return MetadataReader.GetMethodDefinition(_handle).Attributes;
}
}
public MethodImplAttributes ImplAttributes
{
get
{
return MetadataReader.GetMethodDefinition(_handle).ImplAttributes;
}
}
private string InitializeName()
{
var metadataReader = MetadataReader;
var name = metadataReader.GetString(metadataReader.GetMethodDefinition(_handle).Name);
return (_name = name);
}
public override string Name
{
get
{
if (_name == null)
return InitializeName();
return _name;
}
}
private void ComputeGenericParameters()
{
var genericParameterHandles = MetadataReader.GetMethodDefinition(_handle).GetGenericParameters();
int count = genericParameterHandles.Count;
if (count > 0)
{
TypeDesc[] genericParameters = new TypeDesc[count];
int i = 0;
foreach (var genericParameterHandle in genericParameterHandles)
{
genericParameters[i++] = new EcmaGenericParameter(Module, genericParameterHandle);
}
Interlocked.CompareExchange(ref _genericParameters, genericParameters, null);
}
else
{
_genericParameters = TypeDesc.EmptyTypes;
}
}
public override Instantiation Instantiation
{
get
{
if (_genericParameters == null)
ComputeGenericParameters();
return new Instantiation(_genericParameters);
}
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
return !MetadataReader.GetCustomAttributeHandle(MetadataReader.GetMethodDefinition(_handle).GetCustomAttributes(),
attributeNamespace, attributeName).IsNil;
}
public override string ToString()
{
return _type.ToString() + "." + Name;
}
public override bool IsPInvoke
{
get
{
return (((int)Attributes & (int)MethodAttributes.PinvokeImpl) != 0);
}
}
public override PInvokeMetadata GetPInvokeMethodMetadata()
{
if (!IsPInvoke)
return default(PInvokeMetadata);
MetadataReader metadataReader = MetadataReader;
MethodImport import = metadataReader.GetMethodDefinition(_handle).GetImport();
string name = metadataReader.GetString(import.Name);
ModuleReference moduleRef = metadataReader.GetModuleReference(import.Module);
string moduleName = metadataReader.GetString(moduleRef.Name);
// Spot check the enums match
Debug.Assert((int)MethodImportAttributes.CallingConventionStdCall == (int)PInvokeAttributes.CallingConventionStdCall);
Debug.Assert((int)MethodImportAttributes.CharSetAuto == (int)PInvokeAttributes.CharSetAuto);
Debug.Assert((int)MethodImportAttributes.CharSetUnicode == (int)PInvokeAttributes.CharSetUnicode);
Debug.Assert((int)MethodImportAttributes.SetLastError == (int)PInvokeAttributes.SetLastError);
return new PInvokeMetadata(moduleName, name, (PInvokeAttributes)import.Attributes);
}
public override ParameterMetadata[] GetParameterMetadata()
{
MetadataReader metadataReader = MetadataReader;
// Spot check the enums match
Debug.Assert((int)ParameterAttributes.In == (int)ParameterMetadataAttributes.In);
Debug.Assert((int)ParameterAttributes.Out == (int)ParameterMetadataAttributes.Out);
Debug.Assert((int)ParameterAttributes.Optional == (int)ParameterMetadataAttributes.Optional);
Debug.Assert((int)ParameterAttributes.HasDefault == (int)ParameterMetadataAttributes.HasDefault);
Debug.Assert((int)ParameterAttributes.HasFieldMarshal == (int)ParameterMetadataAttributes.HasFieldMarshal);
ParameterHandleCollection parameterHandles = metadataReader.GetMethodDefinition(_handle).GetParameters();
ParameterMetadata[] parameterMetadataArray = new ParameterMetadata[parameterHandles.Count];
int index = 0;
foreach (ParameterHandle parameterHandle in parameterHandles)
{
Parameter parameter = metadataReader.GetParameter(parameterHandle);
MarshalAsDescriptor marshalAsDescriptor = GetMarshalAsDescriptor(parameter);
ParameterMetadata data = new ParameterMetadata(parameter.SequenceNumber, (ParameterMetadataAttributes)parameter.Attributes, marshalAsDescriptor);
parameterMetadataArray[index++] = data;
}
return parameterMetadataArray;
}
private MarshalAsDescriptor GetMarshalAsDescriptor(Parameter parameter)
{
if ((parameter.Attributes & ParameterAttributes.HasFieldMarshal) == ParameterAttributes.HasFieldMarshal)
{
MetadataReader metadataReader = MetadataReader;
BlobReader marshalAsReader = metadataReader.GetBlobReader(parameter.GetMarshallingDescriptor());
EcmaSignatureParser parser = new EcmaSignatureParser(Module, marshalAsReader);
MarshalAsDescriptor marshalAs = parser.ParseMarshalAsDescriptor();
Debug.Assert(marshalAs != null);
return marshalAs;
}
return null;
}
}
}
| |
using System;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
namespace UnityEditor.Rendering.PostProcessing
{
[Decorator(typeof(TrackballAttribute))]
public sealed class TrackballDecorator : AttributeDecorator
{
static readonly int k_ThumbHash = "colorWheelThumb".GetHashCode();
static Material s_Material;
bool m_ResetState;
Vector2 m_CursorPos;
public override bool IsAutoProperty()
{
return false;
}
public override bool OnGUI(SerializedProperty property, SerializedProperty overrideState, GUIContent title, Attribute attribute)
{
if (property.propertyType != SerializedPropertyType.Vector4)
return false;
var value = property.vector4Value;
using (new EditorGUILayout.VerticalScope())
{
using (new EditorGUI.DisabledScope(!overrideState.boolValue))
DrawWheel(ref value, overrideState.boolValue, (TrackballAttribute)attribute);
DrawLabelAndOverride(title, overrideState);
}
if (m_ResetState)
{
value = Vector4.zero;
m_ResetState = false;
}
property.vector4Value = value;
return true;
}
void DrawWheel(ref Vector4 value, bool overrideState, TrackballAttribute attr)
{
var wheelRect = GUILayoutUtility.GetAspectRect(1f);
float size = wheelRect.width;
float hsize = size / 2f;
float radius = 0.38f * size;
Vector3 hsv;
Color.RGBToHSV(value, out hsv.x, out hsv.y, out hsv.z);
float offset = value.w;
// Thumb
var thumbPos = Vector2.zero;
float theta = hsv.x * (Mathf.PI * 2f);
thumbPos.x = Mathf.Cos(theta + (Mathf.PI / 2f));
thumbPos.y = Mathf.Sin(theta - (Mathf.PI / 2f));
thumbPos *= hsv.y * radius;
// Draw the wheel
if (Event.current.type == EventType.Repaint)
{
// Retina support
float scale = EditorGUIUtility.pixelsPerPoint;
if (s_Material == null)
s_Material = new Material(Shader.Find("Hidden/PostProcessing/Editor/Trackball")) { hideFlags = HideFlags.HideAndDontSave };
// Wheel texture
#if UNITY_2018_1_OR_NEWER
const RenderTextureReadWrite kReadWrite = RenderTextureReadWrite.sRGB;
#else
const RenderTextureReadWrite kReadWrite = RenderTextureReadWrite.Linear;
#endif
var oldRT = RenderTexture.active;
var rt = RenderTexture.GetTemporary((int)(size * scale), (int)(size * scale), 0, RenderTextureFormat.ARGB32, kReadWrite);
s_Material.SetFloat("_Offset", offset);
s_Material.SetFloat("_DisabledState", overrideState ? 1f : 0.5f);
s_Material.SetVector("_Resolution", new Vector2(size * scale, size * scale / 2f));
Graphics.Blit(null, rt, s_Material, EditorGUIUtility.isProSkin ? 0 : 1);
RenderTexture.active = oldRT;
GUI.DrawTexture(wheelRect, rt);
RenderTexture.ReleaseTemporary(rt);
var thumbSize = Styling.wheelThumbSize;
var thumbSizeH = thumbSize / 2f;
Styling.wheelThumb.Draw(new Rect(wheelRect.x + hsize + thumbPos.x - thumbSizeH.x, wheelRect.y + hsize + thumbPos.y - thumbSizeH.y, thumbSize.x, thumbSize.y), false, false, false, false);
}
// Input
var bounds = wheelRect;
bounds.x += hsize - radius;
bounds.y += hsize - radius;
bounds.width = bounds.height = radius * 2f;
hsv = GetInput(bounds, hsv, thumbPos, radius);
value = Color.HSVToRGB(hsv.x, hsv.y, 1f);
value.w = offset;
// Offset
var sliderRect = GUILayoutUtility.GetRect(1f, 17f);
float padding = sliderRect.width * 0.05f; // 5% padding
sliderRect.xMin += padding;
sliderRect.xMax -= padding;
value.w = GUI.HorizontalSlider(sliderRect, value.w, -1f, 1f);
if (attr.mode == TrackballAttribute.Mode.None)
return;
// Values
var displayValue = Vector3.zero;
switch (attr.mode)
{
case TrackballAttribute.Mode.Lift: displayValue = ColorUtilities.ColorToLift(value);
break;
case TrackballAttribute.Mode.Gamma: displayValue = ColorUtilities.ColorToInverseGamma(value);
break;
case TrackballAttribute.Mode.Gain: displayValue = ColorUtilities.ColorToGain(value);
break;
}
using (new EditorGUI.DisabledGroupScope(true))
{
var valuesRect = GUILayoutUtility.GetRect(1f, 17f);
valuesRect.width /= 3f;
GUI.Label(valuesRect, displayValue.x.ToString("F2"), EditorStyles.centeredGreyMiniLabel);
valuesRect.x += valuesRect.width;
GUI.Label(valuesRect, displayValue.y.ToString("F2"), EditorStyles.centeredGreyMiniLabel);
valuesRect.x += valuesRect.width;
GUI.Label(valuesRect, displayValue.z.ToString("F2"), EditorStyles.centeredGreyMiniLabel);
valuesRect.x += valuesRect.width;
}
}
void DrawLabelAndOverride(GUIContent title, SerializedProperty overrideState)
{
// Title
var areaRect = GUILayoutUtility.GetRect(1f, 17f);
var labelSize = Styling.wheelLabel.CalcSize(title);
var labelRect = new Rect(areaRect.x + areaRect.width / 2 - labelSize.x / 2, areaRect.y, labelSize.x, labelSize.y);
GUI.Label(labelRect, title, Styling.wheelLabel);
// Override checkbox
var overrideRect = new Rect(labelRect.x - 17, labelRect.y + 3, 17f, 17f);
EditorUtilities.DrawOverrideCheckbox(overrideRect, overrideState);
}
Vector3 GetInput(Rect bounds, Vector3 hsv, Vector2 thumbPos, float radius)
{
var e = Event.current;
var id = GUIUtility.GetControlID(k_ThumbHash, FocusType.Passive, bounds);
var mousePos = e.mousePosition;
if (e.type == EventType.MouseDown && GUIUtility.hotControl == 0 && bounds.Contains(mousePos))
{
if (e.button == 0)
{
var center = new Vector2(bounds.x + radius, bounds.y + radius);
float dist = Vector2.Distance(center, mousePos);
if (dist <= radius)
{
e.Use();
m_CursorPos = new Vector2(thumbPos.x + radius, thumbPos.y + radius);
GUIUtility.hotControl = id;
GUI.changed = true;
}
}
else if (e.button == 1)
{
e.Use();
GUI.changed = true;
m_ResetState = true;
}
}
else if (e.type == EventType.MouseDrag && e.button == 0 && GUIUtility.hotControl == id)
{
e.Use();
GUI.changed = true;
m_CursorPos += e.delta * GlobalSettings.trackballSensitivity;
GetWheelHueSaturation(m_CursorPos.x, m_CursorPos.y, radius, out hsv.x, out hsv.y);
}
else if (e.rawType == EventType.MouseUp && e.button == 0 && GUIUtility.hotControl == id)
{
e.Use();
GUIUtility.hotControl = 0;
}
return hsv;
}
void GetWheelHueSaturation(float x, float y, float radius, out float hue, out float saturation)
{
float dx = (x - radius) / radius;
float dy = (y - radius) / radius;
float d = Mathf.Sqrt(dx * dx + dy * dy);
hue = Mathf.Atan2(dx, -dy);
hue = 1f - ((hue > 0) ? hue : (Mathf.PI * 2f) + hue) / (Mathf.PI * 2f);
saturation = Mathf.Clamp01(d);
}
}
}
| |
// 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;
using System.Security.Authentication.ExtendedProtection;
using System.Threading.Tasks;
namespace System.Net
{
public sealed unsafe partial class HttpListener : IDisposable
{
public delegate ExtendedProtectionPolicy ExtendedProtectionSelector(HttpListenerRequest request);
private readonly object _internalLock;
private volatile State _state; // _state is set only within lock blocks, but often read outside locks.
private readonly HttpListenerPrefixCollection _prefixes;
internal Hashtable _uriPrefixes = new Hashtable();
private bool _ignoreWriteExceptions;
private ServiceNameStore _defaultServiceNames;
private HttpListenerTimeoutManager _timeoutManager;
private ExtendedProtectionPolicy _extendedProtectionPolicy;
private AuthenticationSchemeSelector _authenticationDelegate;
private AuthenticationSchemes _authenticationScheme = AuthenticationSchemes.Anonymous;
private ExtendedProtectionSelector _extendedProtectionSelectorDelegate;
private string _realm;
internal ICollection PrefixCollection => _uriPrefixes.Keys;
public HttpListener()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
_state = State.Stopped;
_internalLock = new object();
_defaultServiceNames = new ServiceNameStore();
_timeoutManager = new HttpListenerTimeoutManager(this);
_prefixes = new HttpListenerPrefixCollection(this);
// default: no CBT checks on any platform (appcompat reasons); applies also to PolicyEnforcement
// config element
_extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
public AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate
{
get => _authenticationDelegate;
set
{
CheckDisposed();
_authenticationDelegate = value;
}
}
public ExtendedProtectionSelector ExtendedProtectionSelectorDelegate
{
get => _extendedProtectionSelectorDelegate;
set
{
CheckDisposed();
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_extendedProtectionSelectorDelegate = value;
}
}
public AuthenticationSchemes AuthenticationSchemes
{
get => _authenticationScheme;
set
{
CheckDisposed();
_authenticationScheme = value;
}
}
public ExtendedProtectionPolicy ExtendedProtectionPolicy
{
get => _extendedProtectionPolicy;
set
{
CheckDisposed();
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value.CustomChannelBinding != null)
{
throw new ArgumentException(SR.net_listener_cannot_set_custom_cbt, nameof(value));
}
_extendedProtectionPolicy = value;
}
}
public ServiceNameCollection DefaultServiceNames => _defaultServiceNames.ServiceNames;
public HttpListenerPrefixCollection Prefixes
{
get
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
CheckDisposed();
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
return _prefixes;
}
}
internal void AddPrefix(string uriPrefix)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"uriPrefix:{uriPrefix}");
string registeredPrefix = null;
try
{
if (uriPrefix == null)
{
throw new ArgumentNullException(nameof(uriPrefix));
}
CheckDisposed();
int i;
if (string.Compare(uriPrefix, 0, "http://", 0, 7, StringComparison.OrdinalIgnoreCase) == 0)
{
i = 7;
}
else if (string.Compare(uriPrefix, 0, "https://", 0, 8, StringComparison.OrdinalIgnoreCase) == 0)
{
i = 8;
}
else
{
throw new ArgumentException(SR.net_listener_scheme, nameof(uriPrefix));
}
bool inSquareBrakets = false;
int j = i;
while (j < uriPrefix.Length && uriPrefix[j] != '/' && (uriPrefix[j] != ':' || inSquareBrakets))
{
if (uriPrefix[j] == '[')
{
if (inSquareBrakets)
{
j = i;
break;
}
inSquareBrakets = true;
}
if (inSquareBrakets && uriPrefix[j] == ']')
{
inSquareBrakets = false;
}
j++;
}
if (i == j)
{
throw new ArgumentException(SR.net_listener_host, nameof(uriPrefix));
}
if (uriPrefix[uriPrefix.Length - 1] != '/')
{
throw new ArgumentException(SR.net_listener_slash, nameof(uriPrefix));
}
registeredPrefix = uriPrefix[j] == ':' ? string.Copy(uriPrefix) : uriPrefix.Substring(0, j) + (i == 7 ? ":80" : ":443") + uriPrefix.Substring(j);
fixed (char* pChar = registeredPrefix)
{
i = 0;
while (pChar[i] != ':')
{
pChar[i] = (char)CaseInsensitiveAscii.AsciiToLower[(byte)pChar[i]];
i++;
}
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"mapped uriPrefix: {uriPrefix} to registeredPrefix: {registeredPrefix}");
if (_state == State.Started)
{
AddPrefixCore(registeredPrefix);
}
_uriPrefixes[uriPrefix] = registeredPrefix;
_defaultServiceNames.Add(uriPrefix);
}
catch (Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception);
throw;
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, $"prefix: {registeredPrefix}");
}
}
internal bool ContainsPrefix(string uriPrefix) => _uriPrefixes.Contains(uriPrefix);
internal bool RemovePrefix(string uriPrefix)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"uriPrefix: {uriPrefix}");
try
{
CheckDisposed();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"uriPrefix: {uriPrefix}");
if (uriPrefix == null)
{
throw new ArgumentNullException(nameof(uriPrefix));
}
if (!_uriPrefixes.Contains(uriPrefix))
{
return false;
}
if (_state == State.Started)
{
RemovePrefixCore((string)_uriPrefixes[uriPrefix]);
}
_uriPrefixes.Remove(uriPrefix);
_defaultServiceNames.Remove(uriPrefix);
}
catch (Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception);
throw;
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, $"uriPrefix: {uriPrefix}");
}
return true;
}
internal void RemoveAll(bool clear)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
CheckDisposed();
// go through the uri list and unregister for each one of them
if (_uriPrefixes.Count > 0)
{
if (_state == State.Started)
{
foreach (string registeredPrefix in _uriPrefixes.Values)
{
RemovePrefixCore(registeredPrefix);
}
}
if (clear)
{
_uriPrefixes.Clear();
_defaultServiceNames.Clear();
}
}
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
public string Realm
{
get => _realm;
set
{
CheckDisposed();
_realm = value;
}
}
public bool IsListening => _state == State.Started;
public bool IgnoreWriteExceptions
{
get => _ignoreWriteExceptions;
set
{
CheckDisposed();
_ignoreWriteExceptions = value;
}
}
public Task<HttpListenerContext> GetContextAsync()
{
return Task.Factory.FromAsync(
(callback, state) => ((HttpListener)state).BeginGetContext(callback, state),
iar => ((HttpListener)iar.AsyncState).EndGetContext(iar),
this);
}
public void Close()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, nameof(Close));
try
{
if (NetEventSource.IsEnabled) NetEventSource.Info("HttpListenerRequest::Close()");
((IDisposable)this).Dispose();
}
catch (Exception exception)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"Close {exception}");
throw;
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
internal void CheckDisposed()
{
if (_state == State.Closed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private enum State
{
Stopped,
Started,
Closed,
}
void IDisposable.Dispose() => Dispose();
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Text.RegularExpressions;
using ClientDependency.Core.CompositeFiles.Providers;
using ClientDependency.Core.Controls;
using ClientDependency.Core.FileRegistration.Providers;
using ClientDependency.Core.Config;
using ClientDependency.Core;
using System.Net;
namespace ClientDependency.Core.Module
{
/// <summary>
/// Used as an http response filter to modify the contents of the output html.
/// This filter is used to intercept js and css rogue registrations on the html page.
/// </summary>
public class RogueFileFilter : IFilter
{
#region Private members
private bool? m_Runnable = null;
private string m_MatchScript = "<script(?:(?:.*(?<src>(?<=src=\")[^\"]*(?=\"))[^>]*)|[^>]*)>(?<content>(?:(?:\n|.)(?!(?:\n|.)<script))*)</script>";
private string m_MatchLink = "<link\\s+[^>]*(href\\s*=\\s*(['\"])(?<href>.*?)\\2)";
private RogueFileCompressionElement m_FoundPath = null;
#endregion
#region IFilter Members
public void SetHttpContext(HttpContextBase ctx)
{
CurrentContext = ctx;
m_FoundPath = GetSupportedPath();
}
/// <summary>
/// This filter can only execute when it's a Page or MvcHandler
/// </summary>
/// <returns></returns>
public virtual bool ValidateCurrentHandler()
{
//don't filter if we're in debug mode
if (CurrentContext.IsDebuggingEnabled || !ClientDependencySettings.Instance.DefaultFileRegistrationProvider.EnableCompositeFiles)
return false;
return (CurrentContext.CurrentHandler is Page);
}
/// <summary>
/// Returns true when this filter should be applied
/// </summary>
/// <returns></returns>
public bool CanExecute()
{
if (!ValidateCurrentHandler())
{
return false;
}
if (!m_Runnable.HasValue)
{
m_Runnable = (m_FoundPath != null);
}
return m_Runnable.Value;
}
/// <summary>
/// Replaces any rogue script tag's with calls to the compression handler instead
/// of just the script.
/// </summary>
public string UpdateOutputHtml(string html)
{
html = ReplaceScripts(html);
html = ReplaceStyles(html);
return html;
}
public HttpContextBase CurrentContext { get; private set; }
#endregion
#region Private methods
private RogueFileCompressionElement GetSupportedPath()
{
var rawUrl = CurrentContext.GetRawUrlSafe();
if (string.IsNullOrWhiteSpace(rawUrl)) return null;
var rogueFiles = ClientDependencySettings.Instance
.ConfigSection
.CompositeFileElement
.RogueFileCompression;
return (from m in rogueFiles.Cast<RogueFileCompressionElement>()
let reg = m.FilePath == "*" ? ".*" : m.FilePath
let matched = Regex.IsMatch(rawUrl, reg, RegexOptions.IgnoreCase)
where matched
let isGood = m.ExcludePaths.Cast<RogueFileCompressionExcludeElement>().Select(e => Regex.IsMatch(rawUrl, e.FilePath, RegexOptions.IgnoreCase)).All(excluded => !excluded)
where isGood
select m).FirstOrDefault();
}
/// <summary>
/// Replaces all src attribute values for a script tag with their corresponding
/// URLs as a composite script.
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
private string ReplaceScripts(string html)
{
//check if we should be processing!
if (CanExecute() && m_FoundPath.CompressJs)
{
return ReplaceContent(html, "src", m_FoundPath.JsRequestExtension.Split(','), ClientDependencyType.Javascript, m_MatchScript, CurrentContext);
}
return html;
}
/// <summary>
/// Replaces all href attribute values for a link tag with their corresponding
/// URLs as a composite style.
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
private string ReplaceStyles(string html)
{
//check if we should be processing!
if (CanExecute() && m_FoundPath.CompressCss)
{
return ReplaceContent(html, "href", m_FoundPath.CssRequestExtension.Split(','), ClientDependencyType.Css, m_MatchLink, CurrentContext);
}
return html;
}
/// <summary>
/// Replaces the content with the new js/css paths
/// </summary>
/// <param name="html"></param>
/// <param name="namedGroup"></param>
/// <param name="extensions"></param>
/// <param name="type"></param>
/// <param name="regex"></param>
/// <param name="http"></param>
/// <returns></returns>
/// <remarks>
/// For some reason ampersands that aren't html escaped are not compliant to HTML standards when they exist in 'link' or 'script' tags in URLs,
/// we need to replace the ampersands with & . This is only required for this one w3c compliancy, the URL itself is a valid URL.
/// </remarks>
private static string ReplaceContent(string html, string namedGroup, string[] extensions,
ClientDependencyType type, string regex, HttpContextBase http)
{
html = Regex.Replace(html, regex,
(m) =>
{
var grp = m.Groups[namedGroup];
//if there is no namedGroup group name or it doesn't end with a js/css extension or it's already using the composite handler,
//the return the existing string.
if (grp == null
|| string.IsNullOrEmpty(grp.ToString())
|| !grp.ToString().EndsWithOneOf(extensions)
|| grp.ToString().StartsWith(ClientDependencySettings.Instance.CompositeFileHandlerPath))
return m.ToString();
//make sure that it's an internal request, though we can deal with external
//requests, we'll leave that up to the developer to register an external request
//explicitly if they want to include in the composite scripts.
try
{
var url = new Uri(grp.ToString(), UriKind.RelativeOrAbsolute);
if (!url.IsLocalUri(http))
return m.ToString(); //not a local uri
else
{
var dependency = new BasicFile(type) { FilePath = grp.ToString() };
var file = new[] { new BasicFile(type) { FilePath = dependency.ResolveFilePath(http) } };
var resolved = ClientDependencySettings.Instance.DefaultCompositeFileProcessingProvider.ProcessCompositeList(
file,
type,
http).Single();
return m.ToString().Replace(grp.ToString(), resolved.Replace("&", "&"));
}
}
catch (UriFormatException)
{
//malformed url, let's exit
return m.ToString();
}
});
return html;
}
#endregion
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
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 additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Text;
using fyiReporting.RDL;
namespace fyiReporting.RDL
{
/// <summary>
/// The VBFunctions class holds a number of static functions for support VB functions.
/// </summary>
sealed public class VBFunctions
{
/// <summary>
/// Obtains the year
/// </summary>
/// <param name="dt"></param>
/// <returns>int year</returns>
static public int Year(DateTime dt)
{
return dt.Year;
}
/// <summary>
/// Returns the integer day of week: 1=Sunday, 2=Monday, ..., 7=Saturday
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
static public int Weekday(DateTime dt)
{
int dow;
switch (dt.DayOfWeek)
{
case DayOfWeek.Sunday:
dow=1;
break;
case DayOfWeek.Monday:
dow=2;
break;
case DayOfWeek.Tuesday:
dow=3;
break;
case DayOfWeek.Wednesday:
dow=4;
break;
case DayOfWeek.Thursday:
dow=5;
break;
case DayOfWeek.Friday:
dow=6;
break;
case DayOfWeek.Saturday:
dow=7;
break;
default: // should never happen
dow=1;
break;
}
return dow;
}
/// <summary>
/// Returns the name of the day of week
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
static public string WeekdayName(int d)
{
return WeekdayName(d, false);
}
/// <summary>
/// Returns the name of the day of week
/// </summary>
/// <param name="d"></param>
/// <param name="bAbbreviation">true for abbreviated name</param>
/// <returns></returns>
static public string WeekdayName(int d, bool bAbbreviation)
{
DateTime dt = new DateTime(2005, 5, d); // May 1, 2005 is a Sunday
string wdn = bAbbreviation? string.Format("{0:ddd}", dt):string.Format("{0:dddd}", dt);
return wdn;
}
/// <summary>
/// Get the day of the month.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
static public int Day(DateTime dt)
{
return dt.Day;
}
/// <summary>
/// Gets the integer month
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
static public int Month(DateTime dt)
{
return dt.Month;
}
/// <summary>
/// Get the month name
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
static public string MonthName(int m)
{
return MonthName(m, false);
}
/// <summary>
/// Gets the month name; optionally abbreviated
/// </summary>
/// <param name="m"></param>
/// <param name="bAbbreviation"></param>
/// <returns></returns>
static public string MonthName(int m, bool bAbbreviation)
{
DateTime dt = new DateTime(2005, m, 1);
string mdn = bAbbreviation? string.Format("{0:MMM}", dt):string.Format("{0:MMMM}", dt);
return mdn;
}
/// <summary>
/// Gets the hour
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
static public int Hour(DateTime dt)
{
return dt.Hour;
}
/// <summary>
/// Get the minute
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
static public int Minute(DateTime dt)
{
return dt.Minute;
}
/// <summary>
/// Get the second
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
static public int Second(DateTime dt)
{
return dt.Second;
}
/// <summary>
/// Gets the current local date on this computer
/// </summary>
/// <returns></returns>
static public DateTime Today()
{
DateTime dt = DateTime.Now;
return new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0, 0);
}
/// <summary>
/// Converts the first letter in a string to ANSI code
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public int Asc(string o)
{
if (o == null || o.Length == 0)
return 0;
return Convert.ToInt32(o[0]);
}
/// <summary>
/// Converts an expression to Boolean
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public bool CBool(object o)
{
return Convert.ToBoolean(o);
}
/// <summary>
/// Converts an expression to type Byte
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public Byte CByte(string o)
{
return Convert.ToByte(o);
}
/// <summary>
/// Converts an expression to type Currency - really Decimal
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public decimal CCur(string o)
{
return Convert.ToDecimal(o);
}
/// <summary>
/// Converts an expression to type Date
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public DateTime CDate(string o)
{
return Convert.ToDateTime(o);
}
/// <summary>
/// Converts the specified ANSI code to a character
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public char Chr(int o)
{
return Convert.ToChar(o);
}
/// <summary>
/// Converts the expression to integer
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public int CInt(object o)
{
return Convert.ToInt32(o);
}
/// <summary>
/// Converts the expression to long
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public long CLng(object o)
{
return Convert.ToInt64(o);
}
/// <summary>
/// Converts the expression to Single
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public Single CSng(object o)
{
return Convert.ToSingle(o);
}
/// <summary>
/// Converts the expression to String
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public string CStr(object o)
{
return Convert.ToString(o);
}
/// <summary>
/// Returns the hexadecimal value of a specified number
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public string Hex(long o)
{
return Convert.ToString(o, 16);
}
/// <summary>
/// Returns the octal value of a specified number
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public string Oct(long o)
{
return Convert.ToString(o, 8);
}
/// <summary>
/// Converts the passed parameter to double
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
static public double CDbl(Object o)
{
return Convert.ToDouble(o);
}
static public DateTime DateAdd(string interval, double number, string date)
{
return DateAdd(interval, number, DateTime.Parse(date));
}
/// <summary>
/// Returns a date to which a specified time interval has been added.
/// </summary>
/// <param name="interval">String expression that is the interval you want to add.</param>
/// <param name="number">Numeric expression that is the number of interval you want to add. The numeric expression can either be positive, for dates in the future, or negative, for dates in the past.</param>
/// <param name="date">The date to which interval is added.</param>
/// <returns></returns>
static public DateTime DateAdd(string interval, double number, DateTime date)
{
switch (interval)
{
case "yyyy": // year
date = date.AddYears((int) Math.Round(number, 0));
break;
case "m": // month
date = date.AddMonths((int)Math.Round(number, 0));
break;
case "d": // day
date = date.AddDays(number);
break;
case "h": // hour
date = date.AddHours(number);
break;
case "n": // minute
date = date.AddMinutes(number);
break;
case "s": // second
date = date.AddSeconds(number);
break;
case "y": // day of year
date = date.AddDays(number);
break;
case "q": // quarter
date = date.AddMonths((int)Math.Round(number, 0) * 3);
break;
case "w": // weekday
date = date.AddDays(number);
break;
case "ww": // week of year
date = date.AddDays((int)Math.Round(number, 0) * 7);
break;
default:
throw new ArgumentException(string.Format("Interval '{0}' is invalid or unsupported.", interval));
}
return date;
}
/// <summary>
/// 1 based offset of string2 in string1
/// </summary>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <returns></returns>
static public int InStr(string string1, string string2)
{
return InStr(1, string1, string2, 0);
}
/// <summary>
/// 1 based offset of string2 in string1
/// </summary>
/// <param name="start"></param>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <returns></returns>
static public int InStr(int start, string string1, string string2)
{
return InStr(start, string1, string2, 0);
}
/// <summary>
/// 1 based offset of string2 in string1; optionally case insensitive
/// </summary>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <param name="compare">1 if you want case insensitive compare</param>
/// <returns></returns>
static public int InStr(string string1, string string2, int compare)
{
return InStr(1, string1, string2, compare);
}
/// <summary>
/// 1 based offset of string2 in string1; optionally case insensitive
/// </summary>
/// <param name="start"></param>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <param name="compare"></param>
/// <returns></returns>
static public int InStr(int start, string string1, string string2, int compare)
{
if (string1 == null || string2 == null ||
string1.Length == 0 || start > string1.Length ||
start < 1)
return 0;
if (string2.Length == 0)
return start;
// Make start zero based
start--;
if (start < 0)
start=0;
if (compare == 1) // Make case insensitive comparison?
{ // yes; just make both strings lower case
string1 = string1.ToLower();
string2 = string2.ToLower();
}
int i = string1.IndexOf(string2, start);
return i+1; // result is 1 based
}
/// <summary>
/// 1 based offset of string2 in string1 starting from end of string
/// </summary>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <returns></returns>
static public int InStrRev(string string1, string string2)
{
return InStrRev(string1, string2, -1, 0);
}
/// <summary>
/// 1 based offset of string2 in string1 starting from end of string - start
/// </summary>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <param name="start"></param>
/// <returns></returns>
static public int InStrRev(string string1, string string2, int start)
{
return InStrRev(string1, string2, start, 0);
}
/// <summary>
/// 1 based offset of string2 in string1 starting from end of string - start optionally case insensitive
/// </summary>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <param name="start"></param>
/// <param name="compare">1 for case insensitive comparison</param>
/// <returns></returns>
static public int InStrRev(string string1, string string2, int start, int compare)
{
if (string1 == null || string2 == null ||
string1.Length == 0 || string2.Length > string1.Length)
return 0;
// TODO this is the brute force method of searching; should use better algorithm
bool bCaseSensitive = compare == 1;
int inc= start == -1? string1.Length: start;
if (inc > string1.Length)
inc = string1.Length;
while (inc >= string2.Length) // go thru the string backwards; but string still needs to long enough to hold find string
{
int i=string2.Length-1;
for ( ; i >= 0; i--) // match the find string backwards as well
{
if (bCaseSensitive)
{
if (Char.ToLower(string1[inc-string2.Length+i]) != string2[i])
break;
}
else
{
if (string1[inc-string2.Length+i] != string2[i])
break;
}
}
if (i < 0) // We got a match
return inc+1-string2.Length;
inc--; // No match try next character
}
return 0;
}
/// <summary>
/// IsNumeric returns True if the data type of Expression is Boolean, Byte, Decimal, Double, Integer, Long,
/// SByte, Short, Single, UInteger, ULong, or UShort.
/// It also returns True if Expression is a Char, String, or Object that can be successfully converted to a number.
///
/// IsNumeric returns False if Expression is of data type Date. It returns False if Expression is a
/// Char, String, or Object that cannot be successfully converted to a number.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
static public bool IsNumeric(object expression)
{
if (expression == null)
return false;
if (expression is string || expression is char)
{
}
else if (expression is bool || expression is byte || expression is sbyte ||
expression is decimal ||
expression is double || expression is float ||
expression is Int16 || expression is Int32 || expression is Int64 ||
expression is UInt16 || expression is UInt32 || expression is UInt64)
return true;
try
{
Convert.ToDouble(expression);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Returns the lower case of the passed string
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public string LCase(string str)
{
return str == null? null: str.ToLower();
}
/// <summary>
/// Returns the left n characters from the string
/// </summary>
/// <param name="str"></param>
/// <param name="count"></param>
/// <returns></returns>
static public string Left(string str, int count)
{
if (str == null || count >= str.Length)
return str;
else
return str.Substring(0, count);
}
/// <summary>
/// Returns the length of the string
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public int Len(string str)
{
return str == null? 0: str.Length;
}
/// <summary>
/// Removes leading blanks from string
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public string LTrim(string str)
{
if (str == null || str.Length == 0)
return str;
return str.TrimStart(' ');
}
/// <summary>
/// Returns the portion of the string denoted by the start.
/// </summary>
/// <param name="str"></param>
/// <param name="start">1 based starting position</param>
/// <returns></returns>
static public string Mid(string str, int start)
{
if (str == null)
return null;
if (start > str.Length)
return "";
return str.Substring(start - 1);
}
/// <summary>
/// Returns the portion of the string denoted by the start and length.
/// </summary>
/// <param name="str"></param>
/// <param name="start">1 based starting position</param>
/// <param name="length">length to extract</param>
/// <returns></returns>
static public string Mid(string str, int start, int length)
{
if (str == null)
return null;
if (start > str.Length)
return "";
if (str.Length < start - 1 + length)
return str.Substring(start - 1); // Length specified is too large
return str.Substring(start-1, length);
}
//Replace(string,find,replacewith[,start[,count[,compare]]])
/// <summary>
/// Returns string replacing all instances of the searched for text with the replace text.
/// </summary>
/// <param name="str"></param>
/// <param name="find"></param>
/// <param name="replacewith"></param>
/// <returns></returns>
static public string Replace(string str, string find, string replacewith)
{
return Replace(str, find, replacewith, 1, -1, 0);
}
/// <summary>
/// Returns string replacing all instances of the searched for text starting at position
/// start with the replace text.
/// </summary>
/// <param name="str"></param>
/// <param name="find"></param>
/// <param name="replacewith"></param>
/// <param name="start"></param>
/// <returns></returns>
static public string Replace(string str, string find, string replacewith, int start)
{
return Replace(str, find, replacewith, start, -1, 0);
}
/// <summary>
/// Returns string replacing 'count' instances of the searched for text starting at position
/// start with the replace text.
/// </summary>
/// <param name="str"></param>
/// <param name="find"></param>
/// <param name="replacewith"></param>
/// <param name="start"></param>
/// <param name="count"></param>
/// <returns></returns>
static public string Replace(string str, string find, string replacewith, int start, int count)
{
return Replace(str, find, replacewith, start, count, 0);
}
/// <summary>
/// Returns string replacing 'count' instances of the searched for text (optionally
/// case insensitive) starting at position start with the replace text.
/// </summary>
/// <param name="str"></param>
/// <param name="find"></param>
/// <param name="replacewith"></param>
/// <param name="start"></param>
/// <param name="count"></param>
/// <param name="compare">1 for case insensitive search</param>
/// <returns></returns>
static public string Replace(string str, string find, string replacewith, int start, int count, int compare)
{
if (str == null || find == null || find.Length == 0 || count == 0)
return str;
if (count == -1) // user want all changed?
count = int.MaxValue;
StringBuilder sb = new StringBuilder(str);
bool bCaseSensitive = compare != 0; // determine if case sensitive; compare = 0 for case sensitive
if (bCaseSensitive)
find = find.ToLower();
int inc=0;
bool bReplace = (replacewith != null && replacewith.Length > 0);
// TODO this is the brute force method of searching; should use better algorithm
while (inc <= sb.Length - find.Length)
{
int i=0;
for ( ; i < find.Length; i++)
{
if (bCaseSensitive)
{
if (Char.ToLower(sb[inc+i]) != find[i])
break;
}
else
{
if (sb[inc+i] != find[i])
break;
}
}
if (i == find.Length) // We got a match
{
// replace the found string with the replacement string
sb.Remove(inc, find.Length);
if (bReplace)
{
sb.Insert(inc, replacewith);
inc += (replacewith.Length + 1);
}
count--;
if (count == 0) // have we done as many replaces as requested?
return sb.ToString(); // yes, return
}
else
inc++; // No match try next character
}
return sb.ToString();
}
/// <summary>
/// Returns the rightmost length of string.
/// </summary>
/// <param name="str"></param>
/// <param name="length"></param>
/// <returns></returns>
static public string Right(string str, int length)
{
if (str == null || str.Length <= length)
return str;
if (length <= 0)
return "";
return str.Substring(str.Length - length);
}
/// <summary>
/// Removes trailing blanks from string.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public string RTrim(string str)
{
if (str == null || str.Length == 0)
return str;
return str.TrimEnd(' ');
}
/// <summary>
/// Returns blank string of the specified length
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
static public string Space(int length)
{
return String(length, ' ');
}
//StrComp(string1,string2[,compare])
/// <summary>
/// Compares the strings. When string1 < string2: -1, string1 = string2: 0, string1 > string2: 1
/// </summary>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <returns></returns>
static public int StrComp(string string1, string string2)
{
return StrComp(string1, string2, 0);
}
/// <summary>
/// Compares the strings; optionally with case insensitivity. When string1 < string2: -1, string1 = string2: 0, string1 > string2: 1
/// </summary>
/// <param name="string1"></param>
/// <param name="string2"></param>
/// <param name="compare">1 for case insensitive comparison</param>
/// <returns></returns>
static public int StrComp(string string1, string string2, int compare)
{
if (string1 == null || string2 == null)
return 0; // not technically correct; should return null
return compare == 0?
string1.CompareTo(string2):
string1.ToLower().CompareTo(string2.ToLower());
}
/// <summary>
/// Return string with the character repeated for the length
/// </summary>
/// <param name="length"></param>
/// <param name="c"></param>
/// <returns></returns>
static public string String(int length, string c)
{
if (length <= 0 || c == null || c.Length == 0)
return "";
return String(length, c[0]);
}
/// <summary>
/// Return string with the character repeated for the length
/// </summary>
/// <param name="length"></param>
/// <param name="c"></param>
/// <returns></returns>
static public string String(int length, char c)
{
if (length <= 0)
return "";
StringBuilder sb = new StringBuilder(length, length);
for (int i = 0; i < length; i++)
sb.Append(c);
return sb.ToString();
}
/// <summary>
/// Returns a string with the characters reversed.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public string StrReverse(string str)
{
if (str == null || str.Length < 2)
return str;
StringBuilder sb = new StringBuilder(str, str.Length);
int i = str.Length-1;
foreach (char c in str)
{
sb[i--] = c;
}
return sb.ToString();
}
/// <summary>
/// Removes whitespace from beginning and end of string.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public string Trim(string str)
{
if (str == null || str.Length == 0)
return str;
return str.Trim(' ');
}
/// <summary>
/// Returns the uppercase version of the string
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public string UCase(string str)
{
return str == null? null: str.ToUpper();
}
/// <summary>
/// Rounds a number to zero decimal places
/// </summary>
/// <param name="n">Number to round</param>
/// <returns></returns>
static public double Round(double n)
{
return Math.Round(n);
}
/// <summary>
/// Rounds a number to the specified decimal places
/// </summary>
/// <param name="n">Number to round</param>
/// <param name="decimals">Number of decimal places</param>
/// <returns></returns>
static public double Round(double n, int decimals)
{
return Math.Round(n, decimals);
}
/// <summary>
/// Rounds a number to zero decimal places
/// </summary>
/// <param name="n">Number to round</param>
/// <returns></returns>
static public decimal Round(decimal n)
{
return Math.Round(n);
}
/// <summary>
/// Rounds a number to the specified decimal places
/// </summary>
/// <param name="n">Number to round</param>
/// <param name="decimals">Number of decimal places</param>
/// <returns></returns>
static public decimal Round(decimal n, int decimals)
{
return Math.Round(n, decimals);
}
}
}
| |
using EFCore.BulkExtensions.SqlAdapters;
using Microsoft.EntityFrameworkCore;
using NetTopologySuite.Geometries;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Xunit;
namespace EFCore.BulkExtensions.Tests
{
public class EFCoreBulkTestAtypical
{
protected int EntitiesNumber => 1000;
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
private void DefaultValuesTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.Truncate<Document>();
context.Documents.BatchDelete();
bool isSqlite = dbServer == DbServer.SQLite;
var entities = new List<Document>()
{
new Document { DocumentId = Guid.Parse("15E5936C-8021-45F4-A055-2BE89B065D9E"), Content = "Info " + 1 },
new Document { DocumentId = Guid.Parse("00C69E47-A08F-49E0-97A6-56C62C9BB47E"), Content = "Info " + 2 },
new Document { DocumentId = Guid.Parse("22CF94AE-20D3-49DE-83FA-90E79DD94706"), Content = "Info " + 3 },
new Document { DocumentId = Guid.Parse("B3A2F9A5-4222-47C3-BEEA-BF50771665D3"), Content = "Info " + 4 },
new Document { DocumentId = Guid.Parse("12AF6361-95BC-44F3-A487-C91C440018D8"), Content = "Info " + 5 },
};
var firstDocumentUp = entities.FirstOrDefault();
context.BulkInsertOrUpdate(entities, bulkConfig => bulkConfig.SetOutputIdentity = true); // example of setting BulkConfig with Action argument
var firstDocument = context.Documents.AsNoTracking().OrderBy(x => x.Content).FirstOrDefault();
var countDb = context.Documents.Count();
var countEntities = entities.Count();
// TEST
Assert.Equal(countDb, countEntities);
Assert.Equal(firstDocument.DocumentId, firstDocumentUp.DocumentId);
}
[Theory]
[InlineData(DbServer.SQLServer)]
private void TemporalTableTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
//context.Truncate<Document>(); // Can not be used because table is Temporal, so BatchDelete used instead
context.Storages.BatchDelete();
var entities = new List<Storage>()
{
new Storage { StorageId = Guid.NewGuid(), Data = "Info " + 1 },
new Storage { StorageId = Guid.NewGuid(), Data = "Info " + 2 },
new Storage { StorageId = Guid.NewGuid(), Data = "Info " + 3 },
};
context.BulkInsert(entities);
var countDb = context.Storages.Count();
var countEntities = entities.Count();
// TEST
Assert.Equal(countDb, countEntities);
}
[Theory]
[InlineData(DbServer.SQLServer)]
private void RunDefaultPKInsertWithGraph(DbServer dbServer)
{
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var department = new Department
{
Name = "Software",
Divisions = new List<Division>
{
new Division{Name = "Student A"},
new Division{Name = "Student B"},
new Division{Name = "Student C"},
}
};
context.BulkInsert(new List<Department> { department }, new BulkConfig { IncludeGraph = true });
};
}
[Theory]
[InlineData(DbServer.SQLServer)]
public void UpsertOrderTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
new EFCoreBatchTest().RunDeleteAll(dbServer);
using var context = new TestContext(ContextUtil.GetOptions());
context.Items.Add(new Item { Name = "name 1", Description = "info 1" });
context.Items.Add(new Item { Name = "name 2", Description = "info 2" });
context.SaveChanges();
var entities = new List<Item>();
for (int i = 1; i <= 4; i++)
{
int j = i;
if (i == 1) j = 2;
if (i == 2) j = 1;
entities.Add(new Item
{
Name = "name " + j,
Description = "info x " + j,
});
}
context.BulkInsertOrUpdate(entities, new BulkConfig { SetOutputIdentity = true, UpdateByProperties = new List<string> { nameof(Item.Name) } });
Assert.Equal(2, entities[0].ItemId);
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)] // Does NOT have Computed Columns
private void ComputedAndDefaultValuesTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.Truncate<Document>();
bool isSqlite = dbServer == DbServer.SQLite;
var entities = new List<Document>();
for (int i = 1; i <= EntitiesNumber; i++)
{
var entity = new Document
{
Content = "Info " + i
};
if (isSqlite)
{
entity.DocumentId = Guid.NewGuid();
entity.ContentLength = entity.Content.Length;
}
entities.Add(entity);
}
context.BulkInsert(entities, bulkAction => bulkAction.SetOutputIdentity = true); // example of setting BulkConfig with Action argument
var firstDocument = context.Documents.AsNoTracking().FirstOrDefault();
var count = context.Documents.Count();
// TEST
Assert.Equal("DefaultData", firstDocument.Tag);
firstDocument.Tag = null;
var upsertList = new List<Document> {
//firstDocument, // GetPropertiesWithDefaultValue .SelectMany(
new Document { Content = "Info " + (count + 1) }, // to test adding new with InsertOrUpdate (entity having Guid DbGenerated)
new Document { Content = "Info " + (count + 2) }
};
if (isSqlite)
{
upsertList[0].DocumentId = Guid.NewGuid(); //[1]
upsertList[1].DocumentId = Guid.NewGuid(); //[2]
}
count += 2;
context.BulkInsertOrUpdate(upsertList);
firstDocument = context.Documents.AsNoTracking().FirstOrDefault();
var entitiesCount = context.Documents.Count();
//Assert.Null(firstDocument.Tag); // OnUpdate columns with Defaults not omitted, should change even to default value, in this case to 'null'
Assert.NotEqual(Guid.Empty, firstDocument.DocumentId);
Assert.Equal(true, firstDocument.IsActive);
Assert.Equal(firstDocument.Content.Length, firstDocument.ContentLength);
Assert.Equal(entitiesCount, count);
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)] // Does NOT have Computed Columns
private void ParameterlessConstructorTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.Truncate<Letter>();
var entities = new List<Letter>();
int counter = 10;
for (int i = 1; i <= counter; i++)
{
var entity = new Letter("Note " + i);
entities.Add(entity);
}
context.BulkInsert(entities);
var count = context.Letters.Count();
var firstDocumentNote = context.Letters.AsNoTracking().FirstOrDefault();
// TEST
Assert.Equal(counter, count);
Assert.Equal("Note 1", firstDocumentNote.Note);
}
[Theory]
[InlineData(DbServer.SQLServer)]
//[InlineData(DbServer.Sqlite)] // No TimeStamp column type but can be set with DefaultValueSql: "CURRENT_TIMESTAMP" as it is in OnModelCreating() method.
private void TimeStampTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.Truncate<File>();
var entities = new List<File>();
for (int i = 1; i <= EntitiesNumber; i++)
{
var entity = new File
{
Description = "Some data " + i
};
entities.Add(entity);
}
context.BulkInsert(entities, bulkAction => bulkAction.SetOutputIdentity = true); // example of setting BulkConfig with Action argument
// Test BulkRead
var entitiesRead = new List<File>
{
new File { Description = "Some data 1" },
new File { Description = "Some data 2" }
};
context.BulkRead(entitiesRead, new BulkConfig
{
UpdateByProperties = new List<string> { nameof(File.Description) }
});
Assert.Equal(1, entitiesRead.First().FileId);
Assert.NotNull(entitiesRead.First().VersionChange);
// For testing concurrency conflict (UPDATE changes RowVersion which is TimeStamp column)
context.Database.ExecuteSqlRaw("UPDATE dbo.[File] SET Description = 'Some data 1 PRE CHANGE' WHERE [Id] = 1;");
var entitiesToUpdate = entities.Take(10).ToList();
foreach (var entityToUpdate in entitiesToUpdate)
{
entityToUpdate.Description += " UPDATED";
}
using var transaction = context.Database.BeginTransaction();
var bulkConfig = new BulkConfig { SetOutputIdentity = true, DoNotUpdateIfTimeStampChanged = true };
context.BulkUpdate(entitiesToUpdate, bulkConfig);
var list = bulkConfig.TimeStampInfo?.EntitiesOutput.Cast<File>().ToList();
Assert.Equal(9, list.Count());
Assert.Equal(1, bulkConfig.TimeStampInfo.NumberOfSkippedForUpdate);
if (bulkConfig.TimeStampInfo?.NumberOfSkippedForUpdate > 0)
{
//Options, based on needs:
// 1. rollback entire Update
transaction.Rollback(); // 1. rollback entire Update
// 2. throw Exception
//throw new DbUpdateConcurrencyException()
// 3. Update them again
// 4. Skip them and leave it unchanged
}
else
{
transaction.Commit();
}
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
private void CompositeKeyTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.Truncate<UserRole>();
// INSERT
var entitiesToInsert = new List<UserRole>();
for (int i = 0; i < EntitiesNumber; i++)
{
entitiesToInsert.Add(new UserRole
{
UserId = i / 10,
RoleId = i % 10,
Description = "desc"
});
}
context.BulkInsert(entitiesToInsert);
// UPDATE
var entitiesToUpdate = context.UserRoles.ToList();
int entitiesCount = entitiesToUpdate.Count();
for (int i = 0; i < entitiesCount; i++)
{
entitiesToUpdate[i].Description = "desc updated " + i;
}
context.BulkUpdate(entitiesToUpdate);
var entitiesToUpsert = new List<UserRole>()
{
new UserRole { UserId = 1, RoleId = 1 },
new UserRole { UserId = 2, RoleId = 2 },
new UserRole { UserId = 100, RoleId = 10 },
};
// TEST
var entities = context.UserRoles.ToList();
Assert.Equal(EntitiesNumber, entities.Count());
context.BulkInsertOrUpdate(entitiesToUpsert, new BulkConfig { PropertiesToInclude = new List<string> { nameof(UserRole.UserId), nameof(UserRole.RoleId) } });
var entitiesFinal = context.UserRoles.ToList();
Assert.Equal(EntitiesNumber + 1, entitiesFinal.Count());
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
private void DiscriminatorShadowTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.BulkDelete(context.Students.ToList());
// INSERT
var entitiesToInsert = new List<Student>();
for (int i = 1; i <= EntitiesNumber; i++)
{
entitiesToInsert.Add(new Student
{
Name = "name " + i,
Subject = "Math"
});
}
context.Students.AddRange(entitiesToInsert); // adding to Context so that Shadow property 'Discriminator' gets set
context.BulkInsert(entitiesToInsert);
// UPDATE
var entitiesToInsertOrUpdate = new List<Student>();
for (int i = 1; i <= EntitiesNumber / 2; i += 2)
{
entitiesToInsertOrUpdate.Add(new Student
{
Name = "name " + i,
Subject = "Math Upd"
});
}
context.Students.AddRange(entitiesToInsertOrUpdate); // adding to Context so that Shadow property 'Discriminator' gets set
context.BulkInsertOrUpdate(entitiesToInsertOrUpdate, new BulkConfig
{
UpdateByProperties = new List<string> { nameof(Student.Name) },
PropertiesToExclude = new List<string> { nameof(Student.PersonId) },
});
// TEST
var entities = context.Students.ToList();
Assert.Equal(EntitiesNumber, entities.Count());
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
private void ValueConversionTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.BulkDelete(context.Infos.ToList());
var dateTime = DateTime.Today;
// INSERT
var entitiesToInsert = new List<Info>();
for (int i = 1; i <= EntitiesNumber; i++)
{
entitiesToInsert.Add(new Info
{
Message = "Msg " + i,
ConvertedTime = dateTime,
InfoType = InfoType.InfoTypeA
});
}
context.BulkInsert(entitiesToInsert);
if (dbServer == DbServer.SQLServer)
{
var entities = context.Infos.ToList();
var entity = entities.FirstOrDefault();
Assert.Equal(entity.ConvertedTime, dateTime);
Assert.Equal("logged", entity.GetLogData());
Assert.Equal(DateTime.Today, entity.GetDateCreated());
var conn = context.Database.GetDbConnection();
if (conn.State != ConnectionState.Open)
conn.Open();
using var command = conn.CreateCommand();
command.CommandText = $"SELECT TOP 1 * FROM {nameof(Info)} ORDER BY {nameof(Info.InfoId)} DESC";
var reader = command.ExecuteReader();
reader.Read();
var row = new Info()
{
ConvertedTime = reader.Field<DateTime>(nameof(Info.ConvertedTime))
};
Assert.Equal(row.ConvertedTime, dateTime.AddDays(1));
}
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
private void OwnedTypesTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
if (dbServer == DbServer.SQLServer)
{
context.Truncate<ChangeLog>();
context.Database.ExecuteSqlRaw("TRUNCATE TABLE [" + nameof(ChangeLog) + "]");
}
else
{
//context.ChangeLogs.BatchDelete(); // TODO
context.BulkDelete(context.ChangeLogs.ToList());
}
var entities = new List<ChangeLog>();
for (int i = 1; i <= EntitiesNumber; i++)
{
entities.Add(new ChangeLog
{
Description = "Dsc " + i,
Audit = new Audit
{
ChangedBy = "User" + 1,
ChangedTime = DateTime.Now,
InfoType = InfoType.InfoTypeA
},
AuditExtended = new AuditExtended
{
CreatedBy = "UserS" + 1,
Remark = "test",
CreatedTime = DateTime.Now
},
AuditExtendedSecond = new AuditExtended
{
CreatedBy = "UserS" + 1,
Remark = "sec",
CreatedTime = DateTime.Now
}
});
}
context.BulkInsert(entities);
if (dbServer == DbServer.SQLServer)
{
context.BulkRead(
entities,
new BulkConfig
{
UpdateByProperties = new List<string> { nameof(Item.Description) }
}
);
Assert.Equal(2, entities[1].ChangeLogId);
}
// TEST
entities[0].Description += " UPD";
entities[0].Audit.InfoType = InfoType.InfoTypeB;
context.BulkUpdate(entities);
if (dbServer == DbServer.SQLServer)
{
context.BulkRead(entities);
}
Assert.Equal("Dsc 1 UPD", entities[0].Description);
Assert.Equal(InfoType.InfoTypeB, entities[0].Audit.InfoType);
}
[Theory]
[InlineData(DbServer.SQLServer)]
//[InlineData(DbServer.Sqlite)] Not supported
private void ShadowFKPropertiesTest(DbServer dbServer) // with Foreign Key as Shadow Property
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
if (dbServer == DbServer.SQLServer)
{
context.Truncate<ItemLink>();
context.Database.ExecuteSqlRaw("TRUNCATE TABLE [" + nameof(ItemLink) + "]");
}
else
{
//context.ChangeLogs.BatchDelete(); // TODO
context.BulkDelete(context.ItemLinks.ToList());
}
//context.BulkDelete(context.Items.ToList()); // On table with FK Truncate does not work
if (context.Items.Count() == 0)
{
for (int i = 1; i <= 10; ++i)
{
var entity = new Item
{
ItemId = 0,
Name = "name " + i,
Description = "info " + Guid.NewGuid().ToString().Substring(0, 3),
Quantity = i % 10,
Price = i / (i % 5 + 1),
TimeUpdated = DateTime.Now,
ItemHistories = new List<ItemHistory>()
};
context.Items.Add(entity);
}
context.SaveChanges();
}
var items = context.Items.ToList();
var entities = new List<ItemLink>();
for (int i = 0; i < EntitiesNumber; i++)
{
entities.Add(new ItemLink
{
ItemLinkId = 0,
Item = items[i % items.Count]
});
}
context.BulkInsert(entities);
if (dbServer == DbServer.SQLServer)
{
List<ItemLink> links = context.ItemLinks.ToList();
Assert.True(links.Count() > 0, "ItemLink row count");
foreach (var link in links)
{
Assert.NotNull(link.Item);
}
}
context.Truncate<ItemLink>();
}
[Theory]
[InlineData(DbServer.SQLServer)]
private void UpsertWithOutputSortTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
new EFCoreBatchTest().RunDeleteAll(dbServer);
var entitiesInitial = new List<Item>();
for (int i = 1; i <= 10; ++i)
{
var entity = new Item { Name = "name " + i };
entitiesInitial.Add(entity);
}
context.Items.AddRange(entitiesInitial);
context.SaveChanges();
var entities = new List<Item>()
{
new Item { ItemId = 0, Name = "name " + 11 + " New" },
new Item { ItemId = 6, Name = "name " + 6 + " Updated" },
new Item { ItemId = 5, Name = "name " + 5 + " Updated" },
new Item { ItemId = 0, Name = "name " + 12 + " New" }
};
context.BulkInsertOrUpdate(entities, new BulkConfig() { SetOutputIdentity = true });
Assert.Equal(11, entities[0].ItemId);
Assert.Equal(6, entities[1].ItemId);
Assert.Equal(5, entities[2].ItemId);
Assert.Equal(12, entities[3].ItemId);
Assert.Equal("name " + 11 + " New", entities[0].Name);
Assert.Equal("name " + 6 + " Updated", entities[1].Name);
Assert.Equal("name " + 5 + " Updated", entities[2].Name);
Assert.Equal("name " + 12 + " New", entities[3].Name);
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
private void NoPrimaryKeyTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
var list = context.Moduls.ToList();
var bulkConfig = new BulkConfig { UpdateByProperties = new List<string> { nameof(Modul.Code) } };
context.BulkDelete(list, bulkConfig);
var list1 = new List<Modul>();
var list2 = new List<Modul>();
for (int i = 1; i <= 20; i++)
{
if (i <= 10)
{
list1.Add(new Modul
{
Code = i.ToString(),
Name = "Name " + i.ToString("00"),
});
}
list2.Add(new Modul
{
Code = i.ToString(),
Name = "Name " + i.ToString("00"),
});
}
context.BulkInsert(list1);
list2[0].Name = "UPD";
context.BulkInsertOrUpdate(list2);
// TEST
Assert.Equal(20, context.Moduls.ToList().Count());
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
private void NonEntityChildTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
var list = context.Animals.ToList();
context.BulkDelete(list);
var mammalList = new List<Mammal>()
{
new Mammal { Name = "Cat" },
new Mammal { Name = "Dog" }
};
var bulkConfig = new BulkConfig { SetOutputIdentity = true };
context.BulkInsert(mammalList, bulkConfig, type: typeof(Animal));
// TEST
Assert.Equal(2, context.Animals.ToList().Count());
}
[Fact]
private void GeometryColumnTest()
{
ContextUtil.DbServer = DbServer.SQLServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.BulkDelete(context.Addresses.ToList());
var entities = new List<Address> {
new Address {
Street = "Some Street nn",
LocationGeography = new Point(52, 13),
LocationGeometry = new Point(52, 13),
}
};
context.BulkInsertOrUpdate(entities);
}
[Fact]
private void GeographyAndGeometryArePersistedCorrectlyTest()
{
ContextUtil.DbServer = DbServer.SQLServer;
using (var context = new TestContext(ContextUtil.GetOptions()))
{
context.BulkDelete(context.Addresses.ToList());
}
var point = new Point(52, 13);
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var entities = new List<Address> {
new Address {
Street = "Some Street nn",
LocationGeography = point,
LocationGeometry = point
}
};
context.BulkInsertOrUpdate(entities);
}
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var address = context.Addresses.Single();
Assert.Equal(point.X, address.LocationGeography.Coordinate.X);
Assert.Equal(point.Y, address.LocationGeography.Coordinate.Y);
Assert.Equal(point.X, address.LocationGeometry.Coordinate.X);
Assert.Equal(point.Y, address.LocationGeometry.Coordinate.Y);
}
}
[Fact]
private void HierarchyIdColumnTest()
{
ContextUtil.DbServer = DbServer.SQLServer;
using (var context = new TestContext(ContextUtil.GetOptions()))
{
context.BulkDelete(context.Categories.ToList());
}
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var nodeIdAsString = "/1/";
var entities = new List<Category> {
new Category
{
Name = "Root Element",
HierarchyDescription = HierarchyId.Parse(nodeIdAsString)
}
};
context.BulkInsertOrUpdate(entities);
}
}
[Fact]
private void HierarchyIdIsPersistedCorrectlySimpleTest()
{
ContextUtil.DbServer = DbServer.SQLServer;
using (var context = new TestContext(ContextUtil.GetOptions()))
{
context.BulkDelete(context.Categories.ToList());
}
var nodeIdAsString = "/1/";
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var entities = new List<Category> {
new Category
{
Name = "Root Element",
HierarchyDescription = HierarchyId.Parse(nodeIdAsString)
}
};
context.BulkInsertOrUpdate(entities);
}
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var category = context.Categories.Single();
Assert.Equal(nodeIdAsString, category.HierarchyDescription.ToString());
}
}
[Fact]
private void HierarchyIdIsPersistedCorrectlyLargerHierarchyTest()
{
ContextUtil.DbServer = DbServer.SQLServer;
using (var context = new TestContext(ContextUtil.GetOptions()))
{
context.BulkDelete(context.Categories.ToList());
}
var nodeIdAsString = "/1.1/-2/3/4/5/";
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var entities = new List<Category> {
new Category
{
Name = "Deep Element",
HierarchyDescription = HierarchyId.Parse(nodeIdAsString)
}
};
context.BulkInsertOrUpdate(entities);
}
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var category = context.Categories.Single();
Assert.Equal(nodeIdAsString, category.HierarchyDescription.ToString());
}
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.PostgreSQL)]
private void DestinationAndSourceTableNameTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.Truncate<Entry>();
context.Truncate<EntryPrep>();
context.Truncate<EntryArchive>();
var entities = new List<Entry>();
for (int i = 1; i <= 10; i++)
{
var entity = new Entry
{
Name = "Name " + i,
};
entities.Add(entity);
}
// [DEST]
context.BulkInsert(entities, b => b.CustomDestinationTableName = nameof(EntryArchive)); // Insert into table 'EntryArchive'
Assert.Equal(10, context.EntryArchives.Count());
// [SOURCE] (With CustomSourceTableName list not used so can be empty)
context.BulkInsert(new List<Entry>(), b => b.CustomSourceTableName = nameof(EntryArchive)); // InsertOrMERGE from table 'EntryArchive' into table 'Entry'
Assert.Equal(10, context.Entries.Count());
var entities2 = new List<EntryPrep>();
for (int i = 1; i <= 20; i++)
{
var entity = new EntryPrep
{
NameInfo = "Name Info " + i,
};
entities2.Add(entity);
}
context.EntryPreps.AddRange(entities2);
context.SaveChanges();
var mappings = new Dictionary<string, string>();
mappings.Add(nameof(EntryPrep.EntryPrepId), nameof(Entry.EntryId)); // here used 'nameof(Prop)' since Columns have the same name as Props
mappings.Add(nameof(EntryPrep.NameInfo), nameof(Entry.Name)); // if columns they were different name then they would be set with string names, eg. "EntryPrepareId"
var bulkConfig = new BulkConfig {
CustomSourceTableName = nameof(EntryPrep),
CustomSourceDestinationMappingColumns = mappings,
//UpdateByProperties = new List<string> { "Name" } // with this all are insert since names are different
};
// [SOURCE]
context.BulkInsertOrUpdate(new List<Entry>(), bulkConfig); // InsertOrMERGE from table 'EntryPrep' into table 'Entry'
Assert.Equal(20, context.Entries.Count());
}
[Fact]
private void TablePerTypeInsertTest()
{
ContextUtil.DbServer = DbServer.SQLServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.LogPersonReports.Add(new LogPersonReport { }); // used for initial add so that after RESEED it starts from 1, not 0
context.SaveChanges();
context.Truncate<LogPersonReport>();
context.Database.ExecuteSqlRaw($"DELETE FROM {nameof(Log)}");
context.Database.ExecuteSqlRaw($"DBCC CHECKIDENT('{nameof(Log)}', RESEED, 0);");
int nextLogId = GetLastRowId(context, tableName: nameof(Log));
int numberOfNewToInsert = 1000;
var entities = new List<LogPersonReport>();
for (int i = 1; i <= numberOfNewToInsert; i++)
{
nextLogId++; // OPTION 1.
var entity = new LogPersonReport
{
LogId = nextLogId, // OPTION 1.
PersonId = (i % 22),
RegBy = 15,
CreatedDate = DateTime.Now,
ReportId = (i % 22) * 10,
LogPersonReportTypeId = 4,
};
entities.Add(entity);
}
var bulkConfigBase = new BulkConfig
{
SqlBulkCopyOptions = Microsoft.Data.SqlClient.SqlBulkCopyOptions.KeepIdentity, // OPTION 1. - to ensure insert order is kept the same since SqlBulkCopy does not guarantee it.
PropertiesToInclude = new List<string>
{
nameof(LogPersonReport.LogId),
nameof(LogPersonReport.PersonId),
nameof(LogPersonReport.RegBy),
nameof(LogPersonReport.CreatedDate)
}
};
var bulkConfig = new BulkConfig
{
PropertiesToInclude = new List<string> {
nameof(LogPersonReport.LogId),
nameof(LogPersonReport.ReportId),
nameof(LogPersonReport.LogPersonReportTypeId)
}
};
context.BulkInsert(entities, bulkConfigBase, type: typeof(Log)); // to base 'Log' table
//foreach(var entity in entities) { // OPTION 2. Could be set here if Id of base table Log was set by Db (when Op.2. used 'Option 1.' have to be commented out)
// entity.LogId = ++nextLogId;
//}
context.BulkInsert(entities, bulkConfig); // to 'LogPersonReport' table
Assert.Equal(nextLogId, context.LogPersonReports.OrderByDescending(a => a.LogId).FirstOrDefault().LogId);
}
[Fact]
private void TableWithSpecialRowVersion()
{
ContextUtil.DbServer = DbServer.SQLServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.AtypicalRowVersionEntities.BatchDelete();
context.AtypicalRowVersionConverterEntities.BatchDelete();
var bulk = new List<AtypicalRowVersionEntity>();
for (var i = 0; i < 100; i++)
bulk.Add(new AtypicalRowVersionEntity { Id = Guid.NewGuid(), Name = $"Row {i}", RowVersion = i, SyncDevice = "Test" });
//Assert.Throws<InvalidOperationException>(() => context.BulkInsertOrUpdate(bulk)); // commented since when running in Debug mode it pauses on Exception
context.BulkInsertOrUpdate(bulk, new BulkConfig { IgnoreRowVersion = true });
Assert.Equal(bulk.Count(), context.AtypicalRowVersionEntities.Count());
var bulk2 = new List<AtypicalRowVersionConverterEntity>();
for (var i = 0; i < 100; i++)
bulk2.Add(new AtypicalRowVersionConverterEntity { Id = Guid.NewGuid(), Name = $"Row {i}" });
context.BulkInsertOrUpdate(bulk2);
Assert.Equal(bulk2.Count(), context.AtypicalRowVersionConverterEntities.Count());
}
private int GetLastRowId(DbContext context, string tableName)
{
var sqlConnection = context.Database.GetDbConnection();
sqlConnection.Open();
using var command = sqlConnection.CreateCommand();
command.CommandText = $"SELECT IDENT_CURRENT('{tableName}')";
int lastRowIdScalar = Convert.ToInt32(command.ExecuteScalar());
return lastRowIdScalar;
}
[Fact]
private void CustomPrecisionDateTimeTest()
{
ContextUtil.DbServer = DbServer.SQLServer;
using var context = new TestContext(ContextUtil.GetOptions());
context.BulkDelete(context.Events.ToList());
var entities = new List<Event>();
for (int i = 1; i <= 10; i++)
{
var entity = new Event
{
Name = "Event " + i,
TimeCreated = DateTime.Now
};
var testTime = new DateTime(2020, 1, 1, 12, 45, 20, 324);
if (i == 1)
{
entity.TimeCreated = testTime.AddTicks(6387); // Ticks will be 3256387 when rounded to 3 digits: 326 ms
}
if (i == 2)
{
entity.TimeCreated = testTime.AddTicks(5000); // Ticks will be 3255000 when rounded to 3 digits: 326 ms (middle .5zeros goes to Upper)
}
var fullDateTimeFormat = "yyyy-MM-dd HH:mm:ss.fffffff";
entity.Description = entity.TimeCreated.ToString(fullDateTimeFormat);
entities.Add(entity);
}
bool useBulk = true;
if (useBulk)
{
context.BulkInsert(entities, b => b.DateTime2PrecisionForceRound = false);
}
else
{
context.AddRange(entities);
context.SaveChanges();
}
// TEST
Assert.Equal(3240000, context.Events.SingleOrDefault(a => a.Name == "Event 1").TimeCreated.Ticks % 10000000);
Assert.Equal(3240000, context.Events.SingleOrDefault(a => a.Name == "Event 2").TimeCreated.Ticks % 10000000);
}
[Fact]
private void ByteArrayPKBulkReadTest()
{
ContextUtil.DbServer = DbServer.SQLite;
using var context = new TestContext(ContextUtil.GetOptions());
var list = context.Archives.ToList();
if (list.Count > 0)
{
context.Archives.RemoveRange(list);
context.SaveChanges();
}
var byte1 = new byte[] { 0x10, 0x10 };
var byte2 = new byte[] { 0x20, 0x20 };
var byte3 = new byte[] { 0x30, 0x30 };
context.Archives.AddRange(
new Archive { ArchiveId = byte1, Description = "Desc1" },
new Archive { ArchiveId = byte2, Description = "Desc2" },
new Archive { ArchiveId = byte3, Description = "Desc3" }
);
context.SaveChanges();
var entities = new List<Archive>();
entities.Add(new Archive { ArchiveId = byte1 });
entities.Add(new Archive { ArchiveId = byte2 });
context.BulkRead(entities);
Assert.Equal("Desc1", entities[0].Description);
Assert.Equal("Desc2", entities[1].Description);
}
[Theory]
[InlineData(DbServer.SQLServer)]
[InlineData(DbServer.SQLite)]
private void PrivateKeyTest(DbServer dbServer)
{
ContextUtil.DbServer = dbServer;
using (var context = new TestContext(ContextUtil.GetOptions()))
{
context.BulkDelete(context.PrivateKeys.ToList());
}
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var entities = new List<PrivateKey> {
new()
{
Name = "foo"
}
};
context.BulkInsertOrUpdate(entities);
}
using (var context = new TestContext(ContextUtil.GetOptions()))
{
var defaultValueTest = context.PrivateKeys.Single();
Assert.Equal("foo", defaultValueTest.Name);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Workflow.ComponentModel;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Workflow.Runtime.Hosting;
namespace System.Workflow.Runtime.Tracking
{
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public abstract class TrackingRecord
{
protected TrackingRecord()
{
}
public abstract DateTime EventDateTime
{
get;
set;
}
public abstract int EventOrder
{
get;
set;
}
public abstract EventArgs EventArgs
{
get;
set;
}
public abstract TrackingAnnotationCollection Annotations
{
get;
}
}
/// <summary>
/// Contains data for a specific extraction point.
/// </summary>
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class ActivityTrackingRecord : TrackingRecord
{
#region Data Members
private string _qualifiedID = null;
private Type _activityType = null;
private ActivityExecutionStatus _status;
private List<TrackingDataItem> _body = new List<TrackingDataItem>();
private Guid _contextGuid = Guid.Empty, _parentContextGuid = Guid.Empty;
private DateTime _eventDateTime = DateTime.MinValue;
private int _eventOrder = -1;
private EventArgs _args = null;
private TrackingAnnotationCollection _annotations = new TrackingAnnotationCollection();
#endregion
#region Constructors
public ActivityTrackingRecord()
{
}
public ActivityTrackingRecord(Type activityType, string qualifiedName, Guid contextGuid, Guid parentContextGuid, ActivityExecutionStatus executionStatus, DateTime eventDateTime, int eventOrder, EventArgs eventArgs)
{
_activityType = activityType;
_qualifiedID = qualifiedName;
_status = executionStatus;
_eventDateTime = eventDateTime;
_contextGuid = contextGuid;
_parentContextGuid = parentContextGuid;
_eventOrder = eventOrder;
_args = eventArgs;
}
#endregion
#region Public Properties
public string QualifiedName
{
get { return _qualifiedID; }
set { _qualifiedID = value; }
}
public Guid ContextGuid
{
get { return _contextGuid; }
set { _contextGuid = value; }
}
public Guid ParentContextGuid
{
get { return _parentContextGuid; }
set { _parentContextGuid = value; }
}
public Type ActivityType
{
get { return _activityType; }
set { _activityType = value; }
}
public ActivityExecutionStatus ExecutionStatus
{
get { return _status; }
set { _status = value; }
}
public IList<TrackingDataItem> Body
{
get { return _body; }
}
#endregion
#region TrackingRecord
public override DateTime EventDateTime
{
get { return _eventDateTime; }
set { _eventDateTime = value; }
}
/// <summary>
/// Contains a value indicating the relative order of this event within the context of a workflow instance.
/// Value will be unique within a workflow instance but is not guaranteed to be sequential.
/// </summary>
public override int EventOrder
{
get { return _eventOrder; }
set { _eventOrder = value; }
}
public override EventArgs EventArgs
{
get { return _args; }
set { _args = value; }
}
public override TrackingAnnotationCollection Annotations
{
get { return _annotations; }
}
#endregion
}
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class UserTrackingRecord : TrackingRecord
{
#region Data Members
private string _qualifiedID = null;
private Type _activityType = null;
private List<TrackingDataItem> _body = new List<TrackingDataItem>();
private Guid _contextGuid = Guid.Empty, _parentContextGuid = Guid.Empty;
private DateTime _eventDateTime = DateTime.MinValue;
private int _eventOrder = -1;
private object _userData = null;
private TrackingAnnotationCollection _annotations = new TrackingAnnotationCollection();
private EventArgs _args = null;
private string _key = null;
#endregion
#region Constructors
public UserTrackingRecord()
{
}
public UserTrackingRecord(Type activityType, string qualifiedName, Guid contextGuid, Guid parentContextGuid, DateTime eventDateTime, int eventOrder, string userDataKey, object userData)
{
_activityType = activityType;
_qualifiedID = qualifiedName;
_eventDateTime = eventDateTime;
_contextGuid = contextGuid;
_parentContextGuid = parentContextGuid;
_eventOrder = eventOrder;
_userData = userData;
_key = userDataKey;
}
#endregion
#region Public Properties
public string QualifiedName
{
get { return _qualifiedID; }
set { _qualifiedID = value; }
}
public Guid ContextGuid
{
get { return _contextGuid; }
set { _contextGuid = value; }
}
public Guid ParentContextGuid
{
get { return _parentContextGuid; }
set { _parentContextGuid = value; }
}
public Type ActivityType
{
get { return _activityType; }
set { _activityType = value; }
}
public IList<TrackingDataItem> Body
{
get { return _body; }
}
public string UserDataKey
{
get { return _key; }
set { _key = value; }
}
public object UserData
{
get { return _userData; }
set { _userData = value; }
}
#endregion
#region TrackingRecord
public override DateTime EventDateTime
{
get { return _eventDateTime; }
set { _eventDateTime = value; }
}
/// <summary>
/// Contains a value indicating the relative order of this event within the context of a workflow instance.
/// Value will be unique within a workflow instance but is not guaranteed to be sequential.
/// </summary>
public override int EventOrder
{
get { return _eventOrder; }
set { _eventOrder = value; }
}
public override TrackingAnnotationCollection Annotations
{
get { return _annotations; }
}
public override EventArgs EventArgs
{
get { return _args; }
set { _args = value; }
}
#endregion
}
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class WorkflowTrackingRecord : TrackingRecord
{
#region Private Data Members
private TrackingWorkflowEvent _event;
private DateTime _eventDateTime = DateTime.MinValue;
private int _eventOrder = -1;
private EventArgs _args = null;
private TrackingAnnotationCollection _annotations = new TrackingAnnotationCollection();
#endregion
#region Constructors
public WorkflowTrackingRecord()
{
}
public WorkflowTrackingRecord(TrackingWorkflowEvent trackingWorkflowEvent, DateTime eventDateTime, int eventOrder, EventArgs eventArgs)
{
_event = trackingWorkflowEvent;
_eventDateTime = eventDateTime;
_eventOrder = eventOrder;
_args = eventArgs;
}
#endregion
#region TrackingRecord
public TrackingWorkflowEvent TrackingWorkflowEvent
{
get { return _event; }
set { _event = value; }
}
public override DateTime EventDateTime
{
get { return _eventDateTime; }
set { _eventDateTime = value; }
}
/// <summary>
/// Contains a value indicating the relative order of this event within the context of a workflow instance.
/// Value will be unique within a workflow instance but is not guaranteed to be sequential.
/// </summary>
public override int EventOrder
{
get { return _eventOrder; }
set { _eventOrder = value; }
}
public override EventArgs EventArgs
{
get { return _args; }
set { _args = value; }
}
public override TrackingAnnotationCollection Annotations
{
get { return _annotations; }
}
#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.
#if XMLCHARTYPE_GEN_RESOURCE
#undef XMLCHARTYPE_USE_RESOURCE
#endif
//------------------------------------------------------------------------------
// </copyright>
//------------------------------------------------------------------------------
//#define XMLCHARTYPE_USE_RESOURCE // load the character properties from resources (XmlCharType.bin must be linked to System.Xml.dll)
//#define XMLCHARTYPE_GEN_RESOURCE // generate the character properties into XmlCharType.bin
#if XMLCHARTYPE_GEN_RESOURCE || XMLCHARTYPE_USE_RESOURCE
using System.IO;
using System.Reflection;
#endif
using System.Threading;
using System.Diagnostics;
namespace System.Xml
{
/// <internalonly/>
/// <devdoc>
/// The XmlCharType class is used for quick character type recognition
/// which is optimized for the first 127 ascii characters.
/// </devdoc>
#if XMLCHARTYPE_USE_RESOURCE
unsafe internal struct XmlCharType {
#else
internal struct XmlCharType
{
#endif
// Whitespace chars -- Section 2.3 [3]
// Letters -- Appendix B [84]
// Starting NCName characters -- Section 2.3 [5] (Starting Name characters without ':')
// NCName characters -- Section 2.3 [4] (Name characters without ':')
// Character data characters -- Section 2.2 [2]
// PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] Section 2.3 of spec
internal const int fWhitespace = 1;
internal const int fLetter = 2;
internal const int fNCStartName = 4;
internal const int fNCName = 8;
internal const int fCharData = 16;
internal const int fPublicId = 32;
internal const int fText = 64;
internal const int fAttrValue = 128;
private const uint CharPropertiesSize = (uint)char.MaxValue + 1;
#if !XMLCHARTYPE_USE_RESOURCE || XMLCHARTYPE_GEN_RESOURCE
internal const string s_Whitespace =
"\u0009\u000a\u000d\u000d\u0020\u0020";
private const string s_Letter =
"\u0041\u005a\u0061\u007a\u00c0\u00d6\u00d8\u00f6" +
"\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e" +
"\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217" +
"\u0250\u02a8\u02bb\u02c1\u0386\u0386\u0388\u038a" +
"\u038c\u038c\u038e\u03a1\u03a3\u03ce\u03d0\u03d6" +
"\u03da\u03da\u03dc\u03dc\u03de\u03de\u03e0\u03e0" +
"\u03e2\u03f3\u0401\u040c\u040e\u044f\u0451\u045c" +
"\u045e\u0481\u0490\u04c4\u04c7\u04c8\u04cb\u04cc" +
"\u04d0\u04eb\u04ee\u04f5\u04f8\u04f9\u0531\u0556" +
"\u0559\u0559\u0561\u0586\u05d0\u05ea\u05f0\u05f2" +
"\u0621\u063a\u0641\u064a\u0671\u06b7\u06ba\u06be" +
"\u06c0\u06ce\u06d0\u06d3\u06d5\u06d5\u06e5\u06e6" +
"\u0905\u0939\u093d\u093d\u0958\u0961\u0985\u098c" +
"\u098f\u0990\u0993\u09a8\u09aa\u09b0\u09b2\u09b2" +
"\u09b6\u09b9\u09dc\u09dd\u09df\u09e1\u09f0\u09f1" +
"\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28\u0a2a\u0a30" +
"\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59\u0a5c" +
"\u0a5e\u0a5e\u0a72\u0a74\u0a85\u0a8b\u0a8d\u0a8d" +
"\u0a8f\u0a91\u0a93\u0aa8\u0aaa\u0ab0\u0ab2\u0ab3" +
"\u0ab5\u0ab9\u0abd\u0abd\u0ae0\u0ae0\u0b05\u0b0c" +
"\u0b0f\u0b10\u0b13\u0b28\u0b2a\u0b30\u0b32\u0b33" +
"\u0b36\u0b39\u0b3d\u0b3d\u0b5c\u0b5d\u0b5f\u0b61" +
"\u0b85\u0b8a\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a" +
"\u0b9c\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa" +
"\u0bae\u0bb5\u0bb7\u0bb9\u0c05\u0c0c\u0c0e\u0c10" +
"\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39\u0c60\u0c61" +
"\u0c85\u0c8c\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3" +
"\u0cb5\u0cb9\u0cde\u0cde\u0ce0\u0ce1\u0d05\u0d0c" +
"\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39\u0d60\u0d61" +
"\u0e01\u0e2e\u0e30\u0e30\u0e32\u0e33\u0e40\u0e45" +
"\u0e81\u0e82\u0e84\u0e84\u0e87\u0e88\u0e8a\u0e8a" +
"\u0e8d\u0e8d\u0e94\u0e97\u0e99\u0e9f\u0ea1\u0ea3" +
"\u0ea5\u0ea5\u0ea7\u0ea7\u0eaa\u0eab\u0ead\u0eae" +
"\u0eb0\u0eb0\u0eb2\u0eb3\u0ebd\u0ebd\u0ec0\u0ec4" +
"\u0f40\u0f47\u0f49\u0f69\u10a0\u10c5\u10d0\u10f6" +
"\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109" +
"\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e" +
"\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150" +
"\u1154\u1155\u1159\u1159\u115f\u1161\u1163\u1163" +
"\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e" +
"\u1172\u1173\u1175\u1175\u119e\u119e\u11a8\u11a8" +
"\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba" +
"\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9" +
"\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d" +
"\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59" +
"\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d\u1f80\u1fb4" +
"\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc" +
"\u1fd0\u1fd3\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4" +
"\u1ff6\u1ffc\u2126\u2126\u212a\u212b\u212e\u212e" +
"\u2180\u2182\u3007\u3007\u3021\u3029\u3041\u3094" +
"\u30a1\u30fa\u3105\u312c\u4e00\u9fa5\uac00\ud7a3";
private const string s_NCStartName =
"\u0041\u005a\u005f\u005f\u0061\u007a" +
"\u00c0\u00d6\u00d8\u00f6\u00f8\u0131\u0134\u013e" +
"\u0141\u0148\u014a\u017e\u0180\u01c3\u01cd\u01f0" +
"\u01f4\u01f5\u01fa\u0217\u0250\u02a8\u02bb\u02c1" +
"\u0386\u0386\u0388\u038a\u038c\u038c\u038e\u03a1" +
"\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" +
"\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c" +
"\u040e\u044f\u0451\u045c\u045e\u0481\u0490\u04c4" +
"\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb\u04ee\u04f5" +
"\u04f8\u04f9\u0531\u0556\u0559\u0559\u0561\u0586" +
"\u05d0\u05ea\u05f0\u05f2\u0621\u063a\u0641\u064a" +
"\u0671\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3" +
"\u06d5\u06d5\u06e5\u06e6\u0905\u0939\u093d\u093d" +
"\u0958\u0961\u0985\u098c\u098f\u0990\u0993\u09a8" +
"\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9\u09dc\u09dd" +
"\u09df\u09e1\u09f0\u09f1\u0a05\u0a0a\u0a0f\u0a10" +
"\u0a13\u0a28\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36" +
"\u0a38\u0a39\u0a59\u0a5c\u0a5e\u0a5e\u0a72\u0a74" +
"\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8" +
"\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9\u0abd\u0abd" +
"\u0ae0\u0ae0\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28" +
"\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39\u0b3d\u0b3d" +
"\u0b5c\u0b5d\u0b5f\u0b61\u0b85\u0b8a\u0b8e\u0b90" +
"\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c\u0b9e\u0b9f" +
"\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5\u0bb7\u0bb9" +
"\u0c05\u0c0c\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33" +
"\u0c35\u0c39\u0c60\u0c61\u0c85\u0c8c\u0c8e\u0c90" +
"\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9\u0cde\u0cde" +
"\u0ce0\u0ce1\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28" +
"\u0d2a\u0d39\u0d60\u0d61\u0e01\u0e2e\u0e30\u0e30" +
"\u0e32\u0e33\u0e40\u0e45\u0e81\u0e82\u0e84\u0e84" +
"\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" +
"\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7" +
"\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb0\u0eb2\u0eb3" +
"\u0ebd\u0ebd\u0ec0\u0ec4\u0f40\u0f47\u0f49\u0f69" +
"\u10a0\u10c5\u10d0\u10f6\u1100\u1100\u1102\u1103" +
"\u1105\u1107\u1109\u1109\u110b\u110c\u110e\u1112" +
"\u113c\u113c\u113e\u113e\u1140\u1140\u114c\u114c" +
"\u114e\u114e\u1150\u1150\u1154\u1155\u1159\u1159" +
"\u115f\u1161\u1163\u1163\u1165\u1165\u1167\u1167" +
"\u1169\u1169\u116d\u116e\u1172\u1173\u1175\u1175" +
"\u119e\u119e\u11a8\u11a8\u11ab\u11ab\u11ae\u11af" +
"\u11b7\u11b8\u11ba\u11ba\u11bc\u11c2\u11eb\u11eb" +
"\u11f0\u11f0\u11f9\u11f9\u1e00\u1e9b\u1ea0\u1ef9" +
"\u1f00\u1f15\u1f18\u1f1d\u1f20\u1f45\u1f48\u1f4d" +
"\u1f50\u1f57\u1f59\u1f59\u1f5b\u1f5b\u1f5d\u1f5d" +
"\u1f5f\u1f7d\u1f80\u1fb4\u1fb6\u1fbc\u1fbe\u1fbe" +
"\u1fc2\u1fc4\u1fc6\u1fcc\u1fd0\u1fd3\u1fd6\u1fdb" +
"\u1fe0\u1fec\u1ff2\u1ff4\u1ff6\u1ffc\u2126\u2126" +
"\u212a\u212b\u212e\u212e\u2180\u2182\u3007\u3007" +
"\u3021\u3029\u3041\u3094\u30a1\u30fa\u3105\u312c" +
"\u4e00\u9fa5\uac00\ud7a3";
private const string s_NCName =
"\u002d\u002e\u0030\u0039\u0041\u005a\u005f\u005f" +
"\u0061\u007a\u00b7\u00b7\u00c0\u00d6\u00d8\u00f6" +
"\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e" +
"\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217" +
"\u0250\u02a8\u02bb\u02c1\u02d0\u02d1\u0300\u0345" +
"\u0360\u0361\u0386\u038a\u038c\u038c\u038e\u03a1" +
"\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" +
"\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c" +
"\u040e\u044f\u0451\u045c\u045e\u0481\u0483\u0486" +
"\u0490\u04c4\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb" +
"\u04ee\u04f5\u04f8\u04f9\u0531\u0556\u0559\u0559" +
"\u0561\u0586\u0591\u05a1\u05a3\u05b9\u05bb\u05bd" +
"\u05bf\u05bf\u05c1\u05c2\u05c4\u05c4\u05d0\u05ea" +
"\u05f0\u05f2\u0621\u063a\u0640\u0652\u0660\u0669" +
"\u0670\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3" +
"\u06d5\u06e8\u06ea\u06ed\u06f0\u06f9\u0901\u0903" +
"\u0905\u0939\u093c\u094d\u0951\u0954\u0958\u0963" +
"\u0966\u096f\u0981\u0983\u0985\u098c\u098f\u0990" +
"\u0993\u09a8\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9" +
"\u09bc\u09bc\u09be\u09c4\u09c7\u09c8\u09cb\u09cd" +
"\u09d7\u09d7\u09dc\u09dd\u09df\u09e3\u09e6\u09f1" +
"\u0a02\u0a02\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28" +
"\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39" +
"\u0a3c\u0a3c\u0a3e\u0a42\u0a47\u0a48\u0a4b\u0a4d" +
"\u0a59\u0a5c\u0a5e\u0a5e\u0a66\u0a74\u0a81\u0a83" +
"\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8" +
"\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9\u0abc\u0ac5" +
"\u0ac7\u0ac9\u0acb\u0acd\u0ae0\u0ae0\u0ae6\u0aef" +
"\u0b01\u0b03\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28" +
"\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39\u0b3c\u0b43" +
"\u0b47\u0b48\u0b4b\u0b4d\u0b56\u0b57\u0b5c\u0b5d" +
"\u0b5f\u0b61\u0b66\u0b6f\u0b82\u0b83\u0b85\u0b8a" +
"\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c" +
"\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5" +
"\u0bb7\u0bb9\u0bbe\u0bc2\u0bc6\u0bc8\u0bca\u0bcd" +
"\u0bd7\u0bd7\u0be7\u0bef\u0c01\u0c03\u0c05\u0c0c" +
"\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39" +
"\u0c3e\u0c44\u0c46\u0c48\u0c4a\u0c4d\u0c55\u0c56" +
"\u0c60\u0c61\u0c66\u0c6f\u0c82\u0c83\u0c85\u0c8c" +
"\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9" +
"\u0cbe\u0cc4\u0cc6\u0cc8\u0cca\u0ccd\u0cd5\u0cd6" +
"\u0cde\u0cde\u0ce0\u0ce1\u0ce6\u0cef\u0d02\u0d03" +
"\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39" +
"\u0d3e\u0d43\u0d46\u0d48\u0d4a\u0d4d\u0d57\u0d57" +
"\u0d60\u0d61\u0d66\u0d6f\u0e01\u0e2e\u0e30\u0e3a" +
"\u0e40\u0e4e\u0e50\u0e59\u0e81\u0e82\u0e84\u0e84" +
"\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" +
"\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7" +
"\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb9\u0ebb\u0ebd" +
"\u0ec0\u0ec4\u0ec6\u0ec6\u0ec8\u0ecd\u0ed0\u0ed9" +
"\u0f18\u0f19\u0f20\u0f29\u0f35\u0f35\u0f37\u0f37" +
"\u0f39\u0f39\u0f3e\u0f47\u0f49\u0f69\u0f71\u0f84" +
"\u0f86\u0f8b\u0f90\u0f95\u0f97\u0f97\u0f99\u0fad" +
"\u0fb1\u0fb7\u0fb9\u0fb9\u10a0\u10c5\u10d0\u10f6" +
"\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109" +
"\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e" +
"\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150" +
"\u1154\u1155\u1159\u1159\u115f\u1161\u1163\u1163" +
"\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e" +
"\u1172\u1173\u1175\u1175\u119e\u119e\u11a8\u11a8" +
"\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba" +
"\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9" +
"\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d" +
"\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59" +
"\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d\u1f80\u1fb4" +
"\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc" +
"\u1fd0\u1fd3\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4" +
"\u1ff6\u1ffc\u20d0\u20dc\u20e1\u20e1\u2126\u2126" +
"\u212a\u212b\u212e\u212e\u2180\u2182\u3005\u3005" +
"\u3007\u3007\u3021\u302f\u3031\u3035\u3041\u3094" +
"\u3099\u309a\u309d\u309e\u30a1\u30fa\u30fc\u30fe" +
"\u3105\u312c\u4e00\u9fa5\uac00\ud7a3";
private const string s_CharData =
"\u0009\u000a\u000d\u000d\u0020\ud7ff\ue000\ufffd";
private const string s_PublicID =
"\u000a\u000a\u000d\u000d\u0020\u0021\u0023\u0025" +
"\u0027\u003b\u003d\u003d\u003f\u005a\u005f\u005f" +
"\u0061\u007a";
private const string s_Text = // TextChar = CharData - { 0xA | 0xD | '<' | '&' | 0x9 | ']' | 0xDC00 - 0xDFFF }
"\u0020\u0025\u0027\u003b\u003d\u005c\u005e\ud7ff\ue000\ufffd";
private const string s_AttrValue = // AttrValueChar = CharData - { 0xA | 0xD | 0x9 | '<' | '>' | '&' | '\'' | '"' | 0xDC00 - 0xDFFF }
"\u0020\u0021\u0023\u0025\u0028\u003b\u003d\u003d\u003f\ud7ff\ue000\ufffd";
#endif
// static lock for XmlCharType class
private static object s_Lock;
private static object StaticLock
{
get
{
if (s_Lock == null)
{
object o = new object();
Interlocked.CompareExchange(ref s_Lock, o, null);
}
return s_Lock;
}
}
#if XMLCHARTYPE_USE_RESOURCE
private static byte* s_CharProperties;
internal byte* charProperties;
static void InitInstance() {
lock ( StaticLock ) {
if ( s_CharProperties != null ) {
return;
}
UnmanagedMemoryStream memStream = (UnmanagedMemoryStream)Assembly.GetExecutingAssembly().GetManifestResourceStream( "XmlCharType.bin" );
Debug.Assert( memStream.Length == CharPropertiesSize );
byte* chProps = memStream.PositionPointer;
Interlocked.MemoryBarrier(); // For weak memory models (IA64)
s_CharProperties = chProps;
}
}
#else // !XMLCHARTYPE_USE_RESOURCE
private static byte[] s_CharProperties;
internal byte[] charProperties;
private static void InitInstance()
{
lock (StaticLock)
{
if (s_CharProperties != null)
{
return;
}
byte[] chProps = new byte[CharPropertiesSize];
Interlocked.MemoryBarrier(); // For weak memory models (IA64)
SetProperties(chProps, s_Whitespace, fWhitespace);
SetProperties(chProps, s_Letter, fLetter);
SetProperties(chProps, s_NCStartName, fNCStartName);
SetProperties(chProps, s_NCName, fNCName);
SetProperties(chProps, s_CharData, fCharData);
SetProperties(chProps, s_PublicID, fPublicId);
SetProperties(chProps, s_Text, fText);
SetProperties(chProps, s_AttrValue, fAttrValue);
s_CharProperties = chProps;
}
}
private static void SetProperties(byte[] chProps, string ranges, byte value)
{
for (int p = 0; p < ranges.Length; p += 2)
{
for (int i = ranges[p], last = ranges[p + 1]; i <= last; i++)
{
chProps[i] |= value;
}
}
}
#endif
#if XMLCHARTYPE_USE_RESOURCE
private XmlCharType( byte* charProperties ) {
#else
private XmlCharType(byte[] charProperties)
{
#endif
Debug.Assert(s_CharProperties != null);
this.charProperties = charProperties;
}
internal static XmlCharType Instance
{
get
{
if (s_CharProperties == null)
{
InitInstance();
}
return new XmlCharType(s_CharProperties);
}
}
// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsWhiteSpace(char ch)
{
return (charProperties[ch] & fWhitespace) != 0;
}
// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsLetter(char ch)
{
return (charProperties[ch] & fLetter) != 0;
}
public bool IsExtender(char ch)
{
return (ch == 0xb7);
}
/// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsNCNameChar(char ch)
{
return (charProperties[ch] & fNCName) != 0;
}
// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsStartNCNameChar(char ch)
{
return (charProperties[ch] & fNCStartName) != 0;
}
// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsCharData(char ch)
{
return (charProperties[ch] & fCharData) != 0;
}
// [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] Section 2.3 of spec
// NOTE: This method will not be inlined (because it uses byte* charProperties)
public bool IsPubidChar(char ch)
{
return (charProperties[ch] & fPublicId) != 0;
}
// TextChar = CharData - { 0xA, 0xD, '<', '&', ']' }
// NOTE: This method will not be inlined (because it uses byte* charProperties)
internal bool IsTextChar(char ch)
{
return (charProperties[ch] & fText) != 0;
}
// AttrValueChar = CharData - { 0xA, 0xD, 0x9, '<', '>', '&', '\'', '"' }
// NOTE: This method will not be inlined (because it uses byte* charProperties)
internal bool IsAttributeValueChar(char ch)
{
return (charProperties[ch] & fAttrValue) != 0;
}
public bool IsNameChar(char ch)
{
return IsNCNameChar(ch) || ch == ':';
}
public bool IsStartNameChar(char ch)
{
return IsStartNCNameChar(ch) || ch == ':';
}
public bool IsDigit(char ch)
{
return (ch >= 0x30 && ch <= 0x39);
}
public bool IsHexDigit(char ch)
{
return (ch >= 0x30 && ch <= 0x39) || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F');
}
internal bool IsOnlyWhitespace(string str)
{
return IsOnlyWhitespaceWithPos(str) == -1;
}
internal int IsOnlyWhitespaceWithPos(string str)
{
if (str != null)
{
for (int i = 0; i < str.Length; i++)
{
if ((charProperties[str[i]] & fWhitespace) == 0)
{
return i;
}
}
}
return -1;
}
internal bool IsName(string str)
{
if (str.Length == 0 || !IsStartNameChar(str[0]))
{
return false;
}
for (int i = 1; i < str.Length; i++)
{
if (!IsNameChar(str[i]))
{
return false;
}
}
return true;
}
internal bool IsNmToken(string str)
{
if (str.Length == 0)
{
return false;
}
for (int i = 0; i < str.Length; i++)
{
if ((charProperties[str[i]] & fNCName) == 0 && str[i] != ':')
{
return false;
}
}
return true;
}
internal int IsOnlyCharData(string str)
{
if (str != null)
{
for (int i = 0; i < str.Length; i++)
{
if ((charProperties[str[i]] & fCharData) == 0)
{
return i;
}
}
}
return -1;
}
internal int IsPublicId(string str)
{
if (str != null)
{
for (int i = 0; i < str.Length; i++)
{
if ((charProperties[str[i]] & fPublicId) == 0)
{
return i;
}
}
}
return -1;
}
#if XMLCHARTYPE_GEN_RESOURCE
public static void Main( string[] args ) {
try {
InitInstance();
string fileName = ( args.Length == 0 ) ? "XmlCharType.bin" : args[0];
Console.Write( "Writing XmlCharType character properties to {0}...", fileName );
FileStream fs = new FileStream( fileName, FileMode.Create );
for ( int i = 0; i < CharPropertiesSize; i += 4096 ) {
fs.Write( s_CharProperties, i, 4096 );
}
fs.Close();
Console.WriteLine( "done." );
}
catch ( Exception e ) {
Console.WriteLine();
Console.WriteLine( "Exception: {0}", e.Message );
}
}
#endif
}
}
| |
//***************************************************
//* This file was generated by tool
//* SharpKit
//* At: 29/08/2012 03:59:41 p.m.
//***************************************************
using SharpKit.JavaScript;
namespace Ext.grid.property
{
#region Grid
/// <inheritdocs />
/// <summary>
/// <p>A specialized grid implementation intended to mimic the traditional property grid as typically seen in
/// development IDEs. Each row in the grid represents a property of some object, and the data is stored
/// as a set of name/value pairs in <see cref="Ext.grid.property.Property">Properties</see>. Example usage:</p>
/// <pre><code><see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.grid.property.Grid">Ext.grid.property.Grid</see>', {
/// title: 'Properties Grid',
/// width: 300,
/// renderTo: <see cref="Ext.ExtContext.getBody">Ext.getBody</see>(),
/// source: {
/// "(name)": "My Object",
/// "Created": <see cref="Ext.Date.parse">Ext.Date.parse</see>('10/15/2006', 'm/d/Y'),
/// "Available": false,
/// "Version": 0.01,
/// "Description": "A test object"
/// }
/// });
/// </code></pre>
/// </summary>
[JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)]
public partial class Grid : Ext.grid.Panel
{
/// <summary>
/// An object containing name/value pairs of custom editor type definitions that allow
/// the grid to support additional types of editable fields. By default, the grid supports strongly-typed editing
/// of strings, dates, numbers and booleans using built-in form editors, but any custom type can be supported and
/// associated with a custom input control by specifying a custom editor. The name of the editor
/// type should correspond with the name of the property that will use the editor. Example usage:
/// <code>var grid = new <see cref="Ext.grid.property.Grid">Ext.grid.property.Grid</see>({
/// // Custom editors for certain property names
/// customEditors: {
/// evtStart: <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.form.field.Time">Ext.form.TimeField</see>', {selectOnFocus: true})
/// },
/// // Displayed name for property names in the source
/// propertyNames: {
/// evtStart: 'Start Time'
/// },
/// // Data object containing properties to edit
/// source: {
/// evtStart: '10:00 AM'
/// }
/// });
/// </code>
/// </summary>
public JsObject customEditors;
/// <summary>
/// An object containing name/value pairs of custom renderer type definitions that allow
/// the grid to support custom rendering of fields. By default, the grid supports strongly-typed rendering
/// of strings, dates, numbers and booleans using built-in form editors, but any custom type can be supported and
/// associated with the type of the value. The name of the renderer type should correspond with the name of the property
/// that it will render. Example usage:
/// <code>var grid = <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.grid.property.Grid">Ext.grid.property.Grid</see>', {
/// customRenderers: {
/// Available: function(v){
/// if (v) {
/// return '<span style="color: green;">Yes</span>';
/// } else {
/// return '<span style="color: red;">No</span>';
/// }
/// }
/// },
/// source: {
/// Available: true
/// }
/// });
/// </code>
/// </summary>
public JsObject customRenderers;
/// <summary>
/// Specify the width for the name column. The value column will take any remaining space.
/// Defaults to: <c>115</c>
/// </summary>
public JsNumber nameColumnWidth;
/// <summary>
/// The name of the field from the property store to use as the property field name.
/// This may be useful if you do not configure the property Grid from an object, but use your own store configuration.
/// Defaults to: <c>"name"</c>
/// </summary>
public JsString nameField;
/// <summary>
/// An object containing custom property name/display name pairs.
/// If specified, the display name will be shown in the name column instead of the property name.
/// </summary>
public JsObject propertyNames;
/// <summary>
/// A data object to use as the data source of the grid (see setSource for details).
/// </summary>
public JsObject source;
/// <summary>
/// The name of the field from the property store to use as the value field name.
/// This may be useful if you do not configure the property Grid from an object, but use your own store configuration.
/// Defaults to: <c>"value"</c>
/// </summary>
public JsString valueField;
/// <summary>
/// Gets the source data object containing the property data. See setSource for details regarding the
/// format of the data object.
/// </summary>
/// <returns>
/// <span><see cref="Object">Object</see></span><div><p>The data object</p>
/// </div>
/// </returns>
public object getSource(){return null;}
/// <summary>
/// Removes a property from the grid.
/// </summary>
/// <param name="prop"><p>The name of the property to remove</p>
/// </param>
public void removeProperty(JsString prop){}
/// <summary>
/// Sets the value of a property.
/// </summary>
/// <param name="prop"><p>The name of the property to set</p>
/// </param>
/// <param name="value"><p>The value to test</p>
/// </param>
/// <param name="create"><p>True to create the property if it doesn't already exist.</p>
/// <p>Defaults to: <c>false</c></p></param>
public void setProperty(JsString prop, object value, object create=null){}
/// <summary>
/// Sets the source data object containing the property data. The data object can contain one or more name/value
/// pairs representing all of the properties of an object to display in the grid, and this data will automatically
/// be loaded into the grid's store. The values should be supplied in the proper data type if needed,
/// otherwise string type will be assumed. If the grid already contains data, this method will replace any
/// existing data. See also the source config value. Example usage:
/// <code>grid.setSource({
/// "(name)": "My Object",
/// "Created": <see cref="Ext.Date.parse">Ext.Date.parse</see>('10/15/2006', 'm/d/Y'), // date type
/// "Available": false, // boolean type
/// "Version": .01, // decimal type
/// "Description": "A test object"
/// });
/// </code>
/// </summary>
/// <param name="source"><p>The data object</p>
/// </param>
public void setSource(object source){}
public Grid(GridConfig config){}
public Grid(){}
public Grid(params object[] args){}
}
#endregion
#region GridConfig
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class GridConfig : Ext.grid.PanelConfig
{
/// <summary>
/// An object containing name/value pairs of custom editor type definitions that allow
/// the grid to support additional types of editable fields. By default, the grid supports strongly-typed editing
/// of strings, dates, numbers and booleans using built-in form editors, but any custom type can be supported and
/// associated with a custom input control by specifying a custom editor. The name of the editor
/// type should correspond with the name of the property that will use the editor. Example usage:
/// <code>var grid = new <see cref="Ext.grid.property.Grid">Ext.grid.property.Grid</see>({
/// // Custom editors for certain property names
/// customEditors: {
/// evtStart: <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.form.field.Time">Ext.form.TimeField</see>', {selectOnFocus: true})
/// },
/// // Displayed name for property names in the source
/// propertyNames: {
/// evtStart: 'Start Time'
/// },
/// // Data object containing properties to edit
/// source: {
/// evtStart: '10:00 AM'
/// }
/// });
/// </code>
/// </summary>
public JsObject customEditors;
/// <summary>
/// An object containing name/value pairs of custom renderer type definitions that allow
/// the grid to support custom rendering of fields. By default, the grid supports strongly-typed rendering
/// of strings, dates, numbers and booleans using built-in form editors, but any custom type can be supported and
/// associated with the type of the value. The name of the renderer type should correspond with the name of the property
/// that it will render. Example usage:
/// <code>var grid = <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.grid.property.Grid">Ext.grid.property.Grid</see>', {
/// customRenderers: {
/// Available: function(v){
/// if (v) {
/// return '<span style="color: green;">Yes</span>';
/// } else {
/// return '<span style="color: red;">No</span>';
/// }
/// }
/// },
/// source: {
/// Available: true
/// }
/// });
/// </code>
/// </summary>
public JsObject customRenderers;
/// <summary>
/// Specify the width for the name column. The value column will take any remaining space.
/// Defaults to: <c>115</c>
/// </summary>
public JsNumber nameColumnWidth;
/// <summary>
/// The name of the field from the property store to use as the property field name.
/// This may be useful if you do not configure the property Grid from an object, but use your own store configuration.
/// Defaults to: <c>"name"</c>
/// </summary>
public JsString nameField;
/// <summary>
/// An object containing custom property name/display name pairs.
/// If specified, the display name will be shown in the name column instead of the property name.
/// </summary>
public JsObject propertyNames;
/// <summary>
/// A data object to use as the data source of the grid (see setSource for details).
/// </summary>
public JsObject source;
/// <summary>
/// The name of the field from the property store to use as the value field name.
/// This may be useful if you do not configure the property Grid from an object, but use your own store configuration.
/// Defaults to: <c>"value"</c>
/// </summary>
public JsString valueField;
public GridConfig(params object[] args){}
}
#endregion
#region GridEvents
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class GridEvents : Ext.grid.PanelEvents
{
/// <summary>
/// Fires before a property value changes. Handlers can return false to cancel the property change
/// (this will internally call Ext.data.Model.reject on the property's record).
/// </summary>
/// <param name="source"><p>The source data object for the grid (corresponds to the same object passed in
/// as the <see cref="Ext.grid.GridConfig.source">source</see> config property).</p>
/// </param>
/// <param name="recordId"><p>The record's id in the data store</p>
/// </param>
/// <param name="value"><p>The current edited property value</p>
/// </param>
/// <param name="oldValue"><p>The original property value prior to editing</p>
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void beforepropertychange(object source, JsString recordId, object value, object oldValue, object eOpts){}
/// <summary>
/// Fires after a property value has changed.
/// </summary>
/// <param name="source"><p>The source data object for the grid (corresponds to the same object passed in
/// as the <see cref="Ext.grid.GridConfig.source">source</see> config property).</p>
/// </param>
/// <param name="recordId"><p>The record's id in the data store</p>
/// </param>
/// <param name="value"><p>The current edited property value</p>
/// </param>
/// <param name="oldValue"><p>The original property value prior to editing</p>
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void propertychange(object source, JsString recordId, object value, object oldValue, object eOpts){}
public GridEvents(params object[] args){}
}
#endregion
}
| |
using NUnit.Framework;
using System.Linq;
using System;
using System.Collections.Generic;
using Xamarin.Forms.Core.UnitTests;
namespace Xamarin.Forms.Xaml.UnitTests
{
[ContentProperty ("Content")]
public class CustomView : View
{
public string NotBindable { get; set; }
public View Content { get; set; }
public MockFlags MockFlags { get; set; }
}
[ContentProperty ("Children")]
public class ViewWithChildrenContent : View
{
public ViewWithChildrenContent ()
{
Children = DefaultChildren = new ViewList ();
}
public ViewList DefaultChildren;
public ViewList Children { get; set; }
}
public class ViewList : List<View>
{
}
public class ReverseConverter : IValueConverter
{
public static ReverseConverter Instance = new ReverseConverter ();
public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var s = value as string;
if (s == null)
return value;
return new string (s.Reverse ().ToArray ());
}
public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var s = value as string;
if (s == null)
return value;
return new string (s.Reverse ().ToArray ());
}
}
public class Catalog
{
public static readonly BindableProperty MessageProperty =
#pragma warning disable 618
BindableProperty.CreateAttached<Catalog, string> (bindable => GetMessage (bindable), default(string),
#pragma warning restore 618
propertyChanged: (bindable, oldvalue, newvalue) => {
var label = bindable as Label;
if (label != null)
label.SetValue (Label.TextProperty, new string (newvalue.Reverse ().ToArray ()));
});
public static string GetMessage (BindableObject bindable)
{
return (string)bindable.GetValue (MessageProperty);
}
public static void SetMessage (BindableObject bindable, string value)
{
bindable.SetValue (MessageProperty, value);
}
}
[Flags]
public enum MockFlags
{
Foo = 1<<0,
Bar = 1<<1,
Baz = 1<<2,
Qux = 1<<3,
}
[TestFixture]
public class LoaderTests : BaseTestFixture
{
[Test]
public void TestRootName ()
{
var xaml = @"
<View
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
x:Class=""Xamarin.Forms.Xaml.UnitTests.CustomView""
x:Name=""customView""
/>";
var view = new CustomView ();
view.LoadFromXaml (xaml);
Assert.AreSame (view, ((Forms.Internals.INameScope)view).FindByName("customView"));
}
[Test]
public void TestFindByXName ()
{
var xaml = @"
<StackLayout
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
<StackLayout.Children>
<Label x:Name=""label0"" Text=""Foo""/>
</StackLayout.Children>
</StackLayout>";
var stacklayout = new StackLayout ();
stacklayout.LoadFromXaml (xaml);
var label = stacklayout.FindByName<Label> ("label0");
Assert.NotNull (label);
Assert.AreEqual ("Foo", label.Text);
}
[Test]
public void TestUnknownPropertyShouldThrow ()
{
var xaml = @"
<Label
xmlns=""http://xamarin.com/schemas/2014/forms""
Text=""Foo""
UnknownProperty=""Bar""
/>";
var label = new Label ();
Assert.Throws (new XamlParseExceptionConstraint (5, 5), () => label.LoadFromXaml (xaml));
}
[Test]
public void TestSetValueToBindableProperty ()
{
var xaml = @"
<Label
xmlns=""http://xamarin.com/schemas/2014/forms""
Text=""Foo""
/>";
var label = new Label ();
label.LoadFromXaml (xaml);
Assert.AreEqual ("Foo", label.Text);
}
[Test]
public void TestSetBindingToBindableProperty ()
{
var xaml = @"
<Label
xmlns=""http://xamarin.com/schemas/2014/forms""
Text=""{Binding Path=labeltext}""
/>";
var label = new Label ();
label.LoadFromXaml (xaml);
Assert.AreEqual (Label.TextProperty.DefaultValue, label.Text);
label.BindingContext = new {labeltext="Foo"};
Assert.AreEqual ("Foo", label.Text);
}
[Test]
public void TestBindingAsElement ()
{
var xaml = @"
<Label
xmlns=""http://xamarin.com/schemas/2014/forms"">
<Label.Text>
<Binding Path=""labeltext""/>
</Label.Text>
</Label>";
var label = new Label ();
label.LoadFromXaml (xaml);
Assert.AreEqual (Label.TextProperty.DefaultValue, label.Text);
label.BindingContext = new {labeltext="Foo"};
Assert.AreEqual ("Foo", label.Text);
}
[Test]
public void TestSetBindingToNonBindablePropertyShouldThrow ()
{
var xaml = @"
<View
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
x:Class=""Xamarin.Forms.Xaml.UnitTests.CustomView""
Name=""customView""
NotBindable=""{Binding text}""
/>";
var view = new CustomView ();
Assert.Throws (new XamlParseExceptionConstraint (6, 5), () => view.LoadFromXaml (xaml));
}
[Test]
public void TestBindingPath ()
{
var xaml = @"
<StackLayout
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
<StackLayout.Children>
<Label x:Name=""label0"" Text=""{Binding text}""/>
<Label x:Name=""label1"" Text=""{Binding Path=text}""/>
</StackLayout.Children>
</StackLayout>";
var stacklayout = new StackLayout ();
stacklayout.LoadFromXaml (xaml);
var label0 = stacklayout.FindByName<Label> ("label0");
var label1 = stacklayout.FindByName<Label> ("label1");
Assert.AreEqual (Label.TextProperty.DefaultValue, label0.Text);
Assert.AreEqual (Label.TextProperty.DefaultValue, label1.Text);
stacklayout.BindingContext = new {text = "Foo"};
Assert.AreEqual ("Foo", label0.Text);
Assert.AreEqual ("Foo", label1.Text);
}
class ViewModel
{
public string Text { get; set; }
}
[Test]
public void TestBindingModeAndConverter ()
{
var xaml = @"
<ContentPage
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:local=""clr-namespace:Xamarin.Forms.Xaml.UnitTests;assembly=Xamarin.Forms.Xaml.UnitTests"">
<ContentPage.Resources>
<ResourceDictionary>
<local:ReverseConverter x:Key=""reverseConverter""/>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout Orientation=""Vertical"">
<StackLayout.Children>
<Label x:Name=""label0"" Text=""{Binding Text, Converter={StaticResource reverseConverter}}""/>
<Label x:Name=""label1"" Text=""{Binding Text, Mode=TwoWay}""/>
</StackLayout.Children>
</StackLayout>
</ContentPage.Content>
</ContentPage>";
var contentPage = new ContentPage ();
contentPage.LoadFromXaml (xaml);
contentPage.BindingContext = new ViewModel { Text = "foobar" };
var label0 = contentPage.FindByName<Label> ("label0");
var label1 = contentPage.FindByName<Label> ("label1");
Assert.AreEqual ("raboof", label0.Text);
label1.Text = "baz";
Assert.AreEqual ("baz", ((ViewModel)(contentPage.BindingContext)).Text);
}
[Test]
public void TestNonEmptyCollectionMembers ()
{
var xaml = @"
<StackLayout
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
<StackLayout.Children>
<Grid x:Name=""grid0"">
</Grid>
<Grid x:Name=""grid1"">
</Grid>
</StackLayout.Children>
</StackLayout>";
var stacklayout = new StackLayout ();
stacklayout.LoadFromXaml (xaml);
var grid0 = stacklayout.FindByName<Grid> ("grid0");
var grid1 = stacklayout.FindByName<Grid> ("grid1");
Assert.NotNull (grid0);
Assert.NotNull (grid1);
}
[Test]
public void TestUnknownType ()
{
var xaml = @"
<StackLayout
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
<StackLayout.Children>
<CustomView />
</StackLayout.Children>
</StackLayout>";
var stacklayout = new StackLayout ();
Assert.Throws (new XamlParseExceptionConstraint (6, 8), () => stacklayout.LoadFromXaml (xaml));
}
[Test]
public void TestResources ()
{
var xaml = @"
<Label
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:local=""clr-namespace:Xamarin.Forms.Xaml.UnitTests;assembly=Xamarin.Forms.Xaml.UnitTests"">
<Label.Resources>
<ResourceDictionary>
<local:ReverseConverter x:Key=""reverseConverter""/>
</ResourceDictionary>
</Label.Resources>
</Label>";
var label = new Label ().LoadFromXaml (xaml);
Assert.NotNull (label.Resources);
Assert.True (label.Resources.ContainsKey ("reverseConverter"));
Assert.True (label.Resources ["reverseConverter"] is ReverseConverter);
}
[Test]
public void TestResourceDoesRequireKey ()
{
var xaml = @"
<Label
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:local=""clr-namespace:Xamarin.Forms.Xaml.UnitTests;assembly=Xamarin.Forms.Xaml.UnitTests"">
<Label.Resources>
<ResourceDictionary>
<local:ReverseConverter />
</ResourceDictionary>
</Label.Resources>
</Label>";
var label = new Label ();
Assert.Throws (new XamlParseExceptionConstraint (8, 9), () => label.LoadFromXaml (xaml));
}
[Test]
public void UseResourcesOutsideOfBinding ()
{
var xaml = @"
<ContentView
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
<ContentView.Resources>
<ResourceDictionary>
<Label Text=""Foo"" x:Key=""bar""/>
</ResourceDictionary>
</ContentView.Resources>
<ContentView.Content>
<ContentView Content=""{StaticResource bar}""/>
</ContentView.Content>
</ContentView>";
var contentView = new ContentView ().LoadFromXaml (xaml);
Assert.AreEqual ("Foo", (((ContentView)(contentView.Content)).Content as Label).Text);
}
[Test]
public void MissingStaticResourceShouldThrow ()
{
var xaml = @"<Label Text=""{StaticResource foo}""/>";
var label = new Label ();
Assert.Throws (new XamlParseExceptionConstraint (1, 8), () => label.LoadFromXaml (xaml));
}
public class CustView : Button
{
public bool fired = false;
public void onButtonClicked (object sender, EventArgs e)
{
fired = true;
}
public void wrongSignature (bool a, string b)
{
}
}
class MyApp : Application
{
public MyApp ()
{
Resources = new ResourceDictionary {
{"foo", "FOO"},
{"bar", "BAR"}
};
}
}
[Test]
public void StaticResourceLookForApplicationResources ()
{
Device.PlatformServices = new MockPlatformServices ();
Application.Current = null;
Application.Current = new MyApp ();
var xaml = @"
<ContentView
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
<ContentView.Resources>
<ResourceDictionary>
<x:String x:Key=""bar"">BAZ</x:String>
</ResourceDictionary>
</ContentView.Resources>
<StackLayout>
<Label x:Name=""label0"" Text=""{StaticResource foo}""/>
<Label x:Name=""label1"" Text=""{StaticResource bar}""/>
</StackLayout>
</ContentView>";
var layout = new ContentView ().LoadFromXaml (xaml);
var label0 = layout.FindByName<Label> ("label0");
var label1 = layout.FindByName<Label> ("label1");
//resource from App.Resources
Assert.AreEqual ("FOO", label0.Text);
//local resources have precedence
Assert.AreEqual ("BAZ", label1.Text);
}
[Test]
public void TestEvent ()
{
var xaml = @"
<Button
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
x:Class=""Xamarin.Forms.Xaml.UnitTests.CustView"" Clicked=""onButtonClicked"" />
</Button>";
var view = new CustView ();
view.LoadFromXaml (xaml);
Assert.False (view.fired);
((IButtonController) view).SendClicked ();
Assert.True (view.fired);
}
[Test]
public void TestFailingEvent ()
{
var xaml = @"
<View
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
x:Class=""Xamarin.Forms.Xaml.UnitTests.CustView"" Activated=""missingMethod"" />
</View>";
var view = new CustView ();
Assert.Throws (new XamlParseExceptionConstraint (5, 53), () => view.LoadFromXaml (xaml));
}
[Test]
public void TestConnectingEventOnMethodWithWrongSignature ()
{
var xaml = @"
<View
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
x:Class=""Xamarin.Forms.Xaml.UnitTests.CustView"" Activated=""wrongSignature"" />
</View>";
var view = new CustView ();
Assert.Throws (new XamlParseExceptionConstraint (5, 53), () => view.LoadFromXaml (xaml));
}
public class CustEntry : Entry
{
public bool fired = false;
public void onValueChanged (object sender, TextChangedEventArgs e)
{
fired = true;
}
}
[Test]
public void TestEventWithCustomEventArgs ()
{
var xaml = @"
<Entry
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
x:Class=""Xamarin.Forms.Xaml.UnitTests.CustEntry"" TextChanged=""onValueChanged"" />
</Entry>";
new CustEntry ().LoadFromXaml (xaml);
}
[Test]
public void TestEmptyTemplate ()
{
var xaml = @"
<ContentPage
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
<ContentPage.Resources>
<ResourceDictionary>
<DataTemplate x:Key=""datatemplate""/>
</ResourceDictionary>
</ContentPage.Resources>
</ContentPage>";
var page = new ContentPage ();
page.LoadFromXaml (xaml);
var template = page.Resources["datatemplate"]as Forms.DataTemplate;
Assert.Throws<InvalidOperationException>(() => template.CreateContent());
}
[Test]
public void TestBoolValue ()
{
var xaml = @"
<Image
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
IsOpaque=""true""/>";
var image = new Image ();
Assert.AreEqual (Image.IsOpaqueProperty.DefaultValue, image.IsOpaque);
image.LoadFromXaml (xaml);
Assert.AreEqual (true, image.IsOpaque);
}
[Test]
public void TestAttachedBP ()
{
var xaml = @"
<View
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
Grid.Column=""1"">
<Grid.Row>2</Grid.Row>
</View>";
var view = new View ().LoadFromXaml (xaml);
Assert.AreEqual (1, Grid.GetColumn (view));
Assert.AreEqual (2, Grid.GetRow (view));
}
[Test]
public void TestAttachedBPWithDifferentNS ()
{
//If this looks very similar to Vernacular, well... it's on purpose :)
var xaml = @"
<Label
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:local=""clr-namespace:Xamarin.Forms.Xaml.UnitTests;assembly=Xamarin.Forms.Xaml.UnitTests""
local:Catalog.Message=""foobar""/>";
var label = new Label ().LoadFromXaml (xaml);
Assert.AreEqual ("raboof", label.Text);
}
[Test]
public void TestBindOnAttachedBP ()
{
var xaml = @"
<Label
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:local=""clr-namespace:Xamarin.Forms.Xaml.UnitTests;assembly=Xamarin.Forms.Xaml.UnitTests""
local:Catalog.Message=""{Binding .}""/>";
var label = new Label ().LoadFromXaml (xaml);
label.BindingContext = "foobar";
Assert.AreEqual ("raboof", label.Text);
}
[Test]
public void TestContentProperties ()
{
var xaml = @"
<local:CustomView
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:local=""clr-namespace:Xamarin.Forms.Xaml.UnitTests;assembly=Xamarin.Forms.Xaml.UnitTests"" >
<Label x:Name=""contentview""/>
</local:CustomView>";
CustomView customView = null;
Assert.DoesNotThrow(()=> customView = new CustomView ().LoadFromXaml (xaml));
Assert.NotNull (customView.Content);
Assert.AreSame (customView.Content, ((Forms.Internals.INameScope)customView).FindByName("contentview"));
}
[Test]
public void TestCollectionContentProperties ()
{
var xaml = @"
<StackLayout>
<Label Text=""Foo""/>
<Label Text=""Bar""/>
</StackLayout>";
var layout = new StackLayout ().LoadFromXaml (xaml);
Assert.AreEqual (2, layout.Children.Count);
Assert.AreEqual ("Foo", ((Label)(layout.Children [0])).Text);
Assert.AreEqual ("Bar", ((Label)(layout.Children [1])).Text);
}
[Test]
public void TestCollectionContentPropertiesWithSingleElement ()
{
var xaml = @"
<StackLayout>
<Label Text=""Foo""/>
</StackLayout>";
var layout = new StackLayout ().LoadFromXaml (xaml);
Assert.AreEqual (1, layout.Children.Count);
Assert.AreEqual ("Foo", ((Label)(layout.Children [0])).Text);
}
[Test]
public void TestPropertiesWithContentProperties ()
{
var xaml = @"
<ContentPage
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
<Grid.Row>1</Grid.Row>
<Label Text=""foo""></Label>
</ContentPage>";
var contentPage = new ContentPage ().LoadFromXaml (xaml);
Assert.AreEqual (1, Grid.GetRow (contentPage));
Assert.NotNull (contentPage.Content);
}
[Test]
public void LoadFromXamlResource ()
{
ContentView view = null;
Assert.DoesNotThrow (() => view = new CustomXamlView ());
Assert.NotNull (view);
Assert.That (view.Content, Is.TypeOf<Label> ());
Assert.AreEqual ("foobar", ((Label)view.Content).Text);
}
[Test]
public void ThrowOnMissingXamlResource ()
{
var view = new CustomView ();
Assert.Throws (new XamlParseExceptionConstraint (), () => view.LoadFromXaml (typeof(CustomView)));
}
[Test]
public void CreateNewChildrenCollection ()
{
var xaml = @"
<local:ViewWithChildrenContent
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:local=""clr-namespace:Xamarin.Forms.Xaml.UnitTests;assembly=Xamarin.Forms.Xaml.UnitTests"" >
<local:ViewWithChildrenContent.Children>
<local:ViewList>
<Label x:Name=""child0""/>
<Label x:Name=""child1""/>
</local:ViewList>
</local:ViewWithChildrenContent.Children>
</local:ViewWithChildrenContent>";
ViewWithChildrenContent layout = null;
Assert.DoesNotThrow (() => layout = new ViewWithChildrenContent ().LoadFromXaml (xaml));
Assert.IsNotNull (layout);
Assert.AreNotSame (layout.DefaultChildren, layout.Children);
Assert.Contains (((Forms.Internals.INameScope)layout).FindByName ("child0"), layout.Children);
Assert.Contains (((Forms.Internals.INameScope)layout).FindByName ("child1"), layout.Children);
}
[Test]
public void AddChildrenToCollectionContentProperty ()
{
var xaml = @"
<local:ViewWithChildrenContent
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:local=""clr-namespace:Xamarin.Forms.Xaml.UnitTests;assembly=Xamarin.Forms.Xaml.UnitTests"" >
<Label x:Name=""child0""/>
<Label x:Name=""child1""/>
</local:ViewWithChildrenContent>";
ViewWithChildrenContent layout = null;
Assert.DoesNotThrow (() => layout = new ViewWithChildrenContent ().LoadFromXaml (xaml));
Assert.IsNotNull (layout);
Assert.AreSame (layout.DefaultChildren, layout.Children);
Assert.Contains (((Forms.Internals.INameScope)layout).FindByName ("child0"), layout.Children);
Assert.Contains (((Forms.Internals.INameScope)layout).FindByName ("child1"), layout.Children);
}
[Test]
public void AddChildrenToExistingCollection ()
{
var xaml = @"
<local:ViewWithChildrenContent
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:local=""clr-namespace:Xamarin.Forms.Xaml.UnitTests;assembly=Xamarin.Forms.Xaml.UnitTests"" >
<local:ViewWithChildrenContent.Children>
<Label x:Name=""child0""/>
<Label x:Name=""child1""/>
</local:ViewWithChildrenContent.Children>
</local:ViewWithChildrenContent>";
ViewWithChildrenContent layout = null;
Assert.DoesNotThrow (() => layout = new ViewWithChildrenContent ().LoadFromXaml (xaml));
Assert.IsNotNull (layout);
Assert.AreSame (layout.DefaultChildren, layout.Children);
Assert.Contains (((Forms.Internals.INameScope)layout).FindByName ("child0"), layout.Children);
Assert.Contains (((Forms.Internals.INameScope)layout).FindByName ("child1"), layout.Children);
}
[Test]
public void AddSingleChildToCollectionContentProperty ()
{
var xaml = @"
<local:ViewWithChildrenContent
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:local=""clr-namespace:Xamarin.Forms.Xaml.UnitTests;assembly=Xamarin.Forms.Xaml.UnitTests"" >
<Label x:Name=""child0""/>
</local:ViewWithChildrenContent>";
ViewWithChildrenContent layout = null;
Assert.DoesNotThrow (() => layout = new ViewWithChildrenContent ().LoadFromXaml (xaml));
Assert.IsNotNull (layout);
Assert.AreSame (layout.DefaultChildren, layout.Children);
Assert.Contains (((Forms.Internals.INameScope)layout).FindByName ("child0"), layout.Children);
}
[Test]
public void FindResourceByName ()
{
var xaml = @"
<ContentPage
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
x:Class=""Resources"">
<ContentPage.Resources>
<ResourceDictionary>
<Button x:Key=""buttonKey"" x:Name=""buttonName""/>
</ResourceDictionary>
</ContentPage.Resources>
<Label x:Name=""label""/>
</ContentPage>";
var layout = new ContentPage ().LoadFromXaml (xaml);
Assert.True (layout.Resources.ContainsKey ("buttonKey"));
var resource = layout.FindByName<Button> ("buttonName");
Assert.NotNull (resource);
Assert.That (resource, Is.TypeOf<Button> ());
}
[Test]
public void ParseEnum ()
{
var xaml = @"
<local:CustomView
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:local=""clr-namespace:Xamarin.Forms.Xaml.UnitTests;assembly=Xamarin.Forms.Xaml.UnitTests""
MockFlags=""Bar""
/>";
var view = new CustomView ().LoadFromXaml (xaml);
Assert.AreEqual (MockFlags.Bar, view.MockFlags);
}
[Test]
public void ParseFlags ()
{
var xaml = @"
<local:CustomView
xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:local=""clr-namespace:Xamarin.Forms.Xaml.UnitTests;assembly=Xamarin.Forms.Xaml.UnitTests""
MockFlags=""Baz,Bar""
/>";
var view = new CustomView ().LoadFromXaml (xaml);
Assert.AreEqual (MockFlags.Bar | MockFlags.Baz, view.MockFlags);
}
[Test]
public void StyleWithoutTargetTypeThrows ()
{
var xaml = @"
<Label>
<Label.Style>
<Style>
<Setter Property=""Text"" Value=""Foo"" />
</Style>
</Label.Style>
</Label>";
var label = new Label ();
Assert.Throws (new XamlParseExceptionConstraint (4, 8), () => label.LoadFromXaml (xaml));
}
}
}
| |
using System.Web;
using System.Web.SessionState;
//===============================================================================
//
// Business Logic Layer
//
// Rainbow.Framework.BLL.Utils
//
// Classes to Manage the User Web Collection
//
//===============================================================================
// Created By : bja@reedtek.com Date: 26/04/2003
//===============================================================================
namespace Rainbow.Framework.BLL.Utils
{
/// <summary>
/// Define the Web Bag Interface as the
/// repository for temporary data
/// </summary>
public interface IWebBagHolder
{
// attributes to get and set stored values
// name-value pairs
#region Attributes
/// <summary>
/// Get/Set values from integer key
/// </summary>
/// <value></value>
object this[int index]
{
get;
set;
}
/// <summary>
/// Get/Set values from string key
/// </summary>
/// <value></value>
object this[string index]
{
get;
set;
}
#endregion
} // end of IWebBagHolder
//
// These are the current concrete bag holders for the data.
//
//
#region Cookie Bag
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// This class utilizes cookies to store the data
/// Encryption was not added though and may not be complete
/// </summary>
/// /////////////////////////////////////////////////////////////////////////
public class CookieBag : IWebBagHolder
{
/// <summary>
/// Initializes the <see cref="CookieBag"/> class.
/// </summary>
static CookieBag()
{
}
/// <summary>
/// Default property for accessing resources
/// <param name="index">
/// Index for the desired resource</param>
/// <returns>
/// Resource string value</returns>
/// </summary>
/// <value></value>
public object this[int index]
{
get
{
HttpCookie cookie = (HttpCookie)CookieUtil.Retrieve(index);
if (cookie != null)
return cookie.Value;
return null;
}
set
{
lock (this)
{
CookieUtil.Add(index, value);
}
}
} // endof this[string]
/// <summary>
/// Get Data Value
/// </summary>
/// <value></value>
public object this[string index]
{
get
{
HttpCookie cookie = (HttpCookie)CookieUtil.Retrieve(index);
if (cookie != null)
return cookie.Value;
return null;
}
set
{
lock (this)
{
CookieUtil.Add(index, value);
}
}
} // endof this[int]
} // end of cookiebag
#endregion
#region Session Bag
/////////////////////////////////////////////////////////////////////////
///
/// <summary>
/// The Session bag will attempt to use server-side Session Mgmt. However
/// in the event session is disabled fallback to cookies; otherwise, fallback
/// to the database :(
/// </summary>
//////////////////////////////////////////////////////////////////////////
public class SessionBag : IWebBagHolder
{
/// <summary>
/// Initializes the <see cref="SessionBag"/> class.
/// </summary>
static SessionBag()
{
}
/// <summary>
/// Default property for accessing resources
/// <param name="index">
/// Index for the desired resource</param>
/// <returns>
/// Resource string value</returns>
/// </summary>
/// <value></value>
public object this[int index]
{
get
{
object obj = null;
try
{
// session state enabled
if (HttpContext.Current.Session != null)
obj = HttpContext.Current.Session[index];
}
catch
{
obj = null;
}
return obj;
}
set
{
try
{
// session state enabled
if (HttpContext.Current.Session != null)
HttpContext.Current.Session[index] = value;
}
catch
{
}
}
}
/// <summary>
/// get data back
/// </summary>
/// <value></value>
public object this[string index]
{
get
{
object obj = null;
try
{
// session state enabled
if (HttpContext.Current.Session != null)
obj = HttpContext.Current.Session[index];
}
catch
{
obj = null;
}
return obj;
}
set
{
try
{
// session state enabled
if (HttpContext.Current.Session != null)
HttpContext.Current.Session[index] = value;
}
catch
{
}
}
}
} // end of SessionBag
#endregion
#region Application Bag
/////////////////////////////////////////////////////////////////////////
/// <summary>
/// The Application bag will attempt to use server-side Application Mgmt.
/// This is the fallback. The database could also be a fallback as well
/// but then anonnymous user information would be logged there as well which
/// I don't you would want
/// </summary>
/////////////////////////////////////////////////////////////////////////
public class ApplicationBag : IWebBagHolder
{
/// <summary>
/// Initializes the <see cref="ApplicationBag"/> class.
/// </summary>
static ApplicationBag()
{
}
/// <summary>
/// Default property for accessing resources
/// <param name="index">
/// Index for the desired resource</param>
/// <returns>
/// Resource string value</returns>
/// </summary>
/// <value></value>
public object this[int index]
{
get
{
return HttpContext.Current.Application.Get(index);
}
set
{
HttpContext.Current.Application.Lock();
HttpContext.Current.Application.Add(index.ToString(), value);
HttpContext.Current.Application.UnLock();
}
}
/// <summary>
/// Get data value
/// </summary>
/// <value></value>
public object this[string index]
{
get
{
return HttpContext.Current.Application.Get(index);
}
set
{
HttpContext.Current.Application.Lock();
HttpContext.Current.Application.Add(index, value);
HttpContext.Current.Application.UnLock();
}
}
} // end of ApplicationBag
#endregion
//////////////////////////////////////////////////////////////////////
/// <summary>
/// This singleton factory creates the appropriate Bag for a user to hold data
/// The data retention mechanism varies.
/// </summary>
/// //////////////////////////////////////////////////////////////////////
public sealed class BagFactory
{
/// <summary>
/// valid bag types
/// </summary>
public enum BagFactoryType
{
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
None = 0,
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
ApplicationType = 1,
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
SessionType = 2,
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
CookieType = 3,
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
DbType = 4,
}
/// <summary>
/// the singleton class instance (ONLY ONE -- APPLICATION LEVEL )
/// </summary>
public static readonly BagFactory instance = new BagFactory();
/// <summary>
/// Create the Bag according to what is available. First use Cookies,
/// then try Session and then fallback to Application.
/// </summary>
/// <returns></returns>
public IWebBagHolder create()
{
// if no session, use cookies
if (HttpContext.Current.Session == null)
return new CookieBag();
// using a session
else if (SessionStateMode.InProc == HttpContext.Current.Session.Mode)
// use the session
return new SessionBag();
// get the default bag
return new ApplicationBag();
} // end of create
/// <summary>
/// Create the Bag according to what is available. First use Cookies,
/// then try Session and then fallback to Application.
/// </summary>
/// <param name="bag_type">The bag_type.</param>
/// <returns></returns>
public IWebBagHolder create(BagFactoryType bag_type)
{
// application type
if (bag_type == BagFactoryType.ApplicationType)
// get the appli. bag
return new ApplicationBag();
// session type
else if (bag_type == BagFactoryType.SessionType &&
// if session is not available, then use the default
HttpContext.Current.Session != null)
return new SessionBag();
// cookie type
else if (bag_type == BagFactoryType.CookieType)
return new CookieBag();
// get the default bag
return new ApplicationBag();
} // end of create
/// <summary>
/// don't allow for construction outside of this class
/// </summary>
///
/// <returns>
/// A void value...
/// </returns>
private BagFactory() { }
} // end of BagFactory
}
| |
// Copyright (c) 2014-2019 The Khronos Group Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and/or associated documentation files (the "Materials"),
// to deal in the Materials without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Materials, and to permit persons to whom the
// Materials are 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 Materials.
//
// MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS
// STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND
// HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/
//
// THE MATERIALS ARE 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 MATERIALS OR THE USE OR OTHER DEALINGS
// IN THE MATERIALS.
// This header is automatically generated by the same tool that creates
// the Binary Section of the SPIR-V specification.
// Enumeration tokens for SPIR-V, in various styles:
// C, C++, C++11, JSON, Lua, Python, C#, D
//
// - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL
// - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL
// - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL
// - Lua will use tables, e.g.: spv.SourceLanguage.GLSL
// - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL']
// - C# will use enum classes in the Specification class located in the "Spv" namespace,
// e.g.: Spv.Specification.SourceLanguage.GLSL
// - D will have tokens under the "spv" module, e.g: spv.SourceLanguage.GLSL
//
// Some tokens act like mask values, which can be OR'd together,
// while others are mutually exclusive. The mask-like ones have
// "Mask" in their name, and a parallel enum that has the shift
// amount (1 << x) for each corresponding enumerant.
namespace Spv
{
public static class Specification
{
public const uint MagicNumber = 0x07230203;
public const uint Version = 0x00010300;
public const uint Revision = 7;
public const uint OpCodeMask = 0xffff;
public const uint WordCountShift = 16;
public enum SourceLanguage
{
Unknown = 0,
ESSL = 1,
GLSL = 2,
OpenCL_C = 3,
OpenCL_CPP = 4,
HLSL = 5,
}
public enum ExecutionModel
{
Vertex = 0,
TessellationControl = 1,
TessellationEvaluation = 2,
Geometry = 3,
Fragment = 4,
GLCompute = 5,
Kernel = 6,
TaskNV = 5267,
MeshNV = 5268,
RayGenerationNV = 5313,
IntersectionNV = 5314,
AnyHitNV = 5315,
ClosestHitNV = 5316,
MissNV = 5317,
CallableNV = 5318,
}
public enum AddressingModel
{
Logical = 0,
Physical32 = 1,
Physical64 = 2,
PhysicalStorageBuffer64EXT = 5348,
}
public enum MemoryModel
{
Simple = 0,
GLSL450 = 1,
OpenCL = 2,
VulkanKHR = 3,
}
public enum ExecutionMode
{
Invocations = 0,
SpacingEqual = 1,
SpacingFractionalEven = 2,
SpacingFractionalOdd = 3,
VertexOrderCw = 4,
VertexOrderCcw = 5,
PixelCenterInteger = 6,
OriginUpperLeft = 7,
OriginLowerLeft = 8,
EarlyFragmentTests = 9,
PointMode = 10,
Xfb = 11,
DepthReplacing = 12,
DepthGreater = 14,
DepthLess = 15,
DepthUnchanged = 16,
LocalSize = 17,
LocalSizeHint = 18,
InputPoints = 19,
InputLines = 20,
InputLinesAdjacency = 21,
Triangles = 22,
InputTrianglesAdjacency = 23,
Quads = 24,
Isolines = 25,
OutputVertices = 26,
OutputPoints = 27,
OutputLineStrip = 28,
OutputTriangleStrip = 29,
VecTypeHint = 30,
ContractionOff = 31,
Initializer = 33,
Finalizer = 34,
SubgroupSize = 35,
SubgroupsPerWorkgroup = 36,
SubgroupsPerWorkgroupId = 37,
LocalSizeId = 38,
LocalSizeHintId = 39,
PostDepthCoverage = 4446,
DenormPreserve = 4459,
DenormFlushToZero = 4460,
SignedZeroInfNanPreserve = 4461,
RoundingModeRTE = 4462,
RoundingModeRTZ = 4463,
StencilRefReplacingEXT = 5027,
OutputLinesNV = 5269,
OutputPrimitivesNV = 5270,
DerivativeGroupQuadsNV = 5289,
DerivativeGroupLinearNV = 5290,
OutputTrianglesNV = 5298,
}
public enum StorageClass
{
UniformConstant = 0,
Input = 1,
Uniform = 2,
Output = 3,
Workgroup = 4,
CrossWorkgroup = 5,
Private = 6,
Function = 7,
Generic = 8,
PushConstant = 9,
AtomicCounter = 10,
Image = 11,
StorageBuffer = 12,
CallableDataNV = 5328,
IncomingCallableDataNV = 5329,
RayPayloadNV = 5338,
HitAttributeNV = 5339,
IncomingRayPayloadNV = 5342,
ShaderRecordBufferNV = 5343,
PhysicalStorageBufferEXT = 5349,
}
public enum Dim
{
Dim1D = 0,
Dim2D = 1,
Dim3D = 2,
Cube = 3,
Rect = 4,
Buffer = 5,
SubpassData = 6,
}
public enum SamplerAddressingMode
{
None = 0,
ClampToEdge = 1,
Clamp = 2,
Repeat = 3,
RepeatMirrored = 4,
}
public enum SamplerFilterMode
{
Nearest = 0,
Linear = 1,
}
public enum ImageFormat
{
Unknown = 0,
Rgba32f = 1,
Rgba16f = 2,
R32f = 3,
Rgba8 = 4,
Rgba8Snorm = 5,
Rg32f = 6,
Rg16f = 7,
R11fG11fB10f = 8,
R16f = 9,
Rgba16 = 10,
Rgb10A2 = 11,
Rg16 = 12,
Rg8 = 13,
R16 = 14,
R8 = 15,
Rgba16Snorm = 16,
Rg16Snorm = 17,
Rg8Snorm = 18,
R16Snorm = 19,
R8Snorm = 20,
Rgba32i = 21,
Rgba16i = 22,
Rgba8i = 23,
R32i = 24,
Rg32i = 25,
Rg16i = 26,
Rg8i = 27,
R16i = 28,
R8i = 29,
Rgba32ui = 30,
Rgba16ui = 31,
Rgba8ui = 32,
R32ui = 33,
Rgb10a2ui = 34,
Rg32ui = 35,
Rg16ui = 36,
Rg8ui = 37,
R16ui = 38,
R8ui = 39,
}
public enum ImageChannelOrder
{
R = 0,
A = 1,
RG = 2,
RA = 3,
RGB = 4,
RGBA = 5,
BGRA = 6,
ARGB = 7,
Intensity = 8,
Luminance = 9,
Rx = 10,
RGx = 11,
RGBx = 12,
Depth = 13,
DepthStencil = 14,
sRGB = 15,
sRGBx = 16,
sRGBA = 17,
sBGRA = 18,
ABGR = 19,
}
public enum ImageChannelDataType
{
SnormInt8 = 0,
SnormInt16 = 1,
UnormInt8 = 2,
UnormInt16 = 3,
UnormShort565 = 4,
UnormShort555 = 5,
UnormInt101010 = 6,
SignedInt8 = 7,
SignedInt16 = 8,
SignedInt32 = 9,
UnsignedInt8 = 10,
UnsignedInt16 = 11,
UnsignedInt32 = 12,
HalfFloat = 13,
Float = 14,
UnormInt24 = 15,
UnormInt101010_2 = 16,
}
public enum ImageOperandsShift
{
Bias = 0,
Lod = 1,
Grad = 2,
ConstOffset = 3,
Offset = 4,
ConstOffsets = 5,
Sample = 6,
MinLod = 7,
MakeTexelAvailableKHR = 8,
MakeTexelVisibleKHR = 9,
NonPrivateTexelKHR = 10,
VolatileTexelKHR = 11,
}
public enum ImageOperandsMask
{
MaskNone = 0,
Bias = 0x00000001,
Lod = 0x00000002,
Grad = 0x00000004,
ConstOffset = 0x00000008,
Offset = 0x00000010,
ConstOffsets = 0x00000020,
Sample = 0x00000040,
MinLod = 0x00000080,
MakeTexelAvailableKHR = 0x00000100,
MakeTexelVisibleKHR = 0x00000200,
NonPrivateTexelKHR = 0x00000400,
VolatileTexelKHR = 0x00000800,
}
public enum FPFastMathModeShift
{
NotNaN = 0,
NotInf = 1,
NSZ = 2,
AllowRecip = 3,
Fast = 4,
}
public enum FPFastMathModeMask
{
MaskNone = 0,
NotNaN = 0x00000001,
NotInf = 0x00000002,
NSZ = 0x00000004,
AllowRecip = 0x00000008,
Fast = 0x00000010,
}
public enum FPRoundingMode
{
RTE = 0,
RTZ = 1,
RTP = 2,
RTN = 3,
}
public enum LinkageType
{
Export = 0,
Import = 1,
}
public enum AccessQualifier
{
ReadOnly = 0,
WriteOnly = 1,
ReadWrite = 2,
}
public enum FunctionParameterAttribute
{
Zext = 0,
Sext = 1,
ByVal = 2,
Sret = 3,
NoAlias = 4,
NoCapture = 5,
NoWrite = 6,
NoReadWrite = 7,
}
public enum Decoration
{
RelaxedPrecision = 0,
SpecId = 1,
Block = 2,
BufferBlock = 3,
RowMajor = 4,
ColMajor = 5,
ArrayStride = 6,
MatrixStride = 7,
GLSLShared = 8,
GLSLPacked = 9,
CPacked = 10,
BuiltIn = 11,
NoPerspective = 13,
Flat = 14,
Patch = 15,
Centroid = 16,
Sample = 17,
Invariant = 18,
Restrict = 19,
Aliased = 20,
Volatile = 21,
Constant = 22,
Coherent = 23,
NonWritable = 24,
NonReadable = 25,
Uniform = 26,
SaturatedConversion = 28,
Stream = 29,
Location = 30,
Component = 31,
Index = 32,
Binding = 33,
DescriptorSet = 34,
Offset = 35,
XfbBuffer = 36,
XfbStride = 37,
FuncParamAttr = 38,
FPRoundingMode = 39,
FPFastMathMode = 40,
LinkageAttributes = 41,
NoContraction = 42,
InputAttachmentIndex = 43,
Alignment = 44,
MaxByteOffset = 45,
AlignmentId = 46,
MaxByteOffsetId = 47,
NoSignedWrap = 4469,
NoUnsignedWrap = 4470,
ExplicitInterpAMD = 4999,
OverrideCoverageNV = 5248,
PassthroughNV = 5250,
ViewportRelativeNV = 5252,
SecondaryViewportRelativeNV = 5256,
PerPrimitiveNV = 5271,
PerViewNV = 5272,
PerTaskNV = 5273,
PerVertexNV = 5285,
NonUniformEXT = 5300,
RestrictPointerEXT = 5355,
AliasedPointerEXT = 5356,
HlslCounterBufferGOOGLE = 5634,
HlslSemanticGOOGLE = 5635,
}
public enum BuiltIn
{
Position = 0,
PointSize = 1,
ClipDistance = 3,
CullDistance = 4,
VertexId = 5,
InstanceId = 6,
PrimitiveId = 7,
InvocationId = 8,
Layer = 9,
ViewportIndex = 10,
TessLevelOuter = 11,
TessLevelInner = 12,
TessCoord = 13,
PatchVertices = 14,
FragCoord = 15,
PointCoord = 16,
FrontFacing = 17,
SampleId = 18,
SamplePosition = 19,
SampleMask = 20,
FragDepth = 22,
HelperInvocation = 23,
NumWorkgroups = 24,
WorkgroupSize = 25,
WorkgroupId = 26,
LocalInvocationId = 27,
GlobalInvocationId = 28,
LocalInvocationIndex = 29,
WorkDim = 30,
GlobalSize = 31,
EnqueuedWorkgroupSize = 32,
GlobalOffset = 33,
GlobalLinearId = 34,
SubgroupSize = 36,
SubgroupMaxSize = 37,
NumSubgroups = 38,
NumEnqueuedSubgroups = 39,
SubgroupId = 40,
SubgroupLocalInvocationId = 41,
VertexIndex = 42,
InstanceIndex = 43,
SubgroupEqMask = 4416,
SubgroupEqMaskKHR = 4416,
SubgroupGeMask = 4417,
SubgroupGeMaskKHR = 4417,
SubgroupGtMask = 4418,
SubgroupGtMaskKHR = 4418,
SubgroupLeMask = 4419,
SubgroupLeMaskKHR = 4419,
SubgroupLtMask = 4420,
SubgroupLtMaskKHR = 4420,
BaseVertex = 4424,
BaseInstance = 4425,
DrawIndex = 4426,
DeviceIndex = 4438,
ViewIndex = 4440,
BaryCoordNoPerspAMD = 4992,
BaryCoordNoPerspCentroidAMD = 4993,
BaryCoordNoPerspSampleAMD = 4994,
BaryCoordSmoothAMD = 4995,
BaryCoordSmoothCentroidAMD = 4996,
BaryCoordSmoothSampleAMD = 4997,
BaryCoordPullModelAMD = 4998,
FragStencilRefEXT = 5014,
ViewportMaskNV = 5253,
SecondaryPositionNV = 5257,
SecondaryViewportMaskNV = 5258,
PositionPerViewNV = 5261,
ViewportMaskPerViewNV = 5262,
FullyCoveredEXT = 5264,
TaskCountNV = 5274,
PrimitiveCountNV = 5275,
PrimitiveIndicesNV = 5276,
ClipDistancePerViewNV = 5277,
CullDistancePerViewNV = 5278,
LayerPerViewNV = 5279,
MeshViewCountNV = 5280,
MeshViewIndicesNV = 5281,
BaryCoordNV = 5286,
BaryCoordNoPerspNV = 5287,
FragSizeEXT = 5292,
FragmentSizeNV = 5292,
FragInvocationCountEXT = 5293,
InvocationsPerPixelNV = 5293,
LaunchIdNV = 5319,
LaunchSizeNV = 5320,
WorldRayOriginNV = 5321,
WorldRayDirectionNV = 5322,
ObjectRayOriginNV = 5323,
ObjectRayDirectionNV = 5324,
RayTminNV = 5325,
RayTmaxNV = 5326,
InstanceCustomIndexNV = 5327,
ObjectToWorldNV = 5330,
WorldToObjectNV = 5331,
HitTNV = 5332,
HitKindNV = 5333,
IncomingRayFlagsNV = 5351,
}
public enum SelectionControlShift
{
Flatten = 0,
DontFlatten = 1,
}
public enum SelectionControlMask
{
MaskNone = 0,
Flatten = 0x00000001,
DontFlatten = 0x00000002,
}
public enum LoopControlShift
{
Unroll = 0,
DontUnroll = 1,
DependencyInfinite = 2,
DependencyLength = 3,
}
public enum LoopControlMask
{
MaskNone = 0,
Unroll = 0x00000001,
DontUnroll = 0x00000002,
DependencyInfinite = 0x00000004,
DependencyLength = 0x00000008,
}
public enum FunctionControlShift
{
Inline = 0,
DontInline = 1,
Pure = 2,
Const = 3,
}
public enum FunctionControlMask
{
MaskNone = 0,
Inline = 0x00000001,
DontInline = 0x00000002,
Pure = 0x00000004,
Const = 0x00000008,
}
public enum MemorySemanticsShift
{
Acquire = 1,
Release = 2,
AcquireRelease = 3,
SequentiallyConsistent = 4,
UniformMemory = 6,
SubgroupMemory = 7,
WorkgroupMemory = 8,
CrossWorkgroupMemory = 9,
AtomicCounterMemory = 10,
ImageMemory = 11,
OutputMemoryKHR = 12,
MakeAvailableKHR = 13,
MakeVisibleKHR = 14,
}
public enum MemorySemanticsMask
{
MaskNone = 0,
Acquire = 0x00000002,
Release = 0x00000004,
AcquireRelease = 0x00000008,
SequentiallyConsistent = 0x00000010,
UniformMemory = 0x00000040,
SubgroupMemory = 0x00000080,
WorkgroupMemory = 0x00000100,
CrossWorkgroupMemory = 0x00000200,
AtomicCounterMemory = 0x00000400,
ImageMemory = 0x00000800,
OutputMemoryKHR = 0x00001000,
MakeAvailableKHR = 0x00002000,
MakeVisibleKHR = 0x00004000,
}
public enum MemoryAccessShift
{
Volatile = 0,
Aligned = 1,
Nontemporal = 2,
MakePointerAvailableKHR = 3,
MakePointerVisibleKHR = 4,
NonPrivatePointerKHR = 5,
}
public enum MemoryAccessMask
{
MaskNone = 0,
Volatile = 0x00000001,
Aligned = 0x00000002,
Nontemporal = 0x00000004,
MakePointerAvailableKHR = 0x00000008,
MakePointerVisibleKHR = 0x00000010,
NonPrivatePointerKHR = 0x00000020,
}
public enum Scope
{
CrossDevice = 0,
Device = 1,
Workgroup = 2,
Subgroup = 3,
Invocation = 4,
QueueFamilyKHR = 5,
}
public enum GroupOperation
{
Reduce = 0,
InclusiveScan = 1,
ExclusiveScan = 2,
ClusteredReduce = 3,
PartitionedReduceNV = 6,
PartitionedInclusiveScanNV = 7,
PartitionedExclusiveScanNV = 8,
}
public enum KernelEnqueueFlags
{
NoWait = 0,
WaitKernel = 1,
WaitWorkGroup = 2,
}
public enum KernelProfilingInfoShift
{
CmdExecTime = 0,
}
public enum KernelProfilingInfoMask
{
MaskNone = 0,
CmdExecTime = 0x00000001,
}
public enum Capability
{
Matrix = 0,
Shader = 1,
Geometry = 2,
Tessellation = 3,
Addresses = 4,
Linkage = 5,
Kernel = 6,
Vector16 = 7,
Float16Buffer = 8,
Float16 = 9,
Float64 = 10,
Int64 = 11,
Int64Atomics = 12,
ImageBasic = 13,
ImageReadWrite = 14,
ImageMipmap = 15,
Pipes = 17,
Groups = 18,
DeviceEnqueue = 19,
LiteralSampler = 20,
AtomicStorage = 21,
Int16 = 22,
TessellationPointSize = 23,
GeometryPointSize = 24,
ImageGatherExtended = 25,
StorageImageMultisample = 27,
UniformBufferArrayDynamicIndexing = 28,
SampledImageArrayDynamicIndexing = 29,
StorageBufferArrayDynamicIndexing = 30,
StorageImageArrayDynamicIndexing = 31,
ClipDistance = 32,
CullDistance = 33,
ImageCubeArray = 34,
SampleRateShading = 35,
ImageRect = 36,
SampledRect = 37,
GenericPointer = 38,
Int8 = 39,
InputAttachment = 40,
SparseResidency = 41,
MinLod = 42,
Sampled1D = 43,
Image1D = 44,
SampledCubeArray = 45,
SampledBuffer = 46,
ImageBuffer = 47,
ImageMSArray = 48,
StorageImageExtendedFormats = 49,
ImageQuery = 50,
DerivativeControl = 51,
InterpolationFunction = 52,
TransformFeedback = 53,
GeometryStreams = 54,
StorageImageReadWithoutFormat = 55,
StorageImageWriteWithoutFormat = 56,
MultiViewport = 57,
SubgroupDispatch = 58,
NamedBarrier = 59,
PipeStorage = 60,
GroupNonUniform = 61,
GroupNonUniformVote = 62,
GroupNonUniformArithmetic = 63,
GroupNonUniformBallot = 64,
GroupNonUniformShuffle = 65,
GroupNonUniformShuffleRelative = 66,
GroupNonUniformClustered = 67,
GroupNonUniformQuad = 68,
SubgroupBallotKHR = 4423,
DrawParameters = 4427,
SubgroupVoteKHR = 4431,
StorageBuffer16BitAccess = 4433,
StorageUniformBufferBlock16 = 4433,
StorageUniform16 = 4434,
UniformAndStorageBuffer16BitAccess = 4434,
StoragePushConstant16 = 4435,
StorageInputOutput16 = 4436,
DeviceGroup = 4437,
MultiView = 4439,
VariablePointersStorageBuffer = 4441,
VariablePointers = 4442,
AtomicStorageOps = 4445,
SampleMaskPostDepthCoverage = 4447,
StorageBuffer8BitAccess = 4448,
UniformAndStorageBuffer8BitAccess = 4449,
StoragePushConstant8 = 4450,
DenormPreserve = 4464,
DenormFlushToZero = 4465,
SignedZeroInfNanPreserve = 4466,
RoundingModeRTE = 4467,
RoundingModeRTZ = 4468,
Float16ImageAMD = 5008,
ImageGatherBiasLodAMD = 5009,
FragmentMaskAMD = 5010,
StencilExportEXT = 5013,
ImageReadWriteLodAMD = 5015,
SampleMaskOverrideCoverageNV = 5249,
GeometryShaderPassthroughNV = 5251,
ShaderViewportIndexLayerEXT = 5254,
ShaderViewportIndexLayerNV = 5254,
ShaderViewportMaskNV = 5255,
ShaderStereoViewNV = 5259,
PerViewAttributesNV = 5260,
FragmentFullyCoveredEXT = 5265,
MeshShadingNV = 5266,
ImageFootprintNV = 5282,
FragmentBarycentricNV = 5284,
ComputeDerivativeGroupQuadsNV = 5288,
FragmentDensityEXT = 5291,
ShadingRateNV = 5291,
GroupNonUniformPartitionedNV = 5297,
ShaderNonUniformEXT = 5301,
RuntimeDescriptorArrayEXT = 5302,
InputAttachmentArrayDynamicIndexingEXT = 5303,
UniformTexelBufferArrayDynamicIndexingEXT = 5304,
StorageTexelBufferArrayDynamicIndexingEXT = 5305,
UniformBufferArrayNonUniformIndexingEXT = 5306,
SampledImageArrayNonUniformIndexingEXT = 5307,
StorageBufferArrayNonUniformIndexingEXT = 5308,
StorageImageArrayNonUniformIndexingEXT = 5309,
InputAttachmentArrayNonUniformIndexingEXT = 5310,
UniformTexelBufferArrayNonUniformIndexingEXT = 5311,
StorageTexelBufferArrayNonUniformIndexingEXT = 5312,
RayTracingNV = 5340,
VulkanMemoryModelKHR = 5345,
VulkanMemoryModelDeviceScopeKHR = 5346,
PhysicalStorageBufferAddressesEXT = 5347,
ComputeDerivativeGroupLinearNV = 5350,
CooperativeMatrixNV = 5357,
SubgroupShuffleINTEL = 5568,
SubgroupBufferBlockIOINTEL = 5569,
SubgroupImageBlockIOINTEL = 5570,
SubgroupImageMediaBlockIOINTEL = 5579,
SubgroupAvcMotionEstimationINTEL = 5696,
SubgroupAvcMotionEstimationIntraINTEL = 5697,
SubgroupAvcMotionEstimationChromaINTEL = 5698,
}
public enum Op
{
OpNop = 0,
OpUndef = 1,
OpSourceContinued = 2,
OpSource = 3,
OpSourceExtension = 4,
OpName = 5,
OpMemberName = 6,
OpString = 7,
OpLine = 8,
OpExtension = 10,
OpExtInstImport = 11,
OpExtInst = 12,
OpMemoryModel = 14,
OpEntryPoint = 15,
OpExecutionMode = 16,
OpCapability = 17,
OpTypeVoid = 19,
OpTypeBool = 20,
OpTypeInt = 21,
OpTypeFloat = 22,
OpTypeVector = 23,
OpTypeMatrix = 24,
OpTypeImage = 25,
OpTypeSampler = 26,
OpTypeSampledImage = 27,
OpTypeArray = 28,
OpTypeRuntimeArray = 29,
OpTypeStruct = 30,
OpTypeOpaque = 31,
OpTypePointer = 32,
OpTypeFunction = 33,
OpTypeEvent = 34,
OpTypeDeviceEvent = 35,
OpTypeReserveId = 36,
OpTypeQueue = 37,
OpTypePipe = 38,
OpTypeForwardPointer = 39,
OpConstantTrue = 41,
OpConstantFalse = 42,
OpConstant = 43,
OpConstantComposite = 44,
OpConstantSampler = 45,
OpConstantNull = 46,
OpSpecConstantTrue = 48,
OpSpecConstantFalse = 49,
OpSpecConstant = 50,
OpSpecConstantComposite = 51,
OpSpecConstantOp = 52,
OpFunction = 54,
OpFunctionParameter = 55,
OpFunctionEnd = 56,
OpFunctionCall = 57,
OpVariable = 59,
OpImageTexelPointer = 60,
OpLoad = 61,
OpStore = 62,
OpCopyMemory = 63,
OpCopyMemorySized = 64,
OpAccessChain = 65,
OpInBoundsAccessChain = 66,
OpPtrAccessChain = 67,
OpArrayLength = 68,
OpGenericPtrMemSemantics = 69,
OpInBoundsPtrAccessChain = 70,
OpDecorate = 71,
OpMemberDecorate = 72,
OpDecorationGroup = 73,
OpGroupDecorate = 74,
OpGroupMemberDecorate = 75,
OpVectorExtractDynamic = 77,
OpVectorInsertDynamic = 78,
OpVectorShuffle = 79,
OpCompositeConstruct = 80,
OpCompositeExtract = 81,
OpCompositeInsert = 82,
OpCopyObject = 83,
OpTranspose = 84,
OpSampledImage = 86,
OpImageSampleImplicitLod = 87,
OpImageSampleExplicitLod = 88,
OpImageSampleDrefImplicitLod = 89,
OpImageSampleDrefExplicitLod = 90,
OpImageSampleProjImplicitLod = 91,
OpImageSampleProjExplicitLod = 92,
OpImageSampleProjDrefImplicitLod = 93,
OpImageSampleProjDrefExplicitLod = 94,
OpImageFetch = 95,
OpImageGather = 96,
OpImageDrefGather = 97,
OpImageRead = 98,
OpImageWrite = 99,
OpImage = 100,
OpImageQueryFormat = 101,
OpImageQueryOrder = 102,
OpImageQuerySizeLod = 103,
OpImageQuerySize = 104,
OpImageQueryLod = 105,
OpImageQueryLevels = 106,
OpImageQuerySamples = 107,
OpConvertFToU = 109,
OpConvertFToS = 110,
OpConvertSToF = 111,
OpConvertUToF = 112,
OpUConvert = 113,
OpSConvert = 114,
OpFConvert = 115,
OpQuantizeToF16 = 116,
OpConvertPtrToU = 117,
OpSatConvertSToU = 118,
OpSatConvertUToS = 119,
OpConvertUToPtr = 120,
OpPtrCastToGeneric = 121,
OpGenericCastToPtr = 122,
OpGenericCastToPtrExplicit = 123,
OpBitcast = 124,
OpSNegate = 126,
OpFNegate = 127,
OpIAdd = 128,
OpFAdd = 129,
OpISub = 130,
OpFSub = 131,
OpIMul = 132,
OpFMul = 133,
OpUDiv = 134,
OpSDiv = 135,
OpFDiv = 136,
OpUMod = 137,
OpSRem = 138,
OpSMod = 139,
OpFRem = 140,
OpFMod = 141,
OpVectorTimesScalar = 142,
OpMatrixTimesScalar = 143,
OpVectorTimesMatrix = 144,
OpMatrixTimesVector = 145,
OpMatrixTimesMatrix = 146,
OpOuterProduct = 147,
OpDot = 148,
OpIAddCarry = 149,
OpISubBorrow = 150,
OpUMulExtended = 151,
OpSMulExtended = 152,
OpAny = 154,
OpAll = 155,
OpIsNan = 156,
OpIsInf = 157,
OpIsFinite = 158,
OpIsNormal = 159,
OpSignBitSet = 160,
OpLessOrGreater = 161,
OpOrdered = 162,
OpUnordered = 163,
OpLogicalEqual = 164,
OpLogicalNotEqual = 165,
OpLogicalOr = 166,
OpLogicalAnd = 167,
OpLogicalNot = 168,
OpSelect = 169,
OpIEqual = 170,
OpINotEqual = 171,
OpUGreaterThan = 172,
OpSGreaterThan = 173,
OpUGreaterThanEqual = 174,
OpSGreaterThanEqual = 175,
OpULessThan = 176,
OpSLessThan = 177,
OpULessThanEqual = 178,
OpSLessThanEqual = 179,
OpFOrdEqual = 180,
OpFUnordEqual = 181,
OpFOrdNotEqual = 182,
OpFUnordNotEqual = 183,
OpFOrdLessThan = 184,
OpFUnordLessThan = 185,
OpFOrdGreaterThan = 186,
OpFUnordGreaterThan = 187,
OpFOrdLessThanEqual = 188,
OpFUnordLessThanEqual = 189,
OpFOrdGreaterThanEqual = 190,
OpFUnordGreaterThanEqual = 191,
OpShiftRightLogical = 194,
OpShiftRightArithmetic = 195,
OpShiftLeftLogical = 196,
OpBitwiseOr = 197,
OpBitwiseXor = 198,
OpBitwiseAnd = 199,
OpNot = 200,
OpBitFieldInsert = 201,
OpBitFieldSExtract = 202,
OpBitFieldUExtract = 203,
OpBitReverse = 204,
OpBitCount = 205,
OpDPdx = 207,
OpDPdy = 208,
OpFwidth = 209,
OpDPdxFine = 210,
OpDPdyFine = 211,
OpFwidthFine = 212,
OpDPdxCoarse = 213,
OpDPdyCoarse = 214,
OpFwidthCoarse = 215,
OpEmitVertex = 218,
OpEndPrimitive = 219,
OpEmitStreamVertex = 220,
OpEndStreamPrimitive = 221,
OpControlBarrier = 224,
OpMemoryBarrier = 225,
OpAtomicLoad = 227,
OpAtomicStore = 228,
OpAtomicExchange = 229,
OpAtomicCompareExchange = 230,
OpAtomicCompareExchangeWeak = 231,
OpAtomicIIncrement = 232,
OpAtomicIDecrement = 233,
OpAtomicIAdd = 234,
OpAtomicISub = 235,
OpAtomicSMin = 236,
OpAtomicUMin = 237,
OpAtomicSMax = 238,
OpAtomicUMax = 239,
OpAtomicAnd = 240,
OpAtomicOr = 241,
OpAtomicXor = 242,
OpPhi = 245,
OpLoopMerge = 246,
OpSelectionMerge = 247,
OpLabel = 248,
OpBranch = 249,
OpBranchConditional = 250,
OpSwitch = 251,
OpKill = 252,
OpReturn = 253,
OpReturnValue = 254,
OpUnreachable = 255,
OpLifetimeStart = 256,
OpLifetimeStop = 257,
OpGroupAsyncCopy = 259,
OpGroupWaitEvents = 260,
OpGroupAll = 261,
OpGroupAny = 262,
OpGroupBroadcast = 263,
OpGroupIAdd = 264,
OpGroupFAdd = 265,
OpGroupFMin = 266,
OpGroupUMin = 267,
OpGroupSMin = 268,
OpGroupFMax = 269,
OpGroupUMax = 270,
OpGroupSMax = 271,
OpReadPipe = 274,
OpWritePipe = 275,
OpReservedReadPipe = 276,
OpReservedWritePipe = 277,
OpReserveReadPipePackets = 278,
OpReserveWritePipePackets = 279,
OpCommitReadPipe = 280,
OpCommitWritePipe = 281,
OpIsValidReserveId = 282,
OpGetNumPipePackets = 283,
OpGetMaxPipePackets = 284,
OpGroupReserveReadPipePackets = 285,
OpGroupReserveWritePipePackets = 286,
OpGroupCommitReadPipe = 287,
OpGroupCommitWritePipe = 288,
OpEnqueueMarker = 291,
OpEnqueueKernel = 292,
OpGetKernelNDrangeSubGroupCount = 293,
OpGetKernelNDrangeMaxSubGroupSize = 294,
OpGetKernelWorkGroupSize = 295,
OpGetKernelPreferredWorkGroupSizeMultiple = 296,
OpRetainEvent = 297,
OpReleaseEvent = 298,
OpCreateUserEvent = 299,
OpIsValidEvent = 300,
OpSetUserEventStatus = 301,
OpCaptureEventProfilingInfo = 302,
OpGetDefaultQueue = 303,
OpBuildNDRange = 304,
OpImageSparseSampleImplicitLod = 305,
OpImageSparseSampleExplicitLod = 306,
OpImageSparseSampleDrefImplicitLod = 307,
OpImageSparseSampleDrefExplicitLod = 308,
OpImageSparseSampleProjImplicitLod = 309,
OpImageSparseSampleProjExplicitLod = 310,
OpImageSparseSampleProjDrefImplicitLod = 311,
OpImageSparseSampleProjDrefExplicitLod = 312,
OpImageSparseFetch = 313,
OpImageSparseGather = 314,
OpImageSparseDrefGather = 315,
OpImageSparseTexelsResident = 316,
OpNoLine = 317,
OpAtomicFlagTestAndSet = 318,
OpAtomicFlagClear = 319,
OpImageSparseRead = 320,
OpSizeOf = 321,
OpTypePipeStorage = 322,
OpConstantPipeStorage = 323,
OpCreatePipeFromPipeStorage = 324,
OpGetKernelLocalSizeForSubgroupCount = 325,
OpGetKernelMaxNumSubgroups = 326,
OpTypeNamedBarrier = 327,
OpNamedBarrierInitialize = 328,
OpMemoryNamedBarrier = 329,
OpModuleProcessed = 330,
OpExecutionModeId = 331,
OpDecorateId = 332,
OpGroupNonUniformElect = 333,
OpGroupNonUniformAll = 334,
OpGroupNonUniformAny = 335,
OpGroupNonUniformAllEqual = 336,
OpGroupNonUniformBroadcast = 337,
OpGroupNonUniformBroadcastFirst = 338,
OpGroupNonUniformBallot = 339,
OpGroupNonUniformInverseBallot = 340,
OpGroupNonUniformBallotBitExtract = 341,
OpGroupNonUniformBallotBitCount = 342,
OpGroupNonUniformBallotFindLSB = 343,
OpGroupNonUniformBallotFindMSB = 344,
OpGroupNonUniformShuffle = 345,
OpGroupNonUniformShuffleXor = 346,
OpGroupNonUniformShuffleUp = 347,
OpGroupNonUniformShuffleDown = 348,
OpGroupNonUniformIAdd = 349,
OpGroupNonUniformFAdd = 350,
OpGroupNonUniformIMul = 351,
OpGroupNonUniformFMul = 352,
OpGroupNonUniformSMin = 353,
OpGroupNonUniformUMin = 354,
OpGroupNonUniformFMin = 355,
OpGroupNonUniformSMax = 356,
OpGroupNonUniformUMax = 357,
OpGroupNonUniformFMax = 358,
OpGroupNonUniformBitwiseAnd = 359,
OpGroupNonUniformBitwiseOr = 360,
OpGroupNonUniformBitwiseXor = 361,
OpGroupNonUniformLogicalAnd = 362,
OpGroupNonUniformLogicalOr = 363,
OpGroupNonUniformLogicalXor = 364,
OpGroupNonUniformQuadBroadcast = 365,
OpGroupNonUniformQuadSwap = 366,
OpSubgroupBallotKHR = 4421,
OpSubgroupFirstInvocationKHR = 4422,
OpSubgroupAllKHR = 4428,
OpSubgroupAnyKHR = 4429,
OpSubgroupAllEqualKHR = 4430,
OpSubgroupReadInvocationKHR = 4432,
OpGroupIAddNonUniformAMD = 5000,
OpGroupFAddNonUniformAMD = 5001,
OpGroupFMinNonUniformAMD = 5002,
OpGroupUMinNonUniformAMD = 5003,
OpGroupSMinNonUniformAMD = 5004,
OpGroupFMaxNonUniformAMD = 5005,
OpGroupUMaxNonUniformAMD = 5006,
OpGroupSMaxNonUniformAMD = 5007,
OpFragmentMaskFetchAMD = 5011,
OpFragmentFetchAMD = 5012,
OpImageSampleFootprintNV = 5283,
OpGroupNonUniformPartitionNV = 5296,
OpWritePackedPrimitiveIndices4x8NV = 5299,
OpReportIntersectionNV = 5334,
OpIgnoreIntersectionNV = 5335,
OpTerminateRayNV = 5336,
OpTraceNV = 5337,
OpTypeAccelerationStructureNV = 5341,
OpExecuteCallableNV = 5344,
OpTypeCooperativeMatrixNV = 5358,
OpCooperativeMatrixLoadNV = 5359,
OpCooperativeMatrixStoreNV = 5360,
OpCooperativeMatrixMulAddNV = 5361,
OpCooperativeMatrixLengthNV = 5362,
OpSubgroupShuffleINTEL = 5571,
OpSubgroupShuffleDownINTEL = 5572,
OpSubgroupShuffleUpINTEL = 5573,
OpSubgroupShuffleXorINTEL = 5574,
OpSubgroupBlockReadINTEL = 5575,
OpSubgroupBlockWriteINTEL = 5576,
OpSubgroupImageBlockReadINTEL = 5577,
OpSubgroupImageBlockWriteINTEL = 5578,
OpSubgroupImageMediaBlockReadINTEL = 5580,
OpSubgroupImageMediaBlockWriteINTEL = 5581,
OpDecorateStringGOOGLE = 5632,
OpMemberDecorateStringGOOGLE = 5633,
OpVmeImageINTEL = 5699,
OpTypeVmeImageINTEL = 5700,
OpTypeAvcImePayloadINTEL = 5701,
OpTypeAvcRefPayloadINTEL = 5702,
OpTypeAvcSicPayloadINTEL = 5703,
OpTypeAvcMcePayloadINTEL = 5704,
OpTypeAvcMceResultINTEL = 5705,
OpTypeAvcImeResultINTEL = 5706,
OpTypeAvcImeResultSingleReferenceStreamoutINTEL = 5707,
OpTypeAvcImeResultDualReferenceStreamoutINTEL = 5708,
OpTypeAvcImeSingleReferenceStreaminINTEL = 5709,
OpTypeAvcImeDualReferenceStreaminINTEL = 5710,
OpTypeAvcRefResultINTEL = 5711,
OpTypeAvcSicResultINTEL = 5712,
OpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL = 5713,
OpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL = 5714,
OpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL = 5715,
OpSubgroupAvcMceSetInterShapePenaltyINTEL = 5716,
OpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL = 5717,
OpSubgroupAvcMceSetInterDirectionPenaltyINTEL = 5718,
OpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL = 5719,
OpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL = 5720,
OpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL = 5721,
OpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL = 5722,
OpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL = 5723,
OpSubgroupAvcMceSetMotionVectorCostFunctionINTEL = 5724,
OpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL = 5725,
OpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL = 5726,
OpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL = 5727,
OpSubgroupAvcMceSetAcOnlyHaarINTEL = 5728,
OpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL = 5729,
OpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL = 5730,
OpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL = 5731,
OpSubgroupAvcMceConvertToImePayloadINTEL = 5732,
OpSubgroupAvcMceConvertToImeResultINTEL = 5733,
OpSubgroupAvcMceConvertToRefPayloadINTEL = 5734,
OpSubgroupAvcMceConvertToRefResultINTEL = 5735,
OpSubgroupAvcMceConvertToSicPayloadINTEL = 5736,
OpSubgroupAvcMceConvertToSicResultINTEL = 5737,
OpSubgroupAvcMceGetMotionVectorsINTEL = 5738,
OpSubgroupAvcMceGetInterDistortionsINTEL = 5739,
OpSubgroupAvcMceGetBestInterDistortionsINTEL = 5740,
OpSubgroupAvcMceGetInterMajorShapeINTEL = 5741,
OpSubgroupAvcMceGetInterMinorShapeINTEL = 5742,
OpSubgroupAvcMceGetInterDirectionsINTEL = 5743,
OpSubgroupAvcMceGetInterMotionVectorCountINTEL = 5744,
OpSubgroupAvcMceGetInterReferenceIdsINTEL = 5745,
OpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL = 5746,
OpSubgroupAvcImeInitializeINTEL = 5747,
OpSubgroupAvcImeSetSingleReferenceINTEL = 5748,
OpSubgroupAvcImeSetDualReferenceINTEL = 5749,
OpSubgroupAvcImeRefWindowSizeINTEL = 5750,
OpSubgroupAvcImeAdjustRefOffsetINTEL = 5751,
OpSubgroupAvcImeConvertToMcePayloadINTEL = 5752,
OpSubgroupAvcImeSetMaxMotionVectorCountINTEL = 5753,
OpSubgroupAvcImeSetUnidirectionalMixDisableINTEL = 5754,
OpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL = 5755,
OpSubgroupAvcImeSetWeightedSadINTEL = 5756,
OpSubgroupAvcImeEvaluateWithSingleReferenceINTEL = 5757,
OpSubgroupAvcImeEvaluateWithDualReferenceINTEL = 5758,
OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL = 5759,
OpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL = 5760,
OpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL = 5761,
OpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL = 5762,
OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL = 5763,
OpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL = 5764,
OpSubgroupAvcImeConvertToMceResultINTEL = 5765,
OpSubgroupAvcImeGetSingleReferenceStreaminINTEL = 5766,
OpSubgroupAvcImeGetDualReferenceStreaminINTEL = 5767,
OpSubgroupAvcImeStripSingleReferenceStreamoutINTEL = 5768,
OpSubgroupAvcImeStripDualReferenceStreamoutINTEL = 5769,
OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL = 5770,
OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL = 5771,
OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL = 5772,
OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL = 5773,
OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL = 5774,
OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL = 5775,
OpSubgroupAvcImeGetBorderReachedINTEL = 5776,
OpSubgroupAvcImeGetTruncatedSearchIndicationINTEL = 5777,
OpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL = 5778,
OpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL = 5779,
OpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL = 5780,
OpSubgroupAvcFmeInitializeINTEL = 5781,
OpSubgroupAvcBmeInitializeINTEL = 5782,
OpSubgroupAvcRefConvertToMcePayloadINTEL = 5783,
OpSubgroupAvcRefSetBidirectionalMixDisableINTEL = 5784,
OpSubgroupAvcRefSetBilinearFilterEnableINTEL = 5785,
OpSubgroupAvcRefEvaluateWithSingleReferenceINTEL = 5786,
OpSubgroupAvcRefEvaluateWithDualReferenceINTEL = 5787,
OpSubgroupAvcRefEvaluateWithMultiReferenceINTEL = 5788,
OpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL = 5789,
OpSubgroupAvcRefConvertToMceResultINTEL = 5790,
OpSubgroupAvcSicInitializeINTEL = 5791,
OpSubgroupAvcSicConfigureSkcINTEL = 5792,
OpSubgroupAvcSicConfigureIpeLumaINTEL = 5793,
OpSubgroupAvcSicConfigureIpeLumaChromaINTEL = 5794,
OpSubgroupAvcSicGetMotionVectorMaskINTEL = 5795,
OpSubgroupAvcSicConvertToMcePayloadINTEL = 5796,
OpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL = 5797,
OpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL = 5798,
OpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL = 5799,
OpSubgroupAvcSicSetBilinearFilterEnableINTEL = 5800,
OpSubgroupAvcSicSetSkcForwardTransformEnableINTEL = 5801,
OpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL = 5802,
OpSubgroupAvcSicEvaluateIpeINTEL = 5803,
OpSubgroupAvcSicEvaluateWithSingleReferenceINTEL = 5804,
OpSubgroupAvcSicEvaluateWithDualReferenceINTEL = 5805,
OpSubgroupAvcSicEvaluateWithMultiReferenceINTEL = 5806,
OpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL = 5807,
OpSubgroupAvcSicConvertToMceResultINTEL = 5808,
OpSubgroupAvcSicGetIpeLumaShapeINTEL = 5809,
OpSubgroupAvcSicGetBestIpeLumaDistortionINTEL = 5810,
OpSubgroupAvcSicGetBestIpeChromaDistortionINTEL = 5811,
OpSubgroupAvcSicGetPackedIpeLumaModesINTEL = 5812,
OpSubgroupAvcSicGetIpeChromaModeINTEL = 5813,
OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL = 5814,
OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL = 5815,
OpSubgroupAvcSicGetInterRawSadsINTEL = 5816,
}
}
}
| |
// 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.Buffers;
using System.Diagnostics;
using System.Security;
using ZErrorCode = System.IO.Compression.ZLibNative.ErrorCode;
using ZFlushCode = System.IO.Compression.ZLibNative.FlushCode;
namespace System.IO.Compression
{
/// <summary>
/// Provides a wrapper around the ZLib compression API.
/// </summary>
internal sealed class Deflater : IDisposable
{
private ZLibNative.ZLibStreamHandle _zlibStream;
private MemoryHandle _inputBufferHandle;
private bool _isDisposed;
private const int minWindowBits = -15; // WindowBits must be between -8..-15 to write no header, 8..15 for a
private const int maxWindowBits = 31; // zlib header, or 24..31 for a GZip header
// Note, DeflateStream or the deflater do not try to be thread safe.
// The lock is just used to make writing to unmanaged structures atomic to make sure
// that they do not get inconsistent fields that may lead to an unmanaged memory violation.
// To prevent *managed* buffer corruption or other weird behaviour users need to synchronise
// on the stream explicitly.
private object SyncLock => this;
internal Deflater(CompressionLevel compressionLevel, int windowBits)
{
Debug.Assert(windowBits >= minWindowBits && windowBits <= maxWindowBits);
ZLibNative.CompressionLevel zlibCompressionLevel;
int memLevel;
switch (compressionLevel)
{
// See the note in ZLibNative.CompressionLevel for the recommended combinations.
case CompressionLevel.Optimal:
zlibCompressionLevel = ZLibNative.CompressionLevel.DefaultCompression;
memLevel = ZLibNative.Deflate_DefaultMemLevel;
break;
case CompressionLevel.Fastest:
zlibCompressionLevel = ZLibNative.CompressionLevel.BestSpeed;
memLevel = ZLibNative.Deflate_DefaultMemLevel;
break;
case CompressionLevel.NoCompression:
zlibCompressionLevel = ZLibNative.CompressionLevel.NoCompression;
memLevel = ZLibNative.Deflate_NoCompressionMemLevel;
break;
default:
throw new ArgumentOutOfRangeException(nameof(compressionLevel));
}
ZLibNative.CompressionStrategy strategy = ZLibNative.CompressionStrategy.DefaultStrategy;
DeflateInit(zlibCompressionLevel, windowBits, memLevel, strategy);
}
~Deflater()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
_zlibStream.Dispose();
DeallocateInputBufferHandle();
_isDisposed = true;
}
}
public bool NeedsInput() => 0 == _zlibStream.AvailIn;
internal unsafe void SetInput(ReadOnlyMemory<byte> inputBuffer)
{
Debug.Assert(NeedsInput(), "We have something left in previous input!");
Debug.Assert(!_inputBufferHandle.HasPointer);
if (0 == inputBuffer.Length)
{
return;
}
lock (SyncLock)
{
_inputBufferHandle = inputBuffer.Retain(pin: true);
_zlibStream.NextIn = (IntPtr)_inputBufferHandle.Pointer;
_zlibStream.AvailIn = (uint)inputBuffer.Length;
}
}
internal unsafe void SetInput(byte* inputBufferPtr, int count)
{
Debug.Assert(NeedsInput(), "We have something left in previous input!");
Debug.Assert(inputBufferPtr != null);
Debug.Assert(!_inputBufferHandle.HasPointer);
if (count == 0)
{
return;
}
lock (SyncLock)
{
_zlibStream.NextIn = (IntPtr)inputBufferPtr;
_zlibStream.AvailIn = (uint)count;
}
}
internal int GetDeflateOutput(byte[] outputBuffer)
{
Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
Debug.Assert(!NeedsInput(), "GetDeflateOutput should only be called after providing input");
try
{
int bytesRead;
ReadDeflateOutput(outputBuffer, ZFlushCode.NoFlush, out bytesRead);
return bytesRead;
}
finally
{
// Before returning, make sure to release input buffer if necessary:
if (0 == _zlibStream.AvailIn)
{
DeallocateInputBufferHandle();
}
}
}
private unsafe ZErrorCode ReadDeflateOutput(byte[] outputBuffer, ZFlushCode flushCode, out int bytesRead)
{
Debug.Assert(outputBuffer?.Length > 0);
lock (SyncLock)
{
fixed (byte* bufPtr = &outputBuffer[0])
{
_zlibStream.NextOut = (IntPtr)bufPtr;
_zlibStream.AvailOut = (uint)outputBuffer.Length;
ZErrorCode errC = Deflate(flushCode);
bytesRead = outputBuffer.Length - (int)_zlibStream.AvailOut;
return errC;
}
}
}
internal bool Finish(byte[] outputBuffer, out int bytesRead)
{
Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
Debug.Assert(outputBuffer.Length > 0, "Can't pass in an empty output buffer!");
ZErrorCode errC = ReadDeflateOutput(outputBuffer, ZFlushCode.Finish, out bytesRead);
return errC == ZErrorCode.StreamEnd;
}
/// <summary>
/// Returns true if there was something to flush. Otherwise False.
/// </summary>
internal bool Flush(byte[] outputBuffer, out int bytesRead)
{
Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
Debug.Assert(outputBuffer.Length > 0, "Can't pass in an empty output buffer!");
Debug.Assert(NeedsInput(), "We have something left in previous input!");
Debug.Assert(!_inputBufferHandle.HasPointer);
// Note: we require that NeedsInput() == true, i.e. that 0 == _zlibStream.AvailIn.
// If there is still input left we should never be getting here; instead we
// should be calling GetDeflateOutput.
return ReadDeflateOutput(outputBuffer, ZFlushCode.SyncFlush, out bytesRead) == ZErrorCode.Ok;
}
private void DeallocateInputBufferHandle()
{
lock (SyncLock)
{
_zlibStream.AvailIn = 0;
_zlibStream.NextIn = ZLibNative.ZNullPtr;
_inputBufferHandle.Dispose();
}
}
private void DeflateInit(ZLibNative.CompressionLevel compressionLevel, int windowBits, int memLevel,
ZLibNative.CompressionStrategy strategy)
{
ZErrorCode errC;
try
{
errC = ZLibNative.CreateZLibStreamForDeflate(out _zlibStream, compressionLevel,
windowBits, memLevel, strategy);
}
catch (Exception cause)
{
throw new ZLibException(SR.ZLibErrorDLLLoadError, cause);
}
switch (errC)
{
case ZErrorCode.Ok:
return;
case ZErrorCode.MemError:
throw new ZLibException(SR.ZLibErrorNotEnoughMemory, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
case ZErrorCode.VersionError:
throw new ZLibException(SR.ZLibErrorVersionMismatch, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
case ZErrorCode.StreamError:
throw new ZLibException(SR.ZLibErrorIncorrectInitParameters, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
default:
throw new ZLibException(SR.ZLibErrorUnexpected, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
}
}
private ZErrorCode Deflate(ZFlushCode flushCode)
{
ZErrorCode errC;
try
{
errC = _zlibStream.Deflate(flushCode);
}
catch (Exception cause)
{
throw new ZLibException(SR.ZLibErrorDLLLoadError, cause);
}
switch (errC)
{
case ZErrorCode.Ok:
case ZErrorCode.StreamEnd:
return errC;
case ZErrorCode.BufError:
return errC; // This is a recoverable error
case ZErrorCode.StreamError:
throw new ZLibException(SR.ZLibErrorInconsistentStream, "deflate", (int)errC, _zlibStream.GetErrorMessage());
default:
throw new ZLibException(SR.ZLibErrorUnexpected, "deflate", (int)errC, _zlibStream.GetErrorMessage());
}
}
}
}
| |
// 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.Globalization;
using System.IO;
using System.Net.Cache;
using System.Net.Http;
using System.Net.Security;
using System.Runtime.Serialization;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
public delegate void HttpContinueDelegate(int StatusCode, WebHeaderCollection httpHeaders);
[Serializable]
public class HttpWebRequest : WebRequest, ISerializable
{
private const int DefaultContinueTimeout = 350; // Current default value from .NET Desktop.
private WebHeaderCollection _webHeaderCollection = new WebHeaderCollection();
private Uri _requestUri;
private string _originVerb = HttpMethod.Get.Method;
// We allow getting and setting this (to preserve app-compat). But we don't do anything with it
// as the underlying System.Net.Http API doesn't support it.
private int _continueTimeout = DefaultContinueTimeout;
private bool _allowReadStreamBuffering = false;
private CookieContainer _cookieContainer = null;
private ICredentials _credentials = null;
private IWebProxy _proxy = WebRequest.DefaultWebProxy;
private Task<HttpResponseMessage> _sendRequestTask;
private static int _defaultMaxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength;
private int _beginGetRequestStreamCalled = 0;
private int _beginGetResponseCalled = 0;
private int _endGetRequestStreamCalled = 0;
private int _endGetResponseCalled = 0;
private int _maximumAllowedRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private int _maximumResponseHeadersLen = _defaultMaxResponseHeadersLength;
private ServicePoint _servicePoint;
private int _timeout = WebRequest.DefaultTimeoutMilliseconds;
private HttpContinueDelegate _continueDelegate;
private RequestStream _requestStream;
private TaskCompletionSource<Stream> _requestStreamOperation = null;
private TaskCompletionSource<WebResponse> _responseOperation = null;
private AsyncCallback _requestStreamCallback = null;
private AsyncCallback _responseCallback = null;
private int _abortCalled = 0;
private CancellationTokenSource _sendRequestCts;
private X509CertificateCollection _clientCertificates;
private Booleans _booleans = Booleans.Default;
private bool _pipelined = true;
private bool _preAuthenticate;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
//these should be safe.
[Flags]
private enum Booleans : uint
{
AllowAutoRedirect = 0x00000001,
AllowWriteStreamBuffering = 0x00000002,
ExpectContinue = 0x00000004,
ProxySet = 0x00000010,
UnsafeAuthenticatedConnectionSharing = 0x00000040,
IsVersionHttp10 = 0x00000080,
SendChunked = 0x00000100,
EnableDecompression = 0x00000200,
IsTunnelRequest = 0x00000400,
IsWebSocketRequest = 0x00000800,
Default = AllowAutoRedirect | AllowWriteStreamBuffering | ExpectContinue
}
private const string ContinueHeader = "100-continue";
private const string ChunkedHeader = "chunked";
private const string GZipHeader = "gzip";
private const string DeflateHeader = "deflate";
public HttpWebRequest()
{
}
[Obsolete("Serialization is obsoleted for this type. http://go.microsoft.com/fwlink/?linkid=14202")]
protected HttpWebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext)
{
throw new PlatformNotSupportedException();
}
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
protected override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
internal HttpWebRequest(Uri uri)
{
_requestUri = uri;
}
private void SetSpecialHeaders(string HeaderName, string value)
{
_webHeaderCollection.Remove(HeaderName);
if (!string.IsNullOrEmpty(value))
{
_webHeaderCollection[HeaderName] = value;
}
}
public string Accept
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Accept];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.Accept, value);
}
}
public virtual bool AllowReadStreamBuffering
{
get
{
return false;
}
set
{
if (value)
{
throw new InvalidOperationException(SR.net_OperationNotSupportedException);
}
}
}
public int MaximumResponseHeadersLength
{
get
{
return _maximumResponseHeadersLen;
}
set
{
_maximumResponseHeadersLen = value;
}
}
public int MaximumAutomaticRedirections
{
get
{
return _maximumAllowedRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentException(SR.net_toosmall, nameof(value));
}
_maximumAllowedRedirections = value;
}
}
public override String ContentType
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.ContentType];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.ContentType, value);
}
}
public int ContinueTimeout
{
get
{
return _continueTimeout;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
if ((value < 0) && (value != System.Threading.Timeout.Infinite))
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero);
}
_continueTimeout = value;
}
}
public override int Timeout
{
get
{
return _timeout;
}
set
{
if (value < 0 && value != System.Threading.Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero);
}
_timeout = value;
}
}
public override long ContentLength
{
get
{
long value;
long.TryParse(_webHeaderCollection[HttpKnownHeaderNames.ContentLength], out value);
return value;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_ge_zero);
}
SetSpecialHeaders(HttpKnownHeaderNames.ContentLength, value.ToString());
}
}
public Uri Address
{
get
{
return _requestUri;
}
}
public string UserAgent
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.UserAgent];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.UserAgent, value);
}
}
public string Host
{
get
{
throw new PlatformNotSupportedException();
}
set
{
throw new PlatformNotSupportedException();
}
}
public bool Pipelined
{
get
{
return _pipelined;
}
set
{
_pipelined = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the value of the Referer header.
/// </para>
/// </devdoc>
public string Referer
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Referer];
}
set
{
SetSpecialHeaders(HttpKnownHeaderNames.Referer, value);
}
}
/// <devdoc>
/// <para>Sets the media type header</para>
/// </devdoc>
public string MediaType
{
get
{
throw new PlatformNotSupportedException();
}
set
{
throw new PlatformNotSupportedException();
}
}
/// <devdoc>
/// <para>
/// Gets or sets the value of the Transfer-Encoding header. Setting null clears it out.
/// </para>
/// </devdoc>
public string TransferEncoding
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.TransferEncoding];
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
bool fChunked;
//
// on blank string, remove current header
//
if (string.IsNullOrWhiteSpace(value))
{
//
// if the value is blank, then remove the header
//
_webHeaderCollection.Remove(HttpKnownHeaderNames.TransferEncoding);
return;
}
//
// if not check if the user is trying to set chunked:
//
string newValue = value.ToLower();
fChunked = (newValue.IndexOf(ChunkedHeader) != -1);
//
// prevent them from adding chunked, or from adding an Encoding without
// turing on chunked, the reason is due to the HTTP Spec which prevents
// additional encoding types from being used without chunked
//
if (fChunked)
{
throw new ArgumentException(SR.net_nochunked, nameof(value));
}
else if (!SendChunked)
{
throw new InvalidOperationException(SR.net_needchunked);
}
else
{
string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value);
_webHeaderCollection[HttpKnownHeaderNames.TransferEncoding] = checkedValue;
}
#if DEBUG
}
#endif
}
}
public bool KeepAlive
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.KeepAlive] == bool.TrueString;
}
set
{
if (value)
{
SetSpecialHeaders(HttpKnownHeaderNames.KeepAlive, bool.TrueString);
}
else
{
SetSpecialHeaders(HttpKnownHeaderNames.KeepAlive, bool.FalseString);
}
}
}
public bool UnsafeAuthenticatedConnectionSharing
{
get
{
return (_booleans & Booleans.UnsafeAuthenticatedConnectionSharing) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.UnsafeAuthenticatedConnectionSharing;
}
else
{
_booleans &= ~Booleans.UnsafeAuthenticatedConnectionSharing;
}
}
}
public DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
_automaticDecompression = value;
}
}
public virtual bool AllowWriteStreamBuffering
{
get
{
return (_booleans & Booleans.AllowWriteStreamBuffering) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.AllowWriteStreamBuffering;
}
else
{
_booleans &= ~Booleans.AllowWriteStreamBuffering;
}
}
}
/// <devdoc>
/// <para>
/// Enables or disables automatically following redirection responses.
/// </para>
/// </devdoc>
public virtual bool AllowAutoRedirect
{
get
{
return (_booleans & Booleans.AllowAutoRedirect) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.AllowAutoRedirect;
}
else
{
_booleans &= ~Booleans.AllowAutoRedirect;
}
}
}
public override string ConnectionGroupName
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public override bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
_preAuthenticate = value;
}
}
public string Connection
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Connection];
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
bool fKeepAlive;
bool fClose;
//
// on blank string, remove current header
//
if (string.IsNullOrWhiteSpace(value))
{
_webHeaderCollection.Remove(HttpKnownHeaderNames.Connection);
return;
}
string newValue = value.ToLower();
fKeepAlive = (newValue.IndexOf("keep-alive") != -1);
fClose = (newValue.IndexOf("close") != -1);
//
// Prevent keep-alive and close from being added
//
if (fKeepAlive ||
fClose)
{
throw new ArgumentException(SR.net_connarg, nameof(value));
}
else
{
string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value);
_webHeaderCollection[HttpKnownHeaderNames.Connection] = checkedValue;
}
#if DEBUG
}
#endif
}
}
/*
Accessor: Expect
The property that controls the Expect header
Input:
string Expect, null clears the Expect except for 100-continue value
Returns: The value of the Expect on get.
*/
public string Expect
{
get
{
return _webHeaderCollection[HttpKnownHeaderNames.Expect];
}
set
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
// only remove everything other than 100-cont
bool fContinue100;
//
// on blank string, remove current header
//
if (string.IsNullOrWhiteSpace(value))
{
_webHeaderCollection.Remove(HttpKnownHeaderNames.Expect);
return;
}
//
// Prevent 100-continues from being added
//
string newValue = value.ToLower();
fContinue100 = (newValue.IndexOf(ContinueHeader) != -1);
if (fContinue100)
{
throw new ArgumentException(SR.net_no100, nameof(value));
}
else
{
string checkedValue = HttpValidationHelpers.CheckBadHeaderValueChars(value);
_webHeaderCollection[HttpKnownHeaderNames.Expect] = checkedValue;
}
#if DEBUG
}
#endif
}
}
/// <devdoc>
/// <para>
/// Gets or sets the default for the MaximumResponseHeadersLength property.
/// </para>
/// <remarks>
/// This value can be set in the config file, the default can be overridden using the MaximumResponseHeadersLength property.
/// </remarks>
/// </devdoc>
public static int DefaultMaximumResponseHeadersLength
{
get
{
return _defaultMaxResponseHeadersLength;
}
set
{
_defaultMaxResponseHeadersLength = value;
}
}
// NOP
public static int DefaultMaximumErrorResponseLength
{
get;set;
}
public static new RequestCachePolicy DefaultCachePolicy { get; set; } = new RequestCachePolicy(RequestCacheLevel.BypassCache);
public DateTime IfModifiedSince
{
get
{
return GetDateHeaderHelper(HttpKnownHeaderNames.IfModifiedSince);
}
set
{
SetDateHeaderHelper(HttpKnownHeaderNames.IfModifiedSince, value);
}
}
/// <devdoc>
/// <para>
/// Gets or sets the value of the Date header.
/// </para>
/// </devdoc>
public DateTime Date
{
get
{
return GetDateHeaderHelper(HttpKnownHeaderNames.Date);
}
set
{
SetDateHeaderHelper(HttpKnownHeaderNames.Date, value);
}
}
public bool SendChunked
{
get
{
return (_booleans & Booleans.SendChunked) != 0;
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
if (value)
{
_booleans |= Booleans.SendChunked;
}
else
{
_booleans &= ~Booleans.SendChunked;
}
}
}
public HttpContinueDelegate ContinueDelegate
{
// Nop since the underlying API do not expose 100 continue.
get
{
return _continueDelegate;
}
set
{
_continueDelegate = value;
}
}
public ServicePoint ServicePoint
{
get
{
if (_servicePoint == null)
{
_servicePoint = ServicePointManager.FindServicePoint(Address, Proxy);
}
return _servicePoint;
}
}
public RemoteCertificateValidationCallback ServerCertificateValidationCallback { get; set; }
//
// ClientCertificates - sets our certs for our reqest,
// uses a hash of the collection to create a private connection
// group, to prevent us from using the same Connection as
// non-Client Authenticated requests.
//
public X509CertificateCollection ClientCertificates
{
get
{
if (_clientCertificates == null)
_clientCertificates = new X509CertificateCollection();
return _clientCertificates;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_clientCertificates = value;
}
}
// HTTP Version
/// <devdoc>
/// <para>
/// Gets and sets
/// the HTTP protocol version used in this request.
/// </para>
/// </devdoc>
public Version ProtocolVersion
{
get
{
return IsVersionHttp10 ? HttpVersion.Version10 : HttpVersion.Version11;
}
set
{
if (value.Equals(HttpVersion.Version11))
{
IsVersionHttp10 = false;
}
else if (value.Equals(HttpVersion.Version10))
{
IsVersionHttp10 = true;
}
else
{
throw new ArgumentException(SR.net_wrongversion, nameof(value));
}
}
}
public int ReadWriteTimeout
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
_cookieContainer = value;
}
}
public override ICredentials Credentials
{
get
{
return _credentials;
}
set
{
_credentials = value;
}
}
public virtual bool HaveResponse
{
get
{
return (_sendRequestTask != null) && (_sendRequestTask.Status == TaskStatus.RanToCompletion);
}
}
public override WebHeaderCollection Headers
{
get
{
return _webHeaderCollection;
}
set
{
// We can't change headers after they've already been sent.
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
WebHeaderCollection webHeaders = value;
WebHeaderCollection newWebHeaders = new WebHeaderCollection();
// Copy And Validate -
// Handle the case where their object tries to change
// name, value pairs after they call set, so therefore,
// we need to clone their headers.
foreach (String headerName in webHeaders.AllKeys)
{
newWebHeaders[headerName] = webHeaders[headerName];
}
_webHeaderCollection = newWebHeaders;
}
}
public override string Method
{
get
{
return _originVerb;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_badmethod, nameof(value));
}
if (HttpValidationHelpers.IsInvalidMethodOrHeaderString(value))
{
throw new ArgumentException(SR.net_badmethod, nameof(value));
}
_originVerb = value;
}
}
public override Uri RequestUri
{
get
{
return _requestUri;
}
}
public virtual bool SupportsCookieContainer
{
get
{
return true;
}
}
public override bool UseDefaultCredentials
{
get
{
return (_credentials == CredentialCache.DefaultCredentials);
}
set
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_writestarted);
}
// Match Desktop behavior. Changing this property will also
// change the .Credentials property as well.
_credentials = value ? CredentialCache.DefaultCredentials : null;
}
}
public override IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
// We can't change the proxy while the request is already fired.
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
_proxy = value;
}
}
public override void Abort()
{
if (Interlocked.Exchange(ref _abortCalled, 1) != 0)
{
return;
}
// .NET Desktop behavior requires us to invoke outstanding callbacks
// before returning if used in either the BeginGetRequestStream or
// BeginGetResponse methods.
//
// If we can transition the task to the canceled state, then we invoke
// the callback. If we can't transition the task, it is because it is
// already in the terminal state and the callback has already been invoked
// via the async task continuation.
if (_responseOperation != null)
{
if (_responseOperation.TrySetCanceled() && _responseCallback != null)
{
_responseCallback(_responseOperation.Task);
}
// Cancel the underlying send operation.
Debug.Assert(_sendRequestCts != null);
_sendRequestCts.Cancel();
}
else if (_requestStreamOperation != null)
{
if (_requestStreamOperation.TrySetCanceled() && _requestStreamCallback != null)
{
_requestStreamCallback(_requestStreamOperation.Task);
}
}
}
// HTTP version of the request
private bool IsVersionHttp10
{
get
{
return (_booleans & Booleans.IsVersionHttp10) != 0;
}
set
{
if (value)
{
_booleans |= Booleans.IsVersionHttp10;
}
else
{
_booleans &= ~Booleans.IsVersionHttp10;
}
}
}
public override WebResponse GetResponse()
{
try
{
_sendRequestCts = new CancellationTokenSource();
return SendRequest().GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
}
public override Stream GetRequestStream()
{
return InternalGetRequestStream().Result;
}
private Task<Stream> InternalGetRequestStream()
{
CheckAbort();
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
// Match Desktop behavior: prevent someone from getting a request stream
// if the protocol verb/method doesn't support it. Note that this is not
// entirely compliant RFC2616 for the aforementioned compatibility reasons.
if (string.Equals(HttpMethod.Get.Method, _originVerb, StringComparison.OrdinalIgnoreCase) ||
string.Equals(HttpMethod.Head.Method, _originVerb, StringComparison.OrdinalIgnoreCase) ||
string.Equals("CONNECT", _originVerb, StringComparison.OrdinalIgnoreCase))
{
throw new ProtocolViolationException(SR.net_nouploadonget);
}
_requestStream = new RequestStream();
return Task.FromResult((Stream)_requestStream);
}
public Stream EndGetRequestStream(IAsyncResult asyncResult, out TransportContext context)
{
context = null;
return EndGetRequestStream(asyncResult);
}
public Stream GetRequestStream(out TransportContext context)
{
context = null;
return GetRequestStream();
}
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, Object state)
{
CheckAbort();
if (Interlocked.Exchange(ref _beginGetRequestStreamCalled, 1) != 0)
{
throw new InvalidOperationException(SR.net_repcall);
}
_requestStreamCallback = callback;
_requestStreamOperation = GetRequestStreamTask().ToApm(callback, state);
return _requestStreamOperation.Task;
}
public override Stream EndGetRequestStream(IAsyncResult asyncResult)
{
CheckAbort();
if (asyncResult == null || !(asyncResult is Task<Stream>))
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (Interlocked.Exchange(ref _endGetRequestStreamCalled, 1) != 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetRequestStream"));
}
Stream stream;
try
{
stream = ((Task<Stream>)asyncResult).GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
return stream;
}
private Task<Stream> GetRequestStreamTask()
{
CheckAbort();
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
// Match Desktop behavior: prevent someone from getting a request stream
// if the protocol verb/method doesn't support it. Note that this is not
// entirely compliant RFC2616 for the aforementioned compatibility reasons.
if (string.Equals(HttpMethod.Get.Method, _originVerb, StringComparison.OrdinalIgnoreCase) ||
string.Equals(HttpMethod.Head.Method, _originVerb, StringComparison.OrdinalIgnoreCase) ||
string.Equals("CONNECT", _originVerb, StringComparison.OrdinalIgnoreCase))
{
throw new ProtocolViolationException(SR.net_nouploadonget);
}
_requestStream = new RequestStream();
return Task.FromResult((Stream)_requestStream);
}
private async Task<WebResponse> SendRequest()
{
if (RequestSubmitted)
{
throw new InvalidOperationException(SR.net_reqsubmitted);
}
var handler = new HttpClientHandler();
var request = new HttpRequestMessage(new HttpMethod(_originVerb), _requestUri);
using (var client = new HttpClient(handler))
{
if (_requestStream != null)
{
ArraySegment<byte> bytes = _requestStream.GetBuffer();
request.Content = new ByteArrayContent(bytes.Array, bytes.Offset, bytes.Count);
}
handler.AutomaticDecompression = AutomaticDecompression;
handler.Credentials = _credentials;
handler.AllowAutoRedirect = AllowAutoRedirect;
handler.MaxAutomaticRedirections = MaximumAutomaticRedirections;
handler.MaxResponseHeadersLength = MaximumResponseHeadersLength;
handler.PreAuthenticate = PreAuthenticate;
client.Timeout = Timeout == Threading.Timeout.Infinite ?
Threading.Timeout.InfiniteTimeSpan :
TimeSpan.FromMilliseconds(Timeout);
if (_cookieContainer != null)
{
handler.CookieContainer = _cookieContainer;
Debug.Assert(handler.UseCookies); // Default of handler.UseCookies is true.
}
else
{
handler.UseCookies = false;
}
Debug.Assert(handler.UseProxy); // Default of handler.UseProxy is true.
Debug.Assert(handler.Proxy == null); // Default of handler.Proxy is null.
if (_proxy == null)
{
handler.UseProxy = false;
}
else
{
handler.Proxy = _proxy;
}
handler.ClientCertificates.AddRange(ClientCertificates);
// Set relevant properties from ServicePointManager
handler.SslProtocols = (SslProtocols)ServicePointManager.SecurityProtocol;
handler.CheckCertificateRevocationList = ServicePointManager.CheckCertificateRevocationList;
RemoteCertificateValidationCallback rcvc = ServerCertificateValidationCallback != null ?
ServerCertificateValidationCallback :
ServicePointManager.ServerCertificateValidationCallback;
if (rcvc != null)
{
RemoteCertificateValidationCallback localRcvc = rcvc;
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => localRcvc(this, cert, chain, errors);
}
// Copy the HttpWebRequest request headers from the WebHeaderCollection into HttpRequestMessage.Headers and
// HttpRequestMessage.Content.Headers.
foreach (string headerName in _webHeaderCollection)
{
// The System.Net.Http APIs require HttpRequestMessage headers to be properly divided between the request headers
// collection and the request content headers collection for all well-known header names. And custom headers
// are only allowed in the request headers collection and not in the request content headers collection.
if (IsWellKnownContentHeader(headerName))
{
if (request.Content == null)
{
// Create empty content so that we can send the entity-body header.
request.Content = new ByteArrayContent(Array.Empty<byte>());
}
request.Content.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]);
}
else
{
request.Headers.TryAddWithoutValidation(headerName, _webHeaderCollection[headerName]);
}
}
request.Headers.TransferEncodingChunked = SendChunked;
_sendRequestTask = client.SendAsync(
request,
_allowReadStreamBuffering ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead,
_sendRequestCts.Token);
HttpResponseMessage responseMessage = await _sendRequestTask.ConfigureAwait(false);
HttpWebResponse response = new HttpWebResponse(responseMessage, _requestUri, _cookieContainer);
if (!responseMessage.IsSuccessStatusCode)
{
throw new WebException(
SR.Format(SR.net_servererror, (int)response.StatusCode, response.StatusDescription),
null,
WebExceptionStatus.ProtocolError,
response);
}
return response;
}
}
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
CheckAbort();
if (Interlocked.Exchange(ref _beginGetResponseCalled, 1) != 0)
{
throw new InvalidOperationException(SR.net_repcall);
}
_sendRequestCts = new CancellationTokenSource();
_responseCallback = callback;
_responseOperation = SendRequest().ToApm(callback, state);
return _responseOperation.Task;
}
public override WebResponse EndGetResponse(IAsyncResult asyncResult)
{
CheckAbort();
if (asyncResult == null || !(asyncResult is Task<WebResponse>))
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (Interlocked.Exchange(ref _endGetResponseCalled, 1) != 0)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetResponse"));
}
WebResponse response;
try
{
response = ((Task<WebResponse>)asyncResult).GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
return response;
}
/// <devdoc>
/// <para>
/// Adds a range header to the request for a specified range.
/// </para>
/// </devdoc>
public void AddRange(int from, int to)
{
AddRange("bytes", (long)from, (long)to);
}
/// <devdoc>
/// <para>
/// Adds a range header to the request for a specified range.
/// </para>
/// </devdoc>
public void AddRange(long from, long to)
{
AddRange("bytes", from, to);
}
/// <devdoc>
/// <para>
/// Adds a range header to a request for a specific
/// range from the beginning or end
/// of the requested data.
/// To add the range from the end pass negative value
/// To add the range from the some offset to the end pass positive value
/// </para>
/// </devdoc>
public void AddRange(int range)
{
AddRange("bytes", (long)range);
}
/// <devdoc>
/// <para>
/// Adds a range header to a request for a specific
/// range from the beginning or end
/// of the requested data.
/// To add the range from the end pass negative value
/// To add the range from the some offset to the end pass positive value
/// </para>
/// </devdoc>
public void AddRange(long range)
{
AddRange("bytes", range);
}
public void AddRange(string rangeSpecifier, int from, int to)
{
AddRange(rangeSpecifier, (long)from, (long)to);
}
public void AddRange(string rangeSpecifier, long from, long to)
{
//
// Do some range checking before assembling the header
//
if (rangeSpecifier == null)
{
throw new ArgumentNullException(nameof(rangeSpecifier));
}
if ((from < 0) || (to < 0))
{
throw new ArgumentOutOfRangeException(from < 0 ? nameof(from) : nameof(to), SR.net_rangetoosmall);
}
if (from > to)
{
throw new ArgumentOutOfRangeException(nameof(from), SR.net_fromto);
}
if (!HttpValidationHelpers.IsValidToken(rangeSpecifier))
{
throw new ArgumentException(SR.net_nottoken, nameof(rangeSpecifier));
}
if (!AddRange(rangeSpecifier, from.ToString(NumberFormatInfo.InvariantInfo), to.ToString(NumberFormatInfo.InvariantInfo)))
{
throw new InvalidOperationException(SR.net_rangetype);
}
}
public void AddRange(string rangeSpecifier, int range)
{
AddRange(rangeSpecifier, (long)range);
}
public void AddRange(string rangeSpecifier, long range)
{
if (rangeSpecifier == null)
{
throw new ArgumentNullException(nameof(rangeSpecifier));
}
if (!HttpValidationHelpers.IsValidToken(rangeSpecifier))
{
throw new ArgumentException(SR.net_nottoken, nameof(rangeSpecifier));
}
if (!AddRange(rangeSpecifier, range.ToString(NumberFormatInfo.InvariantInfo), (range >= 0) ? "" : null))
{
throw new InvalidOperationException(SR.net_rangetype);
}
}
private bool AddRange(string rangeSpecifier, string from, string to)
{
string curRange = _webHeaderCollection[HttpKnownHeaderNames.Range];
if ((curRange == null) || (curRange.Length == 0))
{
curRange = rangeSpecifier + "=";
}
else
{
if (String.Compare(curRange.Substring(0, curRange.IndexOf('=')), rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
{
return false;
}
curRange = string.Empty;
}
curRange += from.ToString();
if (to != null)
{
curRange += "-" + to;
}
_webHeaderCollection[HttpKnownHeaderNames.Range] = curRange;
return true;
}
private bool RequestSubmitted
{
get
{
return _sendRequestTask != null;
}
}
private void CheckAbort()
{
if (Volatile.Read(ref _abortCalled) == 1)
{
throw new WebException(SR.net_reqaborted, WebExceptionStatus.RequestCanceled);
}
}
private static readonly string[] s_wellKnownContentHeaders = {
HttpKnownHeaderNames.ContentDisposition,
HttpKnownHeaderNames.ContentEncoding,
HttpKnownHeaderNames.ContentLanguage,
HttpKnownHeaderNames.ContentLength,
HttpKnownHeaderNames.ContentLocation,
HttpKnownHeaderNames.ContentMD5,
HttpKnownHeaderNames.ContentRange,
HttpKnownHeaderNames.ContentType,
HttpKnownHeaderNames.Expires,
HttpKnownHeaderNames.LastModified
};
private bool IsWellKnownContentHeader(string header)
{
foreach (string contentHeaderName in s_wellKnownContentHeaders)
{
if (string.Equals(header, contentHeaderName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
private DateTime GetDateHeaderHelper(string headerName)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
string headerValue = _webHeaderCollection[headerName];
if (headerValue == null)
{
return DateTime.MinValue; // MinValue means header is not present
}
return StringToDate(headerValue);
#if DEBUG
}
#endif
}
private void SetDateHeaderHelper(string headerName, DateTime dateTime)
{
#if DEBUG
using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
if (dateTime == DateTime.MinValue)
SetSpecialHeaders(headerName, null); // remove header
else
SetSpecialHeaders(headerName, DateToString(dateTime));
#if DEBUG
}
#endif
}
// parse String to DateTime format.
private static DateTime StringToDate(String S)
{
DateTime dtOut;
if (HttpDateParse.ParseHttpDate(S, out dtOut))
{
return dtOut;
}
else
{
throw new ProtocolViolationException(SR.net_baddate);
}
}
// convert Date to String using RFC 1123 pattern
private static string DateToString(DateTime D)
{
DateTimeFormatInfo dateFormat = new DateTimeFormatInfo();
return D.ToUniversalTime().ToString("R", dateFormat);
}
}
}
| |
using UnityEngine;
using System;
namespace UnityStandardAssets.CinematicEffects
{
//Improvement ideas:
// Use rgba8 buffer in ldr / in some pass in hdr (in correlation to previous point and remapping coc from -1/0/1 to 0/0.5/1)
// Use temporal stabilisation
// Add a mode to do bokeh texture in quarter res as well
// Support different near and far blur for the bokeh texture
// Try distance field for the bokeh texture
// Try to separate the output of the blur pass to two rendertarget near+far, see the gain in quality vs loss in performance
// Try swirl effect on the samples of the circle blur
//References :
// This DOF implementation use ideas from public sources, a big thank to them :
// http://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare
// http://www.crytek.com/download/Sousa_Graphics_Gems_CryENGINE3.pdf
// http://graphics.cs.williams.edu/papers/MedianShaderX6/
// http://http.developer.nvidia.com/GPUGems/gpugems_ch24.html
// http://vec3.ca/bicubic-filtering-in-fewer-taps/
[ExecuteInEditMode]
[AddComponentMenu("Image Effects/Cinematic/Depth Of Field")]
[RequireComponent(typeof(Camera))]
public class DepthOfField : MonoBehaviour
{
private const float kMaxBlur = 40.0f;
#region Render passes
private enum Passes
{
BlurAlphaWeighted,
BoxBlur,
DilateFgCocFromColor,
DilateFgCoc,
CaptureCocExplicit,
VisualizeCocExplicit,
CocPrefilter,
CircleBlur,
CircleBlurWithDilatedFg,
CircleBlurLowQuality,
CircleBlowLowQualityWithDilatedFg,
MergeExplicit,
ShapeLowQuality,
ShapeLowQualityDilateFg,
ShapeLowQualityMerge,
ShapeLowQualityMergeDilateFg,
ShapeMediumQuality,
ShapeMediumQualityDilateFg,
ShapeMediumQualityMerge,
ShapeMediumQualityMergeDilateFg,
ShapeHighQuality,
ShapeHighQualityDilateFg,
ShapeHighQualityMerge,
ShapeHighQualityMergeDilateFg
}
private enum MedianPasses
{
Median3,
Median3X3
}
private enum BokehTexturesPasses
{
Apply,
Collect
}
#endregion
public enum TweakMode
{
Range,
Explicit
}
public enum ApertureShape
{
Circular,
Hexagonal,
Octogonal
}
public enum QualityPreset
{
Low,
Medium,
High
}
public enum FilterQuality
{
None,
Normal,
High
}
#region Settings
[Serializable]
public struct GlobalSettings
{
[Tooltip("Allows to view where the blur will be applied. Yellow for near blur, blue for far blur.")]
public bool visualizeFocus;
[Tooltip("Setup mode. Use \"Advanced\" if you need more control on blur settings and/or want to use a bokeh texture. \"Explicit\" is the same as \"Advanced\" but makes use of \"Near Plane\" and \"Far Plane\" values instead of \"F-Stop\".")]
public TweakMode tweakMode;
[Tooltip("Quality presets. Use \"Custom\" for more advanced settings.")]
public QualityPreset filteringQuality;
[Tooltip("\"Circular\" is the fastest, followed by \"Hexagonal\" and \"Octogonal\".")]
public ApertureShape apertureShape;
[Range(0f, 179f), Tooltip("Rotates the aperture when working with \"Hexagonal\" and \"Ortogonal\".")]
public float apertureOrientation;
public static GlobalSettings defaultSettings
{
get
{
return new GlobalSettings
{
visualizeFocus = false,
tweakMode = TweakMode.Range,
filteringQuality = QualityPreset.High,
apertureShape = ApertureShape.Circular,
apertureOrientation = 0f
};
}
}
}
[Serializable]
public struct QualitySettings
{
[Tooltip("Enable this to get smooth bokeh.")]
public bool prefilterBlur;
[Tooltip("Applies a median filter for even smoother bokeh.")]
public FilterQuality medianFilter;
[Tooltip("Dilates near blur over in focus area.")]
public bool dilateNearBlur;
public static QualitySettings[] presetQualitySettings =
{
// Low
new QualitySettings
{
prefilterBlur = false,
medianFilter = FilterQuality.None,
dilateNearBlur = false
},
// Medium
new QualitySettings
{
prefilterBlur = true,
medianFilter = FilterQuality.Normal,
dilateNearBlur = false
},
// High
new QualitySettings
{
prefilterBlur = true,
medianFilter = FilterQuality.High,
dilateNearBlur = true
}
};
}
[Serializable]
public struct FocusSettings
{
[Tooltip("Auto-focus on a selected transform.")]
public Transform transform;
[Min(0f), Tooltip("Focus distance (in world units).")]
public float focusPlane;
[Min(0.1f), Tooltip("Focus range (in world units). The focus plane is located in the center of the range.")]
public float range;
[Min(0f), Tooltip("Near focus distance (in world units).")]
public float nearPlane;
[Min(0f), Tooltip("Near blur falloff (in world units).")]
public float nearFalloff;
[Min(0f), Tooltip("Far focus distance (in world units).")]
public float farPlane;
[Min(0f), Tooltip("Far blur falloff (in world units).")]
public float farFalloff;
[Range(0f, kMaxBlur), Tooltip("Maximum blur radius for the near plane.")]
public float nearBlurRadius;
[Range(0f, kMaxBlur), Tooltip("Maximum blur radius for the far plane.")]
public float farBlurRadius;
public static FocusSettings defaultSettings
{
get
{
return new FocusSettings
{
transform = null,
focusPlane = 20f,
range = 35f,
nearPlane = 2.5f,
nearFalloff = 15f,
farPlane = 37.5f,
farFalloff = 50f,
nearBlurRadius = 15f,
farBlurRadius = 20f
};
}
}
}
[Serializable]
public struct BokehTextureSettings
{
[Tooltip("Adding a texture to this field will enable the use of \"Bokeh Textures\". Use with care. This feature is only available on Shader Model 5 compatible-hardware and performance scale with the amount of bokeh.")]
public Texture2D texture;
[Range(0.01f, 10f), Tooltip("Maximum size of bokeh textures on screen.")]
public float scale;
[Range(0.01f, 100f), Tooltip("Bokeh brightness.")]
public float intensity;
[Range(0.01f, 5f), Tooltip("Controls the amount of bokeh textures. Lower values mean more bokeh splats.")]
public float threshold;
[Range(0.01f, 1f), Tooltip("Controls the spawn conditions. Lower values mean more visible bokeh.")]
public float spawnHeuristic;
public static BokehTextureSettings defaultSettings
{
get
{
return new BokehTextureSettings
{
texture = null,
scale = 1f,
intensity = 50f,
threshold = 2f,
spawnHeuristic = 0.15f
};
}
}
}
#endregion
public GlobalSettings settings = GlobalSettings.defaultSettings;
public FocusSettings focus = FocusSettings.defaultSettings;
public BokehTextureSettings bokehTexture = BokehTextureSettings.defaultSettings;
[SerializeField]
private Shader m_FilmicDepthOfFieldShader;
public Shader filmicDepthOfFieldShader
{
get
{
if (m_FilmicDepthOfFieldShader == null)
m_FilmicDepthOfFieldShader = Shader.Find("Hidden/DepthOfField/DepthOfField");
return m_FilmicDepthOfFieldShader;
}
}
[SerializeField]
private Shader m_MedianFilterShader;
public Shader medianFilterShader
{
get
{
if (m_MedianFilterShader == null)
m_MedianFilterShader = Shader.Find("Hidden/DepthOfField/MedianFilter");
return m_MedianFilterShader;
}
}
[SerializeField]
private Shader m_TextureBokehShader;
public Shader textureBokehShader
{
get
{
if (m_TextureBokehShader == null)
m_TextureBokehShader = Shader.Find("Hidden/DepthOfField/BokehSplatting");
return m_TextureBokehShader;
}
}
private RenderTextureUtility m_RTU = new RenderTextureUtility();
private Material m_FilmicDepthOfFieldMaterial;
public Material filmicDepthOfFieldMaterial
{
get
{
if (m_FilmicDepthOfFieldMaterial == null)
m_FilmicDepthOfFieldMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(filmicDepthOfFieldShader);
return m_FilmicDepthOfFieldMaterial;
}
}
private Material m_MedianFilterMaterial;
public Material medianFilterMaterial
{
get
{
if (m_MedianFilterMaterial == null)
m_MedianFilterMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(medianFilterShader);
return m_MedianFilterMaterial;
}
}
private Material m_TextureBokehMaterial;
public Material textureBokehMaterial
{
get
{
if (m_TextureBokehMaterial == null)
m_TextureBokehMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(textureBokehShader);
return m_TextureBokehMaterial;
}
}
private ComputeBuffer m_ComputeBufferDrawArgs;
public ComputeBuffer computeBufferDrawArgs
{
get
{
if (m_ComputeBufferDrawArgs == null)
{
#if UNITY_5_4_OR_NEWER
m_ComputeBufferDrawArgs = new ComputeBuffer(1, 16, ComputeBufferType.IndirectArguments);
#else
m_ComputeBufferDrawArgs = new ComputeBuffer(1, 16, ComputeBufferType.DrawIndirect);
#endif
m_ComputeBufferDrawArgs.SetData(new[] {0, 1, 0, 0});
}
return m_ComputeBufferDrawArgs;
}
}
private ComputeBuffer m_ComputeBufferPoints;
public ComputeBuffer computeBufferPoints
{
get
{
if (m_ComputeBufferPoints == null)
m_ComputeBufferPoints = new ComputeBuffer(90000, 12 + 16, ComputeBufferType.Append);
return m_ComputeBufferPoints;
}
}
private QualitySettings m_CurrentQualitySettings;
private float m_LastApertureOrientation;
private Vector4 m_OctogonalBokehDirection1;
private Vector4 m_OctogonalBokehDirection2;
private Vector4 m_OctogonalBokehDirection3;
private Vector4 m_OctogonalBokehDirection4;
private Vector4 m_HexagonalBokehDirection1;
private Vector4 m_HexagonalBokehDirection2;
private Vector4 m_HexagonalBokehDirection3;
private void OnEnable()
{
if (!ImageEffectHelper.IsSupported(filmicDepthOfFieldShader, true, true, this) || !ImageEffectHelper.IsSupported(medianFilterShader, true, true, this))
{
enabled = false;
return;
}
if (ImageEffectHelper.supportsDX11 && !ImageEffectHelper.IsSupported(textureBokehShader, true, true, this))
{
enabled = false;
return;
}
ComputeBlurDirections(true);
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
}
private void OnDisable()
{
ReleaseComputeResources();
if (m_FilmicDepthOfFieldMaterial != null)
DestroyImmediate(m_FilmicDepthOfFieldMaterial);
if (m_TextureBokehMaterial != null)
DestroyImmediate(m_TextureBokehMaterial);
if (m_MedianFilterMaterial != null)
DestroyImmediate(m_MedianFilterMaterial);
m_FilmicDepthOfFieldMaterial = null;
m_TextureBokehMaterial = null;
m_MedianFilterMaterial = null;
m_RTU.ReleaseAllTemporaryRenderTextures();
}
//-------------------------------------------------------------------//
// Main entry point //
//-------------------------------------------------------------------//
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (medianFilterMaterial == null || filmicDepthOfFieldMaterial == null)
{
Graphics.Blit(source, destination);
return;
}
if (settings.visualizeFocus)
{
Vector4 blurrinessParam;
Vector4 blurrinessCoe;
ComputeCocParameters(out blurrinessParam, out blurrinessCoe);
filmicDepthOfFieldMaterial.SetVector("_BlurParams", blurrinessParam);
filmicDepthOfFieldMaterial.SetVector("_BlurCoe", blurrinessCoe);
Graphics.Blit(null, destination, filmicDepthOfFieldMaterial, (int)Passes.VisualizeCocExplicit);
}
else
{
DoDepthOfField(source, destination);
}
m_RTU.ReleaseAllTemporaryRenderTextures();
}
private void DoDepthOfField(RenderTexture source, RenderTexture destination)
{
m_CurrentQualitySettings = QualitySettings.presetQualitySettings[(int)settings.filteringQuality];
float radiusAdjustement = source.height / 720f;
float textureBokehScale = radiusAdjustement;
float textureBokehMaxRadius = Mathf.Max(focus.nearBlurRadius, focus.farBlurRadius) * textureBokehScale * 0.75f;
float nearBlurRadius = focus.nearBlurRadius * radiusAdjustement;
float farBlurRadius = focus.farBlurRadius * radiusAdjustement;
float maxBlurRadius = Mathf.Max(nearBlurRadius, farBlurRadius);
switch (settings.apertureShape)
{
case ApertureShape.Hexagonal:
maxBlurRadius *= 1.2f;
break;
case ApertureShape.Octogonal:
maxBlurRadius *= 1.15f;
break;
}
if (maxBlurRadius < 0.5f)
{
Graphics.Blit(source, destination);
return;
}
// Quarter resolution
int rtW = source.width / 2;
int rtH = source.height / 2;
var blurrinessCoe = new Vector4(nearBlurRadius * 0.5f, farBlurRadius * 0.5f, 0f, 0f);
var colorAndCoc = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
var colorAndCoc2 = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
// Downsample to Color + COC buffer
Vector4 cocParam;
Vector4 cocCoe;
ComputeCocParameters(out cocParam, out cocCoe);
filmicDepthOfFieldMaterial.SetVector("_BlurParams", cocParam);
filmicDepthOfFieldMaterial.SetVector("_BlurCoe", cocCoe);
Graphics.Blit(source, colorAndCoc2, filmicDepthOfFieldMaterial, (int)Passes.CaptureCocExplicit);
var src = colorAndCoc2;
var dst = colorAndCoc;
// Collect texture bokeh candidates and replace with a darker pixel
if (shouldPerformBokeh)
{
// Blur a bit so we can do a frequency check
var blurred = m_RTU.GetTemporaryRenderTexture(rtW, rtH);
Graphics.Blit(src, blurred, filmicDepthOfFieldMaterial, (int)Passes.BoxBlur);
filmicDepthOfFieldMaterial.SetVector("_Offsets", new Vector4(0f, 1.5f, 0f, 1.5f));
Graphics.Blit(blurred, dst, filmicDepthOfFieldMaterial, (int)Passes.BlurAlphaWeighted);
filmicDepthOfFieldMaterial.SetVector("_Offsets", new Vector4(1.5f, 0f, 0f, 1.5f));
Graphics.Blit(dst, blurred, filmicDepthOfFieldMaterial, (int)Passes.BlurAlphaWeighted);
// Collect texture bokeh candidates and replace with a darker pixel
textureBokehMaterial.SetTexture("_BlurredColor", blurred);
textureBokehMaterial.SetFloat("_SpawnHeuristic", bokehTexture.spawnHeuristic);
textureBokehMaterial.SetVector("_BokehParams", new Vector4(bokehTexture.scale * textureBokehScale, bokehTexture.intensity, bokehTexture.threshold, textureBokehMaxRadius));
Graphics.SetRandomWriteTarget(1, computeBufferPoints);
Graphics.Blit(src, dst, textureBokehMaterial, (int)BokehTexturesPasses.Collect);
Graphics.ClearRandomWriteTargets();
SwapRenderTexture(ref src, ref dst);
m_RTU.ReleaseTemporaryRenderTexture(blurred);
}
filmicDepthOfFieldMaterial.SetVector("_BlurParams", cocParam);
filmicDepthOfFieldMaterial.SetVector("_BlurCoe", blurrinessCoe);
// Dilate near blur factor
RenderTexture blurredFgCoc = null;
if (m_CurrentQualitySettings.dilateNearBlur)
{
var blurredFgCoc2 = m_RTU.GetTemporaryRenderTexture(rtW, rtH, 0, RenderTextureFormat.RGHalf);
blurredFgCoc = m_RTU.GetTemporaryRenderTexture(rtW, rtH, 0, RenderTextureFormat.RGHalf);
filmicDepthOfFieldMaterial.SetVector("_Offsets", new Vector4(0f, nearBlurRadius * 0.75f, 0f, 0f));
Graphics.Blit(src, blurredFgCoc2, filmicDepthOfFieldMaterial, (int)Passes.DilateFgCocFromColor);
filmicDepthOfFieldMaterial.SetVector("_Offsets", new Vector4(nearBlurRadius * 0.75f, 0f, 0f, 0f));
Graphics.Blit(blurredFgCoc2, blurredFgCoc, filmicDepthOfFieldMaterial, (int)Passes.DilateFgCoc);
m_RTU.ReleaseTemporaryRenderTexture(blurredFgCoc2);
blurredFgCoc.filterMode = FilterMode.Point;
}
// Blur downsampled color to fill the gap between samples
if (m_CurrentQualitySettings.prefilterBlur)
{
Graphics.Blit(src, dst, filmicDepthOfFieldMaterial, (int)Passes.CocPrefilter);
SwapRenderTexture(ref src, ref dst);
}
// Apply blur : Circle / Hexagonal or Octagonal (blur will create bokeh if bright pixel where not removed by "m_UseBokehTexture")
switch (settings.apertureShape)
{
case ApertureShape.Circular:
DoCircularBlur(blurredFgCoc, ref src, ref dst, maxBlurRadius);
break;
case ApertureShape.Hexagonal:
DoHexagonalBlur(blurredFgCoc, ref src, ref dst, maxBlurRadius);
break;
case ApertureShape.Octogonal:
DoOctogonalBlur(blurredFgCoc, ref src, ref dst, maxBlurRadius);
break;
}
// Smooth result
switch (m_CurrentQualitySettings.medianFilter)
{
case FilterQuality.Normal:
{
medianFilterMaterial.SetVector("_Offsets", new Vector4(1f, 0f, 0f, 0f));
Graphics.Blit(src, dst, medianFilterMaterial, (int)MedianPasses.Median3);
SwapRenderTexture(ref src, ref dst);
medianFilterMaterial.SetVector("_Offsets", new Vector4(0f, 1f, 0f, 0f));
Graphics.Blit(src, dst, medianFilterMaterial, (int)MedianPasses.Median3);
SwapRenderTexture(ref src, ref dst);
break;
}
case FilterQuality.High:
{
Graphics.Blit(src, dst, medianFilterMaterial, (int)MedianPasses.Median3X3);
SwapRenderTexture(ref src, ref dst);
break;
}
}
// Merge to full resolution (with boost) + upsampling (linear or bicubic)
filmicDepthOfFieldMaterial.SetVector("_BlurCoe", blurrinessCoe);
filmicDepthOfFieldMaterial.SetVector("_Convolved_TexelSize", new Vector4(src.width, src.height, 1f / src.width, 1f / src.height));
filmicDepthOfFieldMaterial.SetTexture("_SecondTex", src);
int mergePass = (int)Passes.MergeExplicit;
// Apply texture bokeh
if (shouldPerformBokeh)
{
var tmp = m_RTU.GetTemporaryRenderTexture(source.height, source.width, 0, source.format);
Graphics.Blit(source, tmp, filmicDepthOfFieldMaterial, mergePass);
Graphics.SetRenderTarget(tmp);
ComputeBuffer.CopyCount(computeBufferPoints, computeBufferDrawArgs, 0);
textureBokehMaterial.SetBuffer("pointBuffer", computeBufferPoints);
textureBokehMaterial.SetTexture("_MainTex", bokehTexture.texture);
textureBokehMaterial.SetVector("_Screen", new Vector3(1f / (1f * source.width), 1f / (1f * source.height), textureBokehMaxRadius));
textureBokehMaterial.SetPass((int)BokehTexturesPasses.Apply);
Graphics.DrawProceduralIndirectNow(MeshTopology.Points, computeBufferDrawArgs, 0);
Graphics.Blit(tmp, destination); // Hackaround for DX11 flipfun (OPTIMIZEME)
}
else
{
Graphics.Blit(source, destination, filmicDepthOfFieldMaterial, mergePass);
}
}
//-------------------------------------------------------------------//
// Blurs //
//-------------------------------------------------------------------//
private void DoHexagonalBlur(RenderTexture blurredFgCoc, ref RenderTexture src, ref RenderTexture dst, float maxRadius)
{
ComputeBlurDirections(false);
int blurPass;
int blurPassMerge;
GetDirectionalBlurPassesFromRadius(blurredFgCoc, maxRadius, out blurPass, out blurPassMerge);
filmicDepthOfFieldMaterial.SetTexture("_SecondTex", blurredFgCoc);
var tmp = m_RTU.GetTemporaryRenderTexture(src.width, src.height, 0, src.format);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_HexagonalBokehDirection1);
Graphics.Blit(src, tmp, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_HexagonalBokehDirection2);
Graphics.Blit(tmp, src, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_HexagonalBokehDirection3);
filmicDepthOfFieldMaterial.SetTexture("_ThirdTex", src);
Graphics.Blit(tmp, dst, filmicDepthOfFieldMaterial, blurPassMerge);
m_RTU.ReleaseTemporaryRenderTexture(tmp);
SwapRenderTexture(ref src, ref dst);
}
private void DoOctogonalBlur(RenderTexture blurredFgCoc, ref RenderTexture src, ref RenderTexture dst, float maxRadius)
{
ComputeBlurDirections(false);
int blurPass;
int blurPassMerge;
GetDirectionalBlurPassesFromRadius(blurredFgCoc, maxRadius, out blurPass, out blurPassMerge);
filmicDepthOfFieldMaterial.SetTexture("_SecondTex", blurredFgCoc);
var tmp = m_RTU.GetTemporaryRenderTexture(src.width, src.height, 0, src.format);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_OctogonalBokehDirection1);
Graphics.Blit(src, tmp, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_OctogonalBokehDirection2);
Graphics.Blit(tmp, dst, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_OctogonalBokehDirection3);
Graphics.Blit(src, tmp, filmicDepthOfFieldMaterial, blurPass);
filmicDepthOfFieldMaterial.SetVector("_Offsets", m_OctogonalBokehDirection4);
filmicDepthOfFieldMaterial.SetTexture("_ThirdTex", dst);
Graphics.Blit(tmp, src, filmicDepthOfFieldMaterial, blurPassMerge);
m_RTU.ReleaseTemporaryRenderTexture(tmp);
}
private void DoCircularBlur(RenderTexture blurredFgCoc, ref RenderTexture src, ref RenderTexture dst, float maxRadius)
{
int bokehPass;
if (blurredFgCoc != null)
{
filmicDepthOfFieldMaterial.SetTexture("_SecondTex", blurredFgCoc);
bokehPass = (maxRadius > 10f) ? (int)Passes.CircleBlurWithDilatedFg : (int)Passes.CircleBlowLowQualityWithDilatedFg;
}
else
{
bokehPass = (maxRadius > 10f) ? (int)Passes.CircleBlur : (int)Passes.CircleBlurLowQuality;
}
Graphics.Blit(src, dst, filmicDepthOfFieldMaterial, bokehPass);
SwapRenderTexture(ref src, ref dst);
}
//-------------------------------------------------------------------//
// Helpers //
//-------------------------------------------------------------------//
private void ComputeCocParameters(out Vector4 blurParams, out Vector4 blurCoe)
{
var sceneCamera = GetComponent<Camera>();
float focusDistance;
float nearFalloff = focus.nearFalloff * 2f;
float farFalloff = focus.farFalloff * 2f;
float nearPlane = focus.nearPlane;
float farPlane = focus.farPlane;
if (settings.tweakMode == TweakMode.Range)
{
if (focus.transform != null)
focusDistance = sceneCamera.WorldToViewportPoint(focus.transform.position).z;
else
focusDistance = focus.focusPlane;
float s = focus.range * 0.5f;
nearPlane = focusDistance - s;
farPlane = focusDistance + s;
}
nearPlane -= (nearFalloff * 0.5f);
farPlane += (farFalloff * 0.5f);
focusDistance = (nearPlane + farPlane) * 0.5f;
float focusDistance01 = focusDistance / sceneCamera.farClipPlane;
float nearDistance01 = nearPlane / sceneCamera.farClipPlane;
float farDistance01 = farPlane / sceneCamera.farClipPlane;
var dof = farPlane - nearPlane;
var dof01 = farDistance01 - nearDistance01;
var nearFalloff01 = nearFalloff / dof;
var farFalloff01 = farFalloff / dof;
float nearFocusRange01 = (1f - nearFalloff01) * (dof01 * 0.5f);
float farFocusRange01 = (1f - farFalloff01) * (dof01 * 0.5f);
if (focusDistance01 <= nearDistance01)
focusDistance01 = nearDistance01 + 1e-6f;
if (focusDistance01 >= farDistance01)
focusDistance01 = farDistance01 - 1e-6f;
if ((focusDistance01 - nearFocusRange01) <= nearDistance01)
nearFocusRange01 = focusDistance01 - nearDistance01 - 1e-6f;
if ((focusDistance01 + farFocusRange01) >= farDistance01)
farFocusRange01 = farDistance01 - focusDistance01 - 1e-6f;
float a1 = 1f / (nearDistance01 - focusDistance01 + nearFocusRange01);
float a2 = 1f / (farDistance01 - focusDistance01 - farFocusRange01);
float b1 = 1f - a1 * nearDistance01;
float b2 = 1f - a2 * farDistance01;
const float c1 = -1f;
const float c2 = 1f;
blurParams = new Vector4(c1 * a1, c1 * b1, c2 * a2, c2 * b2);
blurCoe = new Vector4(0f, 0f, (b2 - b1) / (a1 - a2), 0f);
// Save values so we can switch from one tweak mode to the other on the fly
focus.nearPlane = nearPlane + (nearFalloff * 0.5f);
focus.farPlane = farPlane - (farFalloff * 0.5f);
focus.focusPlane = (focus.nearPlane + focus.farPlane) * 0.5f;
focus.range = focus.farPlane - focus.nearPlane;
}
private void ReleaseComputeResources()
{
if (m_ComputeBufferDrawArgs != null)
m_ComputeBufferDrawArgs.Release();
if (m_ComputeBufferPoints != null)
m_ComputeBufferPoints.Release();
m_ComputeBufferDrawArgs = null;
m_ComputeBufferPoints = null;
}
private void ComputeBlurDirections(bool force)
{
if (!force && Math.Abs(m_LastApertureOrientation - settings.apertureOrientation) < float.Epsilon)
return;
m_LastApertureOrientation = settings.apertureOrientation;
float rotationRadian = settings.apertureOrientation * Mathf.Deg2Rad;
float cosinus = Mathf.Cos(rotationRadian);
float sinus = Mathf.Sin(rotationRadian);
m_OctogonalBokehDirection1 = new Vector4(0.5f, 0f, 0f, 0f);
m_OctogonalBokehDirection2 = new Vector4(0f, 0.5f, 1f, 0f);
m_OctogonalBokehDirection3 = new Vector4(-0.353553f, 0.353553f, 1f, 0f);
m_OctogonalBokehDirection4 = new Vector4(0.353553f, 0.353553f, 1f, 0f);
m_HexagonalBokehDirection1 = new Vector4(0.5f, 0f, 0f, 0f);
m_HexagonalBokehDirection2 = new Vector4(0.25f, 0.433013f, 1f, 0f);
m_HexagonalBokehDirection3 = new Vector4(0.25f, -0.433013f, 1f, 0f);
if (rotationRadian > float.Epsilon)
{
Rotate2D(ref m_OctogonalBokehDirection1, cosinus, sinus);
Rotate2D(ref m_OctogonalBokehDirection2, cosinus, sinus);
Rotate2D(ref m_OctogonalBokehDirection3, cosinus, sinus);
Rotate2D(ref m_OctogonalBokehDirection4, cosinus, sinus);
Rotate2D(ref m_HexagonalBokehDirection1, cosinus, sinus);
Rotate2D(ref m_HexagonalBokehDirection2, cosinus, sinus);
Rotate2D(ref m_HexagonalBokehDirection3, cosinus, sinus);
}
}
private bool shouldPerformBokeh
{
get { return ImageEffectHelper.supportsDX11 && bokehTexture.texture != null && textureBokehMaterial; }
}
private static void Rotate2D(ref Vector4 direction, float cosinus, float sinus)
{
var source = direction;
direction.x = source.x * cosinus - source.y * sinus;
direction.y = source.x * sinus + source.y * cosinus;
}
private static void SwapRenderTexture(ref RenderTexture src, ref RenderTexture dst)
{
RenderTexture tmp = dst;
dst = src;
src = tmp;
}
private static void GetDirectionalBlurPassesFromRadius(RenderTexture blurredFgCoc, float maxRadius, out int blurPass, out int blurAndMergePass)
{
if (blurredFgCoc == null)
{
if (maxRadius > 10f)
{
blurPass = (int)Passes.ShapeHighQuality;
blurAndMergePass = (int)Passes.ShapeHighQualityMerge;
}
else if (maxRadius > 5f)
{
blurPass = (int)Passes.ShapeMediumQuality;
blurAndMergePass = (int)Passes.ShapeMediumQualityMerge;
}
else
{
blurPass = (int)Passes.ShapeLowQuality;
blurAndMergePass = (int)Passes.ShapeLowQualityMerge;
}
}
else
{
if (maxRadius > 10f)
{
blurPass = (int)Passes.ShapeHighQualityDilateFg;
blurAndMergePass = (int)Passes.ShapeHighQualityMergeDilateFg;
}
else if (maxRadius > 5f)
{
blurPass = (int)Passes.ShapeMediumQualityDilateFg;
blurAndMergePass = (int)Passes.ShapeMediumQualityMergeDilateFg;
}
else
{
blurPass = (int)Passes.ShapeLowQualityDilateFg;
blurAndMergePass = (int)Passes.ShapeLowQualityMergeDilateFg;
}
}
}
}
}
| |
// 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;
namespace System.Globalization
{
// List of calendar data
// Note the we cache overrides.
// Note that localized names (resource names) aren't available from here.
//
// NOTE: Calendars depend on the locale name that creates it. Only a few
// properties are available without locales using CalendarData.GetCalendar(CalendarData)
internal partial class CalendarData
{
// Max calendars
internal const int MAX_CALENDARS = 23;
// Identity
internal String sNativeName; // Calendar Name for the locale
// Formats
internal String[] saShortDates; // Short Data format, default first
internal String[] saYearMonths; // Year/Month Data format, default first
internal String[] saLongDates; // Long Data format, default first
internal String sMonthDay; // Month/Day format
// Calendar Parts Names
internal String[] saEraNames; // Names of Eras
internal String[] saAbbrevEraNames; // Abbreviated Era Names
internal String[] saAbbrevEnglishEraNames; // Abbreviated Era Names in English
internal String[] saDayNames; // Day Names, null to use locale data, starts on Sunday
internal String[] saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday
internal String[] saSuperShortDayNames; // Super short Day of week names
internal String[] saMonthNames; // Month Names (13)
internal String[] saAbbrevMonthNames; // Abbrev Month Names (13)
internal String[] saMonthGenitiveNames; // Genitive Month Names (13)
internal String[] saAbbrevMonthGenitiveNames; // Genitive Abbrev Month Names (13)
internal String[] saLeapYearMonthNames; // Multiple strings for the month names in a leap year.
// Integers at end to make marshaller happier
internal int iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry)
internal int iCurrentEra = 0; // current era # (usually 1)
// Use overrides?
internal bool bUseUserOverrides; // True if we want user overrides.
// Static invariant for the invariant locale
internal static CalendarData Invariant;
// Private constructor
private CalendarData() { }
// Invariant constructor
static CalendarData()
{
// Set our default/gregorian US calendar data
// Calendar IDs are 1-based, arrays are 0 based.
CalendarData invariant = new CalendarData();
// Set default data for calendar
// Note that we don't load resources since this IS NOT supposed to change (by definition)
invariant.sNativeName = "Gregorian Calendar"; // Calendar Name
// Year
invariant.iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry)
invariant.iCurrentEra = 1; // Current era #
// Formats
invariant.saShortDates = new String[] { "MM/dd/yyyy", "yyyy-MM-dd" }; // short date format
invariant.saLongDates = new String[] { "dddd, dd MMMM yyyy" }; // long date format
invariant.saYearMonths = new String[] { "yyyy MMMM" }; // year month format
invariant.sMonthDay = "MMMM dd"; // Month day pattern
// Calendar Parts Names
invariant.saEraNames = new String[] { "A.D." }; // Era names
invariant.saAbbrevEraNames = new String[] { "AD" }; // Abbreviated Era names
invariant.saAbbrevEnglishEraNames = new String[] { "AD" }; // Abbreviated era names in English
invariant.saDayNames = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };// day names
invariant.saAbbrevDayNames = new String[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // abbreviated day names
invariant.saSuperShortDayNames = new String[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; // The super short day names
invariant.saMonthNames = new String[] { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December", String.Empty}; // month names
invariant.saAbbrevMonthNames = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", String.Empty}; // abbreviated month names
invariant.saMonthGenitiveNames = invariant.saMonthNames; // Genitive month names (same as month names for invariant)
invariant.saAbbrevMonthGenitiveNames = invariant.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant)
invariant.saLeapYearMonthNames = invariant.saMonthNames; // leap year month names are unused in Gregorian English (invariant)
invariant.bUseUserOverrides = false;
// Calendar was built, go ahead and assign it...
Invariant = invariant;
}
//
// Get a bunch of data for a calendar
//
internal CalendarData(String localeName, CalendarId calendarId, bool bUseUserOverrides)
{
this.bUseUserOverrides = bUseUserOverrides;
if (!LoadCalendarDataFromSystem(localeName, calendarId))
{
Debug.Assert(false, "[CalendarData] LoadCalendarDataFromSystem call isn't expected to fail for calendar " + calendarId + " locale " + localeName);
// Something failed, try invariant for missing parts
// This is really not good, but we don't want the callers to crash.
if (this.sNativeName == null) this.sNativeName = String.Empty; // Calendar Name for the locale.
// Formats
if (this.saShortDates == null) this.saShortDates = Invariant.saShortDates; // Short Data format, default first
if (this.saYearMonths == null) this.saYearMonths = Invariant.saYearMonths; // Year/Month Data format, default first
if (this.saLongDates == null) this.saLongDates = Invariant.saLongDates; // Long Data format, default first
if (this.sMonthDay == null) this.sMonthDay = Invariant.sMonthDay; // Month/Day format
// Calendar Parts Names
if (this.saEraNames == null) this.saEraNames = Invariant.saEraNames; // Names of Eras
if (this.saAbbrevEraNames == null) this.saAbbrevEraNames = Invariant.saAbbrevEraNames; // Abbreviated Era Names
if (this.saAbbrevEnglishEraNames == null) this.saAbbrevEnglishEraNames = Invariant.saAbbrevEnglishEraNames; // Abbreviated Era Names in English
if (this.saDayNames == null) this.saDayNames = Invariant.saDayNames; // Day Names, null to use locale data, starts on Sunday
if (this.saAbbrevDayNames == null) this.saAbbrevDayNames = Invariant.saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday
if (this.saSuperShortDayNames == null) this.saSuperShortDayNames = Invariant.saSuperShortDayNames; // Super short Day of week names
if (this.saMonthNames == null) this.saMonthNames = Invariant.saMonthNames; // Month Names (13)
if (this.saAbbrevMonthNames == null) this.saAbbrevMonthNames = Invariant.saAbbrevMonthNames; // Abbrev Month Names (13)
// Genitive and Leap names can follow the fallback below
}
if (calendarId == CalendarId.TAIWAN)
{
if (SystemSupportsTaiwaneseCalendar())
{
// We got the month/day names from the OS (same as gregorian), but the native name is wrong
this.sNativeName = "\x4e2d\x83ef\x6c11\x570b\x66c6";
}
else
{
this.sNativeName = String.Empty;
}
}
// Check for null genitive names (in case unmanaged side skips it for non-gregorian calendars, etc)
if (this.saMonthGenitiveNames == null || this.saMonthGenitiveNames.Length == 0 || String.IsNullOrEmpty(this.saMonthGenitiveNames[0]))
this.saMonthGenitiveNames = this.saMonthNames; // Genitive month names (same as month names for invariant)
if (this.saAbbrevMonthGenitiveNames == null || this.saAbbrevMonthGenitiveNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevMonthGenitiveNames[0]))
this.saAbbrevMonthGenitiveNames = this.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant)
if (this.saLeapYearMonthNames == null || this.saLeapYearMonthNames.Length == 0 || String.IsNullOrEmpty(this.saLeapYearMonthNames[0]))
this.saLeapYearMonthNames = this.saMonthNames;
InitializeEraNames(localeName, calendarId);
InitializeAbbreviatedEraNames(localeName, calendarId);
// Abbreviated English Era Names are only used for the Japanese calendar.
if (calendarId == CalendarId.JAPAN)
{
this.saAbbrevEnglishEraNames = JapaneseCalendar.EnglishEraNames();
}
else
{
// For all others just use the an empty string (doesn't matter we'll never ask for it for other calendars)
this.saAbbrevEnglishEraNames = new String[] { "" };
}
// Japanese is the only thing with > 1 era. Its current era # is how many ever
// eras are in the array. (And the others all have 1 string in the array)
this.iCurrentEra = this.saEraNames.Length;
}
private void InitializeEraNames(string localeName, CalendarId calendarId)
{
// Note that the saEraNames only include "A.D." We don't have localized names for other calendars available from windows
switch (calendarId)
{
// For Localized Gregorian we really expect the data from the OS.
case CalendarId.GREGORIAN:
// Fallback for CoreCLR < Win7 or culture.dll missing
if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0]))
{
this.saEraNames = new String[] { "A.D." };
}
break;
// The rest of the calendars have constant data, so we'll just use that
case CalendarId.GREGORIAN_US:
case CalendarId.JULIAN:
this.saEraNames = new String[] { "A.D." };
break;
case CalendarId.HEBREW:
this.saEraNames = new String[] { "C.E." };
break;
case CalendarId.HIJRI:
case CalendarId.UMALQURA:
if (localeName == "dv-MV")
{
// Special case for Divehi
this.saEraNames = new String[] { "\x0780\x07a8\x0796\x07b0\x0783\x07a9" };
}
else
{
this.saEraNames = new String[] { "\x0628\x0639\x062F \x0627\x0644\x0647\x062C\x0631\x0629" };
}
break;
case CalendarId.GREGORIAN_ARABIC:
case CalendarId.GREGORIAN_XLIT_ENGLISH:
case CalendarId.GREGORIAN_XLIT_FRENCH:
// These are all the same:
this.saEraNames = new String[] { "\x0645" };
break;
case CalendarId.GREGORIAN_ME_FRENCH:
this.saEraNames = new String[] { "ap. J.-C." };
break;
case CalendarId.TAIWAN:
if (SystemSupportsTaiwaneseCalendar())
{
this.saEraNames = new String[] { "\x4e2d\x83ef\x6c11\x570b" };
}
else
{
this.saEraNames = new String[] { String.Empty };
}
break;
case CalendarId.KOREA:
this.saEraNames = new String[] { "\xb2e8\xae30" };
break;
case CalendarId.THAI:
this.saEraNames = new String[] { "\x0e1e\x002e\x0e28\x002e" };
break;
case CalendarId.JAPAN:
case CalendarId.JAPANESELUNISOLAR:
this.saEraNames = JapaneseCalendar.EraNames();
break;
case CalendarId.PERSIAN:
if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0]))
{
this.saEraNames = new String[] { "\x0647\x002e\x0634" };
}
break;
default:
// Most calendars are just "A.D."
this.saEraNames = Invariant.saEraNames;
break;
}
}
private void InitializeAbbreviatedEraNames(string localeName, CalendarId calendarId)
{
// Note that the saAbbrevEraNames only include "AD" We don't have localized names for other calendars available from windows
switch (calendarId)
{
// For Localized Gregorian we really expect the data from the OS.
case CalendarId.GREGORIAN:
// Fallback for CoreCLR < Win7 or culture.dll missing
if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0]))
{
this.saAbbrevEraNames = new String[] { "AD" };
}
break;
// The rest of the calendars have constant data, so we'll just use that
case CalendarId.GREGORIAN_US:
case CalendarId.JULIAN:
this.saAbbrevEraNames = new String[] { "AD" };
break;
case CalendarId.JAPAN:
case CalendarId.JAPANESELUNISOLAR:
this.saAbbrevEraNames = JapaneseCalendar.AbbrevEraNames();
break;
case CalendarId.HIJRI:
case CalendarId.UMALQURA:
if (localeName == "dv-MV")
{
// Special case for Divehi
this.saAbbrevEraNames = new String[] { "\x0780\x002e" };
}
else
{
this.saAbbrevEraNames = new String[] { "\x0647\x0640" };
}
break;
case CalendarId.TAIWAN:
// Get era name and abbreviate it
this.saAbbrevEraNames = new String[1];
if (this.saEraNames[0].Length == 4)
{
this.saAbbrevEraNames[0] = this.saEraNames[0].Substring(2, 2);
}
else
{
this.saAbbrevEraNames[0] = this.saEraNames[0];
}
break;
case CalendarId.PERSIAN:
if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0]))
{
this.saAbbrevEraNames = this.saEraNames;
}
break;
default:
// Most calendars just use the full name
this.saAbbrevEraNames = this.saEraNames;
break;
}
}
internal static CalendarData GetCalendarData(CalendarId calendarId)
{
//
// Get a calendar.
// Unfortunately we depend on the locale in the OS, so we need a locale
// no matter what. So just get the appropriate calendar from the
// appropriate locale here
//
// Get a culture name
// TODO: Note that this doesn't handle the new calendars (lunisolar, etc)
String culture = CalendarIdToCultureName(calendarId);
// Return our calendar
return CultureInfo.GetCultureInfo(culture).m_cultureData.GetCalendar(calendarId);
}
private static String CalendarIdToCultureName(CalendarId calendarId)
{
switch (calendarId)
{
case CalendarId.GREGORIAN_US:
return "fa-IR"; // "fa-IR" Iran
case CalendarId.JAPAN:
return "ja-JP"; // "ja-JP" Japan
case CalendarId.TAIWAN:
return "zh-TW"; // zh-TW Taiwan
case CalendarId.KOREA:
return "ko-KR"; // "ko-KR" Korea
case CalendarId.HIJRI:
case CalendarId.GREGORIAN_ARABIC:
case CalendarId.UMALQURA:
return "ar-SA"; // "ar-SA" Saudi Arabia
case CalendarId.THAI:
return "th-TH"; // "th-TH" Thailand
case CalendarId.HEBREW:
return "he-IL"; // "he-IL" Israel
case CalendarId.GREGORIAN_ME_FRENCH:
return "ar-DZ"; // "ar-DZ" Algeria
case CalendarId.GREGORIAN_XLIT_ENGLISH:
case CalendarId.GREGORIAN_XLIT_FRENCH:
return "ar-IQ"; // "ar-IQ"; Iraq
default:
// Default to gregorian en-US
break;
}
return "en-US";
}
}
}
| |
namespace ShellExplorer {
partial class ShellExplorer {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ShellExplorer));
this.splitContainer = new System.Windows.Forms.SplitContainer();
this.treeView = new GongSolutions.Shell.ShellTreeView();
this.shellView = new GongSolutions.Shell.ShellView();
this.statusBar = new System.Windows.Forms.StatusBar();
this.mainMenu = new System.Windows.Forms.MainMenu(this.components);
this.fileMenu = new System.Windows.Forms.MenuItem();
this.dummyMenuItem = new System.Windows.Forms.MenuItem();
this.viewMenu = new System.Windows.Forms.MenuItem();
this.refreshMenu = new System.Windows.Forms.MenuItem();
this.toolBar = new System.Windows.Forms.ToolBar();
this.backButton = new System.Windows.Forms.ToolBarButton();
this.backButtonMenu = new System.Windows.Forms.ContextMenu();
this.forwardButton = new System.Windows.Forms.ToolBarButton();
this.forwardButtonMenu = new System.Windows.Forms.ContextMenu();
this.upButton = new System.Windows.Forms.ToolBarButton();
this.imageList = new System.Windows.Forms.ImageList(this.components);
this.shellComboBox1 = new GongSolutions.Shell.ShellComboBox();
this.splitContainer.Panel1.SuspendLayout();
this.splitContainer.Panel2.SuspendLayout();
this.splitContainer.SuspendLayout();
this.SuspendLayout();
//
// splitContainer
//
this.splitContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer.Location = new System.Drawing.Point(0, 51);
this.splitContainer.Name = "splitContainer";
//
// splitContainer.Panel1
//
this.splitContainer.Panel1.Controls.Add(this.treeView);
//
// splitContainer.Panel2
//
this.splitContainer.Panel2.Controls.Add(this.shellView);
this.splitContainer.Size = new System.Drawing.Size(610, 224);
this.splitContainer.SplitterDistance = 197;
this.splitContainer.TabIndex = 1;
//
// treeView
//
this.treeView.AllowDrop = true;
this.treeView.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeView.Location = new System.Drawing.Point(0, 0);
this.treeView.Name = "treeView";
this.treeView.ShellView = this.shellView;
this.treeView.Size = new System.Drawing.Size(197, 224);
this.treeView.TabIndex = 0;
this.treeView.Text = "shellTreeView1";
//
// shellView
//
this.shellView.Dock = System.Windows.Forms.DockStyle.Fill;
this.shellView.Location = new System.Drawing.Point(0, 0);
this.shellView.Name = "shellView";
this.shellView.Size = new System.Drawing.Size(409, 224);
this.shellView.StatusBar = this.statusBar;
this.shellView.TabIndex = 0;
this.shellView.Text = "shellView1";
this.shellView.View = GongSolutions.Shell.ShellViewStyle.Details;
this.shellView.Navigated += new System.EventHandler(this.shellView_Navigated);
//
// statusBar
//
this.statusBar.Location = new System.Drawing.Point(0, 275);
this.statusBar.Name = "statusBar";
this.statusBar.ShowPanels = true;
this.statusBar.Size = new System.Drawing.Size(610, 22);
this.statusBar.TabIndex = 1;
//
// mainMenu
//
this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.fileMenu,
this.viewMenu});
//
// fileMenu
//
this.fileMenu.Index = 0;
this.fileMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.dummyMenuItem});
this.fileMenu.Text = "&File";
this.fileMenu.Popup += new System.EventHandler(this.fileMenu_Popup);
//
// dummyMenuItem
//
this.dummyMenuItem.Index = 0;
this.dummyMenuItem.Text = "Dummy";
this.dummyMenuItem.Visible = false;
//
// viewMenu
//
this.viewMenu.Index = 1;
this.viewMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.refreshMenu});
this.viewMenu.Text = "&View";
//
// refreshMenu
//
this.refreshMenu.Index = 0;
this.refreshMenu.Shortcut = System.Windows.Forms.Shortcut.F5;
this.refreshMenu.Text = "&Refresh";
this.refreshMenu.Click += new System.EventHandler(this.refreshMenu_Click);
//
// toolBar
//
this.toolBar.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
this.toolBar.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
this.backButton,
this.forwardButton,
this.upButton});
this.toolBar.DropDownArrows = true;
this.toolBar.ImageList = this.imageList;
this.toolBar.Location = new System.Drawing.Point(0, 0);
this.toolBar.Name = "toolBar";
this.toolBar.ShowToolTips = true;
this.toolBar.Size = new System.Drawing.Size(610, 28);
this.toolBar.TabIndex = 2;
this.toolBar.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar_ButtonClick);
//
// backButton
//
this.backButton.DropDownMenu = this.backButtonMenu;
this.backButton.ImageIndex = 0;
this.backButton.Name = "backButton";
this.backButton.Style = System.Windows.Forms.ToolBarButtonStyle.DropDownButton;
//
// backButtonMenu
//
this.backButtonMenu.Popup += new System.EventHandler(this.backButton_Popup);
//
// forwardButton
//
this.forwardButton.DropDownMenu = this.forwardButtonMenu;
this.forwardButton.ImageIndex = 1;
this.forwardButton.Name = "forwardButton";
this.forwardButton.Style = System.Windows.Forms.ToolBarButtonStyle.DropDownButton;
//
// forwardButtonMenu
//
this.forwardButtonMenu.Popup += new System.EventHandler(this.forwardButton_Popup);
//
// upButton
//
this.upButton.ImageIndex = 2;
this.upButton.Name = "upButton";
//
// imageList
//
this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream")));
this.imageList.TransparentColor = System.Drawing.Color.Magenta;
this.imageList.Images.SetKeyName(0, "Back.bmp");
this.imageList.Images.SetKeyName(1, "Forward.bmp");
this.imageList.Images.SetKeyName(2, "Up.bmp");
//
// shellComboBox1
//
this.shellComboBox1.Dock = System.Windows.Forms.DockStyle.Top;
this.shellComboBox1.Editable = true;
this.shellComboBox1.Location = new System.Drawing.Point(0, 28);
this.shellComboBox1.Name = "shellComboBox1";
this.shellComboBox1.ShellView = this.shellView;
this.shellComboBox1.Size = new System.Drawing.Size(610, 23);
this.shellComboBox1.TabIndex = 3;
this.shellComboBox1.Text = "shellComboBox1";
//
// ShellExplorer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(610, 297);
this.Controls.Add(this.splitContainer);
this.Controls.Add(this.shellComboBox1);
this.Controls.Add(this.statusBar);
this.Controls.Add(this.toolBar);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Menu = this.mainMenu;
this.MinimumSize = new System.Drawing.Size(600, 200);
this.Name = "ShellExplorer";
this.Text = "Shell Explorer";
this.ResizeEnd += new System.EventHandler(this.ShellExplorer_ResizeEnd);
this.splitContainer.Panel1.ResumeLayout(false);
this.splitContainer.Panel2.ResumeLayout(false);
this.splitContainer.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private GongSolutions.Shell.ShellTreeView treeView;
private System.Windows.Forms.SplitContainer splitContainer;
private GongSolutions.Shell.ShellView shellView;
private System.Windows.Forms.StatusBar statusBar;
private System.Windows.Forms.MainMenu mainMenu;
private System.Windows.Forms.MenuItem fileMenu;
private System.Windows.Forms.ToolBar toolBar;
private System.Windows.Forms.ToolBarButton backButton;
private System.Windows.Forms.ToolBarButton forwardButton;
private System.Windows.Forms.ToolBarButton upButton;
private System.Windows.Forms.ImageList imageList;
private System.Windows.Forms.ContextMenu backButtonMenu;
private System.Windows.Forms.ContextMenu forwardButtonMenu;
private System.Windows.Forms.MenuItem dummyMenuItem;
private System.Windows.Forms.MenuItem viewMenu;
private System.Windows.Forms.MenuItem refreshMenu;
private GongSolutions.Shell.ShellComboBox shellComboBox1;
}
}
| |
using System;
using System.Collections.Generic;
namespace EasyPost.Tests.NetFramework
{
public static class Fixture
{
// We keep the page_size of retrieving `all` records small so cassettes stay small
public const int PageSize = 5;
// This is the carrier account ID for the default USPS account that comes by default. All tests should use this carrier account
public const string UspsCarrierAccountId = "ca_7642d249fdcf47bcb5da9ea34c96dfcf";
// TODO: this ID doesn't exist for the API keys being used for the C# tests
public const string ChildUserId = "user_608a91d0487e419bb465e5acbc999056";
public const string Usps = "USPS";
public const string UspsService = "First";
public const string NextDayService = "NextDay";
// If ever these need to change due to re-recording cassettes, simply increment this date by 1
public const string ReportStartDate = "2022-02-01";
// If ever these need to change due to re-recording cassettes, simply increment this date by 1
public const string ReportEndDate = "2022-02-03";
public static string RandomUrl => $"https://{Guid.NewGuid().ToString().Substring(0, 8)}.com";
public static Dictionary<string, object> BasicAddress
{
get
{
return new Dictionary<string, object>
{
{
"name", "Jack Sparrow"
},
{
"company", "EasyPost"
},
{
"street1", "388 Townsend St"
},
{
"street2", "Apt 20"
},
{
"city", "San Francisco"
},
{
"state", "CA"
},
{
"zip", "94107"
},
{
"country", "US"
},
{
"phone", "5555555555"
},
};
}
}
public static Dictionary<string, object> IncorrectAddressToVerify
{
get
{
return new Dictionary<string, object>
{
{
"verify", new List<bool>
{
true
}
},
{
"street1", "417 montgomery streat"
},
{
"street2", "FL 5"
},
{
"city", "San Francisco"
},
{
"state", "CA"
},
{
"zip", "94104"
},
{
"country", "US"
},
{
"company", "EasyPost"
},
{
"phone", "415-123-4567"
}
};
}
}
public static Dictionary<string, object> PickupAddress
{
get
{
return new Dictionary<string, object>
{
{
"name", "Dr. Steve Brule"
},
{
"street1", "179 N Harbor Dr"
},
{
"city", "Redondo Beach"
},
{
"state", "CA"
},
{
"zip", "90277"
},
{
"country", "US"
},
{
"phone", "3331114444"
}
};
}
}
public static Dictionary<string, object> BasicParcel
{
get
{
return new Dictionary<string, object>
{
{
"length", "10"
},
{
"width", "8"
},
{
"height", "4"
},
{
"weight", "15.4"
}
};
}
}
public static Dictionary<string, object> BasicCustomsItem
{
get
{
return new Dictionary<string, object>
{
{
"description", "Sweet shirts"
},
{
"quantity", 2
},
{
"weight", 11
},
{
"value", 23.00
},
{
"hs_tariff_number", 654321
},
{
"origin_country", "US"
}
};
}
}
public static Dictionary<string, object> BasicCustomsInfo
{
get
{
return new Dictionary<string, object>
{
{
"eel_pfc", "NOEEI 30.37(a)"
},
{
"customs_certify", true
},
{
"customs_signer", "Dr. Steve Brule"
},
{
"contents_type", "merchandise"
},
{
"contents_explanation", ""
},
{
"restriction_type", "none"
},
{
"non_delivery_option", "return"
},
{
"customs_items", new List<object>
{
BasicCustomsItem
}
}
};
}
}
public static Dictionary<string, object> BasicCarrierAccount
{
get
{
return new Dictionary<string, object>
{
{
"type", "UpsAccount"
},
{
"credentials", new Dictionary<string, object>
{
{
"account_number", "A1A1A1"
},
{
"user_id", "USERID"
},
{
"password", "PASSWORD"
},
{
"access_license_number", "ALN"
}
}
}
};
}
}
public static Dictionary<string, object> TaxIdentifier
{
get
{
return new Dictionary<string, object>
{
{
"entity", "SENDER"
},
{
"tax_id_type", "IOSS"
},
{
"tax_id", "12345"
},
{
"issuing_country", "GB"
}
};
}
}
public static Dictionary<string, object> BasicShipment
{
get
{
return new Dictionary<string, object>
{
{
"to_address", BasicAddress
},
{
"from_address", BasicAddress
},
{
"parcel", BasicParcel
}
};
}
}
public static Dictionary<string, object> FullShipment
{
get
{
return new Dictionary<string, object>
{
{
"to_address", BasicAddress
},
{
"from_address", BasicAddress
},
{
"parcel", BasicParcel
},
{
"customs_info", BasicCustomsInfo
},
{
"options", new Dictionary<string, object>
{
{
"label_format", "PNG" // Must be PNG so we can convert to ZPL later
},
{
"invoice_number", "123"
}
}
},
{
"reference", "123"
}
};
}
}
public static Dictionary<string, object> OneCallBuyShipment
{
get
{
return new Dictionary<string, object>
{
{
"to_address", BasicAddress
},
{
"from_address", BasicAddress
},
{
"parcel", BasicParcel
},
{
"service", UspsService
},
{
"carrier_accounts", new List<string>
{
UspsCarrierAccountId
}
},
{
"carrier", Usps
}
};
}
}
public static Dictionary<string, object> BasicInsurance
{
get
{
Shipment shipment = Shipment.Create(OneCallBuyShipment);
return new Dictionary<string, object>
{
{
"to_address", BasicAddress
},
{
"from_address", BasicAddress
},
{
"tracking_code", shipment.tracking_code
},
{
"carrier", Usps
},
{
"amount", 100
}
};
}
}
// This fixture will require you to add a `shipment` key with a Shipment object from a test.
// If you need to re-record cassettes, simply iterate the dates below and ensure they're one day in the future,
// USPS only does "next-day" pickups including Saturday but not Sunday or Holidays.
public static Dictionary<string, object> BasicPickup
{
get
{
return new Dictionary<string, object>
{
{
"address", BasicAddress
},
{
"min_datetime", (DateTime.Today.Date + TimeSpan.FromDays(1)).ToString("yyyy-MM-dd")
},
{
"max_datetime", (DateTime.Today.Date + TimeSpan.FromDays(2)).ToString("yyyy-MM-dd")
},
{
"instructions", "Pickup at front door"
}
};
}
}
public static Dictionary<string, object> BasicOrder
{
get
{
return new Dictionary<string, object>
{
{
"to_address", BasicAddress
},
{
"from_address", BasicAddress
},
{
"shipments", new List<Dictionary<string, object>>
{
BasicShipment
}
}
};
}
}
}
}
| |
// 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.Diagnostics.Contracts;
using System.Globalization;
namespace System.Collections.Immutable
{
public sealed partial class ImmutableSortedDictionary<TKey, TValue>
{
/// <summary>
/// A node in the AVL tree storing this map.
/// </summary>
[DebuggerDisplay("{_key} = {_value}")]
internal sealed class Node : IBinaryTree<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>
{
/// <summary>
/// The default empty node.
/// </summary>
internal static readonly Node EmptyNode = new Node();
/// <summary>
/// The key associated with this node.
/// </summary>
private readonly TKey _key;
/// <summary>
/// The value associated with this node.
/// </summary>
private readonly TValue _value;
/// <summary>
/// A value indicating whether this node has been frozen (made immutable).
/// </summary>
/// <remarks>
/// Nodes must be frozen before ever being observed by a wrapping collection type
/// to protect collections from further mutations.
/// </remarks>
private bool _frozen;
/// <summary>
/// The depth of the tree beneath this node.
/// </summary>
private byte _height; // AVL tree max height <= ~1.44 * log2(maxNodes + 2)
/// <summary>
/// The left tree.
/// </summary>
private Node _left;
/// <summary>
/// The right tree.
/// </summary>
private Node _right;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedDictionary{TKey, TValue}.Node"/> class
/// that is pre-frozen.
/// </summary>
private Node()
{
_frozen = true; // the empty node is *always* frozen.
Debug.Assert(this.IsEmpty);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedDictionary{TKey, TValue}.Node"/> class
/// that is not yet frozen.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <param name="frozen">Whether this node is prefrozen.</param>
private Node(TKey key, TValue value, Node left, Node right, bool frozen = false)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(left, nameof(left));
Requires.NotNull(right, nameof(right));
Debug.Assert(!frozen || (left._frozen && right._frozen));
_key = key;
_value = value;
_left = left;
_right = right;
_height = checked((byte)(1 + Math.Max(left._height, right._height)));
_frozen = frozen;
Debug.Assert(!this.IsEmpty);
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty
{
get
{
return _left == null;
}
}
/// <summary>
/// Gets the left branch of this node.
/// </summary>
IBinaryTree<KeyValuePair<TKey, TValue>> IBinaryTree<KeyValuePair<TKey, TValue>>.Left
{
get { return _left; }
}
/// <summary>
/// Gets the right branch of this node.
/// </summary>
IBinaryTree<KeyValuePair<TKey, TValue>> IBinaryTree<KeyValuePair<TKey, TValue>>.Right
{
get { return _right; }
}
/// <summary>
/// Gets the height of the tree beneath this node.
/// </summary>
public int Height { get { return _height; } }
/// <summary>
/// Gets the left branch of this node.
/// </summary>
public Node Left { get { return _left; } }
/// <summary>
/// Gets the left branch of this node.
/// </summary>
IBinaryTree IBinaryTree.Left
{
get { return _left; }
}
/// <summary>
/// Gets the right branch of this node.
/// </summary>
public Node Right { get { return _right; } }
/// <summary>
/// Gets the right branch of this node.
/// </summary>
IBinaryTree IBinaryTree.Right
{
get { return _right; }
}
/// <summary>
/// Gets the value represented by the current node.
/// </summary>
public KeyValuePair<TKey, TValue> Value
{
get { return new KeyValuePair<TKey, TValue>(_key, _value); }
}
/// <summary>
/// Gets the number of elements contained by this node and below.
/// </summary>
int IBinaryTree.Count
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// Gets the keys.
/// </summary>
internal IEnumerable<TKey> Keys
{
get { return Linq.Enumerable.Select(this, p => p.Key); }
}
/// <summary>
/// Gets the values.
/// </summary>
internal IEnumerable<TValue> Values
{
get { return Linq.Enumerable.Select(this, p => p.Value); }
}
#region IEnumerable<TKey> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <param name="builder">The builder, if applicable.</param>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
internal Enumerator GetEnumerator(Builder builder)
{
return new Enumerator(this, builder);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
internal void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex, int dictionarySize)
{
Requires.NotNull(array, nameof(array));
Requires.Range(arrayIndex >= 0, nameof(arrayIndex));
Requires.Range(array.Length >= arrayIndex + dictionarySize, nameof(arrayIndex));
foreach (var item in this)
{
array[arrayIndex++] = item;
}
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
internal void CopyTo(Array array, int arrayIndex, int dictionarySize)
{
Requires.NotNull(array, nameof(array));
Requires.Range(arrayIndex >= 0, nameof(arrayIndex));
Requires.Range(array.Length >= arrayIndex + dictionarySize, nameof(arrayIndex));
foreach (var item in this)
{
array.SetValue(new DictionaryEntry(item.Key, item.Value), arrayIndex++);
}
}
/// <summary>
/// Creates a node tree from an existing (mutable) collection.
/// </summary>
/// <param name="dictionary">The collection.</param>
/// <returns>The root of the node tree.</returns>
[Pure]
internal static Node NodeTreeFromSortedDictionary(SortedDictionary<TKey, TValue> dictionary)
{
Requires.NotNull(dictionary, nameof(dictionary));
var list = dictionary.AsOrderedCollection();
return NodeTreeFromList(list, 0, list.Count);
}
/// <summary>
/// Adds the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
internal Node Add(TKey key, TValue value, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, out bool mutated)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
Requires.NotNull(valueComparer, nameof(valueComparer));
bool dummy;
return this.SetOrAdd(key, value, keyComparer, valueComparer, false, out dummy, out mutated);
}
/// <summary>
/// Adds the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
internal Node SetItem(TKey key, TValue value, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, out bool replacedExistingValue, out bool mutated)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
Requires.NotNull(valueComparer, nameof(valueComparer));
return this.SetOrAdd(key, value, keyComparer, valueComparer, true, out replacedExistingValue, out mutated);
}
/// <summary>
/// Removes the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new AVL tree.</returns>
internal Node Remove(TKey key, IComparer<TKey> keyComparer, out bool mutated)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
return this.RemoveRecursive(key, keyComparer, out mutated);
}
#if FEATURE_ITEMREFAPI
/// <summary>
/// Returns a read-only reference to the value associated with the provided key.
/// </summary>
/// <exception cref="KeyNotFoundException">If the key is not present.</exception>
[Pure]
internal ref readonly TValue ValueRef(TKey key, IComparer<TKey> keyComparer)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
var match = this.Search(key, keyComparer);
if (match.IsEmpty)
{
throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
}
return ref match._value;
}
#endif
/// <summary>
/// Tries to get the value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="value">The value.</param>
/// <returns>True if the key was found.</returns>
[Pure]
internal bool TryGetValue(TKey key, IComparer<TKey> keyComparer, out TValue value)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
var match = this.Search(key, keyComparer);
if (match.IsEmpty)
{
value = default(TValue);
return false;
}
else
{
value = match._value;
return true;
}
}
/// <summary>
/// Searches the dictionary for a given key and returns the equal key it finds, if any.
/// </summary>
/// <param name="equalKey">The key to search for.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="actualKey">The key from the dictionary that the search found, or <paramref name="equalKey"/> if the search yielded no match.</param>
/// <returns>A value indicating whether the search was successful.</returns>
/// <remarks>
/// This can be useful when you want to reuse a previously stored reference instead of
/// a newly constructed one (so that more sharing of references can occur) or to look up
/// the canonical value, or a value that has more complete data than the value you currently have,
/// although their comparer functions indicate they are equal.
/// </remarks>
[Pure]
internal bool TryGetKey(TKey equalKey, IComparer<TKey> keyComparer, out TKey actualKey)
{
Requires.NotNullAllowStructs(equalKey, nameof(equalKey));
Requires.NotNull(keyComparer, nameof(keyComparer));
var match = this.Search(equalKey, keyComparer);
if (match.IsEmpty)
{
actualKey = equalKey;
return false;
}
else
{
actualKey = match._key;
return true;
}
}
/// <summary>
/// Determines whether the specified key contains key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <returns>
/// <c>true</c> if the specified key contains key; otherwise, <c>false</c>.
/// </returns>
[Pure]
internal bool ContainsKey(TKey key, IComparer<TKey> keyComparer)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
return !this.Search(key, keyComparer).IsEmpty;
}
/// <summary>
/// Determines whether the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>
/// contains an element with the specified value.
/// </summary>
/// <param name="value">
/// The value to locate in the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>.
/// The value can be null for reference types.
/// </param>
/// <param name="valueComparer">The value comparer to use.</param>
/// <returns>
/// true if the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> contains
/// an element with the specified value; otherwise, false.
/// </returns>
[Pure]
internal bool ContainsValue(TValue value, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNull(valueComparer, nameof(valueComparer));
foreach (KeyValuePair<TKey, TValue> item in this)
{
if (valueComparer.Equals(value, item.Value))
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether [contains] [the specified pair].
/// </summary>
/// <param name="pair">The pair.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <returns>
/// <c>true</c> if [contains] [the specified pair]; otherwise, <c>false</c>.
/// </returns>
[Pure]
internal bool Contains(KeyValuePair<TKey, TValue> pair, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNullAllowStructs(pair.Key, nameof(pair.Key));
Requires.NotNull(keyComparer, nameof(keyComparer));
Requires.NotNull(valueComparer, nameof(valueComparer));
var matchingNode = this.Search(pair.Key, keyComparer);
if (matchingNode.IsEmpty)
{
return false;
}
return valueComparer.Equals(matchingNode._value, pair.Value);
}
/// <summary>
/// Freezes this node and all descendant nodes so that any mutations require a new instance of the nodes.
/// </summary>
internal void Freeze()
{
// If this node is frozen, all its descendants must already be frozen.
if (!_frozen)
{
_left.Freeze();
_right.Freeze();
_frozen = true;
}
}
#region Tree balancing methods
/// <summary>
/// AVL rotate left operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static Node RotateLeft(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (tree._right.IsEmpty)
{
return tree;
}
var right = tree._right;
return right.Mutate(left: tree.Mutate(right: right._left));
}
/// <summary>
/// AVL rotate right operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static Node RotateRight(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (tree._left.IsEmpty)
{
return tree;
}
var left = tree._left;
return left.Mutate(right: tree.Mutate(left: left._right));
}
/// <summary>
/// AVL rotate double-left operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static Node DoubleLeft(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (tree._right.IsEmpty)
{
return tree;
}
Node rotatedRightChild = tree.Mutate(right: RotateRight(tree._right));
return RotateLeft(rotatedRightChild);
}
/// <summary>
/// AVL rotate double-right operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static Node DoubleRight(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (tree._left.IsEmpty)
{
return tree;
}
Node rotatedLeftChild = tree.Mutate(left: RotateLeft(tree._left));
return RotateRight(rotatedLeftChild);
}
/// <summary>
/// Returns a value indicating whether the tree is in balance.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>0 if the tree is in balance, a positive integer if the right side is heavy, or a negative integer if the left side is heavy.</returns>
[Pure]
private static int Balance(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return tree._right._height - tree._left._height;
}
/// <summary>
/// Determines whether the specified tree is right heavy.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>
/// <c>true</c> if [is right heavy] [the specified tree]; otherwise, <c>false</c>.
/// </returns>
[Pure]
private static bool IsRightHeavy(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return Balance(tree) >= 2;
}
/// <summary>
/// Determines whether the specified tree is left heavy.
/// </summary>
[Pure]
private static bool IsLeftHeavy(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return Balance(tree) <= -2;
}
/// <summary>
/// Balances the specified tree.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>A balanced tree.</returns>
[Pure]
private static Node MakeBalanced(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (IsRightHeavy(tree))
{
return Balance(tree._right) < 0 ? DoubleLeft(tree) : RotateLeft(tree);
}
if (IsLeftHeavy(tree))
{
return Balance(tree._left) > 0 ? DoubleRight(tree) : RotateRight(tree);
}
return tree;
}
#endregion
/// <summary>
/// Creates a node tree that contains the contents of a list.
/// </summary>
/// <param name="items">An indexable list with the contents that the new node tree should contain.</param>
/// <param name="start">The starting index within <paramref name="items"/> that should be captured by the node tree.</param>
/// <param name="length">The number of elements from <paramref name="items"/> that should be captured by the node tree.</param>
/// <returns>The root of the created node tree.</returns>
[Pure]
private static Node NodeTreeFromList(IOrderedCollection<KeyValuePair<TKey, TValue>> items, int start, int length)
{
Requires.NotNull(items, nameof(items));
Requires.Range(start >= 0, nameof(start));
Requires.Range(length >= 0, nameof(length));
if (length == 0)
{
return EmptyNode;
}
int rightCount = (length - 1) / 2;
int leftCount = (length - 1) - rightCount;
Node left = NodeTreeFromList(items, start, leftCount);
Node right = NodeTreeFromList(items, start + leftCount + 1, rightCount);
var item = items[start + leftCount];
return new Node(item.Key, item.Value, left, right, true);
}
/// <summary>
/// Adds the specified key. Callers are expected to have validated arguments.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="overwriteExistingValue">if <c>true</c>, an existing key=value pair will be overwritten with the new one.</param>
/// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new AVL tree.</returns>
private Node SetOrAdd(TKey key, TValue value, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue, out bool replacedExistingValue, out bool mutated)
{
// Arg validation skipped in this private method because it's recursive and the tax
// of revalidating arguments on each recursive call is significant.
// All our callers are therefore required to have done input validation.
replacedExistingValue = false;
if (this.IsEmpty)
{
mutated = true;
return new Node(key, value, this, this);
}
else
{
Node result = this;
int compareResult = keyComparer.Compare(key, _key);
if (compareResult > 0)
{
var newRight = _right.SetOrAdd(key, value, keyComparer, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated);
if (mutated)
{
result = this.Mutate(right: newRight);
}
}
else if (compareResult < 0)
{
var newLeft = _left.SetOrAdd(key, value, keyComparer, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated);
if (mutated)
{
result = this.Mutate(left: newLeft);
}
}
else
{
if (valueComparer.Equals(_value, value))
{
mutated = false;
return this;
}
else if (overwriteExistingValue)
{
mutated = true;
replacedExistingValue = true;
result = new Node(key, value, _left, _right);
}
else
{
throw new ArgumentException(SR.Format(SR.DuplicateKey, key));
}
}
return mutated ? MakeBalanced(result) : result;
}
}
/// <summary>
/// Removes the specified key. Callers are expected to validate arguments.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new AVL tree.</returns>
private Node RemoveRecursive(TKey key, IComparer<TKey> keyComparer, out bool mutated)
{
// Skip parameter validation because it's too expensive and pointless in recursive methods.
if (this.IsEmpty)
{
mutated = false;
return this;
}
else
{
Node result = this;
int compare = keyComparer.Compare(key, _key);
if (compare == 0)
{
// We have a match.
mutated = true;
// If this is a leaf, just remove it
// by returning Empty. If we have only one child,
// replace the node with the child.
if (_right.IsEmpty && _left.IsEmpty)
{
result = EmptyNode;
}
else if (_right.IsEmpty && !_left.IsEmpty)
{
result = _left;
}
else if (!_right.IsEmpty && _left.IsEmpty)
{
result = _right;
}
else
{
// We have two children. Remove the next-highest node and replace
// this node with it.
var successor = _right;
while (!successor._left.IsEmpty)
{
successor = successor._left;
}
bool dummyMutated;
var newRight = _right.Remove(successor._key, keyComparer, out dummyMutated);
result = successor.Mutate(left: _left, right: newRight);
}
}
else if (compare < 0)
{
var newLeft = _left.Remove(key, keyComparer, out mutated);
if (mutated)
{
result = this.Mutate(left: newLeft);
}
}
else
{
var newRight = _right.Remove(key, keyComparer, out mutated);
if (mutated)
{
result = this.Mutate(right: newRight);
}
}
return result.IsEmpty ? result : MakeBalanced(result);
}
}
/// <summary>
/// Creates a node mutation, either by mutating this node (if not yet frozen) or by creating a clone of this node
/// with the described changes.
/// </summary>
/// <param name="left">The left branch of the mutated node.</param>
/// <param name="right">The right branch of the mutated node.</param>
/// <returns>The mutated (or created) node.</returns>
private Node Mutate(Node left = null, Node right = null)
{
if (_frozen)
{
return new Node(_key, _value, left ?? _left, right ?? _right);
}
else
{
if (left != null)
{
_left = left;
}
if (right != null)
{
_right = right;
}
_height = checked((byte)(1 + Math.Max(_left._height, _right._height)));
return this;
}
}
/// <summary>
/// Searches the specified key. Callers are expected to validate arguments.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="keyComparer">The key comparer.</param>
[Pure]
private Node Search(TKey key, IComparer<TKey> keyComparer)
{
// Arg validation is too expensive for recursive methods.
// Callers are expected to have validated parameters.
if (this.IsEmpty)
{
return this;
}
else
{
int compare = keyComparer.Compare(key, _key);
if (compare == 0)
{
return this;
}
else if (compare > 0)
{
return _right.Search(key, keyComparer);
}
else
{
return _left.Search(key, keyComparer);
}
}
}
}
}
}
| |
/*
* ToolBarButton.cs - Implementation of the
* "System.Windows.Forms.ToolBarButton" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
* Copyright (C) 2003 Free Software Foundation, Inc.
*
* 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 System.Windows.Forms
{
using System;
using System.ComponentModel;
using System.Drawing;
public class ToolBarButton
#if CONFIG_COMPONENT_MODEL
: Component
#endif
{
// Variables
internal ToolBar parent;
internal int tbbcIndex; // index in ToolBarButtonCollection
internal int groupID; // index of last separator (used in wrapping)
internal Rectangle viewRectangle;
internal Rectangle dropRectangle;
private Menu dropDownMenu = null;
private bool enabled = true;
private int imageIndex = -1;
private bool partialPush = false;
private bool pushed = false;
private ToolBarButtonStyle style = ToolBarButtonStyle.PushButton;
private object tag = null;
private string text = "";
private string toolTipText = "";
private bool visible = true;
// Constructors
public ToolBarButton() : base() {}
#if !CONFIG_COMPACT_FORMS
public ToolBarButton(String s) : base() { text = s; }
#endif
// Properties
public Menu DropDownMenu
{
get { return dropDownMenu; }
set
{
// this is called bad design
// this is the compiler's job
if (!(value is ContextMenu))
{
throw new ArgumentException(/* TODO */);
}
if (value == dropDownMenu) { return; }
dropDownMenu = value;
}
}
public bool Enabled
{
get { return enabled; }
set
{
if (value == enabled) { return; }
enabled = value;
if (visible && parent != null)
{
parent.TBBUpdate(tbbcIndex,true);
}
}
}
public int ImageIndex
{
get { return imageIndex; }
set
{
if (value < -1)
{
// ArgumentOutOfRangeException?
throw new ArgumentException(/* TODO */);
}
if (value == imageIndex) { return; }
imageIndex = value;
if (visible && parent != null)
{
parent.TBBUpdate(tbbcIndex,true);
}
}
}
#if !CONFIG_COMPACT_FORMS
public ToolBar Parent { get { return parent; } }
public bool PartialPush
{
get { return partialPush; }
set
{
if (value == partialPush) { return; }
partialPush = value;
if (style == ToolBarButtonStyle.ToggleButton)
{
if (visible && parent != null)
{
parent.TBBUpdate(tbbcIndex,true);
}
}
}
}
#endif
public bool Pushed
{
get { return pushed; }
set
{
if (value == pushed) { return; }
pushed = value;
if (style == ToolBarButtonStyle.ToggleButton)
{
if (visible && parent != null)
{
parent.TBBUpdate(tbbcIndex,true);
}
}
}
}
#if !CONFIG_COMPACT_FORMS
public Rectangle Rectangle
{
get
{
if (parent.Visible && Visible)
{
return Rectangle.Union(viewRectangle,dropRectangle);
}
return Rectangle.Empty;
}
}
#endif
public ToolBarButtonStyle Style
{
get { return style; }
set
{
if (value == style) { return; }
ToolBarButtonStyle oldStyle = style;
style = value;
if (visible && parent != null)
{
if (oldStyle == ToolBarButtonStyle.Separator)
{
parent.buttons.KillGroupQuiet(tbbcIndex);
}
else if (value == ToolBarButtonStyle.Separator)
{
parent.buttons.MakeGroupQuiet(tbbcIndex);
}
parent.TBBUpdate(tbbcIndex,false);
}
}
}
#if !CONFIG_COMPACT_FORMS
public object Tag
{
get { return tag; }
set { tag = value; }
}
public string Text
{
get { return text; }
set
{
if (value == text) { return; }
if (value == null) { value = ""; }
text = value;
if (visible && parent != null)
{
parent.TBBUpdate(tbbcIndex,false);
}
}
}
public string ToolTipText
{
get { return toolTipText; }
set
{
if (value == toolTipText) { return; }
if (value == null) { value = ""; }
toolTipText = value;
}
}
#endif
public bool Visible
{
get { return visible; }
set
{
if (value == visible) { return; }
visible = value;
if (!visible)
{
viewRectangle = Rectangle.Empty;
dropRectangle = Rectangle.Empty;
}
if (parent != null)
{
if (style == ToolBarButtonStyle.Separator)
{
if (visible)
{
// if the separator is visible
// it should act as a wrap point
parent.buttons.MakeGroupQuiet(tbbcIndex);
}
else
{
// if the separator isn't visible
// it shouldn't act as a wrap point
parent.buttons.KillGroupQuiet(tbbcIndex);
}
// no point in recalculating all the text
// and button sizing info for a group change
parent.TBBCUpdate(true);
}
else
{
parent.TBBUpdate(tbbcIndex,false);
}
}
}
}
// Methods
/*protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}*/
internal int Contains(int x, int y, bool dropDowns)
{
if (!visible)
{
return 0;
}
else if (style == ToolBarButtonStyle.Separator)
{
if (viewRectangle.Contains(x,y))
{
return -1;
}
return 0;
}
else if (dropDowns)
{
if (viewRectangle.Contains(x,y))
{
return 1;
}
else if (dropRectangle.Contains(x,y))
{
return 2;
}
else
{
return 0;
}
}
else if (style == ToolBarButtonStyle.DropDownButton)
{
if (viewRectangle.Contains(x,y))
{
return 2;
}
else
{
return 0;
}
}
else if (viewRectangle.Contains(x,y))
{
return 1;
}
else
{
return 0;
}
}
internal void Reset()
{
parent = null;
tbbcIndex = -1;
groupID = -1;
viewRectangle = Rectangle.Empty;
dropRectangle = Rectangle.Empty;
}
public override string ToString()
{
return String.Format("ToolBarButton: {0}, Style: {1}",
Text, Style);
}
}; // class ToolBarButton
}; // namespace System.Windows.Forms
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace YourFood.Services.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// 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.Metadata.ManagedReference
{
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.DocAsCode.DataContracts.ManagedReference;
public abstract class ReferenceItemVisitor : SymbolVisitor
{
public static readonly SymbolDisplayFormat ShortFormat = SimpleYamlModelGenerator.ShortFormat;
public static readonly SymbolDisplayFormat QualifiedFormat = SimpleYamlModelGenerator.QualifiedFormat;
public static readonly SymbolDisplayFormat ShortFormatWithoutGenericeParameter = ShortFormat
.WithGenericsOptions(SymbolDisplayGenericsOptions.None);
public static readonly SymbolDisplayFormat QualifiedFormatWithoutGenericeParameter = QualifiedFormat
.WithGenericsOptions(SymbolDisplayGenericsOptions.None);
protected ReferenceItemVisitor(ReferenceItem referenceItem)
{
ReferenceItem = referenceItem;
}
protected ReferenceItem ReferenceItem { get; private set; }
public override void VisitNamedType(INamedTypeSymbol symbol)
{
if (symbol.IsTupleType)
{
symbol = symbol.TupleUnderlyingType;
}
if (symbol.IsGenericType)
{
if (symbol.IsUnboundGenericType)
{
AddLinkItems(symbol, true);
}
else
{
AddLinkItems(symbol.OriginalDefinition, false);
AddBeginGenericParameter();
for (int i = 0; i < symbol.TypeArguments.Length; i++)
{
if (i > 0)
{
AddGenericParameterSeparator();
}
symbol.TypeArguments[i].Accept(this);
}
AddEndGenericParameter();
}
}
else
{
AddLinkItems(symbol, true);
}
}
protected abstract void AddLinkItems(INamedTypeSymbol symbol, bool withGenericeParameter);
protected abstract void AddBeginGenericParameter();
protected abstract void AddGenericParameterSeparator();
protected abstract void AddEndGenericParameter();
}
public class CSReferenceItemVisitor
: ReferenceItemVisitor
{
private readonly bool _asOverload;
public CSReferenceItemVisitor(ReferenceItem referenceItem, bool asOverload) : base(referenceItem)
{
_asOverload = asOverload;
if (!referenceItem.Parts.ContainsKey(SyntaxLanguage.CSharp))
{
referenceItem.Parts.Add(SyntaxLanguage.CSharp, new List<LinkItem>());
}
}
public override void VisitNamespace(INamespaceSymbol symbol)
{
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = NameVisitorCreator.GetCSharp(NameOptions.None).GetName(symbol),
DisplayNamesWithType = NameVisitorCreator.GetCSharp(NameOptions.WithType).GetName(symbol),
DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified).GetName(symbol),
IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0,
});
}
public override void VisitTypeParameter(ITypeParameterSymbol symbol)
{
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = symbol.Name,
DisplayNamesWithType = symbol.Name,
DisplayQualifiedNames = symbol.Name,
});
}
public override void VisitArrayType(IArrayTypeSymbol symbol)
{
symbol.ElementType.Accept(this);
if (symbol.Rank == 1)
{
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = "[]",
DisplayNamesWithType = "[]",
DisplayQualifiedNames = "[]",
});
}
else
{
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = "[" + new string(',', symbol.Rank - 1) + "]",
DisplayNamesWithType = "[" + new string(',', symbol.Rank - 1) + "]",
DisplayQualifiedNames = "[" + new string(',', symbol.Rank - 1) + "]",
});
}
}
public override void VisitPointerType(IPointerTypeSymbol symbol)
{
symbol.PointedAtType.Accept(this);
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = "*",
DisplayNamesWithType = "*",
DisplayQualifiedNames = "*",
});
}
public override void VisitMethod(IMethodSymbol symbol)
{
var id = _asOverload ? VisitorHelper.GetOverloadId(symbol.OriginalDefinition) : VisitorHelper.GetId(symbol.OriginalDefinition);
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = NameVisitorCreator.GetCSharp(_asOverload ? NameOptions.WithTypeGenericParameter : NameOptions.WithGenericParameter).GetName(symbol),
DisplayNamesWithType = NameVisitorCreator.GetCSharp(NameOptions.WithType | (_asOverload ? NameOptions.WithTypeGenericParameter : NameOptions.WithGenericParameter)).GetName(symbol),
DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified | (_asOverload ? NameOptions.WithTypeGenericParameter : NameOptions.WithGenericParameter)).GetName(symbol),
Name = id,
IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0,
});
if (_asOverload)
{
return;
}
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = "(",
DisplayNamesWithType = "(",
DisplayQualifiedNames = "(",
});
for (int i = 0; i < symbol.Parameters.Length; i++)
{
if (i > 0)
{
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = ", ",
DisplayNamesWithType = ", ",
DisplayQualifiedNames = ", ",
});
}
symbol.Parameters[i].Type.Accept(this);
}
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = ")",
DisplayNamesWithType = ")",
DisplayQualifiedNames = ")",
});
}
public override void VisitProperty(IPropertySymbol symbol)
{
var id = _asOverload ? VisitorHelper.GetOverloadId(symbol.OriginalDefinition) : VisitorHelper.GetId(symbol.OriginalDefinition);
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = NameVisitorCreator.GetCSharp(NameOptions.WithTypeGenericParameter).GetName(symbol),
DisplayNamesWithType = NameVisitorCreator.GetCSharp(NameOptions.WithType | NameOptions.WithTypeGenericParameter).GetName(symbol),
DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified | NameOptions.WithTypeGenericParameter).GetName(symbol),
Name = id,
IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0,
});
if (symbol.Parameters.Length > 0 && !_asOverload)
{
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = "[",
DisplayNamesWithType = "[",
DisplayQualifiedNames = "[",
});
for (int i = 0; i < symbol.Parameters.Length; i++)
{
if (i > 0)
{
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = ", ",
DisplayNamesWithType = ", ",
DisplayQualifiedNames = ", ",
});
}
symbol.Parameters[i].Type.Accept(this);
}
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = "]",
DisplayNamesWithType = "]",
DisplayQualifiedNames = "]",
});
}
}
public override void VisitEvent(IEventSymbol symbol)
{
var id = VisitorHelper.GetId(symbol.OriginalDefinition);
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = NameVisitorCreator.GetCSharp(NameOptions.WithTypeGenericParameter).GetName(symbol),
DisplayNamesWithType = NameVisitorCreator.GetCSharp(NameOptions.WithType | NameOptions.WithTypeGenericParameter).GetName(symbol),
DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified | NameOptions.WithTypeGenericParameter).GetName(symbol),
Name = id,
IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0,
});
}
public override void VisitField(IFieldSymbol symbol)
{
var id = VisitorHelper.GetId(symbol.OriginalDefinition);
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = NameVisitorCreator.GetCSharp(NameOptions.WithTypeGenericParameter).GetName(symbol),
DisplayNamesWithType = NameVisitorCreator.GetCSharp(NameOptions.WithType | NameOptions.WithTypeGenericParameter).GetName(symbol),
DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified | NameOptions.WithTypeGenericParameter).GetName(symbol),
Name = id,
IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0,
});
}
public override void VisitDynamicType(IDynamicTypeSymbol symbol)
{
var id = VisitorHelper.GetId(symbol.OriginalDefinition);
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = NameVisitorCreator.GetCSharp(NameOptions.None).GetName(symbol),
DisplayNamesWithType = NameVisitorCreator.GetCSharp(NameOptions.WithType).GetName(symbol),
DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified).GetName(symbol),
Name = id,
});
}
protected override void AddBeginGenericParameter()
{
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = "<",
DisplayNamesWithType = "<",
DisplayQualifiedNames = "<",
});
}
protected override void AddEndGenericParameter()
{
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = ">",
DisplayNamesWithType = ">",
DisplayQualifiedNames = ">",
});
}
protected override void AddGenericParameterSeparator()
{
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = ", ",
DisplayNamesWithType = ", ",
DisplayQualifiedNames = ", ",
});
}
protected override void AddLinkItems(INamedTypeSymbol symbol, bool withGenericeParameter)
{
var id = VisitorHelper.GetId(symbol);
if (withGenericeParameter)
{
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = NameVisitorCreator.GetCSharp(NameOptions.WithGenericParameter).GetName(symbol),
DisplayNamesWithType = NameVisitorCreator.GetCSharp(NameOptions.WithType | NameOptions.WithGenericParameter).GetName(symbol),
DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified | NameOptions.WithGenericParameter).GetName(symbol),
Name = id,
IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0,
});
}
else
{
ReferenceItem.Parts[SyntaxLanguage.CSharp].Add(new LinkItem
{
DisplayName = NameVisitorCreator.GetCSharp(NameOptions.None).GetName(symbol),
DisplayNamesWithType = NameVisitorCreator.GetCSharp(NameOptions.WithType).GetName(symbol),
DisplayQualifiedNames = NameVisitorCreator.GetCSharp(NameOptions.Qualified).GetName(symbol),
Name = id,
IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0,
});
}
}
}
public class VBReferenceItemVisitor
: ReferenceItemVisitor
{
private readonly bool _asOverload;
public VBReferenceItemVisitor(ReferenceItem referenceItem, bool asOverload) : base(referenceItem)
{
_asOverload = asOverload;
if (!referenceItem.Parts.ContainsKey(SyntaxLanguage.VB))
{
referenceItem.Parts.Add(SyntaxLanguage.VB, new List<LinkItem>());
}
}
public override void VisitNamespace(INamespaceSymbol symbol)
{
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = NameVisitorCreator.GetVB(NameOptions.None).GetName(symbol),
DisplayNamesWithType = NameVisitorCreator.GetVB(NameOptions.WithType).GetName(symbol),
DisplayQualifiedNames = NameVisitorCreator.GetVB(NameOptions.Qualified).GetName(symbol),
});
}
public override void VisitTypeParameter(ITypeParameterSymbol symbol)
{
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = symbol.Name,
DisplayNamesWithType = symbol.Name,
DisplayQualifiedNames = symbol.Name,
});
}
public override void VisitArrayType(IArrayTypeSymbol symbol)
{
symbol.ElementType.Accept(this);
if (symbol.Rank == 1)
{
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = "()",
DisplayNamesWithType = "()",
DisplayQualifiedNames = "()",
});
}
else
{
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = "(" + new string(',', symbol.Rank - 1) + ")",
DisplayNamesWithType = "(" + new string(',', symbol.Rank - 1) + ")",
DisplayQualifiedNames = "(" + new string(',', symbol.Rank - 1) + ")",
});
}
}
public override void VisitPointerType(IPointerTypeSymbol symbol)
{
symbol.PointedAtType.Accept(this);
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = "*",
DisplayNamesWithType = "*",
DisplayQualifiedNames = "*",
});
}
public override void VisitMethod(IMethodSymbol symbol)
{
var id = _asOverload ? VisitorHelper.GetOverloadId(symbol.OriginalDefinition) : VisitorHelper.GetId(symbol.OriginalDefinition);
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = NameVisitorCreator.GetVB(_asOverload ? NameOptions.WithTypeGenericParameter : NameOptions.WithGenericParameter).GetName(symbol),
DisplayNamesWithType = NameVisitorCreator.GetVB(NameOptions.WithType | (_asOverload ? NameOptions.WithTypeGenericParameter : NameOptions.WithGenericParameter)).GetName(symbol),
DisplayQualifiedNames = NameVisitorCreator.GetVB(NameOptions.Qualified | (_asOverload ? NameOptions.WithTypeGenericParameter : NameOptions.WithGenericParameter)).GetName(symbol),
Name = id,
IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0,
});
if (_asOverload)
{
return;
}
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = "(",
DisplayNamesWithType = "(",
DisplayQualifiedNames = "(",
});
for (int i = 0; i < symbol.Parameters.Length; i++)
{
if (i > 0)
{
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = ", ",
DisplayNamesWithType = ", ",
DisplayQualifiedNames = ", ",
});
}
symbol.Parameters[i].Type.Accept(this);
}
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = ")",
DisplayNamesWithType = ")",
DisplayQualifiedNames = ")",
});
}
public override void VisitProperty(IPropertySymbol symbol)
{
var id = _asOverload ? VisitorHelper.GetOverloadId(symbol.OriginalDefinition) : VisitorHelper.GetId(symbol.OriginalDefinition);
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = NameVisitorCreator.GetVB(NameOptions.WithTypeGenericParameter).GetName(symbol),
DisplayNamesWithType = NameVisitorCreator.GetVB(NameOptions.WithType | NameOptions.WithTypeGenericParameter).GetName(symbol),
DisplayQualifiedNames = NameVisitorCreator.GetVB(NameOptions.Qualified | NameOptions.WithTypeGenericParameter).GetName(symbol),
Name = id,
IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0,
});
if (symbol.Parameters.Length > 0 && !_asOverload)
{
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = "(",
DisplayNamesWithType = "(",
DisplayQualifiedNames = "(",
});
for (int i = 0; i < symbol.Parameters.Length; i++)
{
if (i > 0)
{
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = ", ",
DisplayNamesWithType = ", ",
DisplayQualifiedNames = ", ",
});
}
symbol.Parameters[i].Type.Accept(this);
}
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = ")",
DisplayNamesWithType = ")",
DisplayQualifiedNames = ")",
});
}
}
public override void VisitEvent(IEventSymbol symbol)
{
var id = VisitorHelper.GetId(symbol.OriginalDefinition);
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = NameVisitorCreator.GetVB(NameOptions.WithTypeGenericParameter).GetName(symbol),
DisplayNamesWithType = NameVisitorCreator.GetVB(NameOptions.WithType | NameOptions.WithTypeGenericParameter).GetName(symbol),
DisplayQualifiedNames = NameVisitorCreator.GetVB(NameOptions.Qualified | NameOptions.WithTypeGenericParameter).GetName(symbol),
Name = id,
IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0,
});
}
public override void VisitField(IFieldSymbol symbol)
{
var id = VisitorHelper.GetId(symbol.OriginalDefinition);
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = NameVisitorCreator.GetVB(NameOptions.WithTypeGenericParameter).GetName(symbol),
DisplayNamesWithType = NameVisitorCreator.GetVB(NameOptions.WithType | NameOptions.WithTypeGenericParameter).GetName(symbol),
DisplayQualifiedNames = NameVisitorCreator.GetVB(NameOptions.Qualified | NameOptions.WithTypeGenericParameter).GetName(symbol),
Name = id,
IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0,
});
}
protected override void AddBeginGenericParameter()
{
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = "(Of ",
DisplayNamesWithType = "(Of ",
DisplayQualifiedNames = "(Of ",
});
}
protected override void AddEndGenericParameter()
{
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = ")",
DisplayNamesWithType = ")",
DisplayQualifiedNames = ")",
});
}
protected override void AddGenericParameterSeparator()
{
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = ", ",
DisplayNamesWithType = ", ",
DisplayQualifiedNames = ", ",
});
}
protected override void AddLinkItems(INamedTypeSymbol symbol, bool withGenericeParameter)
{
var id = VisitorHelper.GetId(symbol);
if (withGenericeParameter)
{
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = NameVisitorCreator.GetVB(NameOptions.WithGenericParameter).GetName(symbol),
DisplayNamesWithType = NameVisitorCreator.GetVB(NameOptions.WithType | NameOptions.WithGenericParameter).GetName(symbol),
DisplayQualifiedNames = NameVisitorCreator.GetVB(NameOptions.Qualified | NameOptions.WithGenericParameter).GetName(symbol),
Name = id,
IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0,
});
}
else
{
ReferenceItem.Parts[SyntaxLanguage.VB].Add(new LinkItem
{
DisplayName = NameVisitorCreator.GetVB(NameOptions.None).GetName(symbol),
DisplayNamesWithType = NameVisitorCreator.GetVB(NameOptions.WithType).GetName(symbol),
DisplayQualifiedNames = NameVisitorCreator.GetVB(NameOptions.Qualified).GetName(symbol),
Name = id,
IsExternalPath = symbol.IsExtern || symbol.DeclaringSyntaxReferences.Length == 0,
});
}
}
}
}
| |
/*
* OEML - REST API
*
* This section will provide necessary information about the `CoinAPI OEML REST API` protocol. <br/> This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a> <br/><br/> Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)
*
* The version of the OpenAPI document: v1
* Contact: support@coinapi.io
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = CoinAPI.OMS.API.SDK.Client.OpenAPIDateConverter;
namespace CoinAPI.OMS.API.SDK.Model
{
/// <summary>
/// BalanceData
/// </summary>
[DataContract(Name = "Balance_data")]
public partial class BalanceData : IEquatable<BalanceData>, IValidatableObject
{
/// <summary>
/// Source of the last modification.
/// </summary>
/// <value>Source of the last modification. </value>
[JsonConverter(typeof(StringEnumConverter))]
public enum LastUpdatedByEnum
{
/// <summary>
/// Enum INITIALIZATION for value: INITIALIZATION
/// </summary>
[EnumMember(Value = "INITIALIZATION")]
INITIALIZATION = 1,
/// <summary>
/// Enum BALANCEMANAGER for value: BALANCE_MANAGER
/// </summary>
[EnumMember(Value = "BALANCE_MANAGER")]
BALANCEMANAGER = 2,
/// <summary>
/// Enum EXCHANGE for value: EXCHANGE
/// </summary>
[EnumMember(Value = "EXCHANGE")]
EXCHANGE = 3
}
/// <summary>
/// Source of the last modification.
/// </summary>
/// <value>Source of the last modification. </value>
[DataMember(Name = "last_updated_by", EmitDefaultValue = false)]
public LastUpdatedByEnum? LastUpdatedBy { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="BalanceData" /> class.
/// </summary>
/// <param name="assetIdExchange">Exchange currency code..</param>
/// <param name="assetIdCoinapi">CoinAPI currency code..</param>
/// <param name="balance">Value of the current total currency balance on the exchange..</param>
/// <param name="available">Value of the current available currency balance on the exchange that can be used as collateral..</param>
/// <param name="locked">Value of the current locked currency balance by the exchange..</param>
/// <param name="lastUpdatedBy">Source of the last modification. .</param>
/// <param name="rateUsd">Current exchange rate to the USD for the single unit of the currency. .</param>
/// <param name="traded">Value of the current total traded..</param>
public BalanceData(string assetIdExchange = default(string), string assetIdCoinapi = default(string), double balance = default(double), double available = default(double), double locked = default(double), LastUpdatedByEnum? lastUpdatedBy = default(LastUpdatedByEnum?), double rateUsd = default(double), double traded = default(double))
{
this.AssetIdExchange = assetIdExchange;
this.AssetIdCoinapi = assetIdCoinapi;
this.Balance = balance;
this.Available = available;
this.Locked = locked;
this.LastUpdatedBy = lastUpdatedBy;
this.RateUsd = rateUsd;
this.Traded = traded;
}
/// <summary>
/// Exchange currency code.
/// </summary>
/// <value>Exchange currency code.</value>
[DataMember(Name = "asset_id_exchange", EmitDefaultValue = false)]
public string AssetIdExchange { get; set; }
/// <summary>
/// CoinAPI currency code.
/// </summary>
/// <value>CoinAPI currency code.</value>
[DataMember(Name = "asset_id_coinapi", EmitDefaultValue = false)]
public string AssetIdCoinapi { get; set; }
/// <summary>
/// Value of the current total currency balance on the exchange.
/// </summary>
/// <value>Value of the current total currency balance on the exchange.</value>
[DataMember(Name = "balance", EmitDefaultValue = false)]
public double Balance { get; set; }
/// <summary>
/// Value of the current available currency balance on the exchange that can be used as collateral.
/// </summary>
/// <value>Value of the current available currency balance on the exchange that can be used as collateral.</value>
[DataMember(Name = "available", EmitDefaultValue = false)]
public double Available { get; set; }
/// <summary>
/// Value of the current locked currency balance by the exchange.
/// </summary>
/// <value>Value of the current locked currency balance by the exchange.</value>
[DataMember(Name = "locked", EmitDefaultValue = false)]
public double Locked { get; set; }
/// <summary>
/// Current exchange rate to the USD for the single unit of the currency.
/// </summary>
/// <value>Current exchange rate to the USD for the single unit of the currency. </value>
[DataMember(Name = "rate_usd", EmitDefaultValue = false)]
public double RateUsd { get; set; }
/// <summary>
/// Value of the current total traded.
/// </summary>
/// <value>Value of the current total traded.</value>
[DataMember(Name = "traded", EmitDefaultValue = false)]
public double Traded { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class BalanceData {\n");
sb.Append(" AssetIdExchange: ").Append(AssetIdExchange).Append("\n");
sb.Append(" AssetIdCoinapi: ").Append(AssetIdCoinapi).Append("\n");
sb.Append(" Balance: ").Append(Balance).Append("\n");
sb.Append(" Available: ").Append(Available).Append("\n");
sb.Append(" Locked: ").Append(Locked).Append("\n");
sb.Append(" LastUpdatedBy: ").Append(LastUpdatedBy).Append("\n");
sb.Append(" RateUsd: ").Append(RateUsd).Append("\n");
sb.Append(" Traded: ").Append(Traded).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 virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as BalanceData);
}
/// <summary>
/// Returns true if BalanceData instances are equal
/// </summary>
/// <param name="input">Instance of BalanceData to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(BalanceData input)
{
if (input == null)
{
return false;
}
return
(
this.AssetIdExchange == input.AssetIdExchange ||
(this.AssetIdExchange != null &&
this.AssetIdExchange.Equals(input.AssetIdExchange))
) &&
(
this.AssetIdCoinapi == input.AssetIdCoinapi ||
(this.AssetIdCoinapi != null &&
this.AssetIdCoinapi.Equals(input.AssetIdCoinapi))
) &&
(
this.Balance == input.Balance ||
this.Balance.Equals(input.Balance)
) &&
(
this.Available == input.Available ||
this.Available.Equals(input.Available)
) &&
(
this.Locked == input.Locked ||
this.Locked.Equals(input.Locked)
) &&
(
this.LastUpdatedBy == input.LastUpdatedBy ||
this.LastUpdatedBy.Equals(input.LastUpdatedBy)
) &&
(
this.RateUsd == input.RateUsd ||
this.RateUsd.Equals(input.RateUsd)
) &&
(
this.Traded == input.Traded ||
this.Traded.Equals(input.Traded)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.AssetIdExchange != null)
{
hashCode = (hashCode * 59) + this.AssetIdExchange.GetHashCode();
}
if (this.AssetIdCoinapi != null)
{
hashCode = (hashCode * 59) + this.AssetIdCoinapi.GetHashCode();
}
hashCode = (hashCode * 59) + this.Balance.GetHashCode();
hashCode = (hashCode * 59) + this.Available.GetHashCode();
hashCode = (hashCode * 59) + this.Locked.GetHashCode();
hashCode = (hashCode * 59) + this.LastUpdatedBy.GetHashCode();
hashCode = (hashCode * 59) + this.RateUsd.GetHashCode();
hashCode = (hashCode * 59) + this.Traded.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Baseline;
using LamarCodeGeneration;
using LamarCodeGeneration.Frames;
using LamarCodeGeneration.Model;
using LamarCompiler;
using Marten.Events.CodeGeneration;
using Marten.Events.Daemon;
using Marten.Exceptions;
using Marten.Internal;
using Marten.Internal.CodeGeneration;
using Marten.Linq.SqlGeneration;
using Marten.Schema;
using Marten.Storage;
using Weasel.Postgresql.SqlGeneration;
namespace Marten.Events.Projections
{
/// <summary>
/// This is the "do anything" projection type
/// </summary>
public abstract class EventProjection : ProjectionSource
{
private readonly ProjectMethodCollection _projectMethods;
private readonly CreateMethodCollection _createMethods;
public EventProjection() : base("Projections")
{
_projectMethods = new ProjectMethodCollection(GetType());
_createMethods = new CreateMethodCollection(GetType());
ProjectionName = GetType().FullNameInCode();
}
public override Type ProjectionType => GetType();
internal override void AssertValidity()
{
if (!_projectMethods.Methods.Any() && !_createMethods.Methods.Any())
{
throw new InvalidProjectionException(
$"EventProjection {GetType().FullNameInCode()} has no valid projection operations");
}
var invalidMethods = MethodCollection.FindInvalidMethods(GetType(), _projectMethods, _createMethods);
if (invalidMethods.Any())
{
throw new InvalidProjectionException(this, invalidMethods);
}
}
[MartenIgnore]
public void Project<TEvent>(Action<TEvent, IDocumentOperations> project)
{
_projectMethods.AddLambda(project, typeof(TEvent));
}
[MartenIgnore]
public void ProjectAsync<TEvent>(Func<TEvent, IDocumentOperations, Task> project)
{
_projectMethods.AddLambda(project, typeof(TEvent));
}
/// <summary>
/// This would be a helper for the open ended EventProjection
/// </summary>
internal class ProjectMethodCollection: MethodCollection
{
public static readonly string MethodName = "Project";
public ProjectMethodCollection(Type projectionType) : base(MethodName, projectionType, null)
{
_validArgumentTypes.Add(typeof(IDocumentOperations));
_validReturnTypes.Add(typeof(void));
_validReturnTypes.Add(typeof(Task));
}
internal override void validateMethod(MethodSlot method)
{
if (method.Method.GetParameters().All(x => x.ParameterType != typeof(IDocumentOperations)))
{
method.AddError($"{typeof(IDocumentOperations).FullNameInCode()} is a required parameter");
}
}
public override IEventHandlingFrame CreateEventTypeHandler(Type aggregateType,
IDocumentMapping aggregateMapping,
MethodSlot slot)
{
return new ProjectMethodCall(slot);
}
}
internal class ProjectMethodCall: MethodCall, IEventHandlingFrame
{
public ProjectMethodCall(MethodSlot slot) : base(slot.HandlerType, (MethodInfo) slot.Method)
{
EventType = Method.GetEventType(null);
Target = slot.Setter;
}
public Type EventType { get; }
public void Configure(EventProcessingFrame parent)
{
// Replace any arguments to IEvent<T>
TrySetArgument(parent.SpecificEvent);
// Replace any arguments to the specific T event type
TrySetArgument(parent.DataOnly);
}
}
/// <summary>
/// This would be a helper for the open ended EventProjection
/// </summary>
internal class CreateMethodCollection: MethodCollection
{
public static readonly string MethodName = "Create";
public static readonly string TransformMethodName = "Transform";
public CreateMethodCollection(Type projectionType): base(new[] { MethodName, TransformMethodName}, projectionType, null)
{
_validArgumentTypes.Add(typeof(IDocumentOperations));
}
public override IEventHandlingFrame CreateEventTypeHandler(Type aggregateType,
IDocumentMapping aggregateMapping,
MethodSlot slot)
{
return new CreateMethodFrame(slot);
}
internal override void validateMethod(MethodSlot method)
{
if (method.ReturnType == typeof(void))
{
method.AddError($"The return value must be a new document");
}
}
}
internal class CreateMethodFrame: MethodCall, IEventHandlingFrame
{
private static int _counter = 0;
private Variable _operations;
public CreateMethodFrame(MethodSlot slot) : base(slot.HandlerType, (MethodInfo) slot.Method)
{
EventType = Method.GetEventType(null);
ReturnVariable.OverrideName(ReturnVariable.Usage + ++_counter);
}
public Type EventType { get; }
public void Configure(EventProcessingFrame parent)
{
// Replace any arguments to IEvent<T>
TrySetArgument(parent.SpecificEvent);
// Replace any arguments to the specific T event type
TrySetArgument(parent.DataOnly);
}
public override IEnumerable<Variable> FindVariables(IMethodVariables chain)
{
foreach (var variable in base.FindVariables(chain))
{
yield return variable;
}
_operations = chain.FindVariable(typeof(IDocumentOperations));
}
public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
{
base.GenerateCode(method, writer);
writer.WriteLine($"{_operations.Usage}.Store({ReturnVariable.Usage});");
}
}
private GeneratedType _inlineType;
private GeneratedAssembly _assembly;
private bool _isAsync;
internal override IProjection Build(DocumentStore store)
{
if (_inlineType == null)
{
Compile();
}
var inline = (IProjection)Activator.CreateInstance(_inlineType.CompiledType, this);
_inlineType.ApplySetterValues(inline);
return inline;
}
internal override IReadOnlyList<AsyncProjectionShard> AsyncProjectionShards(DocumentStore store)
{
var baseFilters = new ISqlFragment[0];
var eventTypes = MethodCollection.AllEventTypes(_createMethods, _projectMethods);
if (!eventTypes.Any(x => x.IsAbstract || x.IsInterface))
{
baseFilters = new ISqlFragment[] {new Marten.Events.Daemon.EventTypeFilter(store.Events, eventTypes)};
}
return new List<AsyncProjectionShard> {new(this, baseFilters)};
}
internal void Compile()
{
_assembly = new GeneratedAssembly(new GenerationRules(SchemaConstants.MartenGeneratedNamespace));
_assembly.Generation.Assemblies.Add(GetType().Assembly);
_assembly.Generation.Assemblies.AddRange(_projectMethods.ReferencedAssemblies());
_assembly.Generation.Assemblies.AddRange(_createMethods.ReferencedAssemblies());
_assembly.Namespaces.Add("System.Linq");
_isAsync = _createMethods.IsAsync || _projectMethods.IsAsync;
var baseType = _isAsync ? typeof(AsyncEventProjection<>) : typeof(SyncEventProjection<>);
baseType = baseType.MakeGenericType(GetType());
_inlineType = _assembly.AddType(GetType().Name.Sanitize() + "GeneratedInlineProjection", baseType);
var method = _inlineType.MethodFor("ApplyEvent");
method.DerivedVariables.Add(new Variable(GetType(), "Projection"));
var eventHandling = MethodCollection.AddEventHandling(null, null, _createMethods, _projectMethods);
method.Frames.Add(eventHandling);
var assemblyGenerator = new AssemblyGenerator();
assemblyGenerator.ReferenceAssembly(typeof(IMartenSession).Assembly);
assemblyGenerator.Compile(_assembly);
Debug.WriteLine(_inlineType.SourceCode);
}
protected override IEnumerable<Type> publishedTypes()
{
foreach (var method in _createMethods.Methods)
{
var docType = method.ReturnType;
if (docType.Closes(typeof(Task<>)))
{
yield return docType.GetGenericArguments().Single();
}
else
{
yield return docType;
}
}
}
}
public abstract class SyncEventProjection<T>: SyncEventProjectionBase where T : EventProjection
{
public T Projection { get; }
public SyncEventProjection(T projection)
{
Projection = projection;
}
}
public abstract class AsyncEventProjection<T> : AsyncEventProjectionBase where T : EventProjection
{
public T Projection { get; }
public AsyncEventProjection(T projection)
{
Projection = projection;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace System.Reflection.Emit
{
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics.Contracts;
internal sealed class MethodOnTypeBuilderInstantiation : MethodInfo
{
#region Private Static Members
internal static MethodInfo GetMethod(MethodInfo method, TypeBuilderInstantiation type)
{
return new MethodOnTypeBuilderInstantiation(method, type);
}
#endregion
#region Private Data Mebers
internal MethodInfo m_method;
private TypeBuilderInstantiation m_type;
#endregion
#region Constructor
internal MethodOnTypeBuilderInstantiation(MethodInfo method, TypeBuilderInstantiation type)
{
Contract.Assert(method is MethodBuilder || method is RuntimeMethodInfo);
m_method = method;
m_type = type;
}
#endregion
internal override Type[] GetParameterTypes()
{
return m_method.GetParameterTypes();
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return m_method.MemberType; } }
public override String Name { get { return m_method.Name; } }
public override Type DeclaringType { get { return m_type; } }
public override Type ReflectedType { get { return m_type; } }
public override Object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_method.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_method.IsDefined(attributeType, inherit); }
internal int MetadataTokenInternal
{
get
{
MethodBuilder mb = m_method as MethodBuilder;
if (mb != null)
return mb.MetadataTokenInternal;
else
{
Contract.Assert(m_method is RuntimeMethodInfo);
return m_method.MetadataToken;
}
}
}
public override Module Module { get { return m_method.Module; } }
public new Type GetType() { return base.GetType(); }
#endregion
#region MethodBase Members
[Pure]
public override ParameterInfo[] GetParameters() { return m_method.GetParameters(); }
public override MethodImplAttributes GetMethodImplementationFlags() { return m_method.GetMethodImplementationFlags(); }
public override RuntimeMethodHandle MethodHandle { get { return m_method.MethodHandle; } }
public override MethodAttributes Attributes { get { return m_method.Attributes; } }
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException();
}
public override CallingConventions CallingConvention { get { return m_method.CallingConvention; } }
public override Type [] GetGenericArguments() { return m_method.GetGenericArguments(); }
public override MethodInfo GetGenericMethodDefinition() { return m_method; }
public override bool IsGenericMethodDefinition { get { return m_method.IsGenericMethodDefinition; } }
public override bool ContainsGenericParameters { get { return m_method.ContainsGenericParameters; } }
public override MethodInfo MakeGenericMethod(params Type[] typeArgs)
{
if (!IsGenericMethodDefinition)
throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericMethodDefinition"));
Contract.EndContractBlock();
return MethodBuilderInstantiation.MakeGenericMethod(this, typeArgs);
}
public override bool IsGenericMethod { get { return m_method.IsGenericMethod; } }
#endregion
#region Public Abstract\Virtual Members
public override Type ReturnType { get { return m_method.ReturnType; } }
public override ParameterInfo ReturnParameter { get { throw new NotSupportedException(); } }
public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw new NotSupportedException(); } }
public override MethodInfo GetBaseDefinition() { throw new NotSupportedException(); }
#endregion
}
internal sealed class ConstructorOnTypeBuilderInstantiation : ConstructorInfo
{
#region Private Static Members
internal static ConstructorInfo GetConstructor(ConstructorInfo Constructor, TypeBuilderInstantiation type)
{
return new ConstructorOnTypeBuilderInstantiation(Constructor, type);
}
#endregion
#region Private Data Mebers
internal ConstructorInfo m_ctor;
private TypeBuilderInstantiation m_type;
#endregion
#region Constructor
internal ConstructorOnTypeBuilderInstantiation(ConstructorInfo constructor, TypeBuilderInstantiation type)
{
Contract.Assert(constructor is ConstructorBuilder || constructor is RuntimeConstructorInfo);
m_ctor = constructor;
m_type = type;
}
#endregion
internal override Type[] GetParameterTypes()
{
return m_ctor.GetParameterTypes();
}
internal override Type GetReturnType()
{
return DeclaringType;
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return m_ctor.MemberType; } }
public override String Name { get { return m_ctor.Name; } }
public override Type DeclaringType { get { return m_type; } }
public override Type ReflectedType { get { return m_type; } }
public override Object[] GetCustomAttributes(bool inherit) { return m_ctor.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_ctor.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_ctor.IsDefined(attributeType, inherit); }
internal int MetadataTokenInternal
{
get
{
ConstructorBuilder cb = m_ctor as ConstructorBuilder;
if (cb != null)
return cb.MetadataTokenInternal;
else
{
Contract.Assert(m_ctor is RuntimeConstructorInfo);
return m_ctor.MetadataToken;
}
}
}
public override Module Module { get { return m_ctor.Module; } }
public new Type GetType() { return base.GetType(); }
#endregion
#region MethodBase Members
[Pure]
public override ParameterInfo[] GetParameters() { return m_ctor.GetParameters(); }
public override MethodImplAttributes GetMethodImplementationFlags() { return m_ctor.GetMethodImplementationFlags(); }
public override RuntimeMethodHandle MethodHandle { get { return m_ctor.MethodHandle; } }
public override MethodAttributes Attributes { get { return m_ctor.Attributes; } }
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException();
}
public override CallingConventions CallingConvention { get { return m_ctor.CallingConvention; } }
public override Type[] GetGenericArguments() { return m_ctor.GetGenericArguments(); }
public override bool IsGenericMethodDefinition { get { return false; } }
public override bool ContainsGenericParameters { get { return false; } }
public override bool IsGenericMethod { get { return false; } }
#endregion
#region ConstructorInfo Members
public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new InvalidOperationException();
}
#endregion
}
internal sealed class FieldOnTypeBuilderInstantiation : FieldInfo
{
#region Private Static Members
internal static FieldInfo GetField(FieldInfo Field, TypeBuilderInstantiation type)
{
FieldInfo m = null;
// This ifdef was introduced when non-generic collections were pulled from
// silverlight. See code:Dictionary#DictionaryVersusHashtableThreadSafety
// for information about this change.
//
// There is a pre-existing race condition in this code with the side effect
// that the second thread's value clobbers the first in the hashtable. This is
// an acceptable race condition since we make no guarantees that this will return the
// same object.
//
// We're not entirely sure if this cache helps any specific scenarios, so
// long-term, one could investigate whether it's needed. In any case, this
// method isn't expected to be on any critical paths for performance.
if (type.m_hashtable.Contains(Field)) {
m = type.m_hashtable[Field] as FieldInfo;
}
else {
m = new FieldOnTypeBuilderInstantiation(Field, type);
type.m_hashtable[Field] = m;
}
return m;
}
#endregion
#region Private Data Members
private FieldInfo m_field;
private TypeBuilderInstantiation m_type;
#endregion
#region Constructor
internal FieldOnTypeBuilderInstantiation(FieldInfo field, TypeBuilderInstantiation type)
{
Contract.Assert(field is FieldBuilder || field is RuntimeFieldInfo);
m_field = field;
m_type = type;
}
#endregion
internal FieldInfo FieldInfo { get { return m_field; } }
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } }
public override String Name { get { return m_field.Name; } }
public override Type DeclaringType { get { return m_type; } }
public override Type ReflectedType { get { return m_type; } }
public override Object[] GetCustomAttributes(bool inherit) { return m_field.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_field.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_field.IsDefined(attributeType, inherit); }
internal int MetadataTokenInternal
{
get
{
FieldBuilder fb = m_field as FieldBuilder;
if (fb != null)
return fb.MetadataTokenInternal;
else
{
Contract.Assert(m_field is RuntimeFieldInfo);
return m_field.MetadataToken;
}
}
}
public override Module Module { get { return m_field.Module; } }
public new Type GetType() { return base.GetType(); }
#endregion
#region Public Abstract\Virtual Members
public override Type[] GetRequiredCustomModifiers() { return m_field.GetRequiredCustomModifiers(); }
public override Type[] GetOptionalCustomModifiers() { return m_field.GetOptionalCustomModifiers(); }
public override void SetValueDirect(TypedReference obj, Object value)
{
throw new NotImplementedException();
}
public override Object GetValueDirect(TypedReference obj)
{
throw new NotImplementedException();
}
public override RuntimeFieldHandle FieldHandle
{
get { throw new NotImplementedException(); }
}
public override Type FieldType { get { throw new NotImplementedException(); } }
public override Object GetValue(Object obj) { throw new InvalidOperationException(); }
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { throw new InvalidOperationException(); }
public override FieldAttributes Attributes { get { return m_field.Attributes; } }
#endregion
}
}
| |
#region Using directives
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Diagnostics;
using Microsoft.Msagl.Layout.LargeGraphLayout;
#endregion
namespace Microsoft.Msagl.Core.Geometry {
/// <summary>
/// Represents a node containing a box and some user data.
/// Is used in curve intersections routines.
/// </summary>
public class IntervalNode<TData> {
#if TEST_MSAGL
/// <summary>
///
/// </summary>
/// <returns></returns>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public override string ToString() {
return IsLeaf ? (Count + " " + UserData) : Count.ToString();
}
#endif
/// <summary>
///
/// </summary>
public int Count { get; set; }
IntervalNode<TData> left;
IntervalNode<TData> right;
/// <summary>
/// creates an empty node
/// </summary>
public IntervalNode() {
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="rect"></param>
public IntervalNode(TData data, Interval rect) {
UserData = data;
Interval = rect;
Count = 1;
}
IntervalNode(int count) {
Count=count;
}
/// <summary>
/// This field provides direct internal access to the value type Interval, which RTree and other callers
/// modify directly with .Add(); the auto-property returns a temporary value-by-copy that is immediately discarded.
/// </summary>
// ReSharper disable InconsistentNaming
internal Interval interval;
// ReSharper restore InconsistentNaming
/// <summary>
/// gets or sets the interval of the node
/// </summary>
public Interval Interval {
get { return interval; }
set { interval = value; }
}
/// <summary>
/// false if it is an internal node and true if it is a leaf
/// </summary>
internal bool IsLeaf
{
get { return left==null /*&& right==null*/; } //if left is a null then right is also a null
}
/// <summary>
///
/// </summary>
public IntervalNode<TData> Left {
get { return left; }
internal set {
if (left != null && left.Parent==this)
left.Parent = null;
left = value;
if (left != null)
left.Parent = this;
}
}
/// <summary>
///
/// </summary>
public IntervalNode<TData> Right {
get { return right; }
internal set {
if (right != null&& right.Parent==this)
right.Parent = null;
right = value;
if (right != null)
right.Parent = this;
}
}
/// <summary>
/// The actual data if a leaf node, else null or a value-type default.
/// </summary>
public TData UserData { get; set; }
/// <summary>
/// Parent of this node.
/// </summary>
public IntervalNode<TData> Parent { get; private set; }
internal bool IsLeftChild {
get {
Debug.Assert(Parent!=null);
return Equals(Parent.Left);
}
}
/// <summary>
/// brings the first leaf which interval was hit and the delegate is happy with the object
/// </summary>
/// <param name="point"></param>
/// <param name="hitTestFordoubleDelegate"></param>
/// <returns></returns>
public IntervalNode<TData> FirstHitNode(double point, Func<double, TData, HitTestBehavior> hitTestFordoubleDelegate) {
if (interval.Contains(point)) {
if (IsLeaf) {
if (hitTestFordoubleDelegate != null) {
return hitTestFordoubleDelegate(point, UserData) == HitTestBehavior.Stop ? this : null;
}
return this;
}
return Left.FirstHitNode(point, hitTestFordoubleDelegate) ??
Right.FirstHitNode(point, hitTestFordoubleDelegate);
}
return null;
}
/// <summary>
/// brings the first leaf which interval was intersected
/// </summary>
/// <returns></returns>
public IntervalNode<TData> FirstIntersectedNode(Interval r) {
if (r.Intersects(interval)) {
if (IsLeaf)
return this;
return Left.FirstIntersectedNode(r) ?? Right.FirstIntersectedNode(r);
}
return null;
}
/// <summary>
/// brings the first leaf which interval was hit and the delegate is happy with the object
/// </summary>
/// <param name="point"></param>
/// <returns></returns>
public IntervalNode<TData> FirstHitNode(double point) {
if (interval.Contains(point)) {
if (IsLeaf)
return this;
return Left.FirstHitNode(point) ?? Right.FirstHitNode(point);
}
return null;
}
/// <summary>
/// returns all leaf nodes for which the interval was hit and the delegate is happy with the object
/// </summary>
/// <param name="intervalPar"></param>
/// <param name="hitTestAccept"></param>
/// <returns></returns>
public IEnumerable<TData> AllHitItems(Interval intervalPar, Func<TData, bool> hitTestAccept) {
var stack = new Stack<IntervalNode<TData>>();
stack.Push(this);
while (stack.Count > 0) {
IntervalNode<TData> node = stack.Pop();
if (node.Interval.Intersects(intervalPar)) {
if (node.IsLeaf) {
if ((null == hitTestAccept) || hitTestAccept(node.UserData)) {
yield return node.UserData;
}
}
else {
stack.Push(node.left);
stack.Push(node.right);
}
}
}
}
/// <summary>
/// returns all items for which the interval contains the point
/// </summary>
/// <returns></returns>
public IEnumerable<TData> AllHitItems(double point) {
var stack = new Stack<IntervalNode<TData>>();
stack.Push(this);
while (stack.Count > 0) {
var node = stack.Pop();
if (node.Interval.Contains(point)) {
if (node.IsLeaf)
yield return node.UserData;
else {
stack.Push(node.left);
stack.Push(node.right);
}
}
}
}
/// <summary>
/// Returns all leaves whose intervals intersect hitInterval (or all leaves before hitTest returns false).
/// </summary>
/// <param name="hitTest"></param>
/// <param name="hitInterval"></param>
/// <returns></returns>
internal void VisitTree(Func<TData, HitTestBehavior> hitTest, Interval hitInterval) {
VisitTreeStatic(this, hitTest, hitInterval);
}
static HitTestBehavior VisitTreeStatic(IntervalNode<TData> intervalNode, Func<TData, HitTestBehavior> hitTest, Interval hitInterval) {
if (intervalNode.Interval.Intersects(hitInterval)) {
if (hitTest(intervalNode.UserData) == HitTestBehavior.Continue) {
if (intervalNode.Left != null) {
// If intervalNode.Left is not null, intervalNode.Right won't be either.
if (VisitTreeStatic(intervalNode.Left, hitTest, hitInterval) == HitTestBehavior.Continue &&
VisitTreeStatic(intervalNode.Right, hitTest, hitInterval) == HitTestBehavior.Continue) {
return HitTestBehavior.Continue;
}
return HitTestBehavior.Stop;
}
return HitTestBehavior.Continue;
}
return HitTestBehavior.Stop;
}
return HitTestBehavior.Continue;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IntervalNode<TData> Clone() {
var ret = new IntervalNode<TData>(Count) {UserData = UserData, Interval = Interval};
if (Left != null)
ret.Left = Left.Clone();
if (Right != null)
ret.Right = Right.Clone();
return ret;
}
/// <summary>
/// yields all leaves which intervals intersect the given one. We suppose that leaves are all nodes having UserData not a null.
/// </summary>
/// <param name="intervalPar"></param>
/// <returns></returns>
public IEnumerable<TData> GetNodeItemsIntersectingInterval(Interval intervalPar) {
return GetLeafIntervalNodesIntersectingInterval(intervalPar).Select(node => node.UserData);
}
/// <summary>
/// yields all leaves whose intervals intersect the given one. We suppose that leaves are all nodes having UserData not a null.
/// </summary>
/// <param name="intervalPar"></param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public IEnumerable<IntervalNode<TData>> GetLeafIntervalNodesIntersectingInterval(Interval intervalPar) {
var stack = new Stack<IntervalNode<TData>>();
stack.Push(this);
while (stack.Count > 0) {
IntervalNode<TData> node = stack.Pop();
if (node.Interval.Intersects(intervalPar)) {
if (node.IsLeaf) {
yield return node;
} else {
stack.Push(node.left);
stack.Push(node.right);
}
}
}
}
/// <summary>
/// Walk the tree and return the data from all leaves
/// </summary>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public IEnumerable<TData> GetAllLeaves() {
return GetAllLeafNodes().Select(n => n.UserData);
}
internal IEnumerable<IntervalNode<TData>> GetAllLeafNodes() {
return EnumIntervalNodes(true /*leafOnly*/);
}
internal IEnumerable<IntervalNode<TData>> GetAllNodes() {
return EnumIntervalNodes(false /*leafOnly*/);
}
IEnumerable<IntervalNode<TData>> EnumIntervalNodes(bool leafOnly) {
var stack = new Stack<IntervalNode<TData>>();
stack.Push(this);
while (stack.Count > 0) {
var node = stack.Pop();
if (node.IsLeaf || !leafOnly) {
yield return node;
}
if (!node.IsLeaf) {
stack.Push(node.left);
stack.Push(node.right);
}
}
}
const int GroupSplitThreshold = 2;
/// <summary>
/// calculates a tree based on the given nodes
/// </summary>
/// <param name="nodes"></param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes"), SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public static IntervalNode<TData> CreateIntervalNodeOnEnumeration(IEnumerable<IntervalNode<TData>> nodes) {
if(nodes==null)
return null;
var nodeList = new List<IntervalNode<TData>>(nodes);
return CreateIntervalNodeOnListOfNodes(nodeList);
}
///<summary>
///calculates a tree based on the given nodes
///</summary>
///<param name="dataEnumeration"></param>
///<param name="intervalDelegate"></param>
///<returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
public static IntervalNode<TData> CreateIntervalNodeOnData(IEnumerable<TData> dataEnumeration, Func<TData, Interval> intervalDelegate) {
if (dataEnumeration == null || intervalDelegate == null)
return null;
var nodeList = new List<IntervalNode<TData>>(dataEnumeration.Select(d=>new IntervalNode<TData>(d, intervalDelegate(d))));
return CreateIntervalNodeOnListOfNodes(nodeList);
}
/// <summary>
///
/// </summary>
/// <param name="nodes"></param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes"), SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
static public IntervalNode<TData> CreateIntervalNodeOnListOfNodes(IList<IntervalNode<TData>> nodes) {
ValidateArg.IsNotNull(nodes, "nodes");
if (nodes.Count == 0) return null;
if (nodes.Count == 1)return nodes[0];
//Finding the seeds
var b0 = nodes[0].Interval;
//the first seed
int seed0 = 1;
int seed1 = ChooseSeeds(nodes, ref b0, ref seed0);
//We have two seeds at hand. Build two groups.
var gr0 = new List<IntervalNode<TData>>();
var gr1 = new List<IntervalNode<TData>>();
gr0.Add(nodes[seed0]);
gr1.Add(nodes[seed1]);
var box0 = nodes[seed0].Interval;
var box1 = nodes[seed1].Interval;
//divide nodes on two groups
DivideNodes(nodes, seed0, seed1, gr0, gr1, ref box0, ref box1, GroupSplitThreshold);
var ret = new IntervalNode<TData>(nodes.Count) {
Interval = new Interval(box0, box1),
Left = CreateIntervalNodeOnListOfNodes(gr0),
Right = CreateIntervalNodeOnListOfNodes(gr1)
};
return ret;
}
static int ChooseSeeds(IList<IntervalNode<TData>> nodes, ref Interval b0, ref int seed0) {
double area = new Interval(b0, nodes[seed0].Interval).Length;
for (int i = 2; i < nodes.Count; i++) {
double area0 = new Interval(b0, nodes[i].Interval).Length;
if (area0 > area) {
seed0 = i;
area = area0;
}
}
//Got the first seed seed0
//Now looking for a seed for the second group
int seed1 = 0; //the compiler forces me to init it
//init seed1
for (int i = 0; i < nodes.Count; i++) {
if (i != seed0) {
seed1 = i;
break;
}
}
area = new Interval(nodes[seed0].Interval, nodes[seed1].Interval).Length;
//Now try to improve the second seed
for (int i = 0; i < nodes.Count; i++) {
if (i == seed0)
continue;
double area1 = new Interval(nodes[seed0].Interval, nodes[i].Interval).Length;
if (area1 > area) {
seed1 = i;
area = area1;
}
}
return seed1;
}
static void DivideNodes(IList<IntervalNode<TData>> nodes, int seed0, int seed1, List<IntervalNode<TData>> gr0, List<IntervalNode<TData>> gr1,
ref Interval box0, ref Interval box1, int groupSplitThreshold) {
for (int i = 0; i < nodes.Count; i++) {
if (i == seed0 || i == seed1)
continue;
// ReSharper disable InconsistentNaming
var box0_ = new Interval(box0, nodes[i].Interval);
double delta0 = box0_.Length - box0.Length;
var box1_ = new Interval(box1, nodes[i].Interval);
double delta1 = box1_.Length - box1.Length;
// ReSharper restore InconsistentNaming
//keep the tree roughly balanced
if (gr0.Count * groupSplitThreshold < gr1.Count) {
gr0.Add(nodes[i]);
box0 = box0_;
} else if (gr1.Count * groupSplitThreshold < gr0.Count) {
gr1.Add(nodes[i]);
box1 = box1_;
} else if (delta0 < delta1) {
gr0.Add(nodes[i]);
box0 = box0_;
} else if (delta1 < delta0) {
gr1.Add(nodes[i]);
box1 = box1_;
} else if (box0.Length < box1.Length) {
gr0.Add(nodes[i]);
box0 = box0_;
} else {
gr1.Add(nodes[i]);
box1 = box1_;
}
}
}
/// <summary>
/// Walk the tree from node down and apply visitor to all nodes
/// </summary>
/// <param name="node"></param>
/// <param name="visitor"></param>
[SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes"), SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
static public void TraverseHierarchy(IntervalNode<TData> node, Action<IntervalNode<TData>> visitor) {
ValidateArg.IsNotNull(node, "node");
ValidateArg.IsNotNull(visitor, "visitor");
visitor(node);
if (node.Left != null)
TraverseHierarchy(node.Left, visitor);
if (node.Right != null)
TraverseHierarchy(node.Right, visitor);
}
}
}
| |
/*
* 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 System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Server.Base;
using OpenMetaverse;
namespace OpenSim.Services.Connectors
{
public class GridServicesConnector : IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
public GridServicesConnector()
{
}
public GridServicesConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public GridServicesConnector(IConfigSource source)
{
Initialise(source);
}
public virtual void Initialise(IConfigSource source)
{
IConfig gridConfig = source.Configs["GridService"];
if (gridConfig == null)
{
m_log.Error("[GRID CONNECTOR]: GridService missing from OpenSim.ini");
throw new Exception("Grid connector init error");
}
string serviceURI = gridConfig.GetString("GridServerURI",
String.Empty);
if (serviceURI == String.Empty)
{
m_log.Error("[GRID CONNECTOR]: No Server URI named in section GridService");
throw new Exception("Grid connector init error");
}
m_ServerURI = serviceURI;
}
#region IGridService
public virtual bool RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
Dictionary<string, object> rinfo = regionInfo.ToKeyValuePairs();
Dictionary<string, string> sendData = new Dictionary<string,string>();
foreach (KeyValuePair<string, object> kvp in rinfo)
sendData[kvp.Key] = (string)kvp.Value;
sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "register";
string reqString = ServerUtils.BuildQueryString(sendData);
// m_log.DebugFormat("[GRID CONNECTOR]: queryString = {0}", reqString);
try
{
string reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
reqString);
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData.ContainsKey("Result")&& (replyData["Result"].ToString().ToLower() == "success"))
return true;
else if (!replyData.ContainsKey("Result"))
m_log.DebugFormat("[GRID CONNECTOR]: reply data does not contain result field");
else
m_log.DebugFormat("[GRID CONNECTOR]: unexpected result {0}", replyData["Result"].ToString());
}
else
m_log.DebugFormat("[GRID CONNECTOR]: RegisterRegion received null reply");
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
}
return false;
}
public virtual bool DeregisterRegion(UUID regionID)
{
Dictionary<string, string> sendData = new Dictionary<string, string>();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "deregister";
try
{
string reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData["Result"] != null) && (replyData["Result"].ToString().ToLower() == "success"))
return true;
}
else
m_log.DebugFormat("[GRID CONNECTOR]: DeregisterRegion received null reply");
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
}
return false;
}
public virtual List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
Dictionary<string, string> sendData = new Dictionary<string, string>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "get_neighbours";
List<GridRegion> rinfos = new List<GridRegion>();
string reqString = ServerUtils.BuildQueryString(sendData);
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
reqString);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return rinfos;
}
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
//m_log.DebugFormat("[GRID CONNECTOR]: get neighbours returned {0} elements", rinfosList.Count);
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetNeighbours {0}, {1} received invalid response type {2}",
scopeID, regionID, r.GetType());
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetNeighbours {0}, {1} received null response",
scopeID, regionID);
return rinfos;
}
public virtual GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
Dictionary<string, string> sendData = new Dictionary<string, string>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "get_region_by_uuid";
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return null;
}
GridRegion rinfo = null;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
//else
// m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID {0}, {1} received null response",
// scopeID, regionID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID {0}, {1} received null response",
scopeID, regionID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID received null reply");
return rinfo;
}
public virtual GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
Dictionary<string, string> sendData = new Dictionary<string, string>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["X"] = x.ToString();
sendData["Y"] = y.ToString();
sendData["METHOD"] = "get_region_by_position";
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return null;
}
GridRegion rinfo = null;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received invalid response",
scopeID, x, y);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received null response",
scopeID, x, y);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition received null reply");
return rinfo;
}
public virtual GridRegion GetRegionByName(UUID scopeID, string regionName)
{
Dictionary<string, string> sendData = new Dictionary<string, string>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["NAME"] = regionName;
sendData["METHOD"] = "get_region_by_name";
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return null;
}
GridRegion rinfo = null;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1} received null response",
scopeID, regionName);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByName received null reply");
return rinfo;
}
public virtual List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
Dictionary<string, string> sendData = new Dictionary<string, string>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["NAME"] = name;
sendData["MAX"] = maxNumber.ToString();
sendData["METHOD"] = "get_regions_by_name";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName {0}, {1}, {2} received invalid response",
scopeID, name, maxNumber);
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName {0}, {1}, {2} received null response",
scopeID, name, maxNumber);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName received null reply");
return rinfos;
}
public virtual List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
Dictionary<string, string> sendData = new Dictionary<string, string>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["XMIN"] = xmin.ToString();
sendData["XMAX"] = xmax.ToString();
sendData["YMIN"] = ymin.ToString();
sendData["YMAX"] = ymax.ToString();
sendData["METHOD"] = "get_region_range";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
//m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionRange {0}, {1}-{2} {3}-{4} received null response",
scopeID, xmin, xmax, ymin, ymax);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionRange received null reply");
return rinfos;
}
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="MatrixKeyFrameCollection.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
namespace System.Windows.Media.Animation
{
/// <summary>
/// This collection is used in conjunction with a KeyFrameMatrixAnimation
/// to animate a Matrix property value along a set of key frames.
/// </summary>
public class MatrixKeyFrameCollection : Freezable, IList
{
#region Data
private List<MatrixKeyFrame> _keyFrames;
private static MatrixKeyFrameCollection s_emptyCollection;
#endregion
#region Constructors
/// <Summary>
/// Creates a new MatrixKeyFrameCollection.
/// </Summary>
public MatrixKeyFrameCollection()
: base()
{
_keyFrames = new List< MatrixKeyFrame>(2);
}
#endregion
#region Static Methods
/// <summary>
/// An empty MatrixKeyFrameCollection.
/// </summary>
public static MatrixKeyFrameCollection Empty
{
get
{
if (s_emptyCollection == null)
{
MatrixKeyFrameCollection emptyCollection = new MatrixKeyFrameCollection();
emptyCollection._keyFrames = new List< MatrixKeyFrame>(0);
emptyCollection.Freeze();
s_emptyCollection = emptyCollection;
}
return s_emptyCollection;
}
}
#endregion
#region Freezable
/// <summary>
/// Creates a freezable copy of this MatrixKeyFrameCollection.
/// </summary>
/// <returns>The copy</returns>
public new MatrixKeyFrameCollection Clone()
{
return (MatrixKeyFrameCollection)base.Clone();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new MatrixKeyFrameCollection();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>.
/// </summary>
protected override void CloneCore(Freezable sourceFreezable)
{
MatrixKeyFrameCollection sourceCollection = (MatrixKeyFrameCollection) sourceFreezable;
base.CloneCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< MatrixKeyFrame>(count);
for (int i = 0; i < count; i++)
{
MatrixKeyFrame keyFrame = (MatrixKeyFrame)sourceCollection._keyFrames[i].Clone();
_keyFrames.Add(keyFrame);
OnFreezablePropertyChanged(null, keyFrame);
}
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(System.Windows.Freezable)">Freezable.CloneCurrentValueCore</see>.
/// </summary>
protected override void CloneCurrentValueCore(Freezable sourceFreezable)
{
MatrixKeyFrameCollection sourceCollection = (MatrixKeyFrameCollection) sourceFreezable;
base.CloneCurrentValueCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< MatrixKeyFrame>(count);
for (int i = 0; i < count; i++)
{
MatrixKeyFrame keyFrame = (MatrixKeyFrame)sourceCollection._keyFrames[i].CloneCurrentValue();
_keyFrames.Add(keyFrame);
OnFreezablePropertyChanged(null, keyFrame);
}
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(System.Windows.Freezable)">Freezable.GetAsFrozenCore</see>.
/// </summary>
protected override void GetAsFrozenCore(Freezable sourceFreezable)
{
MatrixKeyFrameCollection sourceCollection = (MatrixKeyFrameCollection) sourceFreezable;
base.GetAsFrozenCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< MatrixKeyFrame>(count);
for (int i = 0; i < count; i++)
{
MatrixKeyFrame keyFrame = (MatrixKeyFrame)sourceCollection._keyFrames[i].GetAsFrozen();
_keyFrames.Add(keyFrame);
OnFreezablePropertyChanged(null, keyFrame);
}
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(System.Windows.Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>.
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable sourceFreezable)
{
MatrixKeyFrameCollection sourceCollection = (MatrixKeyFrameCollection) sourceFreezable;
base.GetCurrentValueAsFrozenCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< MatrixKeyFrame>(count);
for (int i = 0; i < count; i++)
{
MatrixKeyFrame keyFrame = (MatrixKeyFrame)sourceCollection._keyFrames[i].GetCurrentValueAsFrozen();
_keyFrames.Add(keyFrame);
OnFreezablePropertyChanged(null, keyFrame);
}
}
/// <summary>
///
/// </summary>
protected override bool FreezeCore(bool isChecking)
{
bool canFreeze = base.FreezeCore(isChecking);
for (int i = 0; i < _keyFrames.Count && canFreeze; i++)
{
canFreeze &= Freezable.Freeze(_keyFrames[i], isChecking);
}
return canFreeze;
}
#endregion
#region IEnumerable
/// <summary>
/// Returns an enumerator of the MatrixKeyFrames in the collection.
/// </summary>
public IEnumerator GetEnumerator()
{
ReadPreamble();
return _keyFrames.GetEnumerator();
}
#endregion
#region ICollection
/// <summary>
/// Returns the number of MatrixKeyFrames in the collection.
/// </summary>
public int Count
{
get
{
ReadPreamble();
return _keyFrames.Count;
}
}
/// <summary>
/// See <see cref="System.Collections.ICollection.IsSynchronized">ICollection.IsSynchronized</see>.
/// </summary>
public bool IsSynchronized
{
get
{
ReadPreamble();
return (IsFrozen || Dispatcher != null);
}
}
/// <summary>
/// See <see cref="System.Collections.ICollection.SyncRoot">ICollection.SyncRoot</see>.
/// </summary>
public object SyncRoot
{
get
{
ReadPreamble();
return ((ICollection)_keyFrames).SyncRoot;
}
}
/// <summary>
/// Copies all of the MatrixKeyFrames in the collection to an
/// array.
/// </summary>
void ICollection.CopyTo(Array array, int index)
{
ReadPreamble();
((ICollection)_keyFrames).CopyTo(array, index);
}
/// <summary>
/// Copies all of the MatrixKeyFrames in the collection to an
/// array of MatrixKeyFrames.
/// </summary>
public void CopyTo(MatrixKeyFrame[] array, int index)
{
ReadPreamble();
_keyFrames.CopyTo(array, index);
}
#endregion
#region IList
/// <summary>
/// Adds a MatrixKeyFrame to the collection.
/// </summary>
int IList.Add(object keyFrame)
{
return Add((MatrixKeyFrame)keyFrame);
}
/// <summary>
/// Adds a MatrixKeyFrame to the collection.
/// </summary>
public int Add(MatrixKeyFrame keyFrame)
{
if (keyFrame == null)
{
throw new ArgumentNullException("keyFrame");
}
WritePreamble();
OnFreezablePropertyChanged(null, keyFrame);
_keyFrames.Add(keyFrame);
WritePostscript();
return _keyFrames.Count - 1;
}
/// <summary>
/// Removes all MatrixKeyFrames from the collection.
/// </summary>
public void Clear()
{
WritePreamble();
if (_keyFrames.Count > 0)
{
for (int i = 0; i < _keyFrames.Count; i++)
{
OnFreezablePropertyChanged(_keyFrames[i], null);
}
_keyFrames.Clear();
WritePostscript();
}
}
/// <summary>
/// Returns true of the collection contains the given MatrixKeyFrame.
/// </summary>
bool IList.Contains(object keyFrame)
{
return Contains((MatrixKeyFrame)keyFrame);
}
/// <summary>
/// Returns true of the collection contains the given MatrixKeyFrame.
/// </summary>
public bool Contains(MatrixKeyFrame keyFrame)
{
ReadPreamble();
return _keyFrames.Contains(keyFrame);
}
/// <summary>
/// Returns the index of a given MatrixKeyFrame in the collection.
/// </summary>
int IList.IndexOf(object keyFrame)
{
return IndexOf((MatrixKeyFrame)keyFrame);
}
/// <summary>
/// Returns the index of a given MatrixKeyFrame in the collection.
/// </summary>
public int IndexOf(MatrixKeyFrame keyFrame)
{
ReadPreamble();
return _keyFrames.IndexOf(keyFrame);
}
/// <summary>
/// Inserts a MatrixKeyFrame into a specific location in the collection.
/// </summary>
void IList.Insert(int index, object keyFrame)
{
Insert(index, (MatrixKeyFrame)keyFrame);
}
/// <summary>
/// Inserts a MatrixKeyFrame into a specific location in the collection.
/// </summary>
public void Insert(int index, MatrixKeyFrame keyFrame)
{
if (keyFrame == null)
{
throw new ArgumentNullException("keyFrame");
}
WritePreamble();
OnFreezablePropertyChanged(null, keyFrame);
_keyFrames.Insert(index, keyFrame);
WritePostscript();
}
/// <summary>
/// Returns true if the collection is frozen.
/// </summary>
public bool IsFixedSize
{
get
{
ReadPreamble();
return IsFrozen;
}
}
/// <summary>
/// Returns true if the collection is frozen.
/// </summary>
public bool IsReadOnly
{
get
{
ReadPreamble();
return IsFrozen;
}
}
/// <summary>
/// Removes a MatrixKeyFrame from the collection.
/// </summary>
void IList.Remove(object keyFrame)
{
Remove((MatrixKeyFrame)keyFrame);
}
/// <summary>
/// Removes a MatrixKeyFrame from the collection.
/// </summary>
public void Remove(MatrixKeyFrame keyFrame)
{
WritePreamble();
if (_keyFrames.Contains(keyFrame))
{
OnFreezablePropertyChanged(keyFrame, null);
_keyFrames.Remove(keyFrame);
WritePostscript();
}
}
/// <summary>
/// Removes the MatrixKeyFrame at the specified index from the collection.
/// </summary>
public void RemoveAt(int index)
{
WritePreamble();
OnFreezablePropertyChanged(_keyFrames[index], null);
_keyFrames.RemoveAt(index);
WritePostscript();
}
/// <summary>
/// Gets or sets the MatrixKeyFrame at a given index.
/// </summary>
object IList.this[int index]
{
get
{
return this[index];
}
set
{
this[index] = (MatrixKeyFrame)value;
}
}
/// <summary>
/// Gets or sets the MatrixKeyFrame at a given index.
/// </summary>
public MatrixKeyFrame this[int index]
{
get
{
ReadPreamble();
return _keyFrames[index];
}
set
{
if (value == null)
{
throw new ArgumentNullException(String.Format(CultureInfo.InvariantCulture, "MatrixKeyFrameCollection[{0}]", index));
}
WritePreamble();
if (value != _keyFrames[index])
{
OnFreezablePropertyChanged(_keyFrames[index], value);
_keyFrames[index] = value;
Debug.Assert(_keyFrames[index] != null);
WritePostscript();
}
}
}
#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.Collections.Generic;
using System.Collections;
using System.Linq.Expressions;
using Xunit;
namespace System.Linq.Tests
{
public class EnumerableQueryTests
{
[Fact]
public void NullExpressionAllowed()
{
IQueryable<int> query = new EnumerableQuery<int>((Expression)null);
Assert.Null(query.Expression);
Assert.Throws<ArgumentNullException>(() => query.GetEnumerator());
}
[Fact]
public void NullEnumerableConstantNullExpression()
{
IQueryable<int> query = new EnumerableQuery<int>((IEnumerable<int>)null);
var exp = (ConstantExpression)query.Expression;
Assert.Same(query, exp.Value);
Assert.Throws<InvalidOperationException>(() => query.GetEnumerator());
}
[Fact]
public void InappropriateExpressionType()
{
IQueryable<int> query = new EnumerableQuery<int>(Expression.Constant(Math.PI));
Assert.NotNull(query.Expression);
Assert.Throws<ArgumentException>(() => query.GetEnumerator());
}
[Fact]
public void WrapsEnumerableInExpression()
{
int[] source = { 1, 2, 3 };
IQueryable<int> query = (source).AsQueryable();
var exp = (ConstantExpression)query.Expression;
Assert.Equal(source, (IEnumerable<int>)exp.Value);
}
[Fact]
public void IsOwnProvider()
{
IQueryable<int> query = Enumerable.Empty<int>().AsQueryable();
Assert.Same(query, query.Provider);
}
[Fact]
public void FromExpressionReturnsSameExpression()
{
ConstantExpression exp = Expression.Constant(new[] { 1, 2, 3 });
IQueryable<int> query = new EnumerableQuery<int>(exp);
Assert.Same(exp, query.Expression);
}
// Guarantees to return the same enumerator every time from the same instance,
// but not from other instances. As such indicates constancy of enumerable wrapped
// by EnumerableQuery
private class ConstantEnumeratorEmptyEnumerable<T> : IEnumerable<T>, IEnumerator<T>
{
public IEnumerator<T> GetEnumerator()
{
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
public bool MoveNext()
{
return false;
}
public T Current
{
get { return default(T); }
}
object IEnumerator.Current
{
get { return default(T); }
}
public void Reset()
{
}
public void Dispose()
{
}
}
[Fact]
public void FromEnumerableReturnsSameEnumerable()
{
var testEnumerable = new ConstantEnumeratorEmptyEnumerable<int>();
IQueryable<int> query = testEnumerable.AsQueryable();
Assert.Same(testEnumerable.GetEnumerator(), query.GetEnumerator());
}
[Fact]
public void ElementType()
{
Assert.Equal(typeof(Version), Enumerable.Empty<Version>().AsQueryable().ElementType);
}
[Fact]
public void CreateQuery()
{
var exp = Expression.Constant(Enumerable.Range(3, 4).AsQueryable());
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
IQueryable<int> query = provider.CreateQuery<int>(exp);
Assert.Equal(Enumerable.Range(3, 4), query.AsEnumerable());
}
[Fact]
public void CreateQueryNonGeneric()
{
var exp = Expression.Constant(Enumerable.Range(3, 4).AsQueryable());
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
IQueryable query = provider.CreateQuery(exp);
Assert.Equal(Enumerable.Range(3, 4), query.Cast<int>());
}
[Fact]
public void CreateQueryNull()
{
IQueryProvider provider = Enumerable.Empty<int>().AsQueryable().Provider;
Assert.Throws<ArgumentNullException>("expression", () => provider.CreateQuery<int>(null));
}
[Fact]
public void CreateQueryNullNonGeneric()
{
IQueryProvider provider = Enumerable.Empty<int>().AsQueryable().Provider;
Assert.Throws<ArgumentNullException>("expression", () => provider.CreateQuery(null));
}
[Fact]
public void CreateQueryInvalidType()
{
var exp = Expression.Constant(Math.PI);
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
Assert.Throws<ArgumentException>(() => provider.CreateQuery<int>(exp));
}
[Fact]
public void CreateQueryInvalidTypeNonGeneric()
{
var exp = Expression.Constant(Math.PI);
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
Assert.Throws<ArgumentException>(() => provider.CreateQuery(exp));
}
[Fact]
public void Execute()
{
var exp = Expression.Constant(Math.PI);
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
Assert.Equal(Math.PI, provider.Execute<double>(exp));
}
[Fact]
public void ExecuteAssignable()
{
var exp = Expression.Constant(new int[0]);
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
Assert.Empty(provider.Execute<IEnumerable<int>>(exp));
}
[Fact]
public void ExecuteNonGeneric()
{
var exp = Expression.Constant(Math.PI);
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
Assert.Equal(Math.PI, provider.Execute(exp));
}
[Fact]
public void ExecuteNull()
{
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
Assert.Throws<ArgumentNullException>("expression", () => provider.Execute<int>(null));
}
[Fact]
public void ExecuteNullNonGeneric()
{
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
Assert.Throws<ArgumentNullException>("expression", () => provider.Execute(null));
}
[Fact]
public void ExecuteNotAssignable()
{
var exp = Expression.Constant(Math.PI);
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
Assert.Throws<ArgumentException>(() => provider.Execute<IEnumerable<int>>(exp));
}
[Fact]
public void ToStringFromEnumerable()
{
Assert.Equal(new int[0].ToString(), new int[0].AsQueryable().ToString());
}
[Fact]
public void ToStringFromConstantExpression()
{
var exp = Expression.Constant(new int[0]);
Assert.Equal(exp.ToString(), new EnumerableQuery<int>(exp).ToString());
}
[Fact]
public void ToStringNotConstantExpression()
{
var exp = Expression.Constant(new int[0]);
var block = Expression.Block(Expression.Empty(), exp);
Assert.Equal(block.ToString(), new EnumerableQuery<int>(block).ToString());
}
[Fact]
public void NullEnumerable()
{
Assert.Equal("null", new EnumerableQuery<int>(default(int[])).ToString());
}
}
}
| |
// <copyright file="RemoteWebElement.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using OpenQA.Selenium.Interactions.Internal;
using OpenQA.Selenium.Internal;
using System.Text;
namespace OpenQA.Selenium.Remote
{
/// <summary>
/// RemoteWebElement allows you to have access to specific items that are found on the page
/// </summary>
/// <seealso cref="IWebElement"/>
/// <seealso cref="ILocatable"/>
public class RemoteWebElement : IWebElement, IFindsByLinkText, IFindsById, IFindsByName, IFindsByTagName, IFindsByClassName, IFindsByXPath, IFindsByPartialLinkText, IFindsByCssSelector, IFindsElement, IWrapsDriver, ILocatable, ITakesScreenshot, IWebElementReference
{
/// <summary>
/// The property name that represents a web element in the wire protocol.
/// </summary>
public const string ElementReferencePropertyName = "element-6066-11e4-a52e-4f735466cecf";
/// <summary>
/// The property name that represents a web element in the legacy dialect of the wire protocol.
/// </summary>
public const string LegacyElementReferencePropertyName = "ELEMENT";
private RemoteWebDriver driver;
private string elementId;
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebElement"/> class.
/// </summary>
/// <param name="parentDriver">The <see cref="RemoteWebDriver"/> instance hosting this element.</param>
/// <param name="id">The ID assigned to the element.</param>
public RemoteWebElement(RemoteWebDriver parentDriver, string id)
{
this.driver = parentDriver;
this.elementId = id;
}
/// <summary>
/// Gets the <see cref="IWebDriver"/> used to find this element.
/// </summary>
public IWebDriver WrappedDriver
{
get { return this.driver; }
}
/// <summary>
/// Gets the tag name of this element.
/// </summary>
/// <remarks>
/// The <see cref="TagName"/> property returns the tag name of the
/// element, not the value of the name attribute. For example, it will return
/// "input" for an element specified by the HTML markup <input name="foo" />.
/// </remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual string TagName
{
get
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
Response commandResponse = this.Execute(DriverCommand.GetElementTagName, parameters);
return commandResponse.Value.ToString();
}
}
/// <summary>
/// Gets the innerText of this element, without any leading or trailing whitespace,
/// and with other whitespace collapsed.
/// </summary>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual string Text
{
get
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
Response commandResponse = this.Execute(DriverCommand.GetElementText, parameters);
return commandResponse.Value.ToString();
}
}
/// <summary>
/// Gets a value indicating whether or not this element is enabled.
/// </summary>
/// <remarks>The <see cref="Enabled"/> property will generally
/// return <see langword="true"/> for everything except explicitly disabled input elements.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual bool Enabled
{
get
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
Response commandResponse = this.Execute(DriverCommand.IsElementEnabled, parameters);
return (bool)commandResponse.Value;
}
}
/// <summary>
/// Gets a value indicating whether or not this element is selected.
/// </summary>
/// <remarks>This operation only applies to input elements such as checkboxes,
/// options in a select element and radio buttons.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual bool Selected
{
get
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
Response commandResponse = this.Execute(DriverCommand.IsElementSelected, parameters);
return (bool)commandResponse.Value;
}
}
/// <summary>
/// Gets a <see cref="Point"/> object containing the coordinates of the upper-left corner
/// of this element relative to the upper-left corner of the page.
/// </summary>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual Point Location
{
get
{
string getLocationCommand = DriverCommand.GetElementRect;
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
Response commandResponse = this.Execute(getLocationCommand, parameters);
Dictionary<string, object> rawPoint = (Dictionary<string, object>)commandResponse.Value;
int x = Convert.ToInt32(rawPoint["x"], CultureInfo.InvariantCulture);
int y = Convert.ToInt32(rawPoint["y"], CultureInfo.InvariantCulture);
return new Point(x, y);
}
}
/// <summary>
/// Gets a <see cref="Size"/> object containing the height and width of this element.
/// </summary>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual Size Size
{
get
{
string getSizeCommand = DriverCommand.GetElementRect;
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
Response commandResponse = this.Execute(getSizeCommand, parameters);
Dictionary<string, object> rawSize = (Dictionary<string, object>)commandResponse.Value;
int width = Convert.ToInt32(rawSize["width"], CultureInfo.InvariantCulture);
int height = Convert.ToInt32(rawSize["height"], CultureInfo.InvariantCulture);
return new Size(width, height);
}
}
/// <summary>
/// Gets a value indicating whether or not this element is displayed.
/// </summary>
/// <remarks>The <see cref="Displayed"/> property avoids the problem
/// of having to parse an element's "style" attribute to determine
/// visibility of an element.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual bool Displayed
{
get
{
Response commandResponse = null;
Dictionary<string, object> parameters = new Dictionary<string, object>();
string atom = GetAtom("is-displayed.js");
parameters.Add("script", atom);
parameters.Add("args", new object[] { this.ToElementReference().ToDictionary() });
commandResponse = this.Execute(DriverCommand.ExecuteScript, parameters);
return (bool)commandResponse.Value;
}
}
/// <summary>
/// Gets the point where the element would be when scrolled into view.
/// </summary>
public virtual Point LocationOnScreenOnceScrolledIntoView
{
get
{
Dictionary<string, object> rawLocation;
object scriptResponse = this.driver.ExecuteScript("var rect = arguments[0].getBoundingClientRect(); return {'x': rect.left, 'y': rect.top};", this);
rawLocation = scriptResponse as Dictionary<string, object>;
int x = Convert.ToInt32(rawLocation["x"], CultureInfo.InvariantCulture);
int y = Convert.ToInt32(rawLocation["y"], CultureInfo.InvariantCulture);
return new Point(x, y);
}
}
/// <summary>
/// Gets the computed accessible label of this element.
/// </summary>
public virtual string ComputedAccessibleLabel
{
get
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
Response commandResponse = this.Execute(DriverCommand.GetComputedAccessibleLabel, parameters);
return commandResponse.Value.ToString();
}
}
/// <summary>
/// Gets the computed ARIA role for this element.
/// </summary>
public virtual string ComputedAccessibleRole
{
get
{
// TODO: Returning this as a string is incorrect. The W3C WebDriver Specification
// needs to be updated to more throughly document the structure of what is returned
// by this command. Once that is done, a type-safe class will be created, and will
// be returned by this property.
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
Response commandResponse = this.Execute(DriverCommand.GetComputedAccessibleRole, parameters);
return commandResponse.Value.ToString();
}
}
/// <summary>
/// Gets the coordinates identifying the location of this element using
/// various frames of reference.
/// </summary>
public virtual ICoordinates Coordinates
{
get { return new RemoteCoordinates(this); }
}
/// <summary>
/// Gets the internal ID of the element.
/// </summary>
string IWebElementReference.ElementReferenceId
{
get { return this.elementId; }
}
/// <summary>
/// Gets the ID of the element
/// </summary>
/// <remarks>This property is internal to the WebDriver instance, and is
/// not intended to be used in your code. The element's ID has no meaning
/// outside of internal WebDriver usage, so it would be improper to scope
/// it as public. However, both subclasses of <see cref="RemoteWebElement"/>
/// and the parent driver hosting the element have a need to access the
/// internal element ID. Therefore, we have two properties returning the
/// same value, one scoped as internal, the other as protected.</remarks>
protected string Id
{
get { return this.elementId; }
}
/// <summary>
/// Clears the content of this element.
/// </summary>
/// <remarks>If this element is a text entry element, the <see cref="Clear"/>
/// method will clear the value. It has no effect on other elements. Text entry elements
/// are defined as elements with INPUT or TEXTAREA tags.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual void Clear()
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
this.Execute(DriverCommand.ClearElement, parameters);
}
/// <summary>
/// Simulates typing text into the element.
/// </summary>
/// <param name="text">The text to type into the element.</param>
/// <remarks>The text to be typed may include special characters like arrow keys,
/// backspaces, function keys, and so on. Valid special keys are defined in
/// <see cref="Keys"/>.</remarks>
/// <seealso cref="Keys"/>
/// <exception cref="InvalidElementStateException">Thrown when the target element is not enabled.</exception>
/// <exception cref="ElementNotVisibleException">Thrown when the target element is not visible.</exception>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual void SendKeys(string text)
{
if (text == null)
{
throw new ArgumentNullException("text", "text cannot be null");
}
var fileNames = text.Split('\n');
if (fileNames.All(this.driver.FileDetector.IsFile))
{
var uploadResults = new List<string>();
foreach (var fileName in fileNames)
{
uploadResults.Add(this.UploadFile(fileName));
}
text = string.Join("\n", uploadResults);
}
// N.B. The Java remote server expects a CharSequence as the value input to
// SendKeys. In JSON, these are serialized as an array of strings, with a
// single character to each element of the array. Thus, we must use ToCharArray()
// to get the same effect.
// TODO: Remove either "keysToSend" or "value" property, whichever is not the
// appropriate one for spec compliance.
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
parameters.Add("text", text);
parameters.Add("value", text.ToCharArray());
this.Execute(DriverCommand.SendKeysToElement, parameters);
}
/// <summary>
/// Submits this element to the web server.
/// </summary>
/// <remarks>If this current element is a form, or an element within a form,
/// then this will be submitted to the web server. If this causes the current
/// page to change, then this method will attempt to block until the new page
/// is loaded.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual void Submit()
{
string elementType = this.GetAttribute("type");
if (elementType != null && elementType == "submit")
{
this.Click();
}
else
{
IWebElement form = this.FindElement(By.XPath("./ancestor-or-self::form"));
this.driver.ExecuteScript(
"var e = arguments[0].ownerDocument.createEvent('Event');" +
"e.initEvent('submit', true, true);" +
"if (arguments[0].dispatchEvent(e)) { arguments[0].submit(); }", form);
}
}
/// <summary>
/// Clicks this element.
/// </summary>
/// <remarks>
/// Click this element. If the click causes a new page to load, the <see cref="Click"/>
/// method will attempt to block until the page has loaded. After calling the
/// <see cref="Click"/> method, you should discard all references to this
/// element unless you know that the element and the page will still be present.
/// Otherwise, any further operations performed on this element will have an undefined
/// behavior.
/// </remarks>
/// <exception cref="InvalidElementStateException">Thrown when the target element is not enabled.</exception>
/// <exception cref="ElementNotVisibleException">Thrown when the target element is not visible.</exception>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual void Click()
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
this.Execute(DriverCommand.ClickElement, parameters);
}
/// <summary>
/// Gets the value of the specified attribute or property for this element.
/// </summary>
/// <param name="attributeName">The name of the attribute or property.</param>
/// <returns>The attribute's or property's current value. Returns a <see langword="null"/>
/// if the value is not set.</returns>
/// <remarks>The <see cref="GetAttribute"/> method will return the current value
/// of the attribute or property, even if the value has been modified after the page
/// has been loaded. Note that the value of the following attributes will be returned
/// even if there is no explicit attribute on the element:
/// <list type="table">
/// <listheader>
/// <term>Attribute name</term>
/// <term>Value returned if not explicitly specified</term>
/// <term>Valid element types</term>
/// </listheader>
/// <item>
/// <description>checked</description>
/// <description>checked</description>
/// <description>Check Box</description>
/// </item>
/// <item>
/// <description>selected</description>
/// <description>selected</description>
/// <description>Options in Select elements</description>
/// </item>
/// <item>
/// <description>disabled</description>
/// <description>disabled</description>
/// <description>Input and other UI elements</description>
/// </item>
/// </list>
/// The method looks both in declared attributes in the HTML markup of the page, and
/// in the properties of the elemnt as found when accessing the element's properties
/// via JavaScript.
/// </remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual string GetAttribute(string attributeName)
{
Response commandResponse = null;
string attributeValue = string.Empty;
Dictionary<string, object> parameters = new Dictionary<string, object>();
string atom = GetAtom("get-attribute.js");
parameters.Add("script", atom);
parameters.Add("args", new object[] { this.ToElementReference().ToDictionary(), attributeName });
commandResponse = this.Execute(DriverCommand.ExecuteScript, parameters);
if (commandResponse.Value == null)
{
attributeValue = null;
}
else
{
attributeValue = commandResponse.Value.ToString();
// Normalize string values of boolean results as lowercase.
if (commandResponse.Value is bool)
{
attributeValue = attributeValue.ToLowerInvariant();
}
}
return attributeValue;
}
/// <summary>
/// Gets the value of a declared HTML attribute of this element.
/// </summary>
/// <param name="attributeName">The name of the HTML attribugte to get the value of.</param>
/// <returns>The HTML attribute's current value. Returns a <see langword="null"/> if the
/// value is not set or the declared attribute does not exist.</returns>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
/// <remarks>
/// As opposed to the <see cref="GetAttribute(string)"/> method, this method
/// only returns attriibutes decalred in the element's HTML markup. To access the value
/// of an IDL property of the element, either use the <see cref="GetAttribute(string)"/>
/// method or the <see cref="GetDomProperty(string)"/> method.
/// </remarks>
public virtual string GetDomAttribute(string attributeName)
{
string attributeValue = string.Empty;
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
parameters.Add("name", attributeName);
Response commandResponse = this.Execute(DriverCommand.GetElementAttribute, parameters);
if (commandResponse.Value == null)
{
attributeValue = null;
}
else
{
attributeValue = commandResponse.Value.ToString();
}
return attributeValue;
}
/// <summary>
/// Gets the value of a JavaScript property of this element.
/// </summary>
/// <param name="propertyName">The name of the JavaScript property to get the value of.</param>
/// <returns>The JavaScript property's current value. Returns a <see langword="null"/> if the
/// value is not set or the property does not exist.</returns>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
[Obsolete("Use the GetDomProperty method instead.")]
public virtual string GetProperty(string propertyName)
{
return this.GetDomProperty(propertyName);
}
/// <summary>
/// Gets the value of a JavaScript property of this element.
/// </summary>
/// <param name="propertyName">The name of the JavaScript property to get the value of.</param>
/// <returns>The JavaScript property's current value. Returns a <see langword="null"/> if the
/// value is not set or the property does not exist.</returns>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual string GetDomProperty(string propertyName)
{
string propertyValue = string.Empty;
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
parameters.Add("name", propertyName);
Response commandResponse = this.Execute(DriverCommand.GetElementProperty, parameters);
if (commandResponse.Value == null)
{
propertyValue = null;
}
else
{
propertyValue = commandResponse.Value.ToString();
}
return propertyValue;
}
/// <summary>
/// Gets the value of a CSS property of this element.
/// </summary>
/// <param name="propertyName">The name of the CSS property to get the value of.</param>
/// <returns>The value of the specified CSS property.</returns>
/// <remarks>The value returned by the <see cref="GetCssValue"/>
/// method is likely to be unpredictable in a cross-browser environment.
/// Color values should be returned as hex strings. For example, a
/// "background-color" property set as "green" in the HTML source, will
/// return "#008000" for its value.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public virtual string GetCssValue(string propertyName)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
parameters.Add("name", propertyName);
Response commandResponse = this.Execute(DriverCommand.GetElementValueOfCssProperty, parameters);
return commandResponse.Value.ToString();
}
/// <summary>
/// Finds all <see cref="IWebElement">IWebElements</see> within the current context
/// using the given mechanism.
/// </summary>
/// <param name="by">The locating mechanism to use.</param>
/// <returns>A <see cref="ReadOnlyCollection{T}"/> of all <see cref="IWebElement">WebElements</see>
/// matching the current criteria, or an empty list if nothing matches.</returns>
public virtual ReadOnlyCollection<IWebElement> FindElements(By by)
{
if (by == null)
{
throw new ArgumentNullException("by", "by cannot be null");
}
return by.FindElements(this);
}
/// <summary>
/// Finds the first <see cref="IWebElement"/> using the given method.
/// </summary>
/// <param name="by">The locating mechanism to use.</param>
/// <returns>The first matching <see cref="IWebElement"/> on the current context.</returns>
/// <exception cref="NoSuchElementException">If no element matches the criteria.</exception>
public virtual IWebElement FindElement(By by)
{
if (by == null)
{
throw new ArgumentNullException("by", "by cannot be null");
}
return by.FindElement(this);
}
/// <summary>
/// Finds the first of elements that match the link text supplied
/// </summary>
/// <param name="linkText">Link text of element </param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementByLinkText("linktext")
/// </code>
/// </example>
public virtual IWebElement FindElementByLinkText(string linkText)
{
return this.FindElement("link text", linkText);
}
/// <summary>
/// Finds the first of elements that match the link text supplied
/// </summary>
/// <param name="linkText">Link text of element </param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByLinkText("linktext")
/// </code>
/// </example>
public virtual ReadOnlyCollection<IWebElement> FindElementsByLinkText(string linkText)
{
return this.FindElements("link text", linkText);
}
/// <summary>
/// Finds the first element in the page that matches the ID supplied
/// </summary>
/// <param name="id">ID of the element</param>
/// <returns>IWebElement object so that you can interact with that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementById("id")
/// </code>
/// </example>
public virtual IWebElement FindElementById(string id)
{
return this.FindElement("css selector", "#" + By.EscapeCssSelector(id));
}
/// <summary>
/// Finds the first element in the page that matches the ID supplied
/// </summary>
/// <param name="id">ID of the Element</param>
/// <returns>ReadOnlyCollection of Elements that match the object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsById("id")
/// </code>
/// </example>
public virtual ReadOnlyCollection<IWebElement> FindElementsById(string id)
{
return this.FindElements("css selector", "#" + By.EscapeCssSelector(id));
}
/// <summary>
/// Finds the first of elements that match the name supplied
/// </summary>
/// <param name="name">Name of the element</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// elem = driver.FindElementsByName("name")
/// </code>
/// </example>
public virtual IWebElement FindElementByName(string name)
{
return this.FindElement("css selector", "*[name=\"" + name + "\"]");
}
/// <summary>
/// Finds a list of elements that match the name supplied
/// </summary>
/// <param name="name">Name of element</param>
/// <returns>ReadOnlyCollect of IWebElement objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByName("name")
/// </code>
/// </example>
public virtual ReadOnlyCollection<IWebElement> FindElementsByName(string name)
{
return this.FindElements("css selector", "*[name=\"" + name + "\"]");
}
/// <summary>
/// Finds the first of elements that match the DOM Tag supplied
/// </summary>
/// <param name="tagName">tag name of the element</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByTagName("tag")
/// </code>
/// </example>
public virtual IWebElement FindElementByTagName(string tagName)
{
return this.FindElement("css selector", tagName);
}
/// <summary>
/// Finds a list of elements that match the DOM Tag supplied
/// </summary>
/// <param name="tagName">DOM Tag of the element on the page</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByTagName("tag")
/// </code>
/// </example>
public virtual ReadOnlyCollection<IWebElement> FindElementsByTagName(string tagName)
{
return this.FindElements("css selector", tagName);
}
/// <summary>
/// Finds the first element in the page that matches the CSS Class supplied
/// </summary>
/// <param name="className">CSS class name of the element on the page</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementByClassName("classname")
/// </code>
/// </example>
public virtual IWebElement FindElementByClassName(string className)
{
return this.FindElement("css selector", "." + By.EscapeCssSelector(className));
}
/// <summary>
/// Finds a list of elements that match the class name supplied
/// </summary>
/// <param name="className">CSS class name of the elements on the page</param>
/// <returns>ReadOnlyCollection of IWebElement object so that you can interact with those objects</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByClassName("classname")
/// </code>
/// </example>
public virtual ReadOnlyCollection<IWebElement> FindElementsByClassName(string className)
{
return this.FindElements("css selector", "." + By.EscapeCssSelector(className));
}
/// <summary>
/// Finds the first of elements that match the XPath supplied
/// </summary>
/// <param name="xpath">xpath to the element</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByXPath("//table/tbody/tr/td/a");
/// </code>
/// </example>
public virtual IWebElement FindElementByXPath(string xpath)
{
return this.FindElement("xpath", xpath);
}
/// <summary>
/// Finds a list of elements that match the XPath supplied
/// </summary>
/// <param name="xpath">xpath to element on the page</param>
/// <returns>ReadOnlyCollection of IWebElement objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByXpath("//tr/td/a")
/// </code>
/// </example>
public virtual ReadOnlyCollection<IWebElement> FindElementsByXPath(string xpath)
{
return this.FindElements("xpath", xpath);
}
/// <summary>
/// Finds the first of elements that match the part of the link text supplied
/// </summary>
/// <param name="partialLinkText">part of the link text</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByPartialLinkText("partOfLink")
/// </code>
/// </example>
public virtual IWebElement FindElementByPartialLinkText(string partialLinkText)
{
return this.FindElement("partial link text", partialLinkText);
}
/// <summary>
/// Finds a list of elements that match the link text supplied
/// </summary>
/// <param name="partialLinkText">part of the link text</param>
/// <returns>ReadOnlyCollection<![CDATA[<IWebElement>]]> objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByPartialLinkText("partOfTheLink")
/// </code>
/// </example>
public virtual ReadOnlyCollection<IWebElement> FindElementsByPartialLinkText(string partialLinkText)
{
return this.FindElements("partial link text", partialLinkText);
}
/// <summary>
/// Finds the first element matching the specified CSS selector.
/// </summary>
/// <param name="cssSelector">The id to match.</param>
/// <returns>The first <see cref="IWebElement"/> matching the criteria.</returns>
public virtual IWebElement FindElementByCssSelector(string cssSelector)
{
return this.FindElement("css selector", cssSelector);
}
/// <summary>
/// Finds all elements matching the specified CSS selector.
/// </summary>
/// <param name="cssSelector">The CSS selector to match.</param>
/// <returns>A <see cref="ReadOnlyCollection{T}"/> containing all
/// <see cref="IWebElement">IWebElements</see> matching the criteria.</returns>
public virtual ReadOnlyCollection<IWebElement> FindElementsByCssSelector(string cssSelector)
{
return this.FindElements("css selector", cssSelector);
}
/// <summary>
/// Finds a child element matching the given mechanism and value.
/// </summary>
/// <param name="mechanism">The mechanism by which to find the element.</param>
/// <param name="value">The value to use to search for the element.</param>
/// <returns>The first <see cref="IWebElement"/> matching the given criteria.</returns>
public virtual IWebElement FindElement(string mechanism, string value)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
parameters.Add("using", mechanism);
parameters.Add("value", value);
Response commandResponse = this.Execute(DriverCommand.FindChildElement, parameters);
return this.driver.GetElementFromResponse(commandResponse);
}
/// <summary>
/// Finds all child elements matching the given mechanism and value.
/// </summary>
/// <param name="mechanism">The mechanism by which to find the elements.</param>
/// <param name="value">The value to use to search for the elements.</param>
/// <returns>A collection of all of the <see cref="IWebElement">IWebElements</see> matching the given criteria.</returns>
public virtual ReadOnlyCollection<IWebElement> FindElements(string mechanism, string value)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
parameters.Add("using", mechanism);
parameters.Add("value", value);
Response commandResponse = this.Execute(DriverCommand.FindChildElements, parameters);
return this.driver.GetElementsFromResponse(commandResponse);
}
/// <summary>
/// Gets a <see cref="Screenshot"/> object representing the image of this element on the screen.
/// </summary>
/// <returns>A <see cref="Screenshot"/> object containing the image.</returns>
public virtual Screenshot GetScreenshot()
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
// Get the screenshot as base64.
Response screenshotResponse = this.Execute(DriverCommand.ElementScreenshot, parameters);
string base64 = screenshotResponse.Value.ToString();
// ... and convert it.
return new Screenshot(base64);
}
/// <summary>
/// Returns a string that represents the current <see cref="RemoteWebElement"/>.
/// </summary>
/// <returns>A string that represents the current <see cref="RemoteWebElement"/>.</returns>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "Element (id = {0})", this.elementId);
}
/// <summary>
/// Method to get the hash code of the element
/// </summary>
/// <returns>Integer of the hash code for the element</returns>
public override int GetHashCode()
{
return this.elementId.GetHashCode();
}
/// <summary>
/// Compares if two elements are equal
/// </summary>
/// <param name="obj">Object to compare against</param>
/// <returns>A boolean if it is equal or not</returns>
public override bool Equals(object obj)
{
IWebElement other = obj as IWebElement;
if (other == null)
{
return false;
}
IWrapsElement objAsWrapsElement = obj as IWrapsElement;
if (objAsWrapsElement != null)
{
other = objAsWrapsElement.WrappedElement;
}
RemoteWebElement otherAsElement = other as RemoteWebElement;
if (otherAsElement == null)
{
return false;
}
if (this.elementId == otherAsElement.Id)
{
// For drivers that implement ID equality, we can check for equal IDs
// here, and expect them to be equal. There is a potential danger here
// where two different elements are assigned the same ID.
return true;
}
return false;
}
/// <summary>
/// Converts an object into an object that represents an element for the wire protocol.
/// </summary>
/// <returns>A <see cref="Dictionary{TKey, TValue}"/> that represents an element in the wire protocol.</returns>
Dictionary<string, object> IWebElementReference.ToDictionary()
{
Dictionary<string, object> elementDictionary = new Dictionary<string, object>();
elementDictionary.Add(ElementReferencePropertyName, this.elementId);
return elementDictionary;
}
/// <summary>
/// Executes a command on this element using the specified parameters.
/// </summary>
/// <param name="commandToExecute">The <see cref="DriverCommand"/> to execute against this element.</param>
/// <param name="parameters">A <see cref="Dictionary{K, V}"/> containing names and values of the parameters for the command.</param>
/// <returns>The <see cref="Response"/> object containing the result of the command execution.</returns>
protected virtual Response Execute(string commandToExecute, Dictionary<string, object> parameters)
{
return this.driver.InternalExecute(commandToExecute, parameters);
}
private static string GetAtom(string atomResourceName)
{
string atom = string.Empty;
using (Stream atomStream = ResourceUtilities.GetResourceStream(atomResourceName, atomResourceName))
{
using (StreamReader atomReader = new StreamReader(atomStream))
{
atom = atomReader.ReadToEnd();
}
}
string wrappedAtom = string.Format(CultureInfo.InvariantCulture, "return ({0}).apply(null, arguments);", atom);
return wrappedAtom;
}
private string UploadFile(string localFile)
{
string base64zip = string.Empty;
try
{
using (MemoryStream fileUploadMemoryStream = new MemoryStream())
{
using (ZipArchive zipArchive = new ZipArchive(fileUploadMemoryStream, ZipArchiveMode.Create))
{
string fileName = Path.GetFileName(localFile);
zipArchive.CreateEntryFromFile(localFile, fileName);
}
base64zip = Convert.ToBase64String(fileUploadMemoryStream.ToArray());
}
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("file", base64zip);
Response response = this.Execute(DriverCommand.UploadFile, parameters);
return response.Value.ToString();
}
catch (IOException e)
{
throw new WebDriverException("Cannot upload " + localFile, e);
}
}
private IWebElementReference ToElementReference()
{
return this as IWebElementReference;
}
}
}
| |
using NUnit.Framework;
using Spart.Actions;
using Spart.Parsers;
using Spart.Parsers.Composite;
using Spart.Parsers.Primitives;
using Spart.Scanners;
namespace Palaso.Tests.Spart.Parsers.Composite
{
[TestFixture]
public class DifferenceParserTests
{
private CharParser _letterOrDigit;
private CharParser _letter;
private CharParser _symbol;
private DifferenceParser _LetterOrDigitButNotLetterDifferenceParser;
private bool _symbolParserSuccess;
private bool _letterParserSuccess;
private bool _letterOrDigitParserSuccess;
private bool _differenceParserSuccess;
[SetUp]
public void Setup() {
this._letterOrDigit = Prims.LetterOrDigit;
this._letterOrDigit.Act += OnLetterOrDigitParserSuccess;
this._letter = Prims.Letter;
this._letter.Act += OnLetterParserSuccess;
this._symbol = Prims.Symbol;
this._symbol.Act += OnSymbolParserSuccess;
this._LetterOrDigitButNotLetterDifferenceParser = new DifferenceParser(this._letterOrDigit, this._letter);
this._LetterOrDigitButNotLetterDifferenceParser.Act += OnDifferenceParserSuccess;
this._symbolParserSuccess = false;
this._letterParserSuccess = false;
this._letterOrDigitParserSuccess = false;
this._differenceParserSuccess = false;
}
private void OnSymbolParserSuccess(object sender, ActionEventArgs args)
{
this._symbolParserSuccess = true;
}
private void OnLetterParserSuccess(object sender, ActionEventArgs args)
{
this._letterParserSuccess = true;
}
void OnLetterOrDigitParserSuccess(object sender, ActionEventArgs args)
{
this._letterOrDigitParserSuccess = true;
}
private void OnDifferenceParserSuccess(object sender, ActionEventArgs args)
{
this._differenceParserSuccess = true;
}
[Test]
public void DifferenceParser()
{
DifferenceParser parser = new DifferenceParser(this._letterOrDigit, this._symbol);
Assert.AreEqual(this._letterOrDigit, parser.FirstParser);
Assert.AreEqual(this._symbol, parser.SecondParser);
}
[Test]
public void InputMatchesFirstParserDoesNotMatchSecondParser_Success()
{
IScanner digit = new StringScanner("1");
Assert.IsTrue(this._LetterOrDigitButNotLetterDifferenceParser.Parse(digit).Success);
}
[Test]
public void InputMatchesFirstParserAndSecondParser_SameLength_Fail()
{
IScanner letter = new StringScanner("abc");
Assert.IsFalse(this._LetterOrDigitButNotLetterDifferenceParser.Parse(letter).Success);
}
[Test]
public void InputMatchesFirstParserAndSecondParser_SecondParserLonger_Fail()
{
IScanner letter = new StringScanner("abc");
DifferenceParser parser = new DifferenceParser(this._letterOrDigit,
Ops.Sequence(this._letterOrDigit, this._letterOrDigit));
Assert.IsFalse(parser.Parse(letter).Success);
}
[Test]
public void InputMatchesFirstParserAndSecondParser_SecondParserShorter_Success()
{
IScanner letter = new StringScanner("abc");
DifferenceParser parser = new DifferenceParser(Ops.Sequence(this._letterOrDigit, this._letterOrDigit),
this._letterOrDigit);
Assert.IsTrue(parser.Parse(letter).Success);
}
[Test]
public void InputDoesNotMatchFirstParserButMatchesSecondParser_Fail()
{
IScanner symbol = new StringScanner("+");
DifferenceParser parser = new DifferenceParser(this._letterOrDigit, this._symbol);
parser.Act += OnDifferenceParserSuccess;
Assert.IsFalse(parser.Parse(symbol).Success);
}
[Test]
public void InputDoesNotMatchFirstParserAndDoesNotMatchSecondParser_Fail()
{
IScanner symbol = new StringScanner("+");
Assert.IsFalse(this._LetterOrDigitButNotLetterDifferenceParser.Parse(symbol).Success);
}
[Test]
public void InputMatchesFirstParserDoesNotMatchSecondParser_Actions_LetterOrDigitAndDiff()
{
IScanner digit = new StringScanner("1");
this._LetterOrDigitButNotLetterDifferenceParser.Parse(digit);
Assert.IsTrue(_differenceParserSuccess);
Assert.IsTrue(_letterOrDigitParserSuccess);
Assert.IsFalse(_letterParserSuccess);
}
[Test]
public void InputMatchesFirstParserAndSecondParser_Actions_None()
{
IScanner letter = new StringScanner("a");
this._LetterOrDigitButNotLetterDifferenceParser.Parse(letter);
Assert.IsFalse(_differenceParserSuccess);
Assert.IsFalse(_letterOrDigitParserSuccess); // should not be called since it is ultimately not accepted
Assert.IsFalse(_letterParserSuccess); // should not be called since the difference ultimately not accepted
}
[Test]
public void InputDoesNotMatchFirstParserButMatchesSecondParser_Actions_None()
{
IScanner symbol = new StringScanner("+");
DifferenceParser parser = new DifferenceParser(this._letterOrDigit, this._symbol);
parser.Act += OnDifferenceParserSuccess;
parser.Parse(symbol);
Assert.IsFalse(_differenceParserSuccess);
Assert.IsFalse(_letterOrDigitParserSuccess);
Assert.IsFalse(_symbolParserSuccess); // should never call since first parser doesn't match
}
[Test]
public void InputDoesNotMatchFirstParserAndDoesNotMatchSecondParser_Actions_None()
{
IScanner symbol = new StringScanner("+");
this._LetterOrDigitButNotLetterDifferenceParser.Parse(symbol);
Assert.IsFalse(_differenceParserSuccess);
Assert.IsFalse(_letterOrDigitParserSuccess);
Assert.IsFalse(_letterParserSuccess);
}
[Test]
public void InputMatchesFirstParserDoesNotMatchSecondParser_ScanPosition_ForwardByMatchLength()
{
IScanner digit = new StringScanner("1 hello");
ParserMatch match = this._LetterOrDigitButNotLetterDifferenceParser.Parse(digit);
Assert.AreEqual(1, match.Length);
Assert.AreEqual(1, digit.Offset);
}
[Test]
public void InputMatchesFirstParserAndSecondParser_ScanPosition_NoChange()
{
IScanner letter = new StringScanner("a hello");
this._LetterOrDigitButNotLetterDifferenceParser.Parse(letter);
Assert.AreEqual(0, letter.Offset);
}
[Test]
public void InputDoesNotMatchFirstParserButMatchesSecondParser_ScanPosition_NoChange()
{
IScanner symbol = new StringScanner("+hello");
DifferenceParser parser = new DifferenceParser(this._letterOrDigit, this._symbol);
parser.Parse(symbol);
Assert.AreEqual(0, symbol.Offset);
}
[Test]
public void InputDoesNotMatchFirstParserAndDoesNotMatchSecondParser_ScanPosition_NoChange()
{
IScanner symbol = new StringScanner("+hello");
this._LetterOrDigitButNotLetterDifferenceParser.Parse(symbol);
Assert.AreEqual(0, symbol.Offset);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography;
using System.Text;
using Foundation.ExtensionMethods;
namespace Foundation.Services.Security
{
/// <summary>
/// Hashes
/// </summary>
public class Hasher
{
/// <summary>
/// Default constructor, which defaults to using the MD5 algorithm
/// </summary>
public Hasher()
{
Provider = HashProvider.MD5;
}
/// <summary>
/// Creates a Hasher, configuring it to use the specified hashing provider
/// </summary>
/// <param name="provider">Hash algorithm to use by default</param>
public Hasher(HashProvider provider)
{
Provider = provider;
}
#region Public Static Methods
/// <summary>
/// Creates and returns the HashAlgorithm object for the specified provider
/// </summary>
/// <param name="provider">The desired hash algorithm provider</param>
/// <returns>The required hashing object</returns>
public static HashAlgorithm GetHashAlgorithm(HashProvider provider)
{
switch( provider )
{
case HashProvider.MD5:
return System.Security.Cryptography.MD5.Create();
case HashProvider.SHA1:
return SHA1.Create();
case HashProvider.SHA256:
return SHA256.Create();
case HashProvider.SHA384:
return SHA384.Create();
case HashProvider.SHA512:
return SHA512.Create();
}
throw new ArgumentException("Unsupported HashProvider: {0}! ".FormatCurrentCulture(provider) +
"If you add a new algorithm to the HashProvider, make sure you add it to the " +
"switch statement in the Hasher.GetHashAlgorithm method!", "provider");
}
#endregion
#region Hash Methods
/// <summary>
/// Hashes an array of bytes
/// </summary>
/// <param name="data">Bytes to hash</param>
/// <returns>Computed hash</returns>
public virtual byte[] HashBytes(byte[] data)
{
// Get the hasher
var hasher = GetHashAlgorithm(Provider);
// Return the computed hash
return hasher.ComputeHash(data);
}
/// <summary>
/// Hashes a string and returns the result as a hex string
/// </summary>
/// <param name="data">The string to hash</param>
/// <returns>Hashed string made up of hex characters</returns>
public virtual string HashString(string data)
{
var bytes = Encoding.ASCII.GetBytes(data); // Convert string to bytes
bytes = HashBytes(bytes); // Hash the bytes
return BytesToHexString(bytes); // Return as a hex string
}
#endregion
#region Comparison Methods
/// <summary>
/// Hashes a normal string and compares with another hash to see if they are equal
/// </summary>
/// <param name="value">Normal string to compare</param>
/// <param name="expectedHashValue">Expected hash result</param>
/// <returns>True if the string hashes to the expected hash result, otherwise false</returns>
public virtual bool Compare(string value, string expectedHashValue)
{
return HashString(value).Equals(expectedHashValue);
}
/// <summary>
/// Hashes a normal byte array and compares with another hash to see if they are equal
/// </summary>
/// <param name="value">Normal byte array to compare</param>
/// <param name="expectedHashValue">Expected hash result</param>
/// <returns>True if the array hashes to the expected hash result, otherwise false</returns>
public virtual bool Compare(byte[] value, byte[] expectedHashValue)
{
var compareHash = HashBytes(value);
return Equals(compareHash, expectedHashValue);
}
#endregion
#region Hex Conversion Methods
/// <summary>
/// Converts an array of bytes to a hex string
/// </summary>
/// <param name="data">Data to convert to string</param>
/// <param name="expectedLength">Expected length of the string for optimization</param>
/// <returns>Hex string</returns>
/// <exception cref="ArgumentNullException">when <paramref name="data"/> is null</exception>
public static string BytesToHexString(IEnumerable<byte> data, int expectedLength)
{
if (data == null) throw new ArgumentNullException("data");
var sb = new StringBuilder(expectedLength);
// Convert each byte to a 2-character hex string
foreach( var b in data ) sb.AppendFormat("{0:x2}", b);
return sb.ToString();
}
/// <summary>
/// Converts an array of bytes to a hex string
/// </summary>
/// <param name="data">Data to convert to string</param>
/// <returns>Hex string</returns>
public static string BytesToHexString(IEnumerable<byte> data)
{
// Convert the string, allocating the string length to 128 by default
return BytesToHexString(data, 128);
}
#endregion
/// <summary>
/// Computes the 32-character hex string MD5 Hash of the passed string
/// </summary>
/// <param name="toHash">The string to hash</param>
/// <returns>32-character hex MD5 hash</returns>
public static string MD5Hash(string toHash)
{
var hasher = new Hasher(HashProvider.MD5);
return hasher.HashString(toHash);
}
/// <summary>
/// Compares a string to a hash to see if they match
/// </summary>
/// <param name="compare">String to hash and compare</param>
/// <param name="hash">Expected hash result</param>
/// <returns>true if they match, otherwise false</returns>
public static bool MD5Compare(string compare, string hash)
{
var hasher = new Hasher(HashProvider.MD5);
return hasher.Compare(compare, hash);
}
/// <summary>
/// Computes the 32-character hex string SHA256 Hash of the passed string
/// </summary>
/// <param name="toHash">The string to hash</param>
/// <returns>32-character hex MD5 hash</returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sha")]
public static string Sha256Hash(string toHash)
{
var hasher = new Hasher(HashProvider.SHA256);
return hasher.HashString(toHash);
}
/// <summary>
/// Compares a string to a hash to see if they match
/// </summary>
/// <param name="compare">String to hash and compare</param>
/// <param name="hash">Expected hash result</param>
/// <returns>true if they match, otherwise false</returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sha")]
public static bool Sha256Compare(string compare, string hash)
{
var hasher = new Hasher(HashProvider.SHA256);
return hasher.Compare(compare, hash);
}
/// <summary>
/// The Hash algorithm to use
/// </summary>
public HashProvider Provider { get; set; }
}
}
| |
using System;
namespace QRCode
{
public static class Capacity
{
public class Unit {
public int Version; // number between 1 and 10
public string ErrorCorrectionLevel; // One of: L, M, H, or Q
public string DataMode; // One of: Numeric, AlphaNumeric, or byte;
public int NumBytes;
}
public static int GetBytes(int version, string errorCorrectionLevel, string dataMode)
{
// todo add validation for inputs
foreach (Unit u in Units)
if (u.Version == version && u.ErrorCorrectionLevel == errorCorrectionLevel && u.DataMode == dataMode)
return u.NumBytes;
return -1; // return negative if not found
}
public static int GetVersion(string errCorrLevel, string dataMode, int minBytes)
{
for (int version = 1; version <= 10; version++) {
int numBytes = GetBytes(version, errCorrLevel, dataMode);
if (numBytes >= minBytes) {
return version;
}
}
return -1; // return negative if not found
}
public static Unit[] Units = new Unit[] {
// Version 1
new Unit {Version=1, ErrorCorrectionLevel="L", DataMode="Numeric", NumBytes=41},
new Unit {Version=1, ErrorCorrectionLevel="M", DataMode="Numeric", NumBytes=34},
new Unit {Version=1, ErrorCorrectionLevel="Q", DataMode="Numeric", NumBytes=27},
new Unit {Version=1, ErrorCorrectionLevel="H", DataMode="Numeric", NumBytes=17},
new Unit {Version=1, ErrorCorrectionLevel="L", DataMode="AlphaNumeric", NumBytes=25},
new Unit {Version=1, ErrorCorrectionLevel="M", DataMode="AlphaNumeric", NumBytes=20},
new Unit {Version=1, ErrorCorrectionLevel="Q", DataMode="AlphaNumeric", NumBytes=16},
new Unit {Version=1, ErrorCorrectionLevel="H", DataMode="AlphaNumeric", NumBytes=10},
new Unit {Version=1, ErrorCorrectionLevel="L", DataMode="byte", NumBytes=17},
new Unit {Version=1, ErrorCorrectionLevel="M", DataMode="byte", NumBytes=14},
new Unit {Version=1, ErrorCorrectionLevel="Q", DataMode="byte", NumBytes=11},
new Unit {Version=1, ErrorCorrectionLevel="H", DataMode="byte", NumBytes=7},
new Unit {Version=2, ErrorCorrectionLevel="L", DataMode="Kanji", NumBytes=10},
new Unit {Version=2, ErrorCorrectionLevel="M", DataMode="Kanji", NumBytes=8},
new Unit {Version=2, ErrorCorrectionLevel="Q", DataMode="Kanji", NumBytes=7},
new Unit {Version=2, ErrorCorrectionLevel="H", DataMode="Kanji", NumBytes=4},
// Version 2
new Unit {Version=2, ErrorCorrectionLevel="L", DataMode="Numeric", NumBytes=77},
new Unit {Version=2, ErrorCorrectionLevel="M", DataMode="Numeric", NumBytes=63},
new Unit {Version=2, ErrorCorrectionLevel="Q", DataMode="Numeric", NumBytes=48},
new Unit {Version=2, ErrorCorrectionLevel="H", DataMode="Numeric", NumBytes=34},
new Unit {Version=2, ErrorCorrectionLevel="L", DataMode="AlphaNumeric", NumBytes=47},
new Unit {Version=2, ErrorCorrectionLevel="M", DataMode="AlphaNumeric", NumBytes=38},
new Unit {Version=2, ErrorCorrectionLevel="Q", DataMode="AlphaNumeric", NumBytes=29},
new Unit {Version=2, ErrorCorrectionLevel="H", DataMode="AlphaNumeric", NumBytes=20},
new Unit {Version=2, ErrorCorrectionLevel="L", DataMode="byte", NumBytes=32},
new Unit {Version=2, ErrorCorrectionLevel="M", DataMode="byte", NumBytes=26},
new Unit {Version=2, ErrorCorrectionLevel="Q", DataMode="byte", NumBytes=20},
new Unit {Version=2, ErrorCorrectionLevel="H", DataMode="byte", NumBytes=14},
new Unit {Version=2, ErrorCorrectionLevel="L", DataMode="Kanji", NumBytes=20},
new Unit {Version=2, ErrorCorrectionLevel="M", DataMode="Kanji", NumBytes=16},
new Unit {Version=2, ErrorCorrectionLevel="Q", DataMode="Kanji", NumBytes=12},
new Unit {Version=2, ErrorCorrectionLevel="H", DataMode="Kanji", NumBytes=8},
// Version 3
new Unit {Version=3, ErrorCorrectionLevel="L", DataMode="Numeric", NumBytes=127},
new Unit {Version=3, ErrorCorrectionLevel="M", DataMode="Numeric", NumBytes=101},
new Unit {Version=3, ErrorCorrectionLevel="Q", DataMode="Numeric", NumBytes=77},
new Unit {Version=3, ErrorCorrectionLevel="H", DataMode="Numeric", NumBytes=58},
new Unit {Version=3, ErrorCorrectionLevel="L", DataMode="AlphaNumeric", NumBytes=77},
new Unit {Version=3, ErrorCorrectionLevel="M", DataMode="AlphaNumeric", NumBytes=61},
new Unit {Version=3, ErrorCorrectionLevel="Q", DataMode="AlphaNumeric", NumBytes=47},
new Unit {Version=3, ErrorCorrectionLevel="H", DataMode="AlphaNumeric", NumBytes=35},
new Unit {Version=3, ErrorCorrectionLevel="L", DataMode="byte", NumBytes=53},
new Unit {Version=3, ErrorCorrectionLevel="M", DataMode="byte", NumBytes=42},
new Unit {Version=3, ErrorCorrectionLevel="Q", DataMode="byte", NumBytes=32},
new Unit {Version=3, ErrorCorrectionLevel="H", DataMode="byte", NumBytes=24},
new Unit {Version=3, ErrorCorrectionLevel="L", DataMode="Kanji", NumBytes=32},
new Unit {Version=3, ErrorCorrectionLevel="M", DataMode="Kanji", NumBytes=26},
new Unit {Version=3, ErrorCorrectionLevel="Q", DataMode="Kanji", NumBytes=20},
new Unit {Version=3, ErrorCorrectionLevel="H", DataMode="Kanji", NumBytes=15},
// Version 4
new Unit {Version=4, ErrorCorrectionLevel="L", DataMode="Numeric", NumBytes=187},
new Unit {Version=4, ErrorCorrectionLevel="M", DataMode="Numeric", NumBytes=149},
new Unit {Version=4, ErrorCorrectionLevel="Q", DataMode="Numeric", NumBytes=111},
new Unit {Version=4, ErrorCorrectionLevel="H", DataMode="Numeric", NumBytes=82},
new Unit {Version=4, ErrorCorrectionLevel="L", DataMode="AlphaNumeric", NumBytes=114},
new Unit {Version=4, ErrorCorrectionLevel="M", DataMode="AlphaNumeric", NumBytes=90},
new Unit {Version=4, ErrorCorrectionLevel="Q", DataMode="AlphaNumeric", NumBytes=67},
new Unit {Version=4, ErrorCorrectionLevel="H", DataMode="AlphaNumeric", NumBytes=50},
new Unit {Version=4, ErrorCorrectionLevel="L", DataMode="byte", NumBytes=78},
new Unit {Version=4, ErrorCorrectionLevel="M", DataMode="byte", NumBytes=62},
new Unit {Version=4, ErrorCorrectionLevel="Q", DataMode="byte", NumBytes=46},
new Unit {Version=4, ErrorCorrectionLevel="H", DataMode="byte", NumBytes=34},
new Unit {Version=4, ErrorCorrectionLevel="L", DataMode="Kanji", NumBytes=48},
new Unit {Version=4, ErrorCorrectionLevel="M", DataMode="Kanji", NumBytes=38},
new Unit {Version=4, ErrorCorrectionLevel="Q", DataMode="Kanji", NumBytes=28},
new Unit {Version=4, ErrorCorrectionLevel="H", DataMode="Kanji", NumBytes=21},
// Version 5
new Unit {Version=5, ErrorCorrectionLevel="L", DataMode="Numeric", NumBytes=255},
new Unit {Version=5, ErrorCorrectionLevel="M", DataMode="Numeric", NumBytes=202},
new Unit {Version=5, ErrorCorrectionLevel="Q", DataMode="Numeric", NumBytes=144},
new Unit {Version=5, ErrorCorrectionLevel="H", DataMode="Numeric", NumBytes=106},
new Unit {Version=5, ErrorCorrectionLevel="L", DataMode="AlphaNumeric", NumBytes=154},
new Unit {Version=5, ErrorCorrectionLevel="M", DataMode="AlphaNumeric", NumBytes=122},
new Unit {Version=5, ErrorCorrectionLevel="Q", DataMode="AlphaNumeric", NumBytes=87},
new Unit {Version=5, ErrorCorrectionLevel="H", DataMode="AlphaNumeric", NumBytes=64},
new Unit {Version=5, ErrorCorrectionLevel="L", DataMode="byte", NumBytes=106},
new Unit {Version=5, ErrorCorrectionLevel="M", DataMode="byte", NumBytes=84},
new Unit {Version=5, ErrorCorrectionLevel="Q", DataMode="byte", NumBytes=60},
new Unit {Version=5, ErrorCorrectionLevel="H", DataMode="byte", NumBytes=44},
new Unit {Version=5, ErrorCorrectionLevel="L", DataMode="Kanji", NumBytes=65},
new Unit {Version=5, ErrorCorrectionLevel="M", DataMode="Kanji", NumBytes=52},
new Unit {Version=5, ErrorCorrectionLevel="Q", DataMode="Kanji", NumBytes=37},
new Unit {Version=5, ErrorCorrectionLevel="H", DataMode="Kanji", NumBytes=27},
// Version 6
new Unit {Version=6, ErrorCorrectionLevel="L", DataMode="Numeric", NumBytes=322},
new Unit {Version=6, ErrorCorrectionLevel="M", DataMode="Numeric", NumBytes=255},
new Unit {Version=6, ErrorCorrectionLevel="Q", DataMode="Numeric", NumBytes=178},
new Unit {Version=6, ErrorCorrectionLevel="H", DataMode="Numeric", NumBytes=139},
new Unit {Version=6, ErrorCorrectionLevel="L", DataMode="AlphaNumeric", NumBytes=195},
new Unit {Version=6, ErrorCorrectionLevel="M", DataMode="AlphaNumeric", NumBytes=154},
new Unit {Version=6, ErrorCorrectionLevel="Q", DataMode="AlphaNumeric", NumBytes=108},
new Unit {Version=6, ErrorCorrectionLevel="H", DataMode="AlphaNumeric", NumBytes=84},
new Unit {Version=6, ErrorCorrectionLevel="L", DataMode="byte", NumBytes=134},
new Unit {Version=6, ErrorCorrectionLevel="M", DataMode="byte", NumBytes=106},
new Unit {Version=6, ErrorCorrectionLevel="Q", DataMode="byte", NumBytes=74},
new Unit {Version=6, ErrorCorrectionLevel="H", DataMode="byte", NumBytes=58},
new Unit {Version=6, ErrorCorrectionLevel="L", DataMode="Kanji", NumBytes=82},
new Unit {Version=6, ErrorCorrectionLevel="M", DataMode="Kanji", NumBytes=65},
new Unit {Version=6, ErrorCorrectionLevel="Q", DataMode="Kanji", NumBytes=45},
new Unit {Version=6, ErrorCorrectionLevel="H", DataMode="Kanji", NumBytes=36},
// Version 7
new Unit {Version=7, ErrorCorrectionLevel="L", DataMode="Numeric", NumBytes=370},
new Unit {Version=7, ErrorCorrectionLevel="M", DataMode="Numeric", NumBytes=293},
new Unit {Version=7, ErrorCorrectionLevel="Q", DataMode="Numeric", NumBytes=207},
new Unit {Version=7, ErrorCorrectionLevel="H", DataMode="Numeric", NumBytes=154},
new Unit {Version=7, ErrorCorrectionLevel="L", DataMode="AlphaNumeric", NumBytes=224},
new Unit {Version=7, ErrorCorrectionLevel="M", DataMode="AlphaNumeric", NumBytes=178},
new Unit {Version=7, ErrorCorrectionLevel="Q", DataMode="AlphaNumeric", NumBytes=125},
new Unit {Version=7, ErrorCorrectionLevel="H", DataMode="AlphaNumeric", NumBytes=93},
new Unit {Version=7, ErrorCorrectionLevel="L", DataMode="byte", NumBytes=154},
new Unit {Version=7, ErrorCorrectionLevel="M", DataMode="byte", NumBytes=122},
new Unit {Version=7, ErrorCorrectionLevel="Q", DataMode="byte", NumBytes=86},
new Unit {Version=7, ErrorCorrectionLevel="H", DataMode="byte", NumBytes=64},
new Unit {Version=7, ErrorCorrectionLevel="L", DataMode="Kanji", NumBytes=95},
new Unit {Version=7, ErrorCorrectionLevel="M", DataMode="Kanji", NumBytes=75},
new Unit {Version=7, ErrorCorrectionLevel="Q", DataMode="Kanji", NumBytes=53},
new Unit {Version=7, ErrorCorrectionLevel="H", DataMode="Kanji", NumBytes=39},
// Version 8
new Unit {Version=8, ErrorCorrectionLevel="L", DataMode="Numeric", NumBytes=461},
new Unit {Version=8, ErrorCorrectionLevel="M", DataMode="Numeric", NumBytes=365},
new Unit {Version=8, ErrorCorrectionLevel="Q", DataMode="Numeric", NumBytes=259},
new Unit {Version=8, ErrorCorrectionLevel="H", DataMode="Numeric", NumBytes=202},
new Unit {Version=8, ErrorCorrectionLevel="L", DataMode="AlphaNumeric", NumBytes=279},
new Unit {Version=8, ErrorCorrectionLevel="M", DataMode="AlphaNumeric", NumBytes=221},
new Unit {Version=8, ErrorCorrectionLevel="Q", DataMode="AlphaNumeric", NumBytes=157},
new Unit {Version=8, ErrorCorrectionLevel="H", DataMode="AlphaNumeric", NumBytes=122},
new Unit {Version=8, ErrorCorrectionLevel="L", DataMode="byte", NumBytes=192},
new Unit {Version=8, ErrorCorrectionLevel="M", DataMode="byte", NumBytes=152},
new Unit {Version=8, ErrorCorrectionLevel="Q", DataMode="byte", NumBytes=108},
new Unit {Version=8, ErrorCorrectionLevel="H", DataMode="byte", NumBytes=84},
new Unit {Version=8, ErrorCorrectionLevel="L", DataMode="Kanji", NumBytes=118},
new Unit {Version=8, ErrorCorrectionLevel="M", DataMode="Kanji", NumBytes=93},
new Unit {Version=8, ErrorCorrectionLevel="Q", DataMode="Kanji", NumBytes=66},
new Unit {Version=8, ErrorCorrectionLevel="H", DataMode="Kanji", NumBytes=52},
// Version 9
new Unit {Version=9, ErrorCorrectionLevel="L", DataMode="Numeric", NumBytes=552},
new Unit {Version=9, ErrorCorrectionLevel="M", DataMode="Numeric", NumBytes=432},
new Unit {Version=9, ErrorCorrectionLevel="Q", DataMode="Numeric", NumBytes=312},
new Unit {Version=9, ErrorCorrectionLevel="H", DataMode="Numeric", NumBytes=235},
new Unit {Version=9, ErrorCorrectionLevel="L", DataMode="AlphaNumeric", NumBytes=335},
new Unit {Version=9, ErrorCorrectionLevel="M", DataMode="AlphaNumeric", NumBytes=262},
new Unit {Version=9, ErrorCorrectionLevel="Q", DataMode="AlphaNumeric", NumBytes=189},
new Unit {Version=9, ErrorCorrectionLevel="H", DataMode="AlphaNumeric", NumBytes=143},
new Unit {Version=9, ErrorCorrectionLevel="L", DataMode="byte", NumBytes=230},
new Unit {Version=9, ErrorCorrectionLevel="M", DataMode="byte", NumBytes=180},
new Unit {Version=9, ErrorCorrectionLevel="Q", DataMode="byte", NumBytes=130},
new Unit {Version=9, ErrorCorrectionLevel="H", DataMode="byte", NumBytes=98},
new Unit {Version=9, ErrorCorrectionLevel="L", DataMode="Kanji", NumBytes=141},
new Unit {Version=9, ErrorCorrectionLevel="M", DataMode="Kanji", NumBytes=111},
new Unit {Version=9, ErrorCorrectionLevel="Q", DataMode="Kanji", NumBytes=80},
new Unit {Version=9, ErrorCorrectionLevel="H", DataMode="Kanji", NumBytes=60},
// Version 10
new Unit {Version=10, ErrorCorrectionLevel="L", DataMode="Numeric", NumBytes=652},
new Unit {Version=10, ErrorCorrectionLevel="M", DataMode="Numeric", NumBytes=513},
new Unit {Version=10, ErrorCorrectionLevel="Q", DataMode="Numeric", NumBytes=364},
new Unit {Version=10, ErrorCorrectionLevel="H", DataMode="Numeric", NumBytes=288},
new Unit {Version=10, ErrorCorrectionLevel="L", DataMode="AlphaNumeric", NumBytes=395},
new Unit {Version=10, ErrorCorrectionLevel="M", DataMode="AlphaNumeric", NumBytes=311},
new Unit {Version=10, ErrorCorrectionLevel="Q", DataMode="AlphaNumeric", NumBytes=221},
new Unit {Version=10, ErrorCorrectionLevel="H", DataMode="AlphaNumeric", NumBytes=174},
new Unit {Version=10, ErrorCorrectionLevel="L", DataMode="byte", NumBytes=271},
new Unit {Version=10, ErrorCorrectionLevel="M", DataMode="byte", NumBytes=213},
new Unit {Version=10, ErrorCorrectionLevel="Q", DataMode="byte", NumBytes=151},
new Unit {Version=10, ErrorCorrectionLevel="H", DataMode="byte", NumBytes=119},
new Unit {Version=10, ErrorCorrectionLevel="L", DataMode="Kanji", NumBytes=167},
new Unit {Version=10, ErrorCorrectionLevel="M", DataMode="Kanji", NumBytes=131},
new Unit {Version=10, ErrorCorrectionLevel="Q", DataMode="Kanji", NumBytes=93},
new Unit {Version=10, ErrorCorrectionLevel="H", DataMode="Kanji", NumBytes=74}
};
}
}
| |
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Text;
namespace ImGuiNET
{
public unsafe partial struct ImFontAtlas
{
public byte Locked;
public ImFontAtlasFlags Flags;
public IntPtr TexID;
public int TexDesiredWidth;
public int TexGlyphPadding;
public byte* TexPixelsAlpha8;
public uint* TexPixelsRGBA32;
public int TexWidth;
public int TexHeight;
public Vector2 TexUvScale;
public Vector2 TexUvWhitePixel;
public ImVector Fonts;
public ImVector CustomRects;
public ImVector ConfigData;
public fixed int CustomRectIds[1];
}
public unsafe partial struct ImFontAtlasPtr
{
public ImFontAtlas* NativePtr { get; }
public ImFontAtlasPtr(ImFontAtlas* nativePtr) => NativePtr = nativePtr;
public ImFontAtlasPtr(IntPtr nativePtr) => NativePtr = (ImFontAtlas*)nativePtr;
public static implicit operator ImFontAtlasPtr(ImFontAtlas* nativePtr) => new ImFontAtlasPtr(nativePtr);
public static implicit operator ImFontAtlas* (ImFontAtlasPtr wrappedPtr) => wrappedPtr.NativePtr;
public static implicit operator ImFontAtlasPtr(IntPtr nativePtr) => new ImFontAtlasPtr(nativePtr);
public ref bool Locked => ref Unsafe.AsRef<bool>(&NativePtr->Locked);
public ref ImFontAtlasFlags Flags => ref Unsafe.AsRef<ImFontAtlasFlags>(&NativePtr->Flags);
public ref IntPtr TexID => ref Unsafe.AsRef<IntPtr>(&NativePtr->TexID);
public ref int TexDesiredWidth => ref Unsafe.AsRef<int>(&NativePtr->TexDesiredWidth);
public ref int TexGlyphPadding => ref Unsafe.AsRef<int>(&NativePtr->TexGlyphPadding);
public IntPtr TexPixelsAlpha8 { get => (IntPtr)NativePtr->TexPixelsAlpha8; set => NativePtr->TexPixelsAlpha8 = (byte*)value; }
public IntPtr TexPixelsRGBA32 { get => (IntPtr)NativePtr->TexPixelsRGBA32; set => NativePtr->TexPixelsRGBA32 = (uint*)value; }
public ref int TexWidth => ref Unsafe.AsRef<int>(&NativePtr->TexWidth);
public ref int TexHeight => ref Unsafe.AsRef<int>(&NativePtr->TexHeight);
public ref Vector2 TexUvScale => ref Unsafe.AsRef<Vector2>(&NativePtr->TexUvScale);
public ref Vector2 TexUvWhitePixel => ref Unsafe.AsRef<Vector2>(&NativePtr->TexUvWhitePixel);
public ImVector<ImFontPtr> Fonts => new ImVector<ImFontPtr>(NativePtr->Fonts);
public ImVector<CustomRect> CustomRects => new ImVector<CustomRect>(NativePtr->CustomRects);
public ImPtrVector<ImFontConfigPtr> ConfigData => new ImPtrVector<ImFontConfigPtr>(NativePtr->ConfigData, Unsafe.SizeOf<ImFontConfig>());
public RangeAccessor<int> CustomRectIds => new RangeAccessor<int>(NativePtr->CustomRectIds, 1);
public int AddCustomRectFontGlyph(ImFontPtr font, ushort id, int width, int height, float advance_x)
{
ImFont* native_font = font.NativePtr;
Vector2 offset = new Vector2();
int ret = ImGuiNative.ImFontAtlas_AddCustomRectFontGlyph(NativePtr, native_font, id, width, height, advance_x, offset);
return ret;
}
public int AddCustomRectFontGlyph(ImFontPtr font, ushort id, int width, int height, float advance_x, Vector2 offset)
{
ImFont* native_font = font.NativePtr;
int ret = ImGuiNative.ImFontAtlas_AddCustomRectFontGlyph(NativePtr, native_font, id, width, height, advance_x, offset);
return ret;
}
public int AddCustomRectRegular(uint id, int width, int height)
{
int ret = ImGuiNative.ImFontAtlas_AddCustomRectRegular(NativePtr, id, width, height);
return ret;
}
public ImFontPtr AddFont(ImFontConfigPtr font_cfg)
{
ImFontConfig* native_font_cfg = font_cfg.NativePtr;
ImFont* ret = ImGuiNative.ImFontAtlas_AddFont(NativePtr, native_font_cfg);
return new ImFontPtr(ret);
}
public ImFontPtr AddFontDefault()
{
ImFontConfig* font_cfg = null;
ImFont* ret = ImGuiNative.ImFontAtlas_AddFontDefault(NativePtr, font_cfg);
return new ImFontPtr(ret);
}
public ImFontPtr AddFontDefault(ImFontConfigPtr font_cfg)
{
ImFontConfig* native_font_cfg = font_cfg.NativePtr;
ImFont* ret = ImGuiNative.ImFontAtlas_AddFontDefault(NativePtr, native_font_cfg);
return new ImFontPtr(ret);
}
public ImFontPtr AddFontFromFileTTF(string filename, float size_pixels)
{
byte* native_filename;
if (filename != null)
{
int filename_byteCount = Encoding.UTF8.GetByteCount(filename);
byte* native_filename_stackBytes = stackalloc byte[filename_byteCount + 1];
native_filename = native_filename_stackBytes;
fixed (char* filename_ptr = filename)
{
int native_filename_offset = Encoding.UTF8.GetBytes(filename_ptr, filename.Length, native_filename, filename_byteCount);
native_filename[native_filename_offset] = 0;
}
}
else { native_filename = null; }
ImFontConfig* font_cfg = null;
ushort* glyph_ranges = null;
ImFont* ret = ImGuiNative.ImFontAtlas_AddFontFromFileTTF(NativePtr, native_filename, size_pixels, font_cfg, glyph_ranges);
return new ImFontPtr(ret);
}
public ImFontPtr AddFontFromFileTTF(string filename, float size_pixels, ImFontConfigPtr font_cfg)
{
byte* native_filename;
if (filename != null)
{
int filename_byteCount = Encoding.UTF8.GetByteCount(filename);
byte* native_filename_stackBytes = stackalloc byte[filename_byteCount + 1];
native_filename = native_filename_stackBytes;
fixed (char* filename_ptr = filename)
{
int native_filename_offset = Encoding.UTF8.GetBytes(filename_ptr, filename.Length, native_filename, filename_byteCount);
native_filename[native_filename_offset] = 0;
}
}
else { native_filename = null; }
ImFontConfig* native_font_cfg = font_cfg.NativePtr;
ushort* glyph_ranges = null;
ImFont* ret = ImGuiNative.ImFontAtlas_AddFontFromFileTTF(NativePtr, native_filename, size_pixels, native_font_cfg, glyph_ranges);
return new ImFontPtr(ret);
}
public ImFontPtr AddFontFromFileTTF(string filename, float size_pixels, ImFontConfigPtr font_cfg, IntPtr glyph_ranges)
{
byte* native_filename;
if (filename != null)
{
int filename_byteCount = Encoding.UTF8.GetByteCount(filename);
byte* native_filename_stackBytes = stackalloc byte[filename_byteCount + 1];
native_filename = native_filename_stackBytes;
fixed (char* filename_ptr = filename)
{
int native_filename_offset = Encoding.UTF8.GetBytes(filename_ptr, filename.Length, native_filename, filename_byteCount);
native_filename[native_filename_offset] = 0;
}
}
else { native_filename = null; }
ImFontConfig* native_font_cfg = font_cfg.NativePtr;
ushort* native_glyph_ranges = (ushort*)glyph_ranges.ToPointer();
ImFont* ret = ImGuiNative.ImFontAtlas_AddFontFromFileTTF(NativePtr, native_filename, size_pixels, native_font_cfg, native_glyph_ranges);
return new ImFontPtr(ret);
}
public ImFontPtr AddFontFromMemoryCompressedBase85TTF(string compressed_font_data_base85, float size_pixels)
{
byte* native_compressed_font_data_base85;
if (compressed_font_data_base85 != null)
{
int compressed_font_data_base85_byteCount = Encoding.UTF8.GetByteCount(compressed_font_data_base85);
byte* native_compressed_font_data_base85_stackBytes = stackalloc byte[compressed_font_data_base85_byteCount + 1];
native_compressed_font_data_base85 = native_compressed_font_data_base85_stackBytes;
fixed (char* compressed_font_data_base85_ptr = compressed_font_data_base85)
{
int native_compressed_font_data_base85_offset = Encoding.UTF8.GetBytes(compressed_font_data_base85_ptr, compressed_font_data_base85.Length, native_compressed_font_data_base85, compressed_font_data_base85_byteCount);
native_compressed_font_data_base85[native_compressed_font_data_base85_offset] = 0;
}
}
else { native_compressed_font_data_base85 = null; }
ImFontConfig* font_cfg = null;
ushort* glyph_ranges = null;
ImFont* ret = ImGuiNative.ImFontAtlas_AddFontFromMemoryCompressedBase85TTF(NativePtr, native_compressed_font_data_base85, size_pixels, font_cfg, glyph_ranges);
return new ImFontPtr(ret);
}
public ImFontPtr AddFontFromMemoryCompressedBase85TTF(string compressed_font_data_base85, float size_pixels, ImFontConfigPtr font_cfg)
{
byte* native_compressed_font_data_base85;
if (compressed_font_data_base85 != null)
{
int compressed_font_data_base85_byteCount = Encoding.UTF8.GetByteCount(compressed_font_data_base85);
byte* native_compressed_font_data_base85_stackBytes = stackalloc byte[compressed_font_data_base85_byteCount + 1];
native_compressed_font_data_base85 = native_compressed_font_data_base85_stackBytes;
fixed (char* compressed_font_data_base85_ptr = compressed_font_data_base85)
{
int native_compressed_font_data_base85_offset = Encoding.UTF8.GetBytes(compressed_font_data_base85_ptr, compressed_font_data_base85.Length, native_compressed_font_data_base85, compressed_font_data_base85_byteCount);
native_compressed_font_data_base85[native_compressed_font_data_base85_offset] = 0;
}
}
else { native_compressed_font_data_base85 = null; }
ImFontConfig* native_font_cfg = font_cfg.NativePtr;
ushort* glyph_ranges = null;
ImFont* ret = ImGuiNative.ImFontAtlas_AddFontFromMemoryCompressedBase85TTF(NativePtr, native_compressed_font_data_base85, size_pixels, native_font_cfg, glyph_ranges);
return new ImFontPtr(ret);
}
public ImFontPtr AddFontFromMemoryCompressedBase85TTF(string compressed_font_data_base85, float size_pixels, ImFontConfigPtr font_cfg, IntPtr glyph_ranges)
{
byte* native_compressed_font_data_base85;
if (compressed_font_data_base85 != null)
{
int compressed_font_data_base85_byteCount = Encoding.UTF8.GetByteCount(compressed_font_data_base85);
byte* native_compressed_font_data_base85_stackBytes = stackalloc byte[compressed_font_data_base85_byteCount + 1];
native_compressed_font_data_base85 = native_compressed_font_data_base85_stackBytes;
fixed (char* compressed_font_data_base85_ptr = compressed_font_data_base85)
{
int native_compressed_font_data_base85_offset = Encoding.UTF8.GetBytes(compressed_font_data_base85_ptr, compressed_font_data_base85.Length, native_compressed_font_data_base85, compressed_font_data_base85_byteCount);
native_compressed_font_data_base85[native_compressed_font_data_base85_offset] = 0;
}
}
else { native_compressed_font_data_base85 = null; }
ImFontConfig* native_font_cfg = font_cfg.NativePtr;
ushort* native_glyph_ranges = (ushort*)glyph_ranges.ToPointer();
ImFont* ret = ImGuiNative.ImFontAtlas_AddFontFromMemoryCompressedBase85TTF(NativePtr, native_compressed_font_data_base85, size_pixels, native_font_cfg, native_glyph_ranges);
return new ImFontPtr(ret);
}
public ImFontPtr AddFontFromMemoryCompressedTTF(IntPtr compressed_font_data, int compressed_font_size, float size_pixels)
{
void* native_compressed_font_data = (void*)compressed_font_data.ToPointer();
ImFontConfig* font_cfg = null;
ushort* glyph_ranges = null;
ImFont* ret = ImGuiNative.ImFontAtlas_AddFontFromMemoryCompressedTTF(NativePtr, native_compressed_font_data, compressed_font_size, size_pixels, font_cfg, glyph_ranges);
return new ImFontPtr(ret);
}
public ImFontPtr AddFontFromMemoryCompressedTTF(IntPtr compressed_font_data, int compressed_font_size, float size_pixels, ImFontConfigPtr font_cfg)
{
void* native_compressed_font_data = (void*)compressed_font_data.ToPointer();
ImFontConfig* native_font_cfg = font_cfg.NativePtr;
ushort* glyph_ranges = null;
ImFont* ret = ImGuiNative.ImFontAtlas_AddFontFromMemoryCompressedTTF(NativePtr, native_compressed_font_data, compressed_font_size, size_pixels, native_font_cfg, glyph_ranges);
return new ImFontPtr(ret);
}
public ImFontPtr AddFontFromMemoryCompressedTTF(IntPtr compressed_font_data, int compressed_font_size, float size_pixels, ImFontConfigPtr font_cfg, IntPtr glyph_ranges)
{
void* native_compressed_font_data = (void*)compressed_font_data.ToPointer();
ImFontConfig* native_font_cfg = font_cfg.NativePtr;
ushort* native_glyph_ranges = (ushort*)glyph_ranges.ToPointer();
ImFont* ret = ImGuiNative.ImFontAtlas_AddFontFromMemoryCompressedTTF(NativePtr, native_compressed_font_data, compressed_font_size, size_pixels, native_font_cfg, native_glyph_ranges);
return new ImFontPtr(ret);
}
public ImFontPtr AddFontFromMemoryTTF(IntPtr font_data, int font_size, float size_pixels)
{
void* native_font_data = (void*)font_data.ToPointer();
ImFontConfig* font_cfg = null;
ushort* glyph_ranges = null;
ImFont* ret = ImGuiNative.ImFontAtlas_AddFontFromMemoryTTF(NativePtr, native_font_data, font_size, size_pixels, font_cfg, glyph_ranges);
return new ImFontPtr(ret);
}
public ImFontPtr AddFontFromMemoryTTF(IntPtr font_data, int font_size, float size_pixels, ImFontConfigPtr font_cfg)
{
void* native_font_data = (void*)font_data.ToPointer();
ImFontConfig* native_font_cfg = font_cfg.NativePtr;
ushort* glyph_ranges = null;
ImFont* ret = ImGuiNative.ImFontAtlas_AddFontFromMemoryTTF(NativePtr, native_font_data, font_size, size_pixels, native_font_cfg, glyph_ranges);
return new ImFontPtr(ret);
}
public ImFontPtr AddFontFromMemoryTTF(IntPtr font_data, int font_size, float size_pixels, ImFontConfigPtr font_cfg, IntPtr glyph_ranges)
{
void* native_font_data = (void*)font_data.ToPointer();
ImFontConfig* native_font_cfg = font_cfg.NativePtr;
ushort* native_glyph_ranges = (ushort*)glyph_ranges.ToPointer();
ImFont* ret = ImGuiNative.ImFontAtlas_AddFontFromMemoryTTF(NativePtr, native_font_data, font_size, size_pixels, native_font_cfg, native_glyph_ranges);
return new ImFontPtr(ret);
}
public bool Build()
{
byte ret = ImGuiNative.ImFontAtlas_Build(NativePtr);
return ret != 0;
}
public void CalcCustomRectUV(ref CustomRect rect, out Vector2 out_uv_min, out Vector2 out_uv_max)
{
fixed (CustomRect* native_rect = &rect)
{
fixed (Vector2* native_out_uv_min = &out_uv_min)
{
fixed (Vector2* native_out_uv_max = &out_uv_max)
{
ImGuiNative.ImFontAtlas_CalcCustomRectUV(NativePtr, native_rect, native_out_uv_min, native_out_uv_max);
}
}
}
}
public void Clear()
{
ImGuiNative.ImFontAtlas_Clear(NativePtr);
}
public void ClearFonts()
{
ImGuiNative.ImFontAtlas_ClearFonts(NativePtr);
}
public void ClearInputData()
{
ImGuiNative.ImFontAtlas_ClearInputData(NativePtr);
}
public void ClearTexData()
{
ImGuiNative.ImFontAtlas_ClearTexData(NativePtr);
}
public CustomRect* GetCustomRectByIndex(int index)
{
CustomRect* ret = ImGuiNative.ImFontAtlas_GetCustomRectByIndex(NativePtr, index);
return ret;
}
public IntPtr GetGlyphRangesChineseFull()
{
ushort* ret = ImGuiNative.ImFontAtlas_GetGlyphRangesChineseFull(NativePtr);
return (IntPtr)ret;
}
public IntPtr GetGlyphRangesChineseSimplifiedCommon()
{
ushort* ret = ImGuiNative.ImFontAtlas_GetGlyphRangesChineseSimplifiedCommon(NativePtr);
return (IntPtr)ret;
}
public IntPtr GetGlyphRangesCyrillic()
{
ushort* ret = ImGuiNative.ImFontAtlas_GetGlyphRangesCyrillic(NativePtr);
return (IntPtr)ret;
}
public IntPtr GetGlyphRangesDefault()
{
ushort* ret = ImGuiNative.ImFontAtlas_GetGlyphRangesDefault(NativePtr);
return (IntPtr)ret;
}
public IntPtr GetGlyphRangesJapanese()
{
ushort* ret = ImGuiNative.ImFontAtlas_GetGlyphRangesJapanese(NativePtr);
return (IntPtr)ret;
}
public IntPtr GetGlyphRangesKorean()
{
ushort* ret = ImGuiNative.ImFontAtlas_GetGlyphRangesKorean(NativePtr);
return (IntPtr)ret;
}
public IntPtr GetGlyphRangesThai()
{
ushort* ret = ImGuiNative.ImFontAtlas_GetGlyphRangesThai(NativePtr);
return (IntPtr)ret;
}
public bool GetMouseCursorTexData(ImGuiMouseCursor cursor, out Vector2 out_offset, out Vector2 out_size, out Vector2 out_uv_border, out Vector2 out_uv_fill)
{
fixed (Vector2* native_out_offset = &out_offset)
{
fixed (Vector2* native_out_size = &out_size)
{
fixed (Vector2* native_out_uv_border = &out_uv_border)
{
fixed (Vector2* native_out_uv_fill = &out_uv_fill)
{
byte ret = ImGuiNative.ImFontAtlas_GetMouseCursorTexData(NativePtr, cursor, native_out_offset, native_out_size, native_out_uv_border, native_out_uv_fill);
return ret != 0;
}
}
}
}
}
public void GetTexDataAsAlpha8(out byte* out_pixels, out int out_width, out int out_height)
{
int* out_bytes_per_pixel = null;
fixed (byte** native_out_pixels = &out_pixels)
{
fixed (int* native_out_width = &out_width)
{
fixed (int* native_out_height = &out_height)
{
ImGuiNative.ImFontAtlas_GetTexDataAsAlpha8(NativePtr, native_out_pixels, native_out_width, native_out_height, out_bytes_per_pixel);
}
}
}
}
public void GetTexDataAsAlpha8(out byte* out_pixels, out int out_width, out int out_height, out int out_bytes_per_pixel)
{
fixed (byte** native_out_pixels = &out_pixels)
{
fixed (int* native_out_width = &out_width)
{
fixed (int* native_out_height = &out_height)
{
fixed (int* native_out_bytes_per_pixel = &out_bytes_per_pixel)
{
ImGuiNative.ImFontAtlas_GetTexDataAsAlpha8(NativePtr, native_out_pixels, native_out_width, native_out_height, native_out_bytes_per_pixel);
}
}
}
}
}
public void GetTexDataAsRGBA32(out byte* out_pixels, out int out_width, out int out_height)
{
int* out_bytes_per_pixel = null;
fixed (byte** native_out_pixels = &out_pixels)
{
fixed (int* native_out_width = &out_width)
{
fixed (int* native_out_height = &out_height)
{
ImGuiNative.ImFontAtlas_GetTexDataAsRGBA32(NativePtr, native_out_pixels, native_out_width, native_out_height, out_bytes_per_pixel);
}
}
}
}
public void GetTexDataAsRGBA32(out byte* out_pixels, out int out_width, out int out_height, out int out_bytes_per_pixel)
{
fixed (byte** native_out_pixels = &out_pixels)
{
fixed (int* native_out_width = &out_width)
{
fixed (int* native_out_height = &out_height)
{
fixed (int* native_out_bytes_per_pixel = &out_bytes_per_pixel)
{
ImGuiNative.ImFontAtlas_GetTexDataAsRGBA32(NativePtr, native_out_pixels, native_out_width, native_out_height, native_out_bytes_per_pixel);
}
}
}
}
}
public bool IsBuilt()
{
byte ret = ImGuiNative.ImFontAtlas_IsBuilt(NativePtr);
return ret != 0;
}
public void SetTexID(IntPtr id)
{
ImGuiNative.ImFontAtlas_SetTexID(NativePtr, id);
}
}
}
| |
// 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 Microsoft.CSharp.RuntimeBinder;
using Xunit;
using static Dynamic.Operator.Tests.TypeCommon;
namespace Dynamic.Operator.Tests
{
public class MinusEqualsTypeTests
{
[Fact]
public static void Bool()
{
dynamic d = true;
Assert.Throws<RuntimeBinderException>(() => d -= s_bool);
Assert.Throws<RuntimeBinderException>(() => d -= s_byte);
Assert.Throws<RuntimeBinderException>(() => d -= s_char);
Assert.Throws<RuntimeBinderException>(() => d -= s_decimal);
Assert.Throws<RuntimeBinderException>(() => d -= s_double);
Assert.Throws<RuntimeBinderException>(() => d -= s_float);
Assert.Throws<RuntimeBinderException>(() => d -= s_int);
Assert.Throws<RuntimeBinderException>(() => d -= s_long);
Assert.Throws<RuntimeBinderException>(() => d -= s_object);
Assert.Throws<RuntimeBinderException>(() => d -= s_sbyte);
Assert.Throws<RuntimeBinderException>(() => d -= s_short);
d = true;
Assert.Throws<RuntimeBinderException>(() => d -= s_string);
d = true;
Assert.Throws<RuntimeBinderException>(() => d -= s_uint);
Assert.Throws<RuntimeBinderException>(() => d -= s_ulong);
Assert.Throws<RuntimeBinderException>(() => d -= s_ushort);
}
[Fact]
public static void Byte()
{
dynamic d = (byte)1;
Assert.Throws<RuntimeBinderException>(() => d -= s_bool);
d = (byte)1;
d -= s_byte;
d = (byte)1;
d -= s_char;
d = (byte)1;
d -= s_decimal;
d = (byte)1;
d -= s_double;
d = (byte)1;
d -= s_float;
d = (byte)1;
d -= s_int;
d = (byte)1;
d -= s_long;
d = (byte)1;
Assert.Throws<RuntimeBinderException>(() => d -= s_object);
d = (byte)1;
d -= s_sbyte;
d = (byte)1;
d -= s_short;
d = (byte)1;
Assert.Throws<RuntimeBinderException>(() => d -= s_string);
d = (byte)1;
d -= s_uint;
d = (byte)1;
d -= s_ulong;
d = (byte)1;
d -= s_ushort;
}
[Fact]
public static void Char()
{
dynamic d = 'a';
Assert.Throws<RuntimeBinderException>(() => d -= s_bool);
d = 'a';
d -= s_byte;
d = 'a';
d -= s_char;
d = 'a';
d -= s_decimal;
d = 'a';
d -= s_double;
d = 'a';
d -= s_float;
d = 'a';
d -= s_int;
d = 'a';
d -= s_long;
d = 'a';
Assert.Throws<RuntimeBinderException>(() => d -= s_object);
d = 'a';
d -= s_sbyte;
d = 'a';
d -= s_short;
d = 'a';
Assert.Throws<RuntimeBinderException>(() => d -= s_string);
d = 'a';
d -= s_uint;
d = 'a';
d -= s_ulong;
d = 'a';
d -= s_ushort;
}
[Fact]
public static void Decimal()
{
dynamic d = 10m;
Assert.Throws<RuntimeBinderException>(() => d -= s_bool);
d = 10m;
d -= s_byte;
d = 10m;
d -= s_char;
d = 10m;
d -= s_decimal;
d = 10m;
Assert.Throws<RuntimeBinderException>(() => d -= s_double);
Assert.Throws<RuntimeBinderException>(() => d -= s_float);
d = 10m;
d -= s_int;
d = 10m;
d -= s_long;
d = 10m;
Assert.Throws<RuntimeBinderException>(() => d -= s_object);
d = 10m;
d -= s_sbyte;
d = 10m;
d -= s_short;
d = 10m;
Assert.Throws<RuntimeBinderException>(() => d -= s_string);
d = 10m;
d -= s_uint;
d = 10m;
d -= s_ulong;
d = 10m;
d -= s_ushort;
}
[Fact]
public static void Double()
{
dynamic d = 10d;
Assert.Throws<RuntimeBinderException>(() => d -= s_bool);
d = 10d;
d -= s_byte;
d = 10d;
d -= s_char;
d = 10d;
Assert.Throws<RuntimeBinderException>(() => d -= s_decimal);
d = 10d;
d -= s_double;
d = 10d;
d -= s_float;
d = 10d;
d -= s_int;
d = 10d;
d -= s_long;
d = 10d;
Assert.Throws<RuntimeBinderException>(() => d -= s_object);
d = 10d;
d -= s_sbyte;
d = 10d;
d -= s_short;
d = 10d;
Assert.Throws<RuntimeBinderException>(() => d -= s_string);
d = 10d;
d -= s_uint;
d = 10d;
d -= s_ulong;
d = 10d;
d -= s_ushort;
}
[Fact]
public static void Float()
{
dynamic d = 10f;
Assert.Throws<RuntimeBinderException>(() => d -= s_bool);
d = 10f;
d -= s_byte;
d = 10f;
d -= s_char;
d = 10f;
Assert.Throws<RuntimeBinderException>(() => d -= s_decimal);
d = 10f;
d -= s_double;
d = 10f;
d -= s_float;
d = 10f;
d -= s_int;
d = 10f;
d -= s_long;
d = 10f;
Assert.Throws<RuntimeBinderException>(() => d -= s_object);
d = 10f;
d -= s_sbyte;
d = 10f;
d -= s_short;
d = 10f;
Assert.Throws<RuntimeBinderException>(() => d -= s_string);
d = 10f;
d -= s_uint;
d = 10f;
d -= s_ulong;
d = 10f;
d -= s_ushort;
}
[Fact]
public static void Int()
{
dynamic d = 10;
Assert.Throws<RuntimeBinderException>(() => d -= s_bool);
d = 10;
d -= s_byte;
d = 10;
d -= s_char;
d = 10;
d -= s_decimal;
d = 10;
d -= s_double;
d = 10;
d -= s_float;
d = 10;
d -= s_int;
d = 10;
d -= s_long;
d = 10;
Assert.Throws<RuntimeBinderException>(() => d -= s_object);
d = 10;
d -= s_sbyte;
d = 10;
d -= s_short;
d = 10;
Assert.Throws<RuntimeBinderException>(() => d -= s_string);
d = 10;
d -= s_uint;
d = 10;
Assert.Throws<RuntimeBinderException>(() => d -= s_ulong);
d = 10;
d -= s_ushort;
}
[Fact]
public static void Long()
{
dynamic d = 10L;
Assert.Throws<RuntimeBinderException>(() => d -= s_bool);
d = 10L;
d -= s_byte;
d = 10L;
d -= s_char;
d = 10L;
d -= s_decimal;
d = 10L;
d -= s_double;
d = 10L;
d -= s_float;
d = 10L;
d -= s_int;
d = 10L;
d -= s_long;
d = 10L;
Assert.Throws<RuntimeBinderException>(() => d -= s_object);
d = 10L;
d -= s_sbyte;
d = 10L;
d -= s_short;
d = 10L;
Assert.Throws<RuntimeBinderException>(() => d -= s_string);
d = 10L;
d -= s_uint;
d = 10L;
Assert.Throws<RuntimeBinderException>(() => d -= s_ulong);
d = 10L;
d -= s_ushort;
}
[Fact]
public static void Object()
{
dynamic d = new object();
Assert.Throws<RuntimeBinderException>(() => d -= s_bool);
Assert.Throws<RuntimeBinderException>(() => d -= s_byte);
Assert.Throws<RuntimeBinderException>(() => d -= s_char);
Assert.Throws<RuntimeBinderException>(() => d -= s_decimal);
Assert.Throws<RuntimeBinderException>(() => d -= s_double);
Assert.Throws<RuntimeBinderException>(() => d -= s_float);
Assert.Throws<RuntimeBinderException>(() => d -= s_int);
Assert.Throws<RuntimeBinderException>(() => d -= s_long);
Assert.Throws<RuntimeBinderException>(() => d -= s_object);
Assert.Throws<RuntimeBinderException>(() => d -= s_sbyte);
Assert.Throws<RuntimeBinderException>(() => d -= s_short);
d = new object();
Assert.Throws<RuntimeBinderException>(() => d -= s_string);
d = new object();
Assert.Throws<RuntimeBinderException>(() => d -= s_uint);
Assert.Throws<RuntimeBinderException>(() => d -= s_ulong);
Assert.Throws<RuntimeBinderException>(() => d -= s_ushort);
}
[Fact]
public static void SByte()
{
dynamic d = (sbyte)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_bool);
d = (sbyte)10;
d -= s_byte;
d = (sbyte)10;
d -= s_char;
d = (sbyte)10;
d -= s_decimal;
d = (sbyte)10;
d -= s_double;
d = (sbyte)10;
d -= s_float;
d = (sbyte)10;
d -= s_int;
d = (sbyte)10;
d -= s_long;
d = (sbyte)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_object);
d = (sbyte)10;
d -= s_sbyte;
d = (sbyte)10;
d -= s_short;
d = (sbyte)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_string);
d = (sbyte)10;
d -= s_uint;
d = (sbyte)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_ulong);
d = (sbyte)10;
d -= s_ushort;
}
[Fact]
public static void Short()
{
dynamic d = (short)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_bool);
d = (short)10;
d -= s_byte;
d = (short)10;
d -= s_char;
d = (short)10;
d -= s_decimal;
d = (short)10;
d -= s_double;
d = (short)10;
d -= s_float;
d = (short)10;
d -= s_int;
d = (short)10;
d -= s_long;
d = (short)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_object);
d = (short)10;
d -= s_sbyte;
d = (short)10;
d -= s_short;
d = (short)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_string);
d = (short)10;
d -= s_uint;
d = (short)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_ulong);
d = (short)10;
d -= s_ushort;
}
[Fact]
public static void String()
{
dynamic d = "a";
Assert.Throws<RuntimeBinderException>(() => d -= s_bool);
Assert.Throws<RuntimeBinderException>(() => d -= s_byte);
Assert.Throws<RuntimeBinderException>(() => d -= s_char);
Assert.Throws<RuntimeBinderException>(() => d -= s_decimal);
Assert.Throws<RuntimeBinderException>(() => d -= s_double);
Assert.Throws<RuntimeBinderException>(() => d -= s_float);
Assert.Throws<RuntimeBinderException>(() => d -= s_int);
Assert.Throws<RuntimeBinderException>(() => d -= s_long);
Assert.Throws<RuntimeBinderException>(() => d -= s_object);
Assert.Throws<RuntimeBinderException>(() => d -= s_sbyte);
Assert.Throws<RuntimeBinderException>(() => d -= s_short);
Assert.Throws<RuntimeBinderException>(() => d -= s_string);
Assert.Throws<RuntimeBinderException>(() => d -= s_uint);
Assert.Throws<RuntimeBinderException>(() => d -= s_ulong);
Assert.Throws<RuntimeBinderException>(() => d -= s_ushort);
}
[Fact]
public static void UInt()
{
dynamic d = (uint)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_bool);
d = (uint)10;
d -= s_byte;
d = (uint)10;
d -= s_char;
d = (uint)10;
d -= s_decimal;
d = (uint)10;
d -= s_double;
d = (uint)10;
d -= s_float;
d = (uint)10;
d -= s_int;
d = (uint)10;
d -= s_long;
d = (uint)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_object);
d = (uint)10;
d -= s_sbyte;
d = (uint)10;
d -= s_short;
d = (uint)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_string);
d = (uint)10;
d -= s_uint;
d = (uint)10;
d -= s_ulong;
d = (uint)10;
d -= s_ushort;
}
[Fact]
public static void ULong()
{
dynamic d = (ulong)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_bool);
d = (ulong)10;
d -= s_byte;
d = (ulong)10;
d -= s_char;
d = (ulong)10;
d -= s_decimal;
d = (ulong)10;
d -= s_double;
d = (ulong)10;
d -= s_float;
d = (ulong)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_int);
Assert.Throws<RuntimeBinderException>(() => d -= s_long);
Assert.Throws<RuntimeBinderException>(() => d -= s_object);
Assert.Throws<RuntimeBinderException>(() => d -= s_sbyte);
Assert.Throws<RuntimeBinderException>(() => d -= s_short);
d = (ulong)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_string);
d = (ulong)10;
d -= s_uint;
d = (ulong)10;
d -= s_ulong;
d = (ulong)10;
d -= s_ushort;
}
[Fact]
public static void UShort()
{
dynamic d = (ushort)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_bool);
d = (ushort)10;
d -= s_byte;
d = (ushort)10;
d -= s_char;
d = (ushort)10;
d -= s_decimal;
d = (ushort)10;
d -= s_double;
d = (ushort)10;
d -= s_float;
d = (ushort)10;
d -= s_int;
d = (ushort)10;
d -= s_long;
d = (ushort)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_object);
d = (ushort)10;
d -= s_sbyte;
d = (ushort)10;
d -= s_short;
d = (ushort)10;
Assert.Throws<RuntimeBinderException>(() => d -= s_string);
d = (ushort)10;
d -= s_uint;
d = (ushort)10;
d -= s_ulong;
d = (ushort)10;
d -= s_ushort;
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// 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
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using NLog.Common;
using NLog.Config;
using NLog.Filters;
using NLog.Internal;
using NLog.Targets;
/// <summary>
/// Implementation of logging engine.
/// </summary>
internal static class LoggerImpl
{
private const int StackTraceSkipMethods = 0;
private static readonly Assembly nlogAssembly = typeof(LoggerImpl).Assembly;
private static readonly Assembly mscorlibAssembly = typeof(string).Assembly;
private static readonly Assembly systemAssembly = typeof(Debug).Assembly;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", Justification = "Using 'NLog' in message.")]
internal static void Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
{
if (targets == null)
{
return;
}
StackTraceUsage stu = targets.GetStackTraceUsage();
if (stu != StackTraceUsage.None && !logEvent.HasStackTrace)
{
StackTrace stackTrace;
#if !SILVERLIGHT
stackTrace = new StackTrace(StackTraceSkipMethods, stu == StackTraceUsage.WithSource);
#else
stackTrace = new StackTrace();
#endif
int firstUserFrame = FindCallingMethodOnStackTrace(stackTrace, loggerType);
logEvent.SetStackTrace(stackTrace, firstUserFrame);
}
int originalThreadId = Thread.CurrentThread.ManagedThreadId;
AsyncContinuation exceptionHandler = ex =>
{
if (ex != null)
{
if (factory.ThrowExceptions && Thread.CurrentThread.ManagedThreadId == originalThreadId)
{
throw new NLogRuntimeException("Exception occurred in NLog", ex);
}
}
};
for (var t = targets; t != null; t = t.NextInChain)
{
if (!WriteToTargetWithFilterChain(t, logEvent, exceptionHandler))
{
break;
}
}
}
private static int FindCallingMethodOnStackTrace(StackTrace stackTrace, Type loggerType)
{
int? firstUserFrame = null;
if (loggerType != null)
{
for (int i = 0; i < stackTrace.FrameCount; ++i)
{
StackFrame frame = stackTrace.GetFrame(i);
MethodBase mb = frame.GetMethod();
if (mb.DeclaringType == loggerType)
firstUserFrame = i + 1;
else if (firstUserFrame != null)
break;
}
}
if (firstUserFrame == stackTrace.FrameCount)
firstUserFrame = null;
if (firstUserFrame == null)
{
for (int i = 0; i < stackTrace.FrameCount; ++i)
{
StackFrame frame = stackTrace.GetFrame(i);
MethodBase mb = frame.GetMethod();
Assembly methodAssembly = null;
if (mb.DeclaringType != null)
{
methodAssembly = mb.DeclaringType.Assembly;
}
if (SkipAssembly(methodAssembly))
{
firstUserFrame = i + 1;
}
else
{
if (firstUserFrame != 0)
{
break;
}
}
}
}
return firstUserFrame ?? 0;
}
private static bool SkipAssembly(Assembly assembly)
{
if (assembly == nlogAssembly)
{
return true;
}
if (assembly == mscorlibAssembly)
{
return true;
}
if (assembly == systemAssembly)
{
return true;
}
return false;
}
private static bool WriteToTargetWithFilterChain(TargetWithFilterChain targetListHead, LogEventInfo logEvent, AsyncContinuation onException)
{
Target target = targetListHead.Target;
FilterResult result = GetFilterResult(targetListHead.FilterChain, logEvent);
if ((result == FilterResult.Ignore) || (result == FilterResult.IgnoreFinal))
{
if (InternalLogger.IsDebugEnabled)
{
InternalLogger.Debug("{0}.{1} Rejecting message because of a filter.", logEvent.LoggerName, logEvent.Level);
}
if (result == FilterResult.IgnoreFinal)
{
return false;
}
return true;
}
target.WriteAsyncLogEvent(logEvent.WithContinuation(onException));
if (result == FilterResult.LogFinal)
{
return false;
}
return true;
}
/// <summary>
/// Gets the filter result.
/// </summary>
/// <param name="filterChain">The filter chain.</param>
/// <param name="logEvent">The log event.</param>
/// <returns>The result of the filter.</returns>
private static FilterResult GetFilterResult(IEnumerable<Filter> filterChain, LogEventInfo logEvent)
{
FilterResult result = FilterResult.Neutral;
try
{
foreach (Filter f in filterChain)
{
result = f.GetFilterResult(logEvent);
if (result != FilterResult.Neutral)
{
break;
}
}
return result;
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Warn("Exception during filter evaluation: {0}", exception);
return FilterResult.Ignore;
}
}
}
}
| |
// 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 MultiplySubtractAddDouble()
{
var test = new AlternatingTernaryOpTest__MultiplySubtractAddDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.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 (Avx.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();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.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();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
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 AlternatingTernaryOpTest__MultiplySubtractAddDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] inArray3, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Double, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Double> _fld1;
public Vector256<Double> _fld2;
public Vector256<Double> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
return testStruct;
}
public void RunStructFldScenario(AlternatingTernaryOpTest__MultiplySubtractAddDouble testClass)
{
var result = Fma.MultiplySubtractAdd(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(AlternatingTernaryOpTest__MultiplySubtractAddDouble testClass)
{
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
fixed (Vector256<Double>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtractAdd(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2)),
Avx.LoadVector256((Double*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Double[] _data3 = new Double[Op3ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private static Vector256<Double> _clsVar3;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private Vector256<Double> _fld3;
private DataTable _dataTable;
static AlternatingTernaryOpTest__MultiplySubtractAddDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
}
public AlternatingTernaryOpTest__MultiplySubtractAddDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Fma.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Fma.MultiplySubtractAdd(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Fma.MultiplySubtractAdd(
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Fma.MultiplySubtractAdd(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractAdd), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractAdd), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractAdd), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Fma.MultiplySubtractAdd(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Double>* pClsVar1 = &_clsVar1)
fixed (Vector256<Double>* pClsVar2 = &_clsVar2)
fixed (Vector256<Double>* pClsVar3 = &_clsVar3)
{
var result = Fma.MultiplySubtractAdd(
Avx.LoadVector256((Double*)(pClsVar1)),
Avx.LoadVector256((Double*)(pClsVar2)),
Avx.LoadVector256((Double*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray3Ptr);
var result = Fma.MultiplySubtractAdd(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr));
var op3 = Avx.LoadVector256((Double*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtractAdd(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr));
var op3 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtractAdd(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new AlternatingTernaryOpTest__MultiplySubtractAddDouble();
var result = Fma.MultiplySubtractAdd(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new AlternatingTernaryOpTest__MultiplySubtractAddDouble();
fixed (Vector256<Double>* pFld1 = &test._fld1)
fixed (Vector256<Double>* pFld2 = &test._fld2)
fixed (Vector256<Double>* pFld3 = &test._fld3)
{
var result = Fma.MultiplySubtractAdd(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2)),
Avx.LoadVector256((Double*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Fma.MultiplySubtractAdd(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
fixed (Vector256<Double>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtractAdd(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2)),
Avx.LoadVector256((Double*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Fma.MultiplySubtractAdd(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Fma.MultiplySubtractAdd(
Avx.LoadVector256((Double*)(&test._fld1)),
Avx.LoadVector256((Double*)(&test._fld2)),
Avx.LoadVector256((Double*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(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(Vector256<Double> op1, Vector256<Double> op2, Vector256<Double> op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] secondOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i += 2)
{
if (BitConverter.DoubleToInt64Bits(Math.Round((firstOp[i] * secondOp[i]) + thirdOp[i], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[i], 9)))
{
succeeded = false;
break;
}
if (BitConverter.DoubleToInt64Bits(Math.Round((firstOp[i + 1] * secondOp[i + 1]) - thirdOp[i + 1], 9)) != BitConverter.DoubleToInt64Bits(Math.Round(result[i + 1], 9)))
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtractAdd)}<Double>(Vector256<Double>, Vector256<Double>, Vector256<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Reflection;
using System.Collections.Generic;
namespace System.Reflection.Tests
{
public class TypeInfoDeclaredGenericTypeArgumentsTests
{
//Interfaces
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments1()
{
VerifyGenericTypeArguments(typeof(Test_I), new String[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments2()
{
VerifyGenericTypeArguments(typeof(Test_IG<>), new String[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments3()
{
VerifyGenericTypeArguments(typeof(Test_IG<Int32>), new String[] { "Int32" }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments4()
{
VerifyGenericTypeArguments(typeof(Test_IG2<,>), new String[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments5()
{
VerifyGenericTypeArguments(typeof(Test_IG2<Int32, String>), new String[] { "Int32", "String" }, null);
}
// For Structs
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments6()
{
VerifyGenericTypeArguments(typeof(Test_S), new String[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments7()
{
VerifyGenericTypeArguments(typeof(Test_SG<>), new String[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments8()
{
VerifyGenericTypeArguments(typeof(Test_SG<Int32>), new String[] { "Int32" }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments9()
{
VerifyGenericTypeArguments(typeof(Test_SG2<,>), new String[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments10()
{
VerifyGenericTypeArguments(typeof(Test_SG2<Int32, String>), new String[] { "Int32", "String" }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments11()
{
VerifyGenericTypeArguments(typeof(Test_SI), new String[] { }, new String[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments12()
{
VerifyGenericTypeArguments(typeof(Test_SIG<>), new String[] { }, new String[] { "TS" });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments13()
{
VerifyGenericTypeArguments(typeof(Test_SIG<Int32>), new String[] { "Int32" }, new String[] { "Int32" });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments14()
{
VerifyGenericTypeArguments(typeof(Test_SIG2<,>), new String[] { }, new String[] { "TS", "VS" });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments15()
{
VerifyGenericTypeArguments(typeof(Test_SIG2<Int32, String>), new String[] { "Int32", "String" }, new String[] { "Int32", "String" });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments16()
{
VerifyGenericTypeArguments(typeof(Test_SI_Int), new String[] { }, new String[] { "Int32" });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments17()
{
VerifyGenericTypeArguments(typeof(Test_SIG_Int<>), new String[] { }, new String[] { "TS", "Int32" });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments18()
{
VerifyGenericTypeArguments(typeof(Test_SIG_Int<String>), new String[] { "String" }, new String[] { "String", "Int32" });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments19()
{
VerifyGenericTypeArguments(typeof(Test_SIG_Int_Int), new String[] { }, new String[] { "Int32", "Int32" });
}
//For classes
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments20()
{
VerifyGenericTypeArguments(typeof(Test_C), new String[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments21()
{
VerifyGenericTypeArguments(typeof(Test_CG<>), new String[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments22()
{
VerifyGenericTypeArguments(typeof(Test_CG<Int32>), new String[] { "Int32" }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments23()
{
VerifyGenericTypeArguments(typeof(Test_CG2<,>), new String[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments24()
{
VerifyGenericTypeArguments(typeof(Test_CG2<Int32, String>), new String[] { "Int32", "String" }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments25()
{
VerifyGenericTypeArguments(typeof(Test_CI), new String[] { }, new String[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments26()
{
VerifyGenericTypeArguments(typeof(Test_CIG<Int32>), new String[] { "Int32" }, new String[] { "Int32" });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments27()
{
VerifyGenericTypeArguments(typeof(Test_CIG2<,>), new String[] { }, new String[] { "T", "V" });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments28()
{
VerifyGenericTypeArguments(typeof(Test_CIG2<Int32, String>), new String[] { "Int32", "String" }, new String[] { "Int32", "String" });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments29()
{
VerifyGenericTypeArguments(typeof(Test_CI_Int), new String[] { }, new String[] { "Int32" });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments30()
{
VerifyGenericTypeArguments(typeof(Test_CIG_Int<>), new String[] { }, new String[] { "T", "Int32" });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments31()
{
VerifyGenericTypeArguments(typeof(Test_CIG_Int<String>), new String[] { "String" }, new String[] { "String", "Int32" });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericArguments32()
{
VerifyGenericTypeArguments(typeof(Test_CIG_Int_Int), new String[] { }, new String[] { "Int32", "Int32" });
}
//private helper methods
private static void VerifyGenericTypeArguments(Type type, String[] expectedGTA, String[] expectedBaseGTA)
{
//Fix to initialize Reflection
String str = typeof(Object).Name;
TypeInfo typeInfo = type.GetTypeInfo();
Type[] retGenericTypeArguments = typeInfo.GenericTypeArguments;
Assert.Equal(expectedGTA.Length, retGenericTypeArguments.Length);
for (int i = 0; i < retGenericTypeArguments.Length; i++)
{
Assert.Equal(expectedGTA[i], retGenericTypeArguments[i].Name);
}
Type baseType = typeInfo.BaseType;
if (baseType == null)
return;
if (baseType == typeof(ValueType) || baseType == typeof(Object))
{
Type[] interfaces = getInterfaces(typeInfo);
if (interfaces.Length == 0)
return;
baseType = interfaces[0];
}
TypeInfo typeInfoBase = baseType.GetTypeInfo();
retGenericTypeArguments = typeInfoBase.GenericTypeArguments;
Assert.Equal(expectedBaseGTA.Length, retGenericTypeArguments.Length);
for (int i = 0; i < retGenericTypeArguments.Length; i++)
{
Assert.Equal(expectedBaseGTA[i], retGenericTypeArguments[i].Name);
}
}
private static Type[] getInterfaces(TypeInfo ti)
{
List<Type> list = new List<Type>();
IEnumerator<Type> allinterfaces = ti.ImplementedInterfaces.GetEnumerator();
while (allinterfaces.MoveNext())
{
list.Add(allinterfaces.Current);
}
return list.ToArray();
}
}
//Metadata for Reflection
public interface Test_I { }
public interface Test_IG<TI> { }
public interface Test_IG2<TI, VI> { }
public struct Test_S { }
public struct Test_SG<TS> { }
public struct Test_SG2<TS, VS> { }
public struct Test_SI : Test_I { }
public struct Test_SIG<TS> : Test_IG<TS> { }
public struct Test_SIG2<TS, VS> : Test_IG2<TS, VS> { }
public struct Test_SI_Int : Test_IG<Int32> { }
public struct Test_SIG_Int<TS> : Test_IG2<TS, Int32> { }
public struct Test_SIG_Int_Int : Test_IG2<Int32, Int32> { }
public class Test_C { }
public class Test_CG<T> { }
public class Test_CG2<T, V> { }
public class Test_CI : Test_I { }
public class Test_CIG<T> : Test_IG<T> { }
public class Test_CIG2<T, V> : Test_IG2<T, V> { }
public class Test_CI_Int : Test_IG<Int32> { }
public class Test_CIG_Int<T> : Test_CG2<T, Int32> { }
public class Test_CIG_Int_Int : Test_CG2<Int32, Int32> { }
}
| |
using System;
using NUnit.Framework;
using Python.Runtime;
namespace Python.EmbeddingTest
{
public class TestPyLong
{
[OneTimeSetUp]
public void SetUp()
{
PythonEngine.Initialize();
}
[OneTimeTearDown]
public void Dispose()
{
PythonEngine.Shutdown();
}
[Test]
public void TestToInt64()
{
long largeNumber = 8L * 1024L * 1024L * 1024L; // 8 GB
var pyLargeNumber = new PyLong(largeNumber);
Assert.AreEqual(largeNumber, pyLargeNumber.ToInt64());
}
[Test]
public void TestCtorInt()
{
const int i = 5;
var a = new PyLong(i);
Assert.AreEqual(i, a.ToInt32());
}
[Test]
public void TestCtorUInt()
{
const uint i = 5;
var a = new PyLong(i);
Assert.AreEqual(i, a.ToInt32());
}
[Test]
public void TestCtorLong()
{
const long i = 5;
var a = new PyLong(i);
Assert.AreEqual(i, a.ToInt32());
}
[Test]
public void TestCtorULong()
{
const ulong i = 5;
var a = new PyLong(i);
Assert.AreEqual(i, a.ToInt32());
}
[Test]
public void TestCtorShort()
{
const short i = 5;
var a = new PyLong(i);
Assert.AreEqual(i, a.ToInt32());
}
[Test]
public void TestCtorUShort()
{
const ushort i = 5;
var a = new PyLong(i);
Assert.AreEqual(i, a.ToInt32());
}
[Test]
public void TestCtorByte()
{
const byte i = 5;
var a = new PyLong(i);
Assert.AreEqual(i, a.ToInt32());
}
[Test]
public void TestCtorSByte()
{
const sbyte i = 5;
var a = new PyLong(i);
Assert.AreEqual(i, a.ToInt32());
}
[Test]
public void TestCtorDouble()
{
double i = 5.0;
var a = new PyLong(i);
Assert.AreEqual(i, a.ToInt32());
}
[Test]
public void TestCtorPtr()
{
var i = new PyLong(5);
var a = new PyLong(i.Handle);
Assert.AreEqual(5, a.ToInt32());
}
[Test]
public void TestCtorPyObject()
{
var i = new PyLong(5);
var a = new PyLong(i);
Assert.AreEqual(5, a.ToInt32());
}
[Test]
public void TestCtorBadPyObject()
{
var i = new PyString("Foo");
PyLong a = null;
var ex = Assert.Throws<ArgumentException>(() => a = new PyLong(i));
StringAssert.StartsWith("object is not a long", ex.Message);
Assert.IsNull(a);
}
[Test]
public void TestCtorString()
{
const string i = "5";
var a = new PyLong(i);
Assert.AreEqual(5, a.ToInt32());
}
[Test]
public void TestCtorBadString()
{
const string i = "Foo";
PyLong a = null;
var ex = Assert.Throws<PythonException>(() => a = new PyLong(i));
StringAssert.StartsWith("ValueError : invalid literal", ex.Message);
Assert.IsNull(a);
}
[Test]
public void TestIsIntTypeTrue()
{
var i = new PyLong(5);
Assert.True(PyLong.IsLongType(i));
}
[Test]
public void TestIsLongTypeFalse()
{
var s = new PyString("Foo");
Assert.False(PyLong.IsLongType(s));
}
[Test]
public void TestAsLongGood()
{
var i = new PyLong(5);
var a = PyLong.AsLong(i);
Assert.AreEqual(5, a.ToInt32());
}
[Test]
public void TestAsLongBad()
{
var s = new PyString("Foo");
PyLong a = null;
var ex = Assert.Throws<PythonException>(() => a = PyLong.AsLong(s));
StringAssert.StartsWith("ValueError : invalid literal", ex.Message);
Assert.IsNull(a);
}
[Test]
public void TestConvertToInt32()
{
var a = new PyLong(5);
Assert.IsInstanceOf(typeof(int), a.ToInt32());
Assert.AreEqual(5, a.ToInt32());
}
[Test]
public void TestConvertToInt16()
{
var a = new PyLong(5);
Assert.IsInstanceOf(typeof(short), a.ToInt16());
Assert.AreEqual(5, a.ToInt16());
}
[Test]
public void TestConvertToInt64()
{
var a = new PyLong(5);
Assert.IsInstanceOf(typeof(long), a.ToInt64());
Assert.AreEqual(5, a.ToInt64());
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace HalSwaggerSample.WebApp.Proxies
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// ProductOperations operations.
/// </summary>
public partial class ProductOperations : IServiceOperations<HalSwaggerSampleHalApiApp>, IProductOperations
{
/// <summary>
/// Initializes a new instance of the ProductOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public ProductOperations(HalSwaggerSampleHalApiApp client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the HalSwaggerSampleHalApiApp
/// </summary>
public HalSwaggerSampleHalApiApp Client { get; private set; }
/// <summary>
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<ProductCollection>> GetProductsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetProducts", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/products").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<ProductCollection>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<ProductCollection>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// </summary>
/// <param name='productId'>
/// The product Id.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Product>> GetProductWithHttpMessagesAsync(int? productId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (productId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "productId");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("productId", productId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetProduct", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/products/{productId}").ToString();
url = url.Replace("{productId}", Uri.EscapeDataString(JsonConvert.SerializeObject(productId, this.Client.SerializationSettings).Trim('"')));
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<Product>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<Product>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
// 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.
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using WebsitePanel.EnterpriseServer.Base.Common;
using WebsitePanel.Providers.Common;
using Microsoft.Web.Services3;
using WebsitePanel.Providers.DNS;
using WebsitePanel.Server;
using WebsitePanel.Providers.ResultObjects;
using WebsitePanel.Providers;
using WebsitePanel.Providers.DomainLookup;
namespace WebsitePanel.EnterpriseServer
{
/// <summary>
/// Summary description for esApplicationsInstaller
/// </summary>
[WebService(Namespace = "http://smbsaas/websitepanel/enterpriseserver")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Policy("ServerPolicy")]
[ToolboxItem(false)]
public class esServers : System.Web.Services.WebService
{
/*
public const string MAIN_WPI_FEED = "https://www.microsoft.com/web/webpi/4.2/WebProductList.xml";
public const string HELICON_WPI_FEED = "http://www.helicontech.com/zoo/feed/wsp4";
*/
#region Servers
[WebMethod]
public List<ServerInfo> GetAllServers()
{
return ServerController.GetAllServers();
}
[WebMethod]
public DataSet GetRawAllServers()
{
return ServerController.GetRawAllServers();
}
[WebMethod]
public List<ServerInfo> GetServers()
{
return ServerController.GetServers();
}
[WebMethod]
public DataSet GetRawServers()
{
return ServerController.GetRawServers();
}
[WebMethod]
public ServerInfo GetServerShortDetails(int serverId)
{
return ServerController.GetServerShortDetails(serverId);
}
[WebMethod]
public ServerInfo GetServerById(int serverId)
{
return ServerController.GetServerById(serverId);
}
[WebMethod]
public ServerInfo GetServerByName(string serverName)
{
return ServerController.GetServerByName(serverName);
}
[WebMethod]
public int CheckServerAvailable(string serverUrl, string password)
{
return ServerController.CheckServerAvailable(serverUrl, password);
}
[WebMethod]
public int AddServer(ServerInfo server, bool autoDiscovery)
{
return ServerController.AddServer(server, autoDiscovery);
}
[WebMethod]
public int UpdateServer(ServerInfo server)
{
return ServerController.UpdateServer(server);
}
[WebMethod]
public int UpdateServerConnectionPassword(int serverId, string password)
{
return ServerController.UpdateServerConnectionPassword(serverId, password);
}
[WebMethod]
public int UpdateServerADPassword(int serverId, string adPassword)
{
return ServerController.UpdateServerADPassword(serverId, adPassword);
}
[WebMethod]
public int DeleteServer(int serverId)
{
return ServerController.DeleteServer(serverId);
}
#endregion
#region Virtual Servers
[WebMethod]
public DataSet GetVirtualServers()
{
return ServerController.GetVirtualServers();
}
[WebMethod]
public DataSet GetAvailableVirtualServices(int serverId)
{
return ServerController.GetAvailableVirtualServices(serverId);
}
[WebMethod]
public DataSet GetVirtualServices(int serverId)
{
return ServerController.GetVirtualServices(serverId);
}
[WebMethod]
public int AddVirtualServices(int serverId, int[] ids)
{
return ServerController.AddVirtualServices(serverId, ids);
}
[WebMethod]
public int DeleteVirtualServices(int serverId, int[] ids)
{
return ServerController.DeleteVirtualServices(serverId, ids);
}
[WebMethod]
public int UpdateVirtualGroups(int serverId, VirtualGroupInfo[] groups)
{
return ServerController.UpdateVirtualGroups(serverId, groups);
}
#endregion
#region Services
[WebMethod]
public DataSet GetRawServicesByServerId(int serverId)
{
return ServerController.GetRawServicesByServerId(serverId);
}
[WebMethod]
public List<ServiceInfo> GetServicesByServerId(int serverId)
{
return ServerController.GetServicesByServerId(serverId);
}
[WebMethod]
public List<ServiceInfo> GetServicesByServerIdGroupName(int serverId, string groupName)
{
return ServerController.GetServicesByServerIdGroupName(serverId, groupName);
}
[WebMethod]
public DataSet GetRawServicesByGroupId(int groupId)
{
return ServerController.GetRawServicesByGroupId(groupId);
}
[WebMethod]
public DataSet GetRawServicesByGroupName(string groupName)
{
return ServerController.GetRawServicesByGroupName(groupName);
}
[WebMethod]
public ServiceInfo GetServiceInfo(int serviceId)
{
return ServerController.GetServiceInfoAdmin(serviceId);
}
[WebMethod]
public int AddService(ServiceInfo service)
{
return ServerController.AddService(service);
}
[WebMethod]
public int UpdateService(ServiceInfo service)
{
return ServerController.UpdateService(service);
}
[WebMethod]
public int DeleteService(int serviceId)
{
return ServerController.DeleteService(serviceId);
}
[WebMethod]
public string[] GetServiceSettings(int serviceId)
{
return ConvertDictionaryToArray(ServerController.GetServiceSettingsAdmin(serviceId));
}
[WebMethod]
public int UpdateServiceSettings(int serviceId, string[] settings)
{
return ServerController.UpdateServiceSettings(serviceId, settings);
}
[WebMethod]
public string[] InstallService(int serviceId)
{
return ServerController.InstallService(serviceId);
}
[WebMethod]
public QuotaInfo GetProviderServiceQuota(int providerId)
{
return ServerController.GetProviderServiceQuota(providerId);
}
#endregion
#region Providers
[WebMethod]
public List<ProviderInfo> GetInstalledProviders(int groupId)
{
return ServerController.GetInstalledProviders(groupId);
}
[WebMethod]
public List<ResourceGroupInfo> GetResourceGroups()
{
return ServerController.GetResourceGroups();
}
[WebMethod]
public ResourceGroupInfo GetResourceGroup(int groupId)
{
return ServerController.GetResourceGroup(groupId);
}
[WebMethod]
public ProviderInfo GetProvider(int providerId)
{
return ServerController.GetProvider(providerId);
}
[WebMethod]
public List<ProviderInfo> GetProviders()
{
return ServerController.GetProviders();
}
[WebMethod]
public List<ProviderInfo> GetProvidersByGroupId(int groupId)
{
return ServerController.GetProvidersByGroupID(groupId);
}
[WebMethod]
public ProviderInfo GetPackageServiceProvider(int packageId, string groupName)
{
return ServerController.GetPackageServiceProvider(packageId, groupName);
}
[WebMethod]
public BoolResult IsInstalled(int serverId, int providerId)
{
return ServerController.IsInstalled(serverId, providerId);
}
[WebMethod]
public string GetServerVersion(int serverId)
{
return ServerController.GetServerVersion(serverId);
}
#endregion
#region IP Addresses
[WebMethod]
public List<IPAddressInfo> GetIPAddresses(IPAddressPool pool, int serverId)
{
return ServerController.GetIPAddresses(pool, serverId);
}
[WebMethod]
public IPAddressesPaged GetIPAddressesPaged(IPAddressPool pool, int serverId,
string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows)
{
return ServerController.GetIPAddressesPaged(pool, serverId, filterColumn, filterValue, sortColumn, startRow, maximumRows);
}
[WebMethod]
public IPAddressInfo GetIPAddress(int addressId)
{
return ServerController.GetIPAddress(addressId);
}
[WebMethod]
public IntResult AddIPAddress(IPAddressPool pool, int serverId,
string externalIP, string internalIP, string subnetMask, string defaultGateway, string comments)
{
return ServerController.AddIPAddress(pool, serverId, externalIP, internalIP, subnetMask, defaultGateway, comments);
}
[WebMethod]
public ResultObject AddIPAddressesRange(IPAddressPool pool, int serverId,
string externalIP, string endIP, string internalIP, string subnetMask, string defaultGateway, string comments)
{
return ServerController.AddIPAddressesRange(pool, serverId, externalIP, endIP, internalIP, subnetMask, defaultGateway, comments);
}
[WebMethod]
public ResultObject UpdateIPAddress(int addressId, IPAddressPool pool, int serverId,
string externalIP, string internalIP, string subnetMask, string defaultGateway, string comments)
{
return ServerController.UpdateIPAddress(addressId, pool, serverId, externalIP, internalIP, subnetMask, defaultGateway, comments);
}
[WebMethod]
public ResultObject UpdateIPAddresses(int[] addresses, IPAddressPool pool, int serverId,
string subnetMask, string defaultGateway, string comments)
{
return ServerController.UpdateIPAddresses(addresses, pool, serverId, subnetMask, defaultGateway, comments);
}
[WebMethod]
public ResultObject DeleteIPAddress(int addressId)
{
return ServerController.DeleteIPAddress(addressId);
}
[WebMethod]
public ResultObject DeleteIPAddresses(int[] addresses)
{
return ServerController.DeleteIPAddresses(addresses);
}
#endregion
#region Package IP Adderesses
[WebMethod]
public List<IPAddressInfo> GetUnallottedIPAddresses(int packageId, string groupName, IPAddressPool pool)
{
return ServerController.GetUnallottedIPAddresses(packageId, groupName, pool);
}
[WebMethod]
public PackageIPAddressesPaged GetPackageIPAddresses(int packageId, int orgId, IPAddressPool pool,
string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows, bool recursive)
{
return ServerController.GetPackageIPAddresses(packageId, orgId, pool,
filterColumn, filterValue, sortColumn, startRow, maximumRows, recursive);
}
[WebMethod]
public int GetPackageIPAddressesCount(int packageId, int orgId, IPAddressPool pool)
{
return ServerController.GetPackageIPAddressesCount(packageId, orgId, pool);
}
[WebMethod]
public List<PackageIPAddress> GetPackageUnassignedIPAddresses(int packageId, int orgId, IPAddressPool pool)
{
return ServerController.GetPackageUnassignedIPAddresses(packageId, orgId, pool);
}
[WebMethod]
public ResultObject AllocatePackageIPAddresses(int packageId,int orgId, string groupName, IPAddressPool pool, bool allocateRandom, int addressesNumber,
int[] addressId)
{
return ServerController.AllocatePackageIPAddresses(packageId, orgId, groupName, pool, allocateRandom,
addressesNumber, addressId);
}
[WebMethod]
public ResultObject AllocateMaximumPackageIPAddresses(int packageId, string groupName, IPAddressPool pool)
{
return ServerController.AllocateMaximumPackageIPAddresses(packageId, groupName, pool);
}
[WebMethod]
public ResultObject DeallocatePackageIPAddresses(int packageId, int[] addressId)
{
return ServerController.DeallocatePackageIPAddresses(packageId, addressId);
}
#endregion
#region Clusters
[WebMethod]
public List<ClusterInfo> GetClusters()
{
return ServerController.GetClusters();
}
[WebMethod]
public int AddCluster(ClusterInfo cluster)
{
return ServerController.AddCluster(cluster);
}
[WebMethod]
public int DeleteCluster(int clusterId)
{
return ServerController.DeleteCluster(clusterId);
}
#endregion
#region Global DNS records
[WebMethod]
public DataSet GetRawDnsRecordsByService(int serviceId)
{
return ServerController.GetRawDnsRecordsByService(serviceId);
}
[WebMethod]
public DataSet GetRawDnsRecordsByServer(int serverId)
{
return ServerController.GetRawDnsRecordsByServer(serverId);
}
[WebMethod]
public DataSet GetRawDnsRecordsByPackage(int packageId)
{
return ServerController.GetRawDnsRecordsByPackage(packageId);
}
[WebMethod]
public DataSet GetRawDnsRecordsByGroup(int groupId)
{
return ServerController.GetRawDnsRecordsByGroup(groupId);
}
[WebMethod]
public List<GlobalDnsRecord> GetDnsRecordsByService(int serviceId)
{
return ServerController.GetDnsRecordsByService(serviceId);
}
[WebMethod]
public List<GlobalDnsRecord> GetDnsRecordsByServer(int serverId)
{
return ServerController.GetDnsRecordsByServer(serverId);
}
[WebMethod]
public List<GlobalDnsRecord> GetDnsRecordsByPackage(int packageId)
{
return ServerController.GetDnsRecordsByPackage(packageId);
}
[WebMethod]
public List<GlobalDnsRecord> GetDnsRecordsByGroup(int groupId)
{
return ServerController.GetDnsRecordsByGroup(groupId);
}
[WebMethod]
public GlobalDnsRecord GetDnsRecord(int recordId)
{
return ServerController.GetDnsRecord(recordId);
}
[WebMethod]
public int AddDnsRecord(GlobalDnsRecord record)
{
return ServerController.AddDnsRecord(record);
}
[WebMethod]
public int UpdateDnsRecord(GlobalDnsRecord record)
{
return ServerController.UpdateDnsRecord(record);
}
[WebMethod]
public int DeleteDnsRecord(int recordId)
{
return ServerController.DeleteDnsRecord(recordId);
}
#endregion
#region Domains
[WebMethod]
public List<DnsRecordInfo> GetDomainDnsRecords(int domainId)
{
return ServerController.GetDomainDnsRecords(domainId);
}
[WebMethod]
public List<DomainInfo> GetDomains(int packageId)
{
return ServerController.GetDomains(packageId);
}
[WebMethod]
public List<DomainInfo> GetDomainsByDomainId(int domainId)
{
return ServerController.GetDomainsByDomainItemId(domainId);
}
[WebMethod]
public List<DomainInfo> GetMyDomains(int packageId)
{
return ServerController.GetMyDomains(packageId);
}
[WebMethod]
public List<DomainInfo> GetResellerDomains(int packageId)
{
return ServerController.GetResellerDomains(packageId);
}
[WebMethod]
public DataSet GetDomainsPaged(int packageId, int serverId, bool recursive, string filterColumn, string filterValue,
string sortColumn, int startRow, int maximumRows)
{
return ServerController.GetDomainsPaged(packageId, serverId, recursive, filterColumn, filterValue, sortColumn,
startRow, maximumRows);
}
[WebMethod]
public DomainInfo GetDomain(int domainId)
{
return ServerController.GetDomain(domainId);
}
[WebMethod]
public int AddDomain(DomainInfo domain)
{
return ServerController.AddDomain(domain);
}
[WebMethod]
public int AddDomainWithProvisioning(int packageId, string domainName, DomainType domainType,
bool createWebSite, int pointWebSiteId, int pointMailDomainId,
bool createDnsZone, bool createInstantAlias, bool allowSubDomains, string hostName)
{
return ServerController.AddDomainWithProvisioning(packageId, domainName, domainType,
createWebSite, pointWebSiteId, pointMailDomainId,
createDnsZone, createInstantAlias, allowSubDomains, hostName);
}
[WebMethod]
public int UpdateDomain(DomainInfo domain)
{
return ServerController.UpdateDomain(domain);
}
[WebMethod]
public int DeleteDomain(int domainId)
{
return ServerController.DeleteDomain(domainId);
}
[WebMethod]
public int DetachDomain(int domainId)
{
return ServerController.DetachDomain(domainId);
}
[WebMethod]
public int EnableDomainDns(int domainId)
{
return ServerController.EnableDomainDns(domainId);
}
[WebMethod]
public int DisableDomainDns(int domainId)
{
return ServerController.DisableDomainDns(domainId);
}
[WebMethod]
public int CreateDomainInstantAlias(string hostName, int domainId)
{
return ServerController.CreateDomainInstantAlias(hostName, domainId);
}
[WebMethod]
public int DeleteDomainInstantAlias(int domainId)
{
return ServerController.DeleteDomainInstantAlias(domainId);
}
#endregion
#region DNS Zones
[WebMethod]
public DnsRecord[] GetDnsZoneRecords(int domainId)
{
return ServerController.GetDnsZoneRecords(domainId);
}
[WebMethod]
public DataSet GetRawDnsZoneRecords(int domainId)
{
return ServerController.GetRawDnsZoneRecords(domainId);
}
[WebMethod]
public int AddDnsZoneRecord(int domainId, string recordName, DnsRecordType recordType,
string recordData, int mxPriority, int srvPriority, int srvWeight, int srvPortNumber)
{
return ServerController.AddDnsZoneRecord(domainId, recordName, recordType, recordData, mxPriority, srvPriority, srvWeight, srvPortNumber);
}
[WebMethod]
public int UpdateDnsZoneRecord(int domainId,
string originalRecordName, string originalRecordData,
string recordName, DnsRecordType recordType, string recordData, int mxPriority, int srvPriority, int srvWeight, int srvPortNumber)
{
return ServerController.UpdateDnsZoneRecord(domainId, originalRecordName, originalRecordData,
recordName, recordType, recordData, mxPriority, srvPriority, srvWeight, srvPortNumber);
}
[WebMethod]
public int DeleteDnsZoneRecord(int domainId, string recordName, DnsRecordType recordType, string recordData)
{
return ServerController.DeleteDnsZoneRecord(domainId, recordName, recordType, recordData);
}
#endregion
#region Terminal Services Sessions
[WebMethod]
public TerminalSession[] GetTerminalServicesSessions(int serverId)
{
return OperatingSystemController.GetTerminalServicesSessions(serverId);
}
[WebMethod]
public int CloseTerminalServicesSession(int serverId, int sessionId)
{
return OperatingSystemController.CloseTerminalServicesSession(serverId, sessionId);
}
#endregion
#region Windows Processes
[WebMethod]
public WindowsProcess[] GetWindowsProcesses(int serverId)
{
return OperatingSystemController.GetWindowsProcesses(serverId);
}
[WebMethod]
public int TerminateWindowsProcess(int serverId, int pid)
{
return OperatingSystemController.TerminateWindowsProcess(serverId, pid);
}
#endregion
#region Web Platform Installer
[WebMethod]
public bool CheckLoadUserProfile(int serverId)
{
return OperatingSystemController.CheckLoadUserProfile(serverId);
}
[WebMethod]
public void EnableLoadUserProfile(int serverId)
{
OperatingSystemController.EnableLoadUserProfile(serverId);
}
[WebMethod]
public void InitWPIFeeds(int serverId)
{
var wpiSettings = SystemController.GetSystemSettings(SystemSettings.WPI_SETTINGS);
List<string> feeds = new List<string>();
// Microsoft feed
string mainFeedUrl = wpiSettings[SystemSettings.WPI_MAIN_FEED_KEY];
if (string.IsNullOrEmpty(mainFeedUrl))
{
mainFeedUrl = WebPlatformInstaller.MAIN_FEED_URL;
}
feeds.Add(mainFeedUrl);
// Zoo Feed
feeds.Add(WebPlatformInstaller.ZOO_FEED);
// additional feeds
string additionalFeeds = wpiSettings[SystemSettings.FEED_ULS_KEY];
if (!string.IsNullOrEmpty(additionalFeeds))
{
feeds.AddRange(additionalFeeds.Split(';'));
}
OperatingSystemController.InitWPIFeeds(serverId, string.Join(";", feeds));
}
[WebMethod]
public WPITab[] GetWPITabs(int serverId)
{
InitWPIFeeds(serverId);
return OperatingSystemController.GetWPITabs(serverId);
}
[WebMethod]
public WPIKeyword[] GetWPIKeywords(int serverId)
{
InitWPIFeeds(serverId);
return OperatingSystemController.GetWPIKeywords(serverId);
}
[WebMethod]
public WPIProduct[] GetWPIProducts(int serverId, string tabId, string keywordId)
{
InitWPIFeeds(serverId);
return OperatingSystemController.GetWPIProducts(serverId, tabId, keywordId);
}
[WebMethod]
public WPIProduct[] GetWPIProductsFiltered(int serverId, string keywordId)
{
InitWPIFeeds(serverId);
return OperatingSystemController.GetWPIProductsFiltered(serverId, keywordId);
}
[WebMethod]
public WPIProduct GetWPIProductById(int serverId, string productdId)
{
InitWPIFeeds(serverId);
return OperatingSystemController.GetWPIProductById(serverId, productdId);
}
[WebMethod]
public WPIProduct[] GetWPIProductsWithDependencies(int serverId, string[] products)
{
InitWPIFeeds(serverId);
return OperatingSystemController.GetWPIProductsWithDependencies(serverId, products);
}
[WebMethod]
public void InstallWPIProducts(int serverId, string[] products)
{
InitWPIFeeds(serverId);
OperatingSystemController.InstallWPIProducts(serverId, products);
}
[WebMethod]
public void CancelInstallWPIProducts(int serviceId)
{
OperatingSystemController.CancelInstallWPIProducts(serviceId);
}
[WebMethod]
public string GetWPIStatus(int serverId)
{
return OperatingSystemController.GetWPIStatus(serverId);
}
[WebMethod]
public string WpiGetLogFileDirectory(int serverId)
{
return OperatingSystemController.WpiGetLogFileDirectory(serverId);
}
[WebMethod]
public SettingPair[] WpiGetLogsInDirectory(int serverId, string Path)
{
return OperatingSystemController.WpiGetLogsInDirectory(serverId, Path);
}
#endregion
#region Windows Services
[WebMethod]
public WindowsService[] GetWindowsServices(int serverId)
{
return OperatingSystemController.GetWindowsServices(serverId);
}
[WebMethod]
public int ChangeWindowsServiceStatus(int serverId, string id, WindowsServiceStatus status)
{
return OperatingSystemController.ChangeWindowsServiceStatus(serverId, id, status);
}
#endregion
#region Event Viewer
[WebMethod]
public string[] GetLogNames(int serverId)
{
return OperatingSystemController.GetLogNames(serverId);
}
[WebMethod]
public SystemLogEntry[] GetLogEntries(int serverId, string logName)
{
return OperatingSystemController.GetLogEntries(serverId, logName);
}
[WebMethod]
public SystemLogEntriesPaged GetLogEntriesPaged(int serverId, string logName, int startRow, int maximumRows)
{
return OperatingSystemController.GetLogEntriesPaged(serverId, logName, startRow, maximumRows);
}
[WebMethod]
public int ClearLog(int serverId, string logName)
{
return OperatingSystemController.ClearLog(serverId, logName);
}
#endregion
#region Server Reboot
[WebMethod]
public int RebootSystem(int serverId)
{
return OperatingSystemController.RebootSystem(serverId);
}
#endregion
#region Helper methods
private string[] ConvertDictionaryToArray(StringDictionary settings)
{
List<string> r = new List<string>();
foreach (string key in settings.Keys)
r.Add(key + "=" + settings[key]);
return r.ToArray();
}
private StringDictionary ConvertArrayToDictionary(string[] settings)
{
StringDictionary r = new StringDictionary();
foreach (string setting in settings)
{
int idx = setting.IndexOf('=');
r.Add(setting.Substring(0, idx), setting.Substring(idx + 1));
}
return r;
}
#endregion
}
}
| |
using YAF.Lucene.Net.Support;
using System;
using System.Diagnostics;
using BitUtil = YAF.Lucene.Net.Util.BitUtil;
namespace YAF.Lucene.Net.Codecs.Lucene40
{
/*
* 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 ChecksumIndexInput = YAF.Lucene.Net.Store.ChecksumIndexInput;
using CompoundFileDirectory = YAF.Lucene.Net.Store.CompoundFileDirectory;
using Directory = YAF.Lucene.Net.Store.Directory;
using IndexInput = YAF.Lucene.Net.Store.IndexInput;
using IndexOutput = YAF.Lucene.Net.Store.IndexOutput;
using IOContext = YAF.Lucene.Net.Store.IOContext;
using IOUtils = YAF.Lucene.Net.Util.IOUtils;
using IMutableBits = YAF.Lucene.Net.Util.IMutableBits;
/// <summary>
/// Optimized implementation of a vector of bits. This is more-or-less like
/// <c>java.util.BitSet</c>, but also includes the following:
/// <list type="bullet">
/// <item><description>a count() method, which efficiently computes the number of one bits;</description></item>
/// <item><description>optimized read from and write to disk;</description></item>
/// <item><description>inlinable get() method;</description></item>
/// <item><description>store and load, as bit set or d-gaps, depending on sparseness;</description></item>
/// </list>
/// <para/>
/// @lucene.internal
/// </summary>
// pkg-private: if this thing is generally useful then it can go back in .util,
// but the serialization must be here underneath the codec.
internal sealed class BitVector : IMutableBits
#if FEATURE_CLONEABLE
, System.ICloneable
#endif
{
private byte[] bits;
private int size;
private int count;
private int version;
/// <summary>
/// Constructs a vector capable of holding <paramref name="n"/> bits. </summary>
public BitVector(int n)
{
size = n;
bits = new byte[GetNumBytes(size)];
count = 0;
}
internal BitVector(byte[] bits, int size)
{
this.bits = bits;
this.size = size;
count = -1;
}
private int GetNumBytes(int size)
{
int bytesLength = (int)((uint)size >> 3);
if ((size & 7) != 0)
{
bytesLength++;
}
return bytesLength;
}
public object Clone()
{
byte[] copyBits = new byte[bits.Length];
Array.Copy(bits, 0, copyBits, 0, bits.Length);
BitVector clone = new BitVector(copyBits, size);
clone.count = count;
return clone;
}
/// <summary>
/// Sets the value of <paramref name="bit"/> to one. </summary>
public void Set(int bit)
{
if (bit >= size)
{
throw new System.IndexOutOfRangeException("bit=" + bit + " size=" + size);
}
bits[bit >> 3] |= (byte)(1 << (bit & 7));
count = -1;
}
/// <summary>
/// Sets the value of <paramref name="bit"/> to <c>true</c>, and
/// returns <c>true</c> if bit was already set.
/// </summary>
public bool GetAndSet(int bit)
{
if (bit >= size)
{
throw new System.IndexOutOfRangeException("bit=" + bit + " size=" + size);
}
int pos = bit >> 3;
int v = bits[pos];
int flag = 1 << (bit & 7);
if ((flag & v) != 0)
{
return true;
}
else
{
bits[pos] = (byte)(v | flag);
if (count != -1)
{
count++;
Debug.Assert(count <= size);
}
return false;
}
}
/// <summary>
/// Sets the value of <paramref name="bit"/> to zero. </summary>
public void Clear(int bit)
{
if (bit >= size)
{
throw new System.IndexOutOfRangeException(bit.ToString());
}
bits[bit >> 3] &= (byte)(~(1 << (bit & 7)));
count = -1;
}
public bool GetAndClear(int bit)
{
if (bit >= size)
{
throw new System.IndexOutOfRangeException(bit.ToString());
}
int pos = bit >> 3;
int v = bits[pos];
int flag = 1 << (bit & 7);
if ((flag & v) == 0)
{
return false;
}
else
{
bits[pos] &= (byte)(~flag);
if (count != -1)
{
count--;
Debug.Assert(count >= 0);
}
return true;
}
}
/// <summary>
/// Returns <c>true</c> if <paramref name="bit"/> is one and
/// <c>false</c> if it is zero.
/// </summary>
public bool Get(int bit)
{
Debug.Assert(bit >= 0 && bit < size, "bit " + bit + " is out of bounds 0.." + (size - 1));
return (bits[bit >> 3] & (1 << (bit & 7))) != 0;
}
// LUCENENET specific - removing this because 1) size is not .NETified and 2) it is identical to Length anyway
///// <summary>
///// Returns the number of bits in this vector. this is also one greater than
///// the number of the largest valid bit number.
///// </summary>
//public int Size()
//{
// return Size_Renamed;
//}
/// <summary>
/// Returns the number of bits in this vector. This is also one greater than
/// the number of the largest valid bit number.
/// <para/>
/// This is the equivalent of either size() or length() in Lucene.
/// </summary>
public int Length
{
get { return size; }
}
/// <summary>
/// Returns the total number of one bits in this vector. This is efficiently
/// computed and cached, so that, if the vector is not changed, no
/// recomputation is done for repeated calls.
/// </summary>
public int Count()
{
// if the vector has been modified
if (count == -1)
{
int c = 0;
int end = bits.Length;
for (int i = 0; i < end; i++)
{
c += BitUtil.BitCount(bits[i]); // sum bits per byte
}
count = c;
}
Debug.Assert(count <= size, "count=" + count + " size=" + size);
return count;
}
/// <summary>
/// For testing </summary>
public int GetRecomputedCount()
{
int c = 0;
int end = bits.Length;
for (int i = 0; i < end; i++)
{
c += BitUtil.BitCount(bits[i]); // sum bits per byte
}
return c;
}
private static string CODEC = "BitVector";
// Version before version tracking was added:
public readonly static int VERSION_PRE = -1;
// First version:
public readonly static int VERSION_START = 0;
// Changed DGaps to encode gaps between cleared bits, not
// set:
public readonly static int VERSION_DGAPS_CLEARED = 1;
// added checksum
public readonly static int VERSION_CHECKSUM = 2;
// Increment version to change it:
public readonly static int VERSION_CURRENT = VERSION_CHECKSUM;
public int Version
{
get
{
return version;
}
}
/// <summary>
/// Writes this vector to the file <paramref name="name"/> in Directory
/// <paramref name="d"/>, in a format that can be read by the constructor
/// <see cref="BitVector(Directory, string, IOContext)"/>.
/// </summary>
public void Write(Directory d, string name, IOContext context)
{
Debug.Assert(!(d is CompoundFileDirectory));
IndexOutput output = d.CreateOutput(name, context);
try
{
output.WriteInt32(-2);
CodecUtil.WriteHeader(output, CODEC, VERSION_CURRENT);
if (IsSparse)
{
// sparse bit-set more efficiently saved as d-gaps.
WriteClearedDgaps(output);
}
else
{
WriteBits(output);
}
CodecUtil.WriteFooter(output);
bool verified = VerifyCount();
Debug.Assert(verified);
}
finally
{
IOUtils.Dispose(output);
}
}
/// <summary>
/// Invert all bits. </summary>
public void InvertAll()
{
if (count != -1)
{
count = size - count;
}
if (bits.Length > 0)
{
for (int idx = 0; idx < bits.Length; idx++)
{
bits[idx] = (byte)(~bits[idx]);
}
ClearUnusedBits();
}
}
private void ClearUnusedBits()
{
// Take care not to invert the "unused" bits in the
// last byte:
if (bits.Length > 0)
{
int lastNBits = size & 7;
if (lastNBits != 0)
{
int mask = (1 << lastNBits) - 1;
bits[bits.Length - 1] &= (byte)mask;
}
}
}
/// <summary>
/// Set all bits. </summary>
public void SetAll()
{
Arrays.Fill(bits, (byte)0xff);
ClearUnusedBits();
count = size;
}
/// <summary>
/// Write as a bit set. </summary>
private void WriteBits(IndexOutput output)
{
output.WriteInt32(Length); // write size
output.WriteInt32(Count()); // write count
output.WriteBytes(bits, bits.Length);
}
/// <summary>
/// Write as a d-gaps list. </summary>
private void WriteClearedDgaps(IndexOutput output)
{
output.WriteInt32(-1); // mark using d-gaps
output.WriteInt32(Length); // write size
output.WriteInt32(Count()); // write count
int last = 0;
int numCleared = Length - Count();
for (int i = 0; i < bits.Length && numCleared > 0; i++)
{
if (bits[i] != 0xff)
{
output.WriteVInt32(i - last);
output.WriteByte(bits[i]);
last = i;
numCleared -= (8 - BitUtil.BitCount(bits[i]));
Debug.Assert(numCleared >= 0 || (i == (bits.Length - 1) && numCleared == -(8 - (size & 7))));
}
}
}
/// <summary>
/// Indicates if the bit vector is sparse and should be saved as a d-gaps list, or dense, and should be saved as a bit set. </summary>
private bool IsSparse
{
get
{
int clearedCount = Length - Count();
if (clearedCount == 0)
{
return true;
}
int avgGapLength = bits.Length / clearedCount;
// expected number of bytes for vInt encoding of each gap
int expectedDGapBytes;
if (avgGapLength <= (1 << 7))
{
expectedDGapBytes = 1;
}
else if (avgGapLength <= (1 << 14))
{
expectedDGapBytes = 2;
}
else if (avgGapLength <= (1 << 21))
{
expectedDGapBytes = 3;
}
else if (avgGapLength <= (1 << 28))
{
expectedDGapBytes = 4;
}
else
{
expectedDGapBytes = 5;
}
// +1 because we write the byte itself that contains the
// set bit
int bytesPerSetBit = expectedDGapBytes + 1;
// note: adding 32 because we start with ((int) -1) to indicate d-gaps format.
long expectedBits = 32 + 8 * bytesPerSetBit * clearedCount;
// note: factor is for read/write of byte-arrays being faster than vints.
const long factor = 10;
return factor * expectedBits < Length;
}
}
/// <summary>
/// Constructs a bit vector from the file <paramref name="name"/> in Directory
/// <paramref name="d"/>, as written by the <see cref="Write(Directory, string, IOContext)"/> method.
/// </summary>
public BitVector(Directory d, string name, IOContext context)
{
ChecksumIndexInput input = d.OpenChecksumInput(name, context);
try
{
int firstInt = input.ReadInt32();
if (firstInt == -2)
{
// New format, with full header & version:
version = CodecUtil.CheckHeader(input, CODEC, VERSION_START, VERSION_CURRENT);
size = input.ReadInt32();
}
else
{
version = VERSION_PRE;
size = firstInt;
}
if (size == -1)
{
if (version >= VERSION_DGAPS_CLEARED)
{
ReadClearedDgaps(input);
}
else
{
ReadSetDgaps(input);
}
}
else
{
ReadBits(input);
}
if (version < VERSION_DGAPS_CLEARED)
{
InvertAll();
}
if (version >= VERSION_CHECKSUM)
{
CodecUtil.CheckFooter(input);
}
else
{
#pragma warning disable 612, 618
CodecUtil.CheckEOF(input);
#pragma warning restore 612, 618
}
bool verified = VerifyCount();
Debug.Assert(verified);
}
finally
{
input.Dispose();
}
}
// asserts only
private bool VerifyCount()
{
Debug.Assert(count != -1);
int countSav = count;
count = -1;
bool checkCount = countSav == Count();
Debug.Assert(checkCount, "saved count was " + countSav + " but recomputed count is " + count);
return true;
}
/// <summary>
/// Read as a bit set. </summary>
private void ReadBits(IndexInput input)
{
count = input.ReadInt32(); // read count
bits = new byte[GetNumBytes(size)]; // allocate bits
input.ReadBytes(bits, 0, bits.Length);
}
/// <summary>
/// Read as a d-gaps list. </summary>
private void ReadSetDgaps(IndexInput input)
{
size = input.ReadInt32(); // (re)read size
count = input.ReadInt32(); // read count
bits = new byte[GetNumBytes(size)]; // allocate bits
int last = 0;
int n = Count();
while (n > 0)
{
last += input.ReadVInt32();
bits[last] = input.ReadByte();
n -= BitUtil.BitCount(bits[last]);
Debug.Assert(n >= 0);
}
}
/// <summary>
/// Read as a d-gaps cleared bits list. </summary>
private void ReadClearedDgaps(IndexInput input)
{
size = input.ReadInt32(); // (re)read size
count = input.ReadInt32(); // read count
bits = new byte[GetNumBytes(size)]; // allocate bits
for (int i = 0; i < bits.Length; ++i)
{
bits[i] = 0xff;
}
ClearUnusedBits();
int last = 0;
int numCleared = Length - Count();
while (numCleared > 0)
{
last += input.ReadVInt32();
bits[last] = input.ReadByte();
numCleared -= 8 - BitUtil.BitCount(bits[last]);
Debug.Assert(numCleared >= 0 || (last == (bits.Length - 1) && numCleared == -(8 - (size & 7))));
}
}
}
}
| |
/*
* Copyright 2008 ZXing authors
*
* 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.Text;
using ZXing.Common;
using ZXing.Core;
namespace ZXing.OneD
{
/// <summary>
/// <p>Decodes Code 128 barcodes.</p>
///
/// <author>Sean Owen</author>
/// </summary>
public sealed class Code128Reader : OneDReader
{
internal static int[][] CODE_PATTERNS = {
new[] {2, 1, 2, 2, 2, 2}, // 0
new[] {2, 2, 2, 1, 2, 2},
new[] {2, 2, 2, 2, 2, 1},
new[] {1, 2, 1, 2, 2, 3},
new[] {1, 2, 1, 3, 2, 2},
new[] {1, 3, 1, 2, 2, 2}, // 5
new[] {1, 2, 2, 2, 1, 3},
new[] {1, 2, 2, 3, 1, 2},
new[] {1, 3, 2, 2, 1, 2},
new[] {2, 2, 1, 2, 1, 3},
new[] {2, 2, 1, 3, 1, 2}, // 10
new[] {2, 3, 1, 2, 1, 2},
new[] {1, 1, 2, 2, 3, 2},
new[] {1, 2, 2, 1, 3, 2},
new[] {1, 2, 2, 2, 3, 1},
new[] {1, 1, 3, 2, 2, 2}, // 15
new[] {1, 2, 3, 1, 2, 2},
new[] {1, 2, 3, 2, 2, 1},
new[] {2, 2, 3, 2, 1, 1},
new[] {2, 2, 1, 1, 3, 2},
new[] {2, 2, 1, 2, 3, 1}, // 20
new[] {2, 1, 3, 2, 1, 2},
new[] {2, 2, 3, 1, 1, 2},
new[] {3, 1, 2, 1, 3, 1},
new[] {3, 1, 1, 2, 2, 2},
new[] {3, 2, 1, 1, 2, 2}, // 25
new[] {3, 2, 1, 2, 2, 1},
new[] {3, 1, 2, 2, 1, 2},
new[] {3, 2, 2, 1, 1, 2},
new[] {3, 2, 2, 2, 1, 1},
new[] {2, 1, 2, 1, 2, 3}, // 30
new[] {2, 1, 2, 3, 2, 1},
new[] {2, 3, 2, 1, 2, 1},
new[] {1, 1, 1, 3, 2, 3},
new[] {1, 3, 1, 1, 2, 3},
new[] {1, 3, 1, 3, 2, 1}, // 35
new[] {1, 1, 2, 3, 1, 3},
new[] {1, 3, 2, 1, 1, 3},
new[] {1, 3, 2, 3, 1, 1},
new[] {2, 1, 1, 3, 1, 3},
new[] {2, 3, 1, 1, 1, 3}, // 40
new[] {2, 3, 1, 3, 1, 1},
new[] {1, 1, 2, 1, 3, 3},
new[] {1, 1, 2, 3, 3, 1},
new[] {1, 3, 2, 1, 3, 1},
new[] {1, 1, 3, 1, 2, 3}, // 45
new[] {1, 1, 3, 3, 2, 1},
new[] {1, 3, 3, 1, 2, 1},
new[] {3, 1, 3, 1, 2, 1},
new[] {2, 1, 1, 3, 3, 1},
new[] {2, 3, 1, 1, 3, 1}, // 50
new[] {2, 1, 3, 1, 1, 3},
new[] {2, 1, 3, 3, 1, 1},
new[] {2, 1, 3, 1, 3, 1},
new[] {3, 1, 1, 1, 2, 3},
new[] {3, 1, 1, 3, 2, 1}, // 55
new[] {3, 3, 1, 1, 2, 1},
new[] {3, 1, 2, 1, 1, 3},
new[] {3, 1, 2, 3, 1, 1},
new[] {3, 3, 2, 1, 1, 1},
new[] {3, 1, 4, 1, 1, 1}, // 60
new[] {2, 2, 1, 4, 1, 1},
new[] {4, 3, 1, 1, 1, 1},
new[] {1, 1, 1, 2, 2, 4},
new[] {1, 1, 1, 4, 2, 2},
new[] {1, 2, 1, 1, 2, 4}, // 65
new[] {1, 2, 1, 4, 2, 1},
new[] {1, 4, 1, 1, 2, 2},
new[] {1, 4, 1, 2, 2, 1},
new[] {1, 1, 2, 2, 1, 4},
new[] {1, 1, 2, 4, 1, 2}, // 70
new[] {1, 2, 2, 1, 1, 4},
new[] {1, 2, 2, 4, 1, 1},
new[] {1, 4, 2, 1, 1, 2},
new[] {1, 4, 2, 2, 1, 1},
new[] {2, 4, 1, 2, 1, 1}, // 75
new[] {2, 2, 1, 1, 1, 4},
new[] {4, 1, 3, 1, 1, 1},
new[] {2, 4, 1, 1, 1, 2},
new[] {1, 3, 4, 1, 1, 1},
new[] {1, 1, 1, 2, 4, 2}, // 80
new[] {1, 2, 1, 1, 4, 2},
new[] {1, 2, 1, 2, 4, 1},
new[] {1, 1, 4, 2, 1, 2},
new[] {1, 2, 4, 1, 1, 2},
new[] {1, 2, 4, 2, 1, 1}, // 85
new[] {4, 1, 1, 2, 1, 2},
new[] {4, 2, 1, 1, 1, 2},
new[] {4, 2, 1, 2, 1, 1},
new[] {2, 1, 2, 1, 4, 1},
new[] {2, 1, 4, 1, 2, 1}, // 90
new[] {4, 1, 2, 1, 2, 1},
new[] {1, 1, 1, 1, 4, 3},
new[] {1, 1, 1, 3, 4, 1},
new[] {1, 3, 1, 1, 4, 1},
new[] {1, 1, 4, 1, 1, 3}, // 95
new[] {1, 1, 4, 3, 1, 1},
new[] {4, 1, 1, 1, 1, 3},
new[] {4, 1, 1, 3, 1, 1},
new[] {1, 1, 3, 1, 4, 1},
new[] {1, 1, 4, 1, 3, 1}, // 100
new[] {3, 1, 1, 1, 4, 1},
new[] {4, 1, 1, 1, 3, 1},
new[] {2, 1, 1, 4, 1, 2},
new[] {2, 1, 1, 2, 1, 4},
new[] {2, 1, 1, 2, 3, 2}, // 105
new[] {2, 3, 3, 1, 1, 1, 2}
};
private static readonly int MAX_AVG_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.25f);
private static readonly int MAX_INDIVIDUAL_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f);
private const int CODE_SHIFT = 98;
private const int CODE_CODE_C = 99;
private const int CODE_CODE_B = 100;
private const int CODE_CODE_A = 101;
private const int CODE_FNC_1 = 102;
private const int CODE_FNC_2 = 97;
private const int CODE_FNC_3 = 96;
private const int CODE_FNC_4_A = 101;
private const int CODE_FNC_4_B = 100;
private const int CODE_START_A = 103;
private const int CODE_START_B = 104;
private const int CODE_START_C = 105;
private const int CODE_STOP = 106;
private static int[] findStartPattern(BitArray row)
{
int width = row.Size;
int rowOffset = row.getNextSet(0);
int counterPosition = 0;
int[] counters = new int[6];
int patternStart = rowOffset;
bool isWhite = false;
int patternLength = counters.Length;
for (int i = rowOffset; i < width; i++)
{
if (row[i] ^ isWhite)
{
counters[counterPosition]++;
}
else
{
if (counterPosition == patternLength - 1)
{
int bestVariance = MAX_AVG_VARIANCE;
int bestMatch = -1;
for (int startCode = CODE_START_A; startCode <= CODE_START_C; startCode++)
{
int variance = patternMatchVariance(counters, CODE_PATTERNS[startCode],
MAX_INDIVIDUAL_VARIANCE);
if (variance < bestVariance)
{
bestVariance = variance;
bestMatch = startCode;
}
}
if (bestMatch >= 0)
{
// Look for whitespace before start pattern, >= 50% of width of start pattern
if (row.isRange(Math.Max(0, patternStart - (i - patternStart) / 2), patternStart,
false))
{
return new int[] { patternStart, i, bestMatch };
}
}
patternStart += counters[0] + counters[1];
Array.Copy(counters, 2, counters, 0, patternLength - 2);
counters[patternLength - 2] = 0;
counters[patternLength - 1] = 0;
counterPosition--;
}
else
{
counterPosition++;
}
counters[counterPosition] = 1;
isWhite = !isWhite;
}
}
return null;
}
private static bool decodeCode(BitArray row, int[] counters, int rowOffset, out int code)
{
code = -1;
if (!recordPattern(row, rowOffset, counters))
return false;
int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
for (int d = 0; d < CODE_PATTERNS.Length; d++)
{
int[] pattern = CODE_PATTERNS[d];
int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
if (variance < bestVariance)
{
bestVariance = variance;
code = d;
}
}
// TODO We're overlooking the fact that the STOP pattern has 7 values, not 6.
return code >= 0;
}
override public Result decodeRow(int rowNumber, BitArray row, IDictionary<DecodeHintType, object> hints)
{
bool convertFNC1 = hints != null && hints.ContainsKey(DecodeHintType.ASSUME_GS1);
int[] startPatternInfo = findStartPattern(row);
if (startPatternInfo == null)
return null;
int startCode = startPatternInfo[2];
var rawCodes = new List<byte>(20);
rawCodes.Add((byte)startCode);
int codeSet;
switch (startCode)
{
case CODE_START_A:
codeSet = CODE_CODE_A;
break;
case CODE_START_B:
codeSet = CODE_CODE_B;
break;
case CODE_START_C:
codeSet = CODE_CODE_C;
break;
default:
return null;
}
bool done = false;
bool isNextShifted = false;
var result = new StringBuilder(20);
int lastStart = startPatternInfo[0];
int nextStart = startPatternInfo[1];
int[] counters = new int[6];
int lastCode = 0;
int code = 0;
int checksumTotal = startCode;
int multiplier = 0;
bool lastCharacterWasPrintable = true;
bool upperMode = false;
bool shiftUpperMode = false;
while (!done)
{
bool unshift = isNextShifted;
isNextShifted = false;
// Save off last code
lastCode = code;
// Decode another code from image
if (!decodeCode(row, counters, nextStart, out code))
return null;
rawCodes.Add((byte)code);
// Remember whether the last code was printable or not (excluding CODE_STOP)
if (code != CODE_STOP)
{
lastCharacterWasPrintable = true;
}
// Add to checksum computation (if not CODE_STOP of course)
if (code != CODE_STOP)
{
multiplier++;
checksumTotal += multiplier * code;
}
// Advance to where the next code will to start
lastStart = nextStart;
foreach (int counter in counters)
{
nextStart += counter;
}
// Take care of illegal start codes
switch (code)
{
case CODE_START_A:
case CODE_START_B:
case CODE_START_C:
return null;
}
switch (codeSet)
{
case CODE_CODE_A:
if (code < 64)
{
if (shiftUpperMode == upperMode)
{
result.Append((char) (' ' + code));
}
else
{
result.Append((char) (' ' + code + 128));
}
shiftUpperMode = false;
}
else if (code < 96)
{
if (shiftUpperMode == upperMode)
{
result.Append((char) (code - 64));
}
else
{
result.Append((char) (code + 64));
}
shiftUpperMode = false;
}
else
{
// Don't let CODE_STOP, which always appears, affect whether whether we think the last
// code was printable or not.
if (code != CODE_STOP)
{
lastCharacterWasPrintable = false;
}
switch (code)
{
case CODE_FNC_1:
if (convertFNC1)
{
if (result.Length == 0)
{
// GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code
// is FNC1 then this is GS1-128. We add the symbology identifier.
result.Append("]C1");
}
else
{
// GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS)
result.Append((char) 29);
}
}
break;
case CODE_FNC_2:
case CODE_FNC_3:
// do nothing?
break;
case CODE_FNC_4_A:
if (!upperMode && shiftUpperMode)
{
upperMode = true;
shiftUpperMode = false;
}
else if (upperMode && shiftUpperMode)
{
upperMode = false;
shiftUpperMode = false;
}
else
{
shiftUpperMode = true;
}
break;
case CODE_SHIFT:
isNextShifted = true;
codeSet = CODE_CODE_B;
break;
case CODE_CODE_B:
codeSet = CODE_CODE_B;
break;
case CODE_CODE_C:
codeSet = CODE_CODE_C;
break;
case CODE_STOP:
done = true;
break;
}
}
break;
case CODE_CODE_B:
if (code < 96)
{
if (shiftUpperMode == upperMode)
{
result.Append((char)(' ' + code));
}
else
{
result.Append((char)(' ' + code + 128));
}
shiftUpperMode = false;
}
else
{
if (code != CODE_STOP)
{
lastCharacterWasPrintable = false;
}
switch (code)
{
case CODE_FNC_1:
if (convertFNC1)
{
if (result.Length == 0)
{
// GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code
// is FNC1 then this is GS1-128. We add the symbology identifier.
result.Append("]C1");
}
else
{
// GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS)
result.Append((char)29);
}
}
break;
case CODE_FNC_2:
case CODE_FNC_3:
// do nothing?
break;
case CODE_FNC_4_B:
if (!upperMode && shiftUpperMode)
{
upperMode = true;
shiftUpperMode = false;
}
else if (upperMode && shiftUpperMode)
{
upperMode = false;
shiftUpperMode = false;
}
else
{
shiftUpperMode = true;
}
break;
case CODE_SHIFT:
isNextShifted = true;
codeSet = CODE_CODE_A;
break;
case CODE_CODE_A:
codeSet = CODE_CODE_A;
break;
case CODE_CODE_C:
codeSet = CODE_CODE_C;
break;
case CODE_STOP:
done = true;
break;
}
}
break;
case CODE_CODE_C:
if (code < 100)
{
if (code < 10)
{
result.Append('0');
}
result.Append(code);
}
else
{
if (code != CODE_STOP)
{
lastCharacterWasPrintable = false;
}
switch (code)
{
case CODE_FNC_1:
if (convertFNC1)
{
if (result.Length == 0)
{
// GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code
// is FNC1 then this is GS1-128. We add the symbology identifier.
result.Append("]C1");
}
else
{
// GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS)
result.Append((char) 29);
}
}
break;
case CODE_CODE_A:
codeSet = CODE_CODE_A;
break;
case CODE_CODE_B:
codeSet = CODE_CODE_B;
break;
case CODE_STOP:
done = true;
break;
}
}
break;
}
// Unshift back to another code set if we were shifted
if (unshift)
{
codeSet = codeSet == CODE_CODE_A ? CODE_CODE_B : CODE_CODE_A;
}
}
int lastPatternSize = nextStart - lastStart;
// Check for ample whitespace following pattern, but, to do this we first need to remember that
// we fudged decoding CODE_STOP since it actually has 7 bars, not 6. There is a black bar left
// to read off. Would be slightly better to properly read. Here we just skip it:
nextStart = row.getNextUnset(nextStart);
if (!row.isRange(nextStart,
Math.Min(row.Size, nextStart + (nextStart - lastStart) / 2),
false))
{
return null;
}
// Pull out from sum the value of the penultimate check code
checksumTotal -= multiplier * lastCode;
// lastCode is the checksum then:
if (checksumTotal % 103 != lastCode)
{
return null;
}
// Need to pull out the check digits from string
int resultLength = result.Length;
if (resultLength == 0)
{
// false positive
return null;
}
// Only bother if the result had at least one character, and if the checksum digit happened to
// be a printable character. If it was just interpreted as a control code, nothing to remove.
if (resultLength > 0 && lastCharacterWasPrintable)
{
if (codeSet == CODE_CODE_C)
{
result.Remove(resultLength - 2, 2);
}
else
{
result.Remove(resultLength - 1, 1);
}
}
float left = (startPatternInfo[1] + startPatternInfo[0]) / 2.0f;
float right = lastStart + lastPatternSize / 2.0f;
var resultPointCallback = hints == null || !hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)
? null
: (ResultPointCallback)hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
if (resultPointCallback != null)
{
resultPointCallback(new ResultPoint(left, rowNumber));
resultPointCallback(new ResultPoint(right, rowNumber));
}
int rawCodesSize = rawCodes.Count;
var rawBytes = new byte[rawCodesSize];
for (int i = 0; i < rawCodesSize; i++)
{
rawBytes[i] = rawCodes[i];
}
return new Result(
result.ToString(),
rawBytes,
new []
{
new ResultPoint(left, rowNumber),
new ResultPoint(right, rowNumber)
},
BarcodeFormat.CODE_128);
}
}
}
| |
using System;
using Esiur.Resource;
using Esiur.Core;
using Esiur.Data;
using Esiur.Net.IIP;
namespace Test {
public class MyService : DistributedResource {
public MyService(DistributedConnection connection, uint instanceId, ulong age, string link) : base(connection, instanceId, age, link) {}
public MyService() {}
public AsyncReply<object> Void() {
var rt = new AsyncReply<object>();
_InvokeByArrayArguments(0, new object[] { })
.Then(x => rt.Trigger((object)x))
.Error(x => rt.TriggerError(x))
.Chunk(x => rt.TriggerChunk(x));
return rt; }
public AsyncReply<object> InvokeEvents(string msg) {
var rt = new AsyncReply<object>();
_InvokeByArrayArguments(1, new object[] { msg })
.Then(x => rt.Trigger((object)x))
.Error(x => rt.TriggerError(x))
.Chunk(x => rt.TriggerChunk(x));
return rt; }
public AsyncReply<double> Optional(object a1,int a2,string a3) {
var rt = new AsyncReply<double>();
_InvokeByArrayArguments(2, new object[] { a1, a2, a3 })
.Then(x => rt.Trigger((double)x))
.Error(x => rt.TriggerError(x))
.Chunk(x => rt.TriggerChunk(x));
return rt; }
public AsyncReply<object> Connection(object a1,int a2) {
var rt = new AsyncReply<object>();
_InvokeByArrayArguments(3, new object[] { a1, a2 })
.Then(x => rt.Trigger((object)x))
.Error(x => rt.TriggerError(x))
.Chunk(x => rt.TriggerChunk(x));
return rt; }
public AsyncReply<object> ConnectionOptional(object a1,int a2,string a3) {
var rt = new AsyncReply<object>();
_InvokeByArrayArguments(4, new object[] { a1, a2, a3 })
.Then(x => rt.Trigger((object)x))
.Error(x => rt.TriggerError(x))
.Chunk(x => rt.TriggerChunk(x));
return rt; }
public AsyncReply<(int,string)> Tuple2(int a1,string a2) {
var rt = new AsyncReply<(int,string)>();
_InvokeByArrayArguments(5, new object[] { a1, a2 })
.Then(x => rt.Trigger(((int,string))x))
.Error(x => rt.TriggerError(x))
.Chunk(x => rt.TriggerChunk(x));
return rt; }
public AsyncReply<(int,string,double)> Tuple3(int a1,string a2,double a3) {
var rt = new AsyncReply<(int,string,double)>();
_InvokeByArrayArguments(6, new object[] { a1, a2, a3 })
.Then(x => rt.Trigger(((int,string,double))x))
.Error(x => rt.TriggerError(x))
.Chunk(x => rt.TriggerChunk(x));
return rt; }
public AsyncReply<(int,string,double,bool)> Tuple4(int a1,string a2,double a3,bool a4) {
var rt = new AsyncReply<(int,string,double,bool)>();
_InvokeByArrayArguments(7, new object[] { a1, a2, a3, a4 })
.Then(x => rt.Trigger(((int,string,double,bool))x))
.Error(x => rt.TriggerError(x))
.Chunk(x => rt.TriggerChunk(x));
return rt; }
public int PropertyContext {
get => (int)properties[0];
set => _Set(0, value);
}
public Test.SizeEnum Enum {
get => (Test.SizeEnum)properties[1];
set => _Set(1, value);
}
public Test.MyRecord Record {
get => (Test.MyRecord)properties[2];
set => _Set(2, value);
}
public int[] IntList {
get => (int[])properties[3];
set => _Set(3, value);
}
public IRecord[] RecordsArray {
get => (IRecord[])properties[4];
set => _Set(4, value);
}
public Test.MyRecord[] RecordsList {
get => (Test.MyRecord[])properties[5];
set => _Set(5, value);
}
public Test.MyResource Resource {
get => (Test.MyResource)properties[6];
set => _Set(6, value);
}
public Test.MyChildResource Child {
get => (Test.MyChildResource)properties[7];
set => _Set(7, value);
}
public IResource[] Resources {
get => (IResource[])properties[8];
set => _Set(8, value);
}
public Test.MyService Me {
get => (Test.MyService)properties[9];
set => _Set(9, value);
}
public bool Boolean {
get => (bool)properties[10];
set => _Set(10, value);
}
public bool[] BooleanArray {
get => (bool[])properties[11];
set => _Set(11, value);
}
public byte UInt8 {
get => (byte)properties[12];
set => _Set(12, value);
}
public byte? UInt8Null {
get => (byte?)properties[13];
set => _Set(13, value);
}
public byte[] UInt8Array {
get => (byte[])properties[14];
set => _Set(14, value);
}
public byte?[] UInt8ArrayNull {
get => (byte?[])properties[15];
set => _Set(15, value);
}
public sbyte Int8 {
get => (sbyte)properties[16];
set => _Set(16, value);
}
public sbyte[] Int8Array {
get => (sbyte[])properties[17];
set => _Set(17, value);
}
public char Char16 {
get => (char)properties[18];
set => _Set(18, value);
}
public char[] Char16Array {
get => (char[])properties[19];
set => _Set(19, value);
}
public short Int16 {
get => (short)properties[20];
set => _Set(20, value);
}
public short[] Int16Array {
get => (short[])properties[21];
set => _Set(21, value);
}
public ushort UInt16 {
get => (ushort)properties[22];
set => _Set(22, value);
}
public ushort[] UInt16Array {
get => (ushort[])properties[23];
set => _Set(23, value);
}
public int Int32 {
get => (int)properties[24];
set => _Set(24, value);
}
public int[] Int32Array {
get => (int[])properties[25];
set => _Set(25, value);
}
public uint UInt32 {
get => (uint)properties[26];
set => _Set(26, value);
}
public uint[] UInt32Array {
get => (uint[])properties[27];
set => _Set(27, value);
}
public long Int64 {
get => (long)properties[28];
set => _Set(28, value);
}
public long[] Int64Array {
get => (long[])properties[29];
set => _Set(29, value);
}
public ulong UInt64 {
get => (ulong)properties[30];
set => _Set(30, value);
}
public ulong[] UInt64Array {
get => (ulong[])properties[31];
set => _Set(31, value);
}
public float Float32 {
get => (float)properties[32];
set => _Set(32, value);
}
public float[] Float32Array {
get => (float[])properties[33];
set => _Set(33, value);
}
public double Float64 {
get => (double)properties[34];
set => _Set(34, value);
}
public double[] Float64Array {
get => (double[])properties[35];
set => _Set(35, value);
}
public decimal Float128 {
get => (decimal)properties[36];
set => _Set(36, value);
}
public decimal[] Float128Array {
get => (decimal[])properties[37];
set => _Set(37, value);
}
public string String {
get => (string)properties[38];
set => _Set(38, value);
}
public string[] StringArray {
get => (string[])properties[39];
set => _Set(39, value);
}
public DateTime DateTime {
get => (DateTime)properties[40];
set => _Set(40, value);
}
public Map<string,object> StringMap {
get => (Map<string,object>)properties[41];
set => _Set(41, value);
}
public Map<int,string> IntStringMap {
get => (Map<int,string>)properties[42];
set => _Set(42, value);
}
public object Object {
get => (object)properties[43];
set => _Set(43, value);
}
public object[] ObjectArray {
get => (object[])properties[44];
set => _Set(44, value);
}
public const double PI = 3.14159265358979;
protected override void _EmitEventByIndex(byte index, object args) {
switch (index) {
case 0: StringEvent?.Invoke((string)args); break;
case 1: ArrayEvent?.Invoke((object[])args); break;
}}
public event ResourceEventHandler<string> StringEvent;
public event ResourceEventHandler<object[]> ArrayEvent;
}
}
| |
// 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.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
namespace System.IO
{
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
public sealed partial class FileInfo : FileSystemInfo
{
private String _name;
[System.Security.SecurityCritical]
private FileInfo() { }
[System.Security.SecuritySafeCritical]
public FileInfo(String fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
Contract.EndContractBlock();
Init(fileName);
}
[System.Security.SecurityCritical]
private void Init(String fileName)
{
OriginalPath = fileName;
// Must fully qualify the path for the security check
String fullPath = Path.GetFullPath(fileName);
_name = Path.GetFileName(fileName);
FullPath = fullPath;
DisplayPath = GetDisplayPath(fileName);
}
private String GetDisplayPath(String originalPath)
{
return originalPath;
}
[System.Security.SecuritySafeCritical]
internal FileInfo(String fullPath, String originalPath)
{
Debug.Assert(Path.IsPathRooted(fullPath), "fullPath must be fully qualified!");
_name = originalPath ?? Path.GetFileName(fullPath);
OriginalPath = _name;
FullPath = fullPath;
DisplayPath = _name;
}
public override String Name
{
get { return _name; }
}
public long Length
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if ((FileSystemObject.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
{
throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, DisplayPath), DisplayPath);
}
return FileSystemObject.Length;
}
}
/* Returns the name of the directory that the file is in */
public String DirectoryName
{
[System.Security.SecuritySafeCritical]
get
{
return Path.GetDirectoryName(FullPath);
}
}
/* Creates an instance of the parent directory */
public DirectoryInfo Directory
{
get
{
String dirName = DirectoryName;
if (dirName == null)
return null;
return new DirectoryInfo(dirName);
}
}
public bool IsReadOnly
{
get
{
return (Attributes & FileAttributes.ReadOnly) != 0;
}
set
{
if (value)
Attributes |= FileAttributes.ReadOnly;
else
Attributes &= ~FileAttributes.ReadOnly;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public StreamReader OpenText()
{
Stream stream = FileStream.InternalOpen(FullPath);
return new StreamReader(stream, Encoding.UTF8, true);
}
public StreamWriter CreateText()
{
Stream stream = FileStream.InternalCreate(FullPath);
return new StreamWriter(stream);
}
public StreamWriter AppendText()
{
Stream stream = FileStream.InternalAppend(FullPath);
return new StreamWriter(stream);
}
// Copies an existing file to a new file. An exception is raised if the
// destination file already exists. Use the
// Copy(String, String, boolean) method to allow
// overwriting an existing file.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName
// and Write permissions to destFileName.
//
public FileInfo CopyTo(String destFileName)
{
if (destFileName == null)
throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName);
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName));
Contract.EndContractBlock();
destFileName = File.InternalCopy(FullPath, destFileName, false);
return new FileInfo(destFileName, null);
}
// Copies an existing file to a new file. If overwrite is
// false, then an IOException is thrown if the destination file
// already exists. If overwrite is true, the file is
// overwritten.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName and Create
// and Write permissions to destFileName.
//
public FileInfo CopyTo(String destFileName, bool overwrite)
{
if (destFileName == null)
throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName);
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName));
Contract.EndContractBlock();
destFileName = File.InternalCopy(FullPath, destFileName, overwrite);
return new FileInfo(destFileName, null);
}
public FileStream Create()
{
return File.Create(FullPath);
}
// Deletes a file. The file specified by the designated path is deleted.
// If the file does not exist, Delete succeeds without throwing
// an exception.
//
// On NT, Delete will fail for a file that is open for normal I/O
// or a file that is memory mapped. On Win95, the file will be
// deleted irregardless of whether the file is being used.
//
// Your application must have Delete permission to the target file.
//
[System.Security.SecuritySafeCritical]
public override void Delete()
{
FileSystem.Current.DeleteFile(FullPath);
}
// Tests if the given file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false.
//
// Your application must have Read permission for the target directory.
public override bool Exists
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
try
{
return FileSystemObject.Exists;
}
catch
{
return false;
}
}
}
// User must explicitly specify opening a new file or appending to one.
public FileStream Open(FileMode mode)
{
return Open(mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None);
}
public FileStream Open(FileMode mode, FileAccess access)
{
return Open(mode, access, FileShare.None);
}
public FileStream Open(FileMode mode, FileAccess access, FileShare share)
{
return new FileStream(FullPath, mode, access, share);
}
[System.Security.SecuritySafeCritical] // auto-generated
public FileStream OpenRead()
{
return new FileStream(FullPath, FileMode.Open, FileAccess.Read,
FileShare.Read, 4096, false);
}
public FileStream OpenWrite()
{
return new FileStream(FullPath, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.None);
}
// Moves a given file to a new location and potentially a new file name.
// This method does work across volumes.
//
// The caller must have certain FileIOPermissions. The caller must
// have Read and Write permission to
// sourceFileName and Write
// permissions to destFileName.
//
[System.Security.SecuritySafeCritical]
public void MoveTo(String destFileName)
{
if (destFileName == null)
throw new ArgumentNullException(nameof(destFileName));
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName));
Contract.EndContractBlock();
String fullDestFileName = Path.GetFullPath(destFileName);
// These checks are in place to ensure Unix error throwing happens the same way
// as it does on Windows.These checks can be removed if a solution to #2460 is
// found that doesn't require validity checks before making an API call.
if (!new DirectoryInfo(Path.GetDirectoryName(FullName)).Exists)
{
throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, FullName));
}
if (!Exists)
{
throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, FullName), FullName);
}
FileSystem.Current.MoveFile(FullPath, fullDestFileName);
FullPath = fullDestFileName;
OriginalPath = destFileName;
_name = Path.GetFileName(fullDestFileName);
DisplayPath = GetDisplayPath(destFileName);
// Flush any cached information about the file.
Invalidate();
}
// Returns the display path
public override String ToString()
{
return DisplayPath;
}
public void Decrypt()
{
File.Decrypt(FullPath);
}
public void Encrypt()
{
File.Encrypt(FullPath);
}
}
}
| |
using System;
using FluentNHibernate.MappingModel.Identity;
using NHibernate.Id;
namespace FluentNHibernate.Mapping
{
public class GeneratorBuilder
{
private readonly Type identityType;
private readonly GeneratorMapping mapping;
public GeneratorBuilder(GeneratorMapping mapping, Type identityType)
{
this.mapping = mapping;
this.identityType = identityType;
}
private void SetGenerator(string generator)
{
mapping.Class = generator;
}
private void AddGeneratorParam(string name, string value)
{
mapping.Params.Add(name, value);
}
private void EnsureIntegralIdenityType()
{
if (!IsIntegralType(identityType)) throw new InvalidOperationException("Identity type must be integral (int, long, uint, ulong)");
}
private void EnsureGuidIdentityType()
{
if (identityType != typeof(Guid) && identityType != typeof(Guid?)) throw new InvalidOperationException("Identity type must be Guid");
}
private void EnsureStringIdentityType()
{
if (identityType != typeof(string)) throw new InvalidOperationException("Identity type must be string");
}
private static bool IsIntegralType(Type t)
{
// do we think we'll encounter more?
return t == typeof(int) || t == typeof(int?)
|| t == typeof(long) || t == typeof(long?)
|| t == typeof(uint) || t == typeof(uint?)
|| t == typeof(ulong) || t == typeof(ulong?)
|| t == typeof(byte) || t == typeof(byte?)
|| t == typeof(sbyte) || t == typeof(sbyte?)
|| t == typeof(short) || t == typeof(short?)
|| t == typeof(ushort) || t == typeof(ushort?);
}
public void Increment()
{
EnsureIntegralIdenityType();
SetGenerator("increment");
}
public void Increment(Action<ParamBuilder> paramValues)
{
paramValues(new ParamBuilder(mapping.Params));
Increment();
}
/// <summary>
/// supports identity columns in DB2, MySQL, MS SQL Server and Sybase.
/// The identifier returned by the database is converted to the property type using
/// Convert.ChangeType. Any integral property type is thus supported.
/// </summary>
/// <returns></returns>
public void Identity()
{
EnsureIntegralIdenityType();
SetGenerator("identity");
}
/// <summary>
/// supports identity columns in DB2, MySQL, MS SQL Server and Sybase.
/// The identifier returned by the database is converted to the property type using
/// Convert.ChangeType. Any integral property type is thus supported.
/// </summary>
/// <param name="paramValues">Params configuration</param>
public void Identity(Action<ParamBuilder> paramValues)
{
paramValues(new ParamBuilder(mapping.Params));
Identity();
}
/// <summary>
/// uses a sequence in DB2, PostgreSQL, Oracle or a generator in Firebird.
/// The identifier returned by the database is converted to the property type
/// using Convert.ChangeType. Any integral property type is thus supported.
/// </summary>
/// <param name="sequenceName"></param>
/// <returns></returns>
public void Sequence(string sequenceName)
{
EnsureIntegralIdenityType();
SetGenerator("sequence");
AddGeneratorParam("sequence", sequenceName);
}
/// <summary>
/// uses a sequence in DB2, PostgreSQL, Oracle or a generator in Firebird.
/// The identifier returned by the database is converted to the property type
/// using Convert.ChangeType. Any integral property type is thus supported.
/// </summary>
/// <param name="sequenceName"></param>
/// <param name="paramValues">Params configuration</param>
public void Sequence(string sequenceName, Action<ParamBuilder> paramValues)
{
paramValues(new ParamBuilder(mapping.Params));
Sequence(sequenceName);
}
/// <summary>
/// uses a hi/lo algorithm to efficiently generate identifiers of any integral type,
/// given a table and column (by default hibernate_unique_key and next_hi respectively)
/// as a source of hi values. The hi/lo algorithm generates identifiers that are unique
/// only for a particular database. Do not use this generator with a user-supplied connection.
/// requires a "special" database table to hold the next available "hi" value
/// </summary>
/// <param name="table"></param>
/// <param name="column"></param>
/// <param name="maxLo"></param>
/// <returns></returns>
public void HiLo(string table, string column, string maxLo)
{
AddGeneratorParam("table", table);
AddGeneratorParam("column", column);
HiLo(maxLo);
}
/// <summary>
/// uses a hi/lo algorithm to efficiently generate identifiers of any integral type,
/// given a table and column (by default hibernate_unique_key and next_hi respectively)
/// as a source of hi values. The hi/lo algorithm generates identifiers that are unique
/// only for a particular database. Do not use this generator with a user-supplied connection.
/// requires a "special" database table to hold the next available "hi" value
/// </summary>
/// <param name="table"></param>
/// <param name="column"></param>
/// <param name="maxLo"></param>
/// <param name="paramValues">Params configuration</param>
public void HiLo(string table, string column, string maxLo, Action<ParamBuilder> paramValues)
{
paramValues(new ParamBuilder(mapping.Params));
HiLo(table, column, maxLo);
}
/// <summary>
/// uses a hi/lo algorithm to efficiently generate identifiers of any integral type,
/// given a table and column (by default hibernate_unique_key and next_hi respectively)
/// as a source of hi values. The hi/lo algorithm generates identifiers that are unique
/// only for a particular database. Do not use this generator with a user-supplied connection.
/// requires a "special" database table to hold the next available "hi" value
/// </summary>
/// <param name="maxLo"></param>
/// <returns></returns>
public void HiLo(string maxLo)
{
EnsureIntegralIdenityType();
SetGenerator("hilo");
AddGeneratorParam("max_lo", maxLo);
}
/// <summary>
/// uses a hi/lo algorithm to efficiently generate identifiers of any integral type,
/// given a table and column (by default hibernate_unique_key and next_hi respectively)
/// as a source of hi values. The hi/lo algorithm generates identifiers that are unique
/// only for a particular database. Do not use this generator with a user-supplied connection.
/// requires a "special" database table to hold the next available "hi" value
/// </summary>
/// <param name="maxLo"></param>
/// <param name="paramValues">Params configuration</param>
public void HiLo(string maxLo, Action<ParamBuilder> paramValues)
{
paramValues(new ParamBuilder(mapping.Params));
HiLo(maxLo);
}
/// <summary>
/// uses an Oracle-style sequence (where supported)
/// </summary>
/// <param name="sequence"></param>
/// <param name="maxLo"></param>
/// <returns></returns>
public void SeqHiLo(string sequence, string maxLo)
{
EnsureIntegralIdenityType();
SetGenerator("seqhilo");
AddGeneratorParam("sequence", sequence);
AddGeneratorParam("max_lo", maxLo);
}
/// <summary>
/// uses an Oracle-style sequence (where supported)
/// </summary>
/// <param name="sequence"></param>
/// <param name="maxLo"></param>
/// <param name="paramValues">Params configuration</param>
public void SeqHiLo(string sequence, string maxLo, Action<ParamBuilder> paramValues)
{
paramValues(new ParamBuilder(mapping.Params));
SeqHiLo(sequence, maxLo);
}
/// <summary>
/// uses System.Guid and its ToString(string format) method to generate identifiers
/// of type string. The length of the string returned depends on the configured format.
/// </summary>
/// <param name="format">http://msdn.microsoft.com/en-us/library/97af8hh4.aspx</param>
/// <returns></returns>
public void UuidHex(string format)
{
EnsureStringIdentityType();
SetGenerator("uuid.hex");
AddGeneratorParam("format", format);
}
/// <summary>
/// uses System.Guid and its ToString(string format) method to generate identifiers
/// of type string. The length of the string returned depends on the configured format.
/// </summary>
/// <param name="format">http://msdn.microsoft.com/en-us/library/97af8hh4.aspx</param>
/// <param name="paramValues">Params configuration</param>
public void UuidHex(string format, Action<ParamBuilder> paramValues)
{
paramValues(new ParamBuilder(mapping.Params));
UuidHex(format);
}
/// <summary>
/// uses a new System.Guid to create a byte[] that is converted to a string.
/// </summary>
/// <returns></returns>
public void UuidString()
{
EnsureStringIdentityType();
SetGenerator("uuid.string");
}
/// <summary>
/// uses a new System.Guid to create a byte[] that is converted to a string.
/// </summary>
/// <param name="paramValues">Params configuration</param>
public void UuidString(Action<ParamBuilder> paramValues)
{
paramValues(new ParamBuilder(mapping.Params));
UuidString();
}
/// <summary>
/// uses a new System.Guid as the identifier.
/// </summary>
/// <returns></returns>
public void Guid()
{
EnsureGuidIdentityType();
SetGenerator("guid");
}
public void Guid(Action<ParamBuilder> paramValues)
{
paramValues(new ParamBuilder(mapping.Params));
Guid();
}
public void GuidComb()
{
EnsureGuidIdentityType();
SetGenerator("guid.comb");
}
public void GuidComb(Action<ParamBuilder> paramValues)
{
paramValues(new ParamBuilder(mapping.Params));
GuidComb();
}
public void Assigned()
{
SetGenerator("assigned");
}
public void Assigned(Action<ParamBuilder> paramValues)
{
paramValues(new ParamBuilder(mapping.Params));
Assigned();
}
public void Native()
{
EnsureIntegralIdenityType();
SetGenerator("native");
}
public void Native(Action<ParamBuilder> paramValues)
{
paramValues(new ParamBuilder(mapping.Params));
Native();
}
public void Native(string sequenceName)
{
EnsureIntegralIdenityType();
SetGenerator("native");
AddGeneratorParam("sequence", sequenceName);
}
public void Native(string sequenceName, Action<ParamBuilder> paramValues)
{
paramValues(new ParamBuilder(mapping.Params));
Native(sequenceName);
}
public void Foreign(string property)
{
SetGenerator("foreign");
AddGeneratorParam("property", property);
}
public void Foreign(string property, Action<ParamBuilder> paramValues)
{
paramValues(new ParamBuilder(mapping.Params));
Foreign(property);
}
public void Custom<T>() where T : IIdentifierGenerator
{
Custom(typeof(T));
}
public void Custom(Type generator)
{
Custom(generator.AssemblyQualifiedName);
}
public void Custom(string generator)
{
SetGenerator(generator);
}
public void Custom<T>(Action<ParamBuilder> paramValues) where T : IIdentifierGenerator
{
Custom(typeof(T), paramValues);
}
public void Custom(Type generator, Action<ParamBuilder> paramValues)
{
Custom(generator.AssemblyQualifiedName, paramValues);
}
public void Custom(string generator, Action<ParamBuilder> paramValues)
{
paramValues(new ParamBuilder(mapping.Params));
SetGenerator(generator);
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using Amazon.SimpleDB;
using Amazon.SimpleDB.Model;
using NUnit.Framework;
using CommonTests.Framework;
namespace CommonTests.IntegrationTests
{
/// <summary>
/// Integration tests for SimpleDB client.
/// </summary>
[TestFixture]
public class SimpleDB : TestBase<AmazonSimpleDBClient>
{
[OneTimeTearDown]
public void Cleanup()
{
BaseClean();
}
// Name of the domain used for all the integration tests.
private static string domainName = "aws-net-sdk-domain-" + DateTime.Now.Ticks;
// All test data used in these integration tests.
private static List<ReplaceableItem> ALL_TEST_DATA = new List<ReplaceableItem>{
new ReplaceableItem{
Name= "foo",
Attributes= new List<ReplaceableAttribute>
{
new ReplaceableAttribute{Name="1",Value= "2"},
new ReplaceableAttribute{Name="3",Value= "4"},
new ReplaceableAttribute{Name="5",Value= "6"}
}
},
new ReplaceableItem{
Name="boo",
Attributes= new List<ReplaceableAttribute>
{
new ReplaceableAttribute{Name="X",Value= "Y"},
new ReplaceableAttribute{Name="Z",Value= "Q"}
}
},
new ReplaceableItem{
Name= "baa",
Attributes= new List<ReplaceableAttribute>
{
new ReplaceableAttribute{Name="A'",Value= "B'"},
new ReplaceableAttribute{Name="(C)", Value = "(D)"},
new ReplaceableAttribute{Name="E",Value= "F"}}
}};
private ReplaceableItem FOO_ITEM = ALL_TEST_DATA[0];
private List<ReplaceableItem> ITEM_LIST =
new List<ReplaceableItem> { ALL_TEST_DATA[1], ALL_TEST_DATA[2] };
[TearDown]
public void TearDown()
{
try
{
DeleteDomain(domainName);
}
catch (AmazonSimpleDBException) { }
}
[Test]
[Category("SimpleDB")]
public void TestSimpleDBOperations()
{
TestCreateDomain();
try
{
UtilityMethods.Sleep(TimeSpan.FromSeconds(5));
TestPutAttributes();
TestPutAttributesWithCondition();
TestBatchPutAttributes();
TestGetAttributes();
TestListDomains();
TestDomainMetadata();
TestSelect();
TestDeleteAttributes();
}
finally
{
TestDeleteDomain();
}
}
private void TestCreateDomain()
{
Assert.IsFalse(DoesDomainExist(domainName));
CreateDomain(domainName);
bool found = false;
for (int retries = 0; retries < 5 && !found; retries++)
{
UtilityMethods.Sleep(TimeSpan.FromSeconds(retries));
found = DoesDomainExist(domainName);
}
Assert.IsTrue(found);
}
private void TestDeleteDomain()
{
DeleteDomain(domainName);
Assert.IsFalse(DoesDomainExist(domainName));
}
private void TestListDomains()
{
var listDomainsResult = Client.ListDomainsAsync(new ListDomainsRequest()).Result;
List<string> domainNames = listDomainsResult.DomainNames;
Assert.IsTrue(domainNames.Contains(domainName));
}
private void TestPutAttributes()
{
PutAttributesRequest request = new PutAttributesRequest()
{
DomainName = domainName,
ItemName = FOO_ITEM.Name,
Attributes = FOO_ITEM.Attributes
};
Client.PutAttributesAsync(request).Wait();
assertItemsStoredInDomain(Client, new List<ReplaceableItem> { FOO_ITEM }, domainName);
}
private void TestPutAttributesWithCondition()
{
PutAttributesRequest request = new PutAttributesRequest()
{
DomainName = domainName,
ItemName = FOO_ITEM.Name,
Attributes = new List<ReplaceableAttribute>() { FOO_ITEM.Attributes[0] },
Expected = new UpdateCondition()
{
Name = FOO_ITEM.Attributes[0].Name,
Exists = true,
Value = FOO_ITEM.Attributes[0].Value
}
};
request.Attributes[0].Replace = true;
request.Attributes[0].Value = "11";
FOO_ITEM.Attributes[0].Value = "11";
Client.PutAttributesAsync(request).Wait();
assertItemsStoredInDomain(Client, new List<ReplaceableItem> { FOO_ITEM }, domainName);
}
private void TestBatchPutAttributes()
{
BatchPutAttributesRequest request = new BatchPutAttributesRequest()
{
DomainName = domainName,
Items = ITEM_LIST
};
Client.BatchPutAttributesAsync(request).Wait();
assertItemsStoredInDomain(Client, ITEM_LIST, domainName);
}
private void TestSelect()
{
SelectRequest request = new SelectRequest()
{
SelectExpression = "select * from `" + domainName + "`",
ConsistentRead = true
};
var selectResult = Client.SelectAsync(request).Result;
AssertItemsPresent(ITEM_LIST, selectResult.Items);
AssertItemsPresent(new List<ReplaceableItem> { FOO_ITEM }, selectResult.Items);
}
private void TestDomainMetadata()
{
UtilityMethods.Sleep(TimeSpan.FromSeconds(5));
DomainMetadataRequest request = new DomainMetadataRequest() { DomainName = domainName };
var domainMetadataResult = Client.DomainMetadataAsync(request).Result;
int expectedItemCount = 0;
int expectedAttributeValueCount = 0;
int expectedAttributeNameCount = 0;
foreach (ReplaceableItem item in ALL_TEST_DATA)
{
expectedItemCount++;
expectedAttributeNameCount += item.Attributes.Count;
expectedAttributeValueCount += item.Attributes.Count;
}
Assert.AreEqual(expectedItemCount, domainMetadataResult.ItemCount);
Assert.AreEqual(expectedAttributeNameCount, domainMetadataResult.AttributeNameCount);
Assert.AreEqual(expectedAttributeValueCount, domainMetadataResult.AttributeValueCount);
Assert.IsNotNull(domainMetadataResult.Timestamp);
}
private void TestGetAttributes()
{
GetAttributesRequest request = new GetAttributesRequest()
{
DomainName = domainName,
ItemName = FOO_ITEM.Name,
AttributeNames = new List<string>() { FOO_ITEM.Attributes[0].Name, FOO_ITEM.Attributes[1].Name },
ConsistentRead = true
};
var getAttributesResult = Client.GetAttributesAsync(request).Result;
List<Amazon.SimpleDB.Model.Attribute> attributes = getAttributesResult.Attributes;
Dictionary<string, string> attributeValuesByName = ConvertAttributesToMap(attributes);
Assert.AreEqual(2, attributeValuesByName.Count);
List<ReplaceableAttribute> attrs = new List<ReplaceableAttribute>();
attrs.Add(FOO_ITEM.Attributes[0]);
attrs.Add(FOO_ITEM.Attributes[1]);
foreach (ReplaceableAttribute expectedAttribute in attrs)
{
string expectedAttributeName = expectedAttribute.Name;
Assert.IsTrue(attributeValuesByName.ContainsKey(expectedAttributeName));
Assert.AreEqual(expectedAttribute.Value, attributeValuesByName[expectedAttributeName]);
}
}
private void TestDeleteAttributes()
{
List<string> attributeNames = new List<string>();
attributeNames.Add(FOO_ITEM.Attributes[0].Name);
attributeNames.Add(FOO_ITEM.Attributes[1].Name);
List<Amazon.SimpleDB.Model.Attribute> attributeList = new List<Amazon.SimpleDB.Model.Attribute>();
foreach (string attributeName in attributeNames)
{
attributeList.Add(new Amazon.SimpleDB.Model.Attribute() { Name = attributeName });
}
Assert.IsTrue(DoAttributesExistForItem(Client, FOO_ITEM.Name, domainName, attributeNames));
DeleteAttributesRequest request = new DeleteAttributesRequest()
{
DomainName = domainName,
ItemName = FOO_ITEM.Name,
Attributes = attributeList
};
Client.DeleteAttributesAsync(request).Wait();
Assert.IsFalse(DoAttributesExistForItem(Client, FOO_ITEM.Name, domainName, attributeNames));
}
bool DoesDomainExist(String domainName)
{
try
{
DomainMetadataRequest request = new DomainMetadataRequest() { DomainName = domainName };
Client.DomainMetadataAsync(request).Wait();
return true;
}
catch(AggregateException ae)
{
if (ae.InnerExceptions != null &&
ae.InnerExceptions.Count == 1 &&
ae.InnerExceptions.First() is AmazonSimpleDBException)
return false;
throw;
}
}
void CreateDomain(String domainName)
{
CreateDomainRequest request = new CreateDomainRequest() { DomainName = domainName };
Client.CreateDomainAsync(request).Wait();
}
bool DoAttributesExistForItem(IAmazonSimpleDB sdb, String itemName, String domainName, List<String> attributeNames)
{
GetAttributesRequest request = new GetAttributesRequest()
{
DomainName = domainName,
AttributeNames = attributeNames,
ItemName = itemName,
ConsistentRead = true
};
var result = sdb.GetAttributesAsync(request).Result;
Dictionary<string, string> attributeValuesByName = ConvertAttributesToMap(result.Attributes);
foreach (string expectedAttributeName in attributeNames)
{
if (!attributeValuesByName.ContainsKey(expectedAttributeName))
{
return false;
}
}
return true;
}
Dictionary<string, string> ConvertAttributesToMap(List<Amazon.SimpleDB.Model.Attribute> attributeList)
{
Dictionary<string, string> attributeValuesByName = new Dictionary<string, string>();
foreach (Amazon.SimpleDB.Model.Attribute attribute in attributeList)
{
attributeValuesByName.Add(attribute.Name, attribute.Value);
}
return attributeValuesByName;
}
void DeleteDomain(String domainName)
{
DeleteDomainRequest request = new DeleteDomainRequest()
{
DomainName = domainName,
};
Client.DeleteDomainAsync(request).Wait();
}
void assertItemsStoredInDomain(IAmazonSimpleDB sdb, List<ReplaceableItem> expectedItems, String domainName)
{
SelectRequest request = new SelectRequest()
{
SelectExpression = "select * from `" + domainName + "`",
ConsistentRead = true
};
var selectResult = Client.SelectAsync(request).Result;
AssertItemsPresent(expectedItems, selectResult.Items);
}
void AssertItemsPresent(List<ReplaceableItem> expectedItems, List<Item> items)
{
Dictionary<string, Dictionary<string, string>> expectedAttributesByItemName = ConvertReplaceableItemListToMap(expectedItems);
Dictionary<string, Dictionary<string, string>> retrievedAttributesByItemName = ConvertItemListToMap(items);
foreach (string expectedItemName in expectedAttributesByItemName.Keys)
{
Assert.IsTrue(retrievedAttributesByItemName.ContainsKey(expectedItemName));
Dictionary<string, string> expectedAttributes = expectedAttributesByItemName[expectedItemName];
Dictionary<string, string> retrievedAttributes = retrievedAttributesByItemName[expectedItemName];
foreach (string expectedAttributeName in expectedAttributes.Keys)
{
string expectedAttributeValue = expectedAttributes[expectedAttributeName];
Assert.IsTrue(retrievedAttributes.ContainsKey(expectedAttributeName));
Assert.AreEqual(expectedAttributeValue, retrievedAttributes[expectedAttributeName]);
}
}
}
private Dictionary<string, Dictionary<string, string>> ConvertReplaceableItemListToMap(List<ReplaceableItem> items)
{
Dictionary<string, Dictionary<string, string>> attributesByItemName = new Dictionary<string, Dictionary<string, string>>();
foreach (ReplaceableItem item in items)
{
Dictionary<string, string> attributeValuesByName = new Dictionary<string, string>();
foreach (ReplaceableAttribute attribute in item.Attributes)
{
attributeValuesByName.Add(attribute.Name, attribute.Value);
}
attributesByItemName.Add(item.Name, attributeValuesByName);
}
return attributesByItemName;
}
private Dictionary<string, Dictionary<string, string>> ConvertItemListToMap(List<Item> items)
{
Dictionary<string, Dictionary<string, string>> attributesByItemName = new Dictionary<string, Dictionary<string, string>>();
foreach (Item item in items)
{
attributesByItemName.Add(item.Name, ConvertAttributesToMap(item.Attributes));
}
return attributesByItemName;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Xml.Serialization;
using ClangCompile;
using System.Xml;
using System.IO;
using Microsoft.Build.Framework;
namespace PropSchemaGen
{
/// <summary>
/// Serves as main entry and Attribute parser for ClangCompile
/// </summary>
class Program
{
// Formality is a B.
static string xmlns = "clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework";
/// <summary>
/// Assigns each property of a class to an XML attribute for a given Element
/// </summary>
/// <param name="doc">XmlDocument used to create elements</param>
/// <param name="obj">Class whose properties are to be serialized</param>
/// <param name="elem">Element to add attributes to</param>
/// <returns>The same XmlElement, for brevity of code</returns>
static XmlElement PropsToXmlAttr(XmlDocument doc, object obj, XmlElement elem)
{
foreach (PropertyInfo pi in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance))
{
if (pi.GetValue(obj) != null && pi.GetValue(obj).ToString() != "")
{
DefaultValueAttribute dvAttr = (DefaultValueAttribute)Attribute.GetCustomAttribute(pi, typeof(DefaultValueAttribute));
if (dvAttr == null)
{
elem.SetAttribute(pi.Name, pi.GetValue(obj).ToString());
}
else
{
if(dvAttr.Value.ToLower() == pi.GetValue(obj).ToString().ToLower()) {
Console.WriteLine("Default value of {0} skipped for {1}", dvAttr.Value, pi.Name);
}
else
{
Console.WriteLine("Default value of {0} overwritten by {1} for {2}", dvAttr.Value, pi.GetValue(obj).ToString(), pi.Name);
elem.SetAttribute(pi.Name, pi.GetValue(obj).ToString());
}
}
}
}
return elem;
}
/// <summary>
/// Helper that creates an element "name" under "parentName.name" and populates the attributes with obj's properties.
/// </summary>
/// <param name="doc">XmlDocument used to create elements</param>
/// <param name="obj">Class whose properties are to be serialized</param>
/// <param name="elem">Element to which a subelement will be added</param>
/// <param name="name">Name of the subelement</param>
/// <returns>The same XmlElement, for brevity of code</returns>
static XmlElement AttrToSubElem(XmlDocument doc, object obj, XmlElement elem, string name)
{
XmlElement subElem = (XmlElement)elem.AppendChild(doc.CreateElement(elem.Name + "." + name, xmlns)).AppendChild(doc.CreateElement(name, xmlns));
PropsToXmlAttr(doc, obj, subElem);
return elem;
}
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
XmlElement projectElement = doc.CreateElement("ProjectSchemaDefinitions", xmlns);
List<string> categories = new List<string>();
doc.AppendChild(projectElement);
// These attributes are probably common to all property schemas in Visual Studio.
projectElement.SetAttribute("xmlns", "clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework");
projectElement.SetAttribute("xmlns:x", "http://schemas.microsoft.com/winfx/2006/xaml");
projectElement.SetAttribute("xmlns:sys", "clr-namespace:System;assembly=mscorlib");
projectElement.SetAttribute("xmlns:transformCallback", "Microsoft.Cpp.Dev10.ConvertPropertyCallback");
XmlElement ruleElement = (XmlElement)projectElement.AppendChild(doc.CreateElement("Rule", xmlns));
ruleElement.AppendChild(doc.CreateComment("This file is generated! Modify with caution!"));
RuleAttribute ruleAttr = (RuleAttribute)Attribute.GetCustomAttribute(typeof(Clang), typeof(RuleAttribute));
if (ruleAttr == null)
{
throw new InvalidOperationException("Class requires Rule attribute!");
}
PropsToXmlAttr(doc, ruleAttr, ruleElement);
DataSourceAttribute dataAttr = (DataSourceAttribute)Attribute.GetCustomAttribute(typeof(Clang), typeof(DataSourceAttribute));
if (dataAttr == null)
{
throw new InvalidOperationException("Class requires DataSource attribute!");
}
AttrToSubElem(doc, dataAttr, ruleElement, "DataSource");
XmlElement catsElement = (XmlElement)ruleElement.AppendChild(doc.CreateElement("Rule.Categories", xmlns));
PropertyCategoryAttribute[] allAttributes = (PropertyCategoryAttribute[])Attribute.GetCustomAttributes(typeof(Clang), typeof(PropertyCategoryAttribute));
allAttributes = allAttributes.OrderBy(x => x.Order).ToArray();
Dictionary<string, PropertyCategoryAttribute> categoryMap = allAttributes.ToDictionary(x => x.Name);
MemberInfo[] members = typeof(Clang).GetMembers(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);
foreach (PropertyCategoryAttribute catAttr in allAttributes)
{
XmlElement catElement = (XmlElement)catsElement.AppendChild(doc.CreateElement("Category", xmlns));
PropsToXmlAttr(doc, catAttr, catElement);
}
foreach(MemberInfo member in members) {
PropertyPageAttribute[] attrs = (PropertyPageAttribute[])Attribute.GetCustomAttributes(member, typeof(PropertyPageAttribute));
foreach (PropertyPageAttribute attr in attrs)
{
Console.WriteLine("Member name: {0}", member.Name);
if (attr.Category != null && attr.Category != "")
{
PropertyCategoryAttribute req;
if (!categoryMap.TryGetValue(attr.Category, out req))
{
Console.WriteLine("Category not found: {0}", attr.Category);
}
}
}
XmlElement curElement = null;
switch (member.MemberType)
{
case MemberTypes.Property:
PropertyInfo pInfo = (PropertyInfo)member;
PropertyPageAttribute propAttr = (PropertyPageAttribute)Attribute.GetCustomAttribute(member, typeof(PropertyPageAttribute));
// Untracked parameter.
if (propAttr == null)
{
continue;
}
if (pInfo.PropertyType.IsSubclassOf(typeof(Enum)))
{
Console.WriteLine("Warning: Enumerations are invalid types because VisualStudio isn't that smart. You'll have to make it a string and back it with an enum.");
continue;
}
else if (pInfo.PropertyType.IsAssignableFrom(typeof(ITaskItem[])))
{
curElement = (XmlElement)ruleElement.AppendChild(doc.CreateElement("StringListProperty", xmlns));
PropsToXmlAttr(doc, propAttr, curElement).SetAttribute("Name", member.Name);
}
else if (pInfo.PropertyType.IsAssignableFrom(typeof(String)))
{
EnumeratedValueAttribute enumAttr = (EnumeratedValueAttribute)Attribute.GetCustomAttribute(member, typeof(EnumeratedValueAttribute));
if (enumAttr != null)
{
curElement = (XmlElement)ruleElement.AppendChild(doc.CreateElement("EnumProperty", xmlns));
PropsToXmlAttr(doc, propAttr, curElement).SetAttribute("Name", member.Name);
int foundAttr = 0;
FieldInfo[] fields = enumAttr.Enumeration.GetFields(BindingFlags.Public | BindingFlags.Static);
foreach (FieldInfo field in fields)
{
FieldAttribute attr = (FieldAttribute)field.GetCustomAttribute(typeof(FieldAttribute));
if (attr != null)
{
foundAttr++;
PropsToXmlAttr(doc, attr, (XmlElement)curElement.AppendChild(doc.CreateElement("EnumValue", xmlns))).SetAttribute("Name", field.Name);
}
}
if (foundAttr > 0 && foundAttr != fields.Length)
{
Console.WriteLine("Not all fields in {0} have attributes", pInfo.Name);
}
}
else
{
curElement = (XmlElement)ruleElement.AppendChild(doc.CreateElement("StringProperty", xmlns));
PropsToXmlAttr(doc, propAttr, curElement).SetAttribute("Name", member.Name);
}
}
else if (pInfo.PropertyType.IsAssignableFrom(typeof(String[])))
{
curElement = (XmlElement)ruleElement.AppendChild(doc.CreateElement("StringListProperty", xmlns));
PropsToXmlAttr(doc, propAttr, curElement).SetAttribute("Name", member.Name);
}
else if (pInfo.PropertyType.IsAssignableFrom(typeof(Boolean)))
{
curElement = (XmlElement)ruleElement.AppendChild(doc.CreateElement("BoolProperty", xmlns));
PropsToXmlAttr(doc, propAttr, curElement).SetAttribute("Name", member.Name);
}
break;
// Fields are not exposed, only property accessors.
case MemberTypes.Field:
break;
default:
break;
}
if (curElement != null)
{
DataSourceAttribute dataSrcAttr = (DataSourceAttribute)Attribute.GetCustomAttribute(member, typeof(DataSourceAttribute));
if (dataSrcAttr != null)
{
AttrToSubElem(doc, dataSrcAttr, curElement, "DataSource");
}
}
}
IEnumerable<Attribute> additionalAttrs = Attribute.GetCustomAttributes(typeof(Clang), typeof(ItemTypeAttribute));
additionalAttrs = additionalAttrs.Concat(Attribute.GetCustomAttributes(typeof(Clang), typeof(FileExtensionAttribute)));
additionalAttrs = additionalAttrs.Concat(Attribute.GetCustomAttributes(typeof(Clang), typeof(ContentTypeAttribute)));
foreach (Attribute additionalAttr in additionalAttrs)
{
string attrName = additionalAttr.GetType().Name;
attrName = attrName.Substring(0, attrName.Length - "Attribute".Length);
// So lollers. C# is great.
PropsToXmlAttr(doc, additionalAttr, (XmlElement)projectElement.AppendChild(doc.CreateElement(attrName, xmlns)));
}
FileStream fs = new FileStream(@"..\..\sbclang.xml", FileMode.Create);
XmlWriterSettings xmlSettings = new XmlWriterSettings();
xmlSettings.NewLineOnAttributes = true;
xmlSettings.Indent = true;
xmlSettings.NamespaceHandling = NamespaceHandling.OmitDuplicates;
XmlWriter writer = XmlWriter.Create(fs, xmlSettings);
doc.Save(writer);
Console.WriteLine("All done! Press any key to exit.");
Console.ReadKey();
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.CodeGeneration;
using Orleans.GrainReferences;
using Orleans.Internal;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Messaging;
using Orleans.Serialization;
namespace Orleans.Runtime
{
/// <summary>
/// A client which is hosted within a silo.
/// </summary>
internal sealed class HostedClient : IGrainContext, IGrainExtensionBinder, IDisposable, ILifecycleParticipant<ISiloLifecycle>
{
private readonly object lockObj = new object();
private readonly Channel<Message> incomingMessages;
private readonly IGrainReferenceRuntime grainReferenceRuntime;
private readonly InvokableObjectManager invokableObjects;
private readonly IRuntimeClient runtimeClient;
private readonly ILogger logger;
private readonly IInternalGrainFactory grainFactory;
private readonly MessageCenter siloMessageCenter;
private readonly MessagingTrace messagingTrace;
private readonly ConcurrentDictionary<Type, (object Implementation, IAddressable Reference)> _extensions = new ConcurrentDictionary<Type, (object, IAddressable)>();
private bool disposing;
private Task messagePump;
public HostedClient(
IRuntimeClient runtimeClient,
ILocalSiloDetails siloDetails,
ILogger<HostedClient> logger,
IGrainReferenceRuntime grainReferenceRuntime,
IInternalGrainFactory grainFactory,
MessageCenter messageCenter,
MessagingTrace messagingTrace,
SerializationManager serializationManager,
GrainReferenceActivator referenceActivator)
{
this.incomingMessages = Channel.CreateUnbounded<Message>(new UnboundedChannelOptions
{
SingleReader = true,
SingleWriter = false,
AllowSynchronousContinuations = false,
});
this.runtimeClient = runtimeClient;
this.grainReferenceRuntime = grainReferenceRuntime;
this.grainFactory = grainFactory;
this.invokableObjects = new InvokableObjectManager(
this,
runtimeClient,
serializationManager,
messagingTrace,
logger);
this.siloMessageCenter = messageCenter;
this.messagingTrace = messagingTrace;
this.logger = logger;
this.ClientId = CreateHostedClientGrainId(siloDetails.SiloAddress);
this.Address = Gateway.GetClientActivationAddress(this.ClientId.GrainId, siloDetails.SiloAddress);
this.GrainReference = referenceActivator.CreateReference(this.ClientId.GrainId, default);
}
public static ClientGrainId CreateHostedClientGrainId(SiloAddress siloAddress) => ClientGrainId.Create($"hosted-{siloAddress.ToParsableString()}");
/// <inheritdoc />
public ClientGrainId ClientId { get; }
public GrainReference GrainReference { get; }
public GrainId GrainId => this.ClientId.GrainId;
public IAddressable GrainInstance => null;
public ActivationId ActivationId => this.Address.Activation;
public ActivationAddress Address { get; }
public IServiceProvider ActivationServices => this.runtimeClient.ServiceProvider;
public IGrainLifecycle ObservableLifecycle => throw new NotImplementedException();
/// <inheritdoc />
public override string ToString() => $"{nameof(HostedClient)}_{this.Address}";
/// <inheritdoc />
public IAddressable CreateObjectReference(IAddressable obj, IGrainMethodInvoker invoker)
{
if (obj is GrainReference) throw new ArgumentException("Argument obj is already a grain reference.");
var observerId = ObserverGrainId.Create(this.ClientId);
var grainReference = this.grainFactory.GetGrain(observerId.GrainId);
if (!this.invokableObjects.TryRegister(obj, observerId, invoker))
{
throw new ArgumentException(
string.Format("Failed to add new observer {0} to localObjects collection.", grainReference),
nameof(grainReference));
}
return grainReference;
}
/// <inheritdoc />
public void DeleteObjectReference(IAddressable obj)
{
if (!(obj is GrainReference reference))
{
throw new ArgumentException("Argument reference is not a grain reference.");
}
if (!ObserverGrainId.TryParse(reference.GrainId, out var observerId))
{
throw new ArgumentException($"Reference {reference.GrainId} is not an observer reference");
}
if (!invokableObjects.TryDeregister(observerId))
{
throw new ArgumentException("Reference is not associated with a local object.", "reference");
}
}
public TComponent GetComponent<TComponent>()
{
if (this is TComponent component) return component;
return default;
}
public void SetComponent<TComponent>(TComponent instance)
{
throw new NotSupportedException($"Cannot set components on shared client instance. Extension contract: {typeof(TComponent)}. Component: {instance} (Type: {instance?.GetType()})");
}
/// <inheritdoc />
public bool TryDispatchToClient(Message message)
{
if (!ClientGrainId.TryParse(message.TargetGrain, out var targetClient) || !this.ClientId.Equals(targetClient))
{
return false;
}
if (message.IsExpired)
{
this.messagingTrace.OnDropExpiredMessage(message, MessagingStatisticsGroup.Phase.Receive);
return true;
}
this.ReceiveMessage(message);
return true;
}
public void ReceiveMessage(object message)
{
var msg = (Message)message;
if (msg.Direction == Message.Directions.Response)
{
// Requests are made through the runtime client, so deliver responses to the rutnime client so that the request callback can be executed.
this.runtimeClient.ReceiveResponse(msg);
}
else
{
// Requests against client objects are scheduled for execution on the client.
this.incomingMessages.Writer.TryWrite(msg);
}
}
/// <inheritdoc />
void IDisposable.Dispose()
{
if (this.disposing) return;
this.disposing = true;
Utils.SafeExecute(() => this.siloMessageCenter.SetHostedClient(null));
Utils.SafeExecute(() => this.incomingMessages.Writer.TryComplete());
Utils.SafeExecute(() => this.messagePump?.GetAwaiter().GetResult());
}
private void Start()
{
this.messagePump = Task.Run(this.RunClientMessagePump);
}
private async Task RunClientMessagePump()
{
var reader = this.incomingMessages.Reader;
while (true)
{
try
{
var more = await reader.WaitToReadAsync();
if (!more)
{
this.logger.LogInformation($"{nameof(HostedClient)} completed processing all messages. Shutting down.");
break;
}
while (reader.TryRead(out var message))
{
if (message == null) continue;
switch (message.Direction)
{
case Message.Directions.OneWay:
case Message.Directions.Request:
this.invokableObjects.Dispatch(message);
break;
default:
this.logger.LogError((int)ErrorCode.Runtime_Error_100327, "Message not supported: {Message}", message);
break;
}
}
}
catch (Exception exception)
{
this.logger.LogError((int)ErrorCode.Runtime_Error_100326, "RunClientMessagePump has thrown an exception: {Exception}. Continuing.", exception);
}
}
}
void ILifecycleParticipant<ISiloLifecycle>.Participate(ISiloLifecycle lifecycle)
{
lifecycle.Subscribe("HostedClient", ServiceLifecycleStage.RuntimeGrainServices, OnStart, OnStop);
Task OnStart(CancellationToken cancellation)
{
if (cancellation.IsCancellationRequested) return Task.CompletedTask;
// Register with the message center so that we can receive messages.
this.siloMessageCenter.SetHostedClient(this);
// Start pumping messages.
this.Start();
var clusterClient = this.runtimeClient.ServiceProvider.GetRequiredService<IClusterClient>();
return clusterClient.Connect();
}
async Task OnStop(CancellationToken cancellation)
{
this.incomingMessages.Writer.TryComplete();
if (this.messagePump != null)
{
await Task.WhenAny(cancellation.WhenCancelled(), this.messagePump);
}
if (cancellation.IsCancellationRequested) return;
var clusterClient = this.runtimeClient.ServiceProvider.GetRequiredService<IClusterClient>();
await clusterClient.Close();
}
}
public bool Equals(IGrainContext other) => ReferenceEquals(this, other);
public (TExtension, TExtensionInterface) GetOrSetExtension<TExtension, TExtensionInterface>(Func<TExtension> newExtensionFunc)
where TExtension : TExtensionInterface
where TExtensionInterface : IGrainExtension
{
(TExtension, TExtensionInterface) result;
if (this.TryGetExtension(out result))
{
return result;
}
lock (this.lockObj)
{
if (this.TryGetExtension(out result))
{
return result;
}
var implementation = newExtensionFunc();
var reference = this.grainFactory.CreateObjectReference<TExtensionInterface>(implementation);
_extensions[typeof(TExtensionInterface)] = (implementation, reference);
result = (implementation, reference);
return result;
}
}
private bool TryGetExtension<TExtension, TExtensionInterface>(out (TExtension, TExtensionInterface) result)
where TExtension : TExtensionInterface
where TExtensionInterface : IGrainExtension
{
if (_extensions.TryGetValue(typeof(TExtensionInterface), out var existing))
{
if (existing.Implementation is TExtension typedResult)
{
result = (typedResult, existing.Reference.AsReference<TExtensionInterface>());
return true;
}
throw new InvalidCastException($"Cannot cast existing extension of type {existing.Implementation} to target type {typeof(TExtension)}");
}
result = default;
return false;
}
private bool TryGetExtension<TExtensionInterface>(out TExtensionInterface result)
where TExtensionInterface : IGrainExtension
{
if (_extensions.TryGetValue(typeof(TExtensionInterface), out var existing))
{
result = (TExtensionInterface)existing.Implementation;
return true;
}
result = default;
return false;
}
public TExtensionInterface GetExtension<TExtensionInterface>()
where TExtensionInterface : IGrainExtension
{
if (this.TryGetExtension<TExtensionInterface>(out var result))
{
return result;
}
lock (this.lockObj)
{
if (this.TryGetExtension(out result))
{
return result;
}
var implementation = this.ActivationServices.GetServiceByKey<Type, IGrainExtension>(typeof(TExtensionInterface));
if (implementation is null)
{
throw new GrainExtensionNotInstalledException($"No extension of type {typeof(TExtensionInterface)} is installed on this instance and no implementations are registered for automated install");
}
var reference = this.GrainReference.Cast<TExtensionInterface>();
_extensions[typeof(TExtensionInterface)] = (implementation, reference);
result = (TExtensionInterface)implementation;
return result;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Pb.Collections
{
/// <summary>
/// An integer vector class with two values
/// </summary>
[System.Serializable]
public struct IVector2 :
System.IComparable,
System.IComparable<IVector2>
{
public class IntervalEnumerable :
IEnumerable,
IEnumerable<IVector2>
{
public class Enumerator :
System.IDisposable,
IEnumerator,
IEnumerator<IVector2>
{
private IntervalEnumerable enumerable_ = null;
private IVector2 current_ = IVector2.zero;
private IVector2 Current_()
{
return current_;
}
private bool MoveNext_()
{
if (current_.x < enumerable_.end.x)
current_ = new IVector2(current_.x + 1, current_.y);
else if (current_.y < enumerable_.end.y)
current_ = new IVector2(enumerable_.begin.x, current_.y + 1);
else
return false;
return true;
}
private void Reset_()
{
current_ = IVector2.zero;
}
private void Dispose_()
{
enumerable_ = null;
current_ = IVector2.zero;
}
/// <summary>
/// Constructs the enumerator from an interval enumerable to enumerate over
/// </summary>
/// <param name="enumerable">The interval enumerable to enumerate over</param>
public Enumerator(IntervalEnumerable enumerable)
{
enumerable_ = enumerable;
current_ = enumerable_.begin + IVector2.left;
}
void System.IDisposable.Dispose()
{
Dispose_();
}
object IEnumerator.Current
{
get
{
return Current_();
}
}
bool IEnumerator.MoveNext()
{
return MoveNext_();
}
void IEnumerator.Reset()
{
Reset_();
}
IVector2 IEnumerator<IVector2>.Current
{
get
{
return Current_();
}
}
}
private IVector2 begin;
private IVector2 end;
private Enumerator GetEnumerator_()
{
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator_();
}
IEnumerator<IVector2> IEnumerable<IVector2>.GetEnumerator()
{
return GetEnumerator_();
}
/// <summary>
/// Constructs the interval enumerable with a beginning and ending IVector2
/// </summary>
/// <param name="b">The beginning vector</param>
/// <param name="e">The ending vector</param>
public IntervalEnumerable(IVector2 b, IVector2 e)
{
begin = b;
end = e;
}
}
/// <summary>
/// Gets an enumerator over the interval [a, b]
/// </summary>
/// <param name="a">The beginning IVector2</param>
/// <param name="b">The ending IVector2</param>
/// <returns>An enumerable over the interval between the IVector2s</returns>
public static IntervalEnumerable Interval(IVector2 a, IVector2 b)
{
return new IntervalEnumerable(a, b);
}
/// <summary>
/// Gets an enumerator over the interval [a, b)
/// </summary>
/// <param name="a">The beginning IVector2</param>
/// <param name="b">The ending IVector2</param>
/// <returns>An enumerable over the interval between the IVector2s</returns>
public static IntervalEnumerable Range(IVector2 a, IVector2 b)
{
return new IntervalEnumerable(a, b - IVector2.one);
}
/// <summary>
/// The zero integer vector
/// </summary>
public static readonly IVector2 zero = new IVector2(0, 0);
/// <summary>
/// The one integer vector
/// </summary>
public static readonly IVector2 one = new IVector2(1, 1);
/// <summary>
/// The left integer vector
/// </summary>
public static readonly IVector2 left = new IVector2(-1, 0);
/// <summary>
/// The right integer vector
/// </summary>
public static readonly IVector2 right = new IVector2(1, 0);
/// <summary>
/// The down integer vector
/// </summary>
public static readonly IVector2 down = new IVector2(0, -1);
/// <summary>
/// The up integer vector
/// </summary>
public static readonly IVector2 up = new IVector2(0, 1);
/// <summary>
/// Makes a new Vector2 out of an integer vector with two components
/// </summary>
/// <param name="iv">The IVector2</param>
/// <returns>A new Vector2</returns>
public static explicit operator Vector2(IVector2 iv)
{
return new Vector2(iv.x, iv.y);
}
/// <summary>
/// Makes a new IVector3 out of an integer vector with two components
/// </summary>
/// <param name="iv"></param>
/// <returns></returns>
public static explicit operator IVector3(IVector2 iv)
{
return new IVector3(iv.x, iv.y, 0);
}
/// <summary>
/// Makes a new Vector3 out of an integer vector with two components
/// </summary>
/// <param name="iv"></param>
/// <returns></returns>
public static explicit operator Vector3(IVector2 iv)
{
return new Vector3(iv.x, iv.y, 0.0f);
}
/// <summary>
/// The X component
/// </summary>
public int x;
/// <summary>
/// The Y component
/// </summary>
public int y;
private int CompareTo_(IVector2 other)
{
if (x > other.x)
return 1;
else if (x < other.x)
return -1;
else
if (y > other.y)
return 1;
else if (y < other.y)
return -1;
else
return 0;
}
int System.IComparable.CompareTo(object obj)
{
if (obj == null || !(obj is IVector2))
return 1;
return CompareTo_((IVector2)obj);
}
int System.IComparable<IVector2>.CompareTo(IVector2 other)
{
return CompareTo_(other);
}
/// <summary>
/// Gets the X component if the index is 0, and the Y component if the index is 1
/// </summary>
/// <param name="i">The index of the component to get</param>
/// <returns>The indexed component</returns>
public int this[int i]
{
get
{
switch (i)
{
case 0:
return x;
case 1:
return y;
default:
throw new System.ArgumentOutOfRangeException("Requested value not in range");
}
}
}
/// <summary>
/// Constructor for the integer vector
/// </summary>
/// <param name="a">The X component</param>
/// <param name="b">The Y component</param>
public IVector2(int a = 0, int b = 0)
{
x = a;
y = b;
}
/// <summary>
/// Determines whether the integer vector is in the interval [lower, upper]
/// </summary>
/// <param name="lower">The lower vector</param>
/// <param name="upper">The upper vector</param>
/// <returns>Whether the integer vector is in the interval</returns>
public bool inInterval(IVector2 lower, IVector2 upper)
{
return (x >= lower.x && x <= upper.x && y >= lower.y && y <= upper.y);
}
/// <summary>
/// Determines whether the integer vector is in the range [lower, upper)
/// </summary>
/// <param name="lower">The lower vector</param>
/// <param name="upper">The upper vector</param>
/// <returns>Whether the vector is in the range</returns>
public bool inRange(IVector2 lower, IVector2 upper)
{
return (x >= lower.x && x < upper.x && y >= lower.y && y < upper.y);
}
/// <summary>
/// Calculates the dot product of two integer vectors
/// </summary>
/// <param name="lhs">The left-hand side argument</param>
/// <param name="rhs">The right-hand size argument</param>
/// <returns>The dot product of the two integer vectors</returns>
public static int Dot(IVector2 lhs, IVector2 rhs)
{
return lhs.x * rhs.x + lhs.y * rhs.y;
}
/// <summary>
/// Calculates a new integer vector with the larger components of both integer vectors
/// </summary>
/// <param name="lhs">The left-hand side argument</param>
/// <param name="rhs">The right-hand side argument</param>
/// <returns>A new integer vector with the largest components of both integer vectors</returns>
public static IVector2 Max(IVector2 lhs, IVector2 rhs)
{
return new IVector2((lhs.x > rhs.x ? lhs.x : rhs.x), (lhs.y > rhs.y ? lhs.y : rhs.y));
}
/// <summary>
/// Calculates a new integer vector with the smaller components of both integer vectors
/// </summary>
/// <param name="lhs">The left-hand side argument</param>
/// <param name="rhs">The right-hand side argument</param>
/// <returns>A new integer vector with the smallest components of both integer vectors</returns>
public static IVector2 Min(IVector2 lhs, IVector2 rhs)
{
return new IVector2((lhs.x < rhs.x ? lhs.x : rhs.x), (lhs.y < rhs.y ? lhs.y : rhs.y));
}
/// <summary>
/// Multiplies two integer vectors component-wise
/// </summary>
/// <param name="a">The integer to scale</param>
/// <param name="b">The integer to scale by</param>
/// <returns>A scaled integer vector</returns>
public static IVector2 Scale(IVector2 a, IVector2 b)
{
return new IVector2(a.x * b.x, a.y * b.y);
}
/// <summary>
/// Adds together two integer vectors
/// </summary>
/// <param name="a">The first integer vector to add</param>
/// <param name="b">The second integer vector to add</param>
/// <returns>The sum of the two integer vectors</returns>
public static IVector2 operator +(IVector2 a, IVector2 b)
{
return new IVector2(a.x + b.x, a.y + b.y);
}
/// <summary>
/// Subtracts one integer vector from another
/// </summary>
/// <param name="a">The integer vector to subtract from</param>
/// <param name="b">The integer vector to subtract</param>
/// <returns>The difference of the two integer vectors</returns>
public static IVector2 operator -(IVector2 a, IVector2 b)
{
return new IVector2(a.x - b.x, a.y - b.y);
}
/// <summary>
/// Multiplies an integer vector by a scalar
/// </summary>
/// <param name="a">The integer vector to scale</param>
/// <param name="b">The amount to scale the integer vector by</param>
/// <returns>The integer vector scaled by the given scalar</returns>
public static IVector2 operator *(IVector2 a, int b)
{
return new IVector2(a.x * b, a.y * b);
}
/// <summary>
/// Divides an integer vector by a scalar
/// </summary>
/// <param name="a">The integer vector to divide</param>
/// <param name="b">The amount to divide the integer vector by</param>
/// <returns>The integer vector divided by the given scalar</returns>
public static IVector2 operator /(IVector2 a, int b)
{
return new IVector2(a.x / b, a.y / b);
}
/// <summary>
/// Calculates the area of the rectangle with dimensions of the given vector
/// </summary>
/// <param name="v">The vector to use</param>
/// <returns>The area of the rectangle corresponding to the vector</returns>
public static int Area(IVector2 v)
{
return v.x * v.y;
}
/// <summary>
/// Calculates the index of a position in an area with indices organized X then Y
/// </summary>
/// <param name="position">The position in an area</param>
/// <param name="area">The area</param>
/// <returns>The index of the position in the area</returns>
public static int ToIndex(IVector2 position, IVector2 area)
{
return position.y * area.x + position.x;
}
/// <summary>
/// Calculates the position of an index in an area with indices organized X then Y
/// </summary>
/// <param name="index">The index in an area</param>
/// <param name="area">The area</param>
/// <returns>The position of the index in the area</returns>
public static IVector2 FromIndex(int index, IVector2 area)
{
return new IVector2(index % area.x, index / area.x);
}
/// <summary>
/// Creates a new IVector2 from a Vector2 by flooring the components
/// </summary>
/// <param name="v">A Vector2</param>
/// <returns>An IVector2</returns>
public static IVector2 Floor(Vector2 v)
{
return new IVector2(Mathf.FloorToInt(v.x), Mathf.FloorToInt(v.y));
}
/// <summary>
/// Creates a new IVector2 from a Vector2 by ceiling the components
/// </summary>
/// <param name="v">A Vector2</param>
/// <returns>An IVector2</returns>
public static IVector2 Ceil(Vector2 v)
{
return new IVector2(Mathf.CeilToInt(v.x), Mathf.CeilToInt(v.y));
}
/// <summary>
/// Creates a new IVector2 from a Vector2 by rounding the components
/// </summary>
/// <param name="v">A Vector2</param>
/// <returns>An IVector2</returns>
public static IVector2 Round(Vector2 v)
{
return new IVector2(Mathf.RoundToInt(v.x), Mathf.RoundToInt(v.y));
}
/// <summary>
/// Determines the hash code of the integer vector
/// </summary>
/// <returns>The hash code of the integer vector</returns>
public override int GetHashCode()
{
return Math.NToZ(Math.Pair(Math.ZToN(x.GetHashCode()), Math.ZToN(y.GetHashCode())));
}
/// <summary>
/// Gets a string representing the integer vector
/// </summary>
/// <returns>A string representing the integer vector</returns>
public override string ToString()
{
return "(" + x + ", " + y + ")";
}
}
/// <summary>
/// An integer vector class with two values
/// </summary>
[System.Serializable]
public struct IVector3 :
System.IComparable,
System.IComparable<IVector3>
{
public class RangeEnumerable :
IEnumerable,
IEnumerable<IVector3>
{
public class Enumerator :
System.IDisposable,
IEnumerator,
IEnumerator<IVector3>
{
private RangeEnumerable enumerable_ = null;
private IVector3 current_ = IVector3.zero;
private IVector3 Current_()
{
return current_;
}
private bool MoveNext_()
{
if (current_.x < enumerable_.end.x)
current_ = new IVector3(current_.x + 1, current_.y, current_.z);
else if (current_.y < enumerable_.end.y)
current_ = new IVector3(enumerable_.begin.x, current_.y + 1, current_.z);
else if (current_.z < enumerable_.end.z)
current_ = new IVector3(enumerable_.begin.x, enumerable_.begin.y, current_.z + 1);
else
return false;
return true;
}
private void Reset_()
{
current_ = IVector3.zero;
}
private void Dispose_()
{
enumerable_ = null;
current_ = IVector3.zero;
}
/// <summary>
/// Constructs the enumerator from a range enumerable to enumerate over
/// </summary>
/// <param name="enumerable">The range enumerable to enumerate over</param>
public Enumerator(RangeEnumerable enumerable)
{
enumerable_ = enumerable;
current_ = enumerable_.begin + IVector3.left;
}
void System.IDisposable.Dispose()
{
Dispose_();
}
object IEnumerator.Current
{
get
{
return Current_();
}
}
bool IEnumerator.MoveNext()
{
return MoveNext_();
}
void IEnumerator.Reset()
{
Reset_();
}
IVector3 IEnumerator<IVector3>.Current
{
get
{
return Current_();
}
}
}
private IVector3 begin;
private IVector3 end;
private Enumerator GetEnumerator_()
{
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator_();
}
IEnumerator<IVector3> IEnumerable<IVector3>.GetEnumerator()
{
return GetEnumerator_();
}
/// <summary>
/// Constructs the range enumerable with a beginning and ending IVector2
/// </summary>
/// <param name="b"></param>
/// <param name="e"></param>
public RangeEnumerable(IVector3 b, IVector3 e)
{
begin = b;
end = e;
}
}
/// <summary>
/// Gets an enumerator over the interval [a, b]
/// </summary>
/// <param name="a">The beginning IVector3</param>
/// <param name="b">The ending IVector3</param>
/// <returns>An enumerable over the interval between the IVector3s</returns>
public static RangeEnumerable Interval(IVector3 a, IVector3 b)
{
return new RangeEnumerable(a, b);
}
/// <summary>
/// Gets an enumerator over the interval [a, b)
/// </summary>
/// <param name="a">The beginning IVector3</param>
/// <param name="b">The ending IVector3</param>
/// <returns>An enumerable over the interval between the IVector3s</returns>
public static RangeEnumerable Range(IVector3 a, IVector3 b)
{
return new RangeEnumerable(a, b - IVector3.one);
}
/// <summary>
/// The zero integer vector
/// </summary>
public static readonly IVector3 zero = new IVector3(0, 0, 0);
/// <summary>
/// The one integer vector
/// </summary>
public static readonly IVector3 one = new IVector3(1, 1, 1);
/// <summary>
/// The left integer vector
/// </summary>
public static readonly IVector3 left = new IVector3(-1, 0, 0);
/// <summary>
/// The right integer vector
/// </summary>
public static readonly IVector3 right = new IVector3(1, 0, 0);
/// <summary>
/// The down integer vector
/// </summary>
public static readonly IVector3 down = new IVector3(0, -1, 0);
/// <summary>
/// The up integer vector
/// </summary>
public static readonly IVector3 up = new IVector3(0, 1, 0);
/// <summary>
/// The back integer vector
/// </summary>
public static readonly IVector3 back = new IVector3(0, 0, -1);
/// <summary>
/// The forward integer vector
/// </summary>
public static readonly IVector3 forward = new IVector3(0, 0, 1);
/// <summary>
/// Makes a new Vector3 out of an integer vector with three components
/// </summary>
/// <param name="iv">The IVector3</param>
/// <returns>A new Vector3</returns>
public static explicit operator Vector3(IVector3 iv)
{
return new Vector3(iv.x, iv.y, iv.z);
}
/// <summary>
/// The X component
/// </summary>
public int x;
/// <summary>
/// The Y component
/// </summary>
public int y;
/// <summary>
/// The Z component
/// </summary>
public int z;
private int CompareTo_(IVector3 other)
{
if (x > other.x)
return 1;
else if (x < other.x)
return -1;
else
if (y > other.y)
return 1;
else if (y < other.y)
return -1;
else
if (z > other.z)
return 1;
else if (z < other.z)
return -1;
else
return 0;
}
int System.IComparable.CompareTo(object obj)
{
if (obj == null || !(obj is IVector3))
return 1;
return CompareTo_((IVector3)obj);
}
int System.IComparable<IVector3>.CompareTo(IVector3 other)
{
return CompareTo_(other);
}
/// <summary>
/// Gets the X component if the index is 0, the Y component if the index is 1, and the Z component if the index is 2
/// </summary>
/// <param name="i">The index of the component to get</param>
/// <returns>The indexed component</returns>
public int this[int i]
{
get
{
switch (i)
{
case 0:
return x;
case 1:
return y;
case 2:
return z;
default:
throw new System.ArgumentOutOfRangeException("Requested value not in range");
}
}
}
/// <summary>
/// Constructor for the integer vector
/// </summary>
/// <param name="a">The X component</param>
/// <param name="b">The Y component</param>
/// <param name="c">The Z component</param>
public IVector3(int a = 0, int b = 0, int c = 0)
{
x = a;
y = b;
z = c;
}
/// <summary>
/// Determines whether the integer vector is in the interval [lower, upper]
/// </summary>
/// <param name="lower">The lower vector</param>
/// <param name="upper">The upper vector</param>
/// <returns>Whether the integer vector is in the interval</returns>
public bool inInterval(IVector3 lower, IVector3 upper)
{
return (x >= lower.x && x <= upper.x && y >= lower.y && y <= upper.y && z >= lower.z && z <= upper.z);
}
/// <summary>
/// Determines whether the integer vector is in the range [lower, upper)
/// </summary>
/// <param name="lower">The lower vector</param>
/// <param name="upper">The upper vector</param>
/// <returns>Whether the vector is in the range</returns>
public bool inRange(IVector3 lower, IVector3 upper)
{
return (x >= lower.x && x < upper.x && y >= lower.y && y < upper.y && z >= lower.z && z < upper.z);
}
/// <summary>
/// Creates a new IVector2 by discarding the Z component
/// </summary>
/// <returns>An IVector2</returns>
public IVector2 discardZ()
{
return new IVector2(x, y);
}
/// <summary>
/// Calculates the dot product of two integer vectors
/// </summary>
/// <param name="lhs">The left-hand side argument</param>
/// <param name="rhs">The right-hand size argument</param>
/// <returns>The dot product of the two integer vectors</returns>
public static int Dot(IVector3 lhs, IVector3 rhs)
{
return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z;
}
/// <summary>
/// Calculates a new integer vector with the larger components of both integer vectors
/// </summary>
/// <param name="lhs">The left-hand side argument</param>
/// <param name="rhs">The right-hand side argument</param>
/// <returns>A new integer vector with the largest components of both integer vectors</returns>
public static IVector3 Max(IVector3 lhs, IVector3 rhs)
{
return new IVector3((lhs.x > rhs.x ? lhs.x : rhs.x), (lhs.y > rhs.y ? lhs.y : rhs.y), (lhs.z > rhs.z ? lhs.z : rhs.z));
}
/// <summary>
/// Calculates a new integer vector with the smaller components of both integer vectors
/// </summary>
/// <param name="lhs">The left-hand side argument</param>
/// <param name="rhs">The right-hand side argument</param>
/// <returns>A new integer vector with the smallest components of both integer vectors</returns>
public static IVector3 Min(IVector3 lhs, IVector3 rhs)
{
return new IVector3((lhs.x < rhs.x ? lhs.x : rhs.x), (lhs.y < rhs.y ? lhs.y : rhs.y), (lhs.z < rhs.z ? lhs.z : rhs.z));
}
/// <summary>
/// Multiplies two integer vectors component-wise
/// </summary>
/// <param name="a">The integer to scale</param>
/// <param name="b">The integer to scale by</param>
/// <returns>A scaled integer vector</returns>
public static IVector3 Scale(IVector3 a, IVector3 b)
{
return new IVector3(a.x * b.x, a.y * b.y, a.z * b.z);
}
/// <summary>
/// Adds together two integer vectors
/// </summary>
/// <param name="a">The first integer vector to add</param>
/// <param name="b">The second integer vector to add</param>
/// <returns>The sum of the two integer vectors</returns>
public static IVector3 operator +(IVector3 a, IVector3 b)
{
return new IVector3(a.x + b.x, a.y + b.y, a.z + b.z);
}
/// <summary>
/// Subtracts one integer vector from another
/// </summary>
/// <param name="a">The integer vector to subtract from</param>
/// <param name="b">The integer vector to subtract</param>
/// <returns>The difference of the two integer vectors</returns>
public static IVector3 operator -(IVector3 a, IVector3 b)
{
return new IVector3(a.x - b.x, a.y - b.y, a.z - b.z);
}
/// <summary>
/// Multiplies an integer vector by a scalar
/// </summary>
/// <param name="a">The integer vector to scale</param>
/// <param name="b">The amount to scale the integer vector by</param>
/// <returns>The integer vector scaled by the given scalar</returns>
public static IVector3 operator *(IVector3 a, int b)
{
return new IVector3(a.x * b, a.y * b, a.z * b);
}
/// <summary>
/// Divides an integer vector by a scalar
/// </summary>
/// <param name="a">The integer vector to divide</param>
/// <param name="b">The amount to divide the integer vector by</param>
/// <returns>The integer vector divided by the given scalar</returns>
public static IVector3 operator /(IVector3 a, int b)
{
return new IVector3(a.x / b, a.y / b, a.z / b);
}
/// <summary>
/// Calculates the volume of the rectangular prism with dimensions of the given vector
/// </summary>
/// <param name="v">The vector to use</param>
/// <returns>The volume of the rectangular prism corresponding to the vector</returns>
public static int Volume(IVector3 v)
{
return v.x * v.y * v.z;
}
/// <summary>
/// Calculates the index of a position in a volume with indices organized X, Y, then Z
/// </summary>
/// <param name="position">The position in a volume</param>
/// <param name="volume">The volume</param>
/// <returns>The index of the position in the volume</returns>
public static int ToIndex(IVector3 position, IVector3 volume)
{
return (position.z * volume.y + position.y) * volume.x + position.x;
}
/// <summary>
/// Calculates the position of an index in an volume with indices organized X then Y
/// </summary>
/// <param name="index">The index in an volume</param>
/// <param name="area">The volume</param>
/// <returns>The position of the index in the volume</returns>
public static IVector3 FromIndex(int index, IVector3 volume)
{
return new IVector3(index % volume.x, index / volume.x % volume.y, index / volume.x / volume.y);
}
/// <summary>
/// Creates a new IVector3 from a Vector3 by flooring the components
/// </summary>
/// <param name="v">A Vector3</param>
/// <returns>An IVector3</returns>
public static IVector3 Floor(Vector3 v)
{
return new IVector3(Mathf.FloorToInt(v.x), Mathf.FloorToInt(v.y), Mathf.FloorToInt(v.z));
}
/// <summary>
/// Creates a new IVector3 from a Vector3 by ceiling the components
/// </summary>
/// <param name="v">A Vector3</param>
/// <returns>An IVector3</returns>
public static IVector3 Ceil(Vector3 v)
{
return new IVector3(Mathf.CeilToInt(v.x), Mathf.CeilToInt(v.y), Mathf.CeilToInt(v.z));
}
/// <summary>
/// Creates a new IVector3 from a Vector3 by rounding the components
/// </summary>
/// <param name="v">A Vector3</param>
/// <returns>An IVector3</returns>
public static IVector3 Round(Vector3 v)
{
return new IVector3(Mathf.RoundToInt(v.x), Mathf.RoundToInt(v.y), Mathf.RoundToInt(v.z));
}
/// <summary>
/// Determines the hash code of the integer vector
/// </summary>
/// <returns>The hash code of the integer vector</returns>
public override int GetHashCode()
{
return Math.NToZ(
Math.Pair(
Math.ZToN(x.GetHashCode()),
Math.Pair(
Math.ZToN(y.GetHashCode()),
Math.ZToN(z.GetHashCode())
)
)
);
}
/// <summary>
/// Gets a string representing the integer vector
/// </summary>
/// <returns>A string representing the integer vector</returns>
public override string ToString()
{
return "(" + x + ", " + y + ", " + z + ")";
}
}
}
| |
//-----------------------------------------------------------------------------
// <copyright file="ServerManager.cs" company="WheelMUD Development Team">
// Copyright (c) WheelMUD Development Team. See LICENSE.txt. This file is
// subject to the Microsoft Public License. All other rights reserved.
// </copyright>
// <summary>
// Controls the flow of data through the various server layers.
// Created: August 2006 by Foxedup
// </summary>
//-----------------------------------------------------------------------------
namespace WheelMUD.Server
{
using System;
using WheelMUD.Core;
using WheelMUD.Core.Events;
using WheelMUD.Interfaces;
/// <summary>The ServerManager controls the flow of data through the various server layers.</summary>
public class ServerManager : ManagerSystem
{
/// <summary>The singleton instance of this class.</summary>
private static readonly ServerManager SingletonInstance = new ServerManager();
/// <summary>The base server.</summary>
private readonly BaseServer baseServer = new BaseServer();
/// <summary>The telnet server.</summary>
private readonly TelnetServer telnetServer = new TelnetServer();
/// <summary>The input parser.</summary>
private readonly InputParser inputParser = new InputParser();
/// <summary>Prevents a default instance of the <see cref="ServerManager"/> class from being created.</summary>
private ServerManager()
{
// Set up our event handlers for the base server.
this.baseServer.ClientConnect += this.BaseServer_OnClientConnect;
this.baseServer.DataReceived += this.BaseServer_OnDataReceived;
this.baseServer.DataSent += BaseServer_OnDataSent;
this.baseServer.ClientDisconnected += this.BaseServer_OnClientDisconnected;
// Set up our event handlers for the command server.
this.inputParser.InputReceived += this.CommandServer_OnInputReceived;
// Set up to respond to player log out events by closing those connections.
PlayerManager.GlobalPlayerLogOutEvent += this.PlayerManager_GlobalPlayerLogOutEvent;
}
/// <summary>Gets the singleton instance of this ServerManager.</summary>
public static ServerManager Instance
{
get { return SingletonInstance; }
}
/// <summary>Gets the start time.</summary>
public DateTime StartTime { get; private set; }
/// <summary>Starts this system's individual components.</summary>
public override void Start()
{
this.SystemHost.UpdateSystemHost(this, "Starting...");
this.baseServer.SubscribeToSystem(this);
this.baseServer.Start();
this.telnetServer.Start();
this.SystemHost.UpdateSystemHost(this, "Started on port " + this.baseServer.Port);
this.StartTime = DateTime.Now;
}
/// <summary>Stops this system's individual components.</summary>
public override void Stop()
{
this.SystemHost.UpdateSystemHost(this, "Stopping...");
this.telnetServer.Stop();
this.baseServer.Stop();
this.SystemHost.UpdateSystemHost(this, "Stopped");
}
/// <summary>Closes the specified connection.</summary>
/// <param name="connectionId">The connection ID to be closed.</param>
public void CloseConnection(string connectionId)
{
this.baseServer.CloseConnection(connectionId);
}
/// <summary>Closes the specified connection.</summary>
/// <param name="connection">The connection to be closed.</param>
public void CloseConnection(IConnection connection)
{
this.baseServer.CloseConnection(connection);
}
/// <summary>Gets the specified connection.</summary>
/// <param name="connectionId">The connection ID to get.</param>
/// <returns> The get connection.</returns>
public IConnection GetConnection(string connectionId)
{
return this.baseServer.GetConnection(connectionId);
}
/// <summary>This is called when the base server sent data.</summary>
/// <param name="sender">The sender of this event.</param>
/// <param name="args">The event arguments.</param>
private static void BaseServer_OnDataSent(object sender, ConnectionArgs args)
{
}
/// <summary>Sends the incoming data up the server chain for processing.</summary>
/// <param name="sender">The connection sending the data</param>
/// <param name="data">The data being sent</param>
private void ProcessIncomingData(IConnection sender, byte[] data)
{
byte[] bytes = this.telnetServer.OnDataReceived(sender, data);
// All bytes might have been stripped out so check for that.
if (bytes.Length > 0)
{
this.inputParser.OnDataReceived(sender, bytes);
}
}
/// <summary>This is called when we receive input on a connection.</summary>
/// <param name="sender">The sender of this event.</param>
/// <param name="args">The event arguments.</param>
/// <param name="input">The input received.</param>
private void CommandServer_OnInputReceived(object sender, ConnectionArgs args, string input)
{
// We send the data received onto our session manager to deal with the input.
SessionManager.Instance.OnInputReceived(args.Connection, input);
}
/// <summary>This is called when a client connects to the base server.</summary>
/// <param name="sender">The sender of this event.</param>
/// <param name="args">The event arguments.</param>
private void BaseServer_OnClientConnect(object sender, ConnectionArgs args)
{
// We send the connection to our session manager to deal with.
this.UpdateSubSystemHost((ISubSystem)sender, args.Connection.ID + " - Connected");
SessionManager.Instance.OnSessionConnected(args.Connection);
}
/// <summary>This is called when a client disconnects from the base server.</summary>
/// <param name="sender">The sender of this event.</param>
/// <param name="args">The event arguments.</param>
private void BaseServer_OnClientDisconnected(object sender, ConnectionArgs args)
{
SessionManager.Instance.OnSessionDisconnected(args.Connection);
this.UpdateSubSystemHost((ISubSystem)sender, args.Connection.ID + " - Disconnected");
}
/// <summary>This is called when the base server receives data.</summary>
/// <param name="sender">The sender of this event.</param>
/// <param name="args">The event arguments.</param>
private void BaseServer_OnDataReceived(object sender, ConnectionArgs args)
{
this.ProcessIncomingData(args.Connection, args.Connection.Data);
}
/// <summary>Processes the player log out events from the player manager; disconnects logged out characters.</summary>
/// <param name="root">The root location where the log out event originated.</param>
/// <param name="e">The event arguments.</param>
private void PlayerManager_GlobalPlayerLogOutEvent(Thing root, GameEvent e)
{
// If the player was user-controlled during log out, disconnect that user.
var userControlledBehavior = e.ActiveThing.Behaviors.FindFirst<UserControlledBehavior>();
if (userControlledBehavior != null && userControlledBehavior.Controller != null)
{
var session = userControlledBehavior.Controller as Session;
if (session != null && session.Connection != null)
{
session.Connection.Disconnect();
}
}
}
/// <summary>MEF exporter for ServerManager.</summary>
[ExportSystem]
public class ServerManagerExporter : SystemExporter
{
/// <summary>Gets the singleton system instance.</summary>
/// <returns>A new instance of the singleton system.</returns>
public override ISystem Instance
{
get { return ServerManager.Instance; }
}
/// <summary>Gets the Type of the singleton system, without instantiating it.</summary>
/// <returns>The Type of the singleton system.</returns>
public override Type SystemType
{
get { return typeof(ServerManager); }
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// 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.Diagnostics.Contracts;
/*
Follows "Introduction to Operations Research",Hillier Liberman, eight edition,
chapter "Quadratic Programming"
*/
namespace Microsoft.Glee.Optimization
{
/// <summary>
/// Solves: maximize c*x-0.5xt*Q*x; where xt is transpose of x
/// and Q is a symmetric matrix, Q is also positive semidefinite: that is xt*Qx*x>=0 for any x>=0.
/// Unknown x is not-negative and is a subject to linear constraints added by AddConstraint method.
/// </summary>
public class QP : IQuadraticProgram
{
#region Object Invariant
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(Q != null);
Contract.Invariant(lp != null);
Contract.Invariant(n >= 0);
Contract.Invariant(m >= 0);
Contract.Invariant(A.Count == b.Count);
}
#endregion
readonly List<double[]> A = new List<double[]>();
readonly List<double> b = new List<double>();
readonly Dictionary<IntPair, double> Q = new Dictionary<IntPair, double>();
double[] c;
double[] solution;
int m; //dimensions
int n;
Status status = Status.Infeasible;
readonly LinearProgramInterface lp = LpFactory.CreateLP();
/// <summary>
/// add a linear constraint in the form coeffs*x relation rightSide
/// </summary>
/// <param name="coeffs"></param>
/// <param name="relation">relation can be only "less or equal" or
/// "greater or equal"</param>
/// <param name="rightSide"></param>
public void AddConstraint(double[] coeffs, Relation relation, double rightSide)
{
if (coeffs == null || relation == Relation.Equal)
throw new InvalidDataException();
coeffs = (double[])coeffs.Clone();
//we need to bring every relation to "less or equal"
if (relation == Relation.GreaterOrEqual)
{
for (int i = 0; i < coeffs.Length; i++)
coeffs[i] *= -1;
rightSide = -rightSide;
}
A.Add(coeffs);
b.Add(rightSide);
}
/// <summary>
/// sets i,j element of Q
/// </summary>
/// <param name="i"></param>
/// <param name="j"></param>
/// <param name="qij"></param>
public void SetQMember(int i, int j, double qij)
{
//use here the fact that the matrix is symmetric
if (i <= j)
Q[new IntPair(i, j)] = qij;
else
Q[new IntPair(j, i)] = qij;
if (i + 1 > n)
n = i + 1;
if (j + 1 > n)
n = j + 1;
}
/// <summary>
/// adds d to i,j element of Q
/// </summary>
/// <param name="i"></param>
/// <param name="j"></param>
/// <param name="qij"></param>
public void AddToQMember(int i, int j, double d)
{
IntPair pair = (i <= j) ? new IntPair(i, j) : new IntPair(j, i);
double val = 0;
if (Q.TryGetValue(pair, out val))
{
Q[pair] = val + d;
}
else
Q[pair] = d;
if (i + 1 > n)
n = i + 1;
if (j + 1 > n)
n = j + 1;
}
public void SetLinearCosts(double[] costs)
{
if (costs == null)
throw new InvalidDataException();
this.c = (double[])costs.Clone();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public double[] Solution
{
get
{
if (solution != null)
return solution;
double[] sol = CalculateSolution();
if (sol == null)
{
return null;
}
solution = new double[n];
for (int i = 0; i < n; i++)
{
solution[i] = sol[i];
}
this.status = Status.Optimal;
return solution;
}
}
public Status Status
{
get { return this.status; }
}
double[] CalculateSolution()
{
Contract.Ensures(Contract.Result<double[]>() == null || Contract.Result<double[]>().Length == this.n);
//we need to create an LP system which is KKT condtitions
//of the quadratic problem.
//The conditions look like
//Qx+Atu-y=ct
//Ax+v=b
//So, we have a vector of variables (x,y,u,v).
//Q is an n by n matrix, x has length n.
//Matrix A is a m by n: u's length is m
//y has dimension n, v has length m
//xy+uv=0
m = A.Count;
double t;
var totalVars = 2 * (n + m);
//we put variables in the order x,y,u,v
//make Qx+Au-y=c. There are n equalities here
//coefficients before x
for (var i = 0; i < n; i++)
{//creating the i-th equality
var cf = new double[totalVars];
for (var j = 0; j < n; j++)
{
if (TryGetQMember(i, j, out t))
cf[j] = t;
}
//coefficients before y are all -1, and start from the index n
cf[i + n] = -1;
//coefficients before u start from 2*n
for (var j = 0; j < m; j++)
{
cf[2 * n + j] = A[j][i];
}
if (c != null)
{
Contract.Assume(i < c.Length);
lp.AddConstraint(cf, Relation.Equal, this.c[i]);
}
else
{
lp.AddConstraint(cf, Relation.Equal, 0);
}
}
for (int i = 0; i < totalVars; i++)
lp.LimitVariableFromBelow(i, 0);
//creating Ax+v=b
for (int i = 0; i < m; i++)
{
//creating the i-th equality
var cf = new double[totalVars];
var AI = A[i];
//coefficients before x
for (int j = 0; j < n; j++)
{
Contract.Assume(j < AI.Length);
cf[j] = AI[j];
}
//coefficients before v are all 1
// they start from 2*n+m
cf[i + 2 * n + m] = 1;
lp.AddConstraint(cf, Relation.Equal, this.b[i]);
}
//the pairs forbidden for complimentary slackness
var forbiddenPairs = new int[totalVars];
for (int i = 0; i < n; i++)
{
forbiddenPairs[i] = n + i; //taking care that x[i]y[i]=0
forbiddenPairs[n + i] = i;
}
for (int i = 0; i < m; i++)
{
forbiddenPairs[2 * n + i] = 2 * n + m + i;
forbiddenPairs[2 * n + m + i] = 2 * n + i;
}
lp.ForbiddenPairs = forbiddenPairs;
lp.EpsilonForArtificials = Double.MaxValue;//don't care
lp.EpsilonForReducedCosts = 0.0001;
double[] ret = lp.FeasibleSolution();
if (lp.Status == Status.Feasible)
return ret;
return null;
}
[Pure]
bool TryGetQMember(int i, int j, out double t)
{
if (i <= j)
return Q.TryGetValue(new IntPair(i, j), out t);
return Q.TryGetValue(new IntPair(j, i), out t);
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// 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.Threading;
namespace Alachisoft.NCache.Common.Threading
{
/// <summary>
/// Support class used to handle threads
/// </summary>
public class ThreadClass : IThreadRunnable
{
/// <summary>
/// The instance of Thread
/// </summary>
private Thread threadField;
/// <summary>
/// Initializes a new instance of the ThreadClass class
/// </summary>
public ThreadClass()
{
threadField = new Thread(new ThreadStart(Run));
}
/// <summary>
/// Initializes a new instance of the Thread class.
/// </summary>
/// <param name="Name">The name of the thread</param>
public ThreadClass(string Name)
{
threadField = new Thread(new ThreadStart(Run));
this.Name = Name;
}
/// <summary>
/// Initializes a new instance of the Thread class.
/// </summary>
/// <param name="Start">A ThreadStart delegate that references the methods to be invoked when this thread begins executing</param>
public ThreadClass(ThreadStart Start)
{
threadField = new Thread(Start);
}
/// <summary>
/// Initializes a new instance of the Thread class.
/// </summary>
/// <param name="Start">A ThreadStart delegate that references the methods to be invoked when this thread begins executing</param>
/// <param name="Name">The name of the thread</param>
public ThreadClass(ThreadStart Start, string Name)
{
threadField = new Thread(Start);
this.Name = Name;
}
/// <summary>
/// This method has no functionality unless the method is overridden
/// </summary>
public virtual void Run()
{
}
/// <summary>
/// Causes the operating system to change the state of the current thread instance to ThreadState.Running
/// </summary>
public virtual void Start()
{
threadField.Start();
}
/// <summary>
/// Interrupts a thread that is in the WaitSleepJoin thread state
/// </summary>
public virtual void Interrupt()
{
threadField.Interrupt();
}
/// <summary>
/// Gets or sets the name of the thread
/// </summary>
public string Name
{
get
{
return threadField.Name;
}
set
{
if (threadField.Name == null)
threadField.Name = value;
}
}
/// <summary>
/// Gets or sets a value indicating the scheduling priority of a thread
/// </summary>
public ThreadPriority Priority
{
get
{
return threadField.Priority;
}
set
{
threadField.Priority = value;
}
}
/// <summary>
/// Gets a value indicating the execution status of the current thread
/// </summary>
public bool IsAlive
{
get
{
return threadField.IsAlive;
}
}
/// <summary>
/// Gets a value indicating the execution status of the current thread
/// </summary>
public bool IsInterrupted
{
get
{
return (threadField.ThreadState & ThreadState.WaitSleepJoin) == ThreadState.WaitSleepJoin;
}
}
/// <summary>
/// Gets or sets a value indicating whether or not a thread is a background thread.
/// </summary>
public bool IsBackground
{
get
{
return threadField.IsBackground;
}
set
{
threadField.IsBackground = value;
}
}
/// <summary>
/// Blocks the calling thread until a thread terminates
/// </summary>
public void Join()
{
threadField.Join();
}
/// <summary>
/// Blocks the calling thread until a thread terminates or the specified time elapses
/// </summary>
/// <param name="MiliSeconds">Time of wait in milliseconds</param>
public void Join(long MiliSeconds)
{
lock (this)
{
threadField.Join(new System.TimeSpan(MiliSeconds * 10000));
}
}
/// <summary>
/// Blocks the calling thread until a thread terminates or the specified time elapses
/// </summary>
/// <param name="MiliSeconds">Time of wait in milliseconds</param>
/// <param name="NanoSeconds">Time of wait in nanoseconds</param>
public void Join(long MiliSeconds, int NanoSeconds)
{
lock (this)
{
threadField.Join(new System.TimeSpan(MiliSeconds * 10000 + NanoSeconds * 100));
}
}
/// <summary>
/// Resumes a thread that has been suspended
/// </summary>
public void Resume()
{
threadField.Resume();
}
/// <summary>
/// Raises a ThreadAbortException in the thread on which it is invoked,
/// to begin the process of terminating the thread. Calling this method
/// usually terminates the thread
/// </summary>
public void Abort()
{
#if !NETCORE
threadField.Abort();
#elif NETCORE
threadField.Interrupt();
#endif
}
/// <summary>
/// Raises a ThreadAbortException in the thread on which it is invoked,
/// to begin the process of terminating the thread while also providing
/// exception information about the thread termination.
/// Calling this method usually terminates the thread.
/// </summary>
/// <param name="stateInfo">An object that contains application-specific information, such as state, which can be used by the thread being aborted</param>
public void Abort(object stateInfo)
{
lock (this)
{
#if !NETCORE
threadField.Abort(stateInfo);
#elif NETCORE
threadField.Interrupt();
#endif
}
}
/// <summary>
/// Suspends the thread, if the thread is already suspended it has no effect
/// </summary>
public void Suspend()
{
threadField.Suspend();
}
/// <summary>
/// Obtain a String that represents the current Object
/// </summary>
/// <returns>A String that represents the current Object</returns>
public override string ToString()
{
return "Thread[" + Name + "," + Priority.ToString() + "," + "" + "]";
}
/// <summary>
/// Gets the currently running thread
/// </summary>
/// <returns>The currently running thread</returns>
public static ThreadClass Current()
{
ThreadClass CurrentThread = new ThreadClass();
CurrentThread.threadField = Thread.CurrentThread;
return CurrentThread;
}
}
}
| |
// 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.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Linq.Tests
{
public class ToListTests : EnumerableTests
{
[Fact]
public void ToList_AlwaysCreateACopy()
{
List<int> sourceList = new List<int>() { 1, 2, 3, 4, 5 };
List<int> resultList = sourceList.ToList();
Assert.NotSame(sourceList, resultList);
Assert.Equal(sourceList, resultList);
}
private void RunToListOnAllCollectionTypes<T>(T[] items, Action<List<T>> validation)
{
validation(Enumerable.ToList(items));
validation(Enumerable.ToList(new List<T>(items)));
validation(new TestEnumerable<T>(items).ToList());
validation(new TestReadOnlyCollection<T>(items).ToList());
validation(new TestCollection<T>(items).ToList());
}
[Fact]
public void ToList_WorkWithEmptyCollection()
{
RunToListOnAllCollectionTypes(new int[0],
resultList =>
{
Assert.NotNull(resultList);
Assert.Equal(0, resultList.Count);
});
}
[Fact]
public void ToList_ProduceCorrectList()
{
int[] sourceArray = new int[] { 1, 2, 3, 4, 5, 6, 7 };
RunToListOnAllCollectionTypes(sourceArray,
resultList =>
{
Assert.Equal(sourceArray.Length, resultList.Count);
Assert.Equal(sourceArray, resultList);
});
string[] sourceStringArray = new string[] { "1", "2", "3", "4", "5", "6", "7", "8" };
RunToListOnAllCollectionTypes(sourceStringArray,
resultStringList =>
{
Assert.Equal(sourceStringArray.Length, resultStringList.Count);
for (int i = 0; i < sourceStringArray.Length; i++)
Assert.Same(sourceStringArray[i], resultStringList[i]);
});
}
[Fact]
public void ToList_TouchCountWithICollection()
{
TestCollection<int> source = new TestCollection<int>(new int[] { 1, 2, 3, 4 });
var resultList = source.ToList();
Assert.Equal(source, resultList);
Assert.Equal(1, source.CountTouched);
}
[Fact]
public void ToList_ThrowArgumentNullExceptionWhenSourceIsNull()
{
int[] source = null;
Assert.Throws<ArgumentNullException>("source", () => source.ToList());
}
// Generally the optimal approach. Anything that breaks this should be confirmed as not harming performance.
[Fact]
public void ToList_UseCopyToWithICollection()
{
TestCollection<int> source = new TestCollection<int>(new int[] { 1, 2, 3, 4 });
var resultList = source.ToList();
Assert.Equal(source, resultList);
Assert.Equal(1, source.CopyToTouched);
}
[Theory]
[InlineData(new int[] { }, new string[] { })]
[InlineData(new int[] { 1 }, new string[] { "1" })]
[InlineData(new int[] { 1, 2, 3 }, new string[] { "1", "2", "3" })]
public void ToList_ArrayWhereSelect(int[] sourceIntegers, string[] convertedStrings)
{
var sourceList = new List<int>(sourceIntegers);
var convertedList = new List<string>(convertedStrings);
var emptyIntegersList = new List<int>();
var emptyStringsList = new List<string>();
Assert.Equal(convertedList, sourceIntegers.Select(i => i.ToString()).ToList());
Assert.Equal(sourceList, sourceIntegers.Where(i => true).ToList());
Assert.Equal(emptyIntegersList, sourceIntegers.Where(i => false).ToList());
Assert.Equal(convertedList, sourceIntegers.Where(i => true).Select(i => i.ToString()).ToList());
Assert.Equal(emptyStringsList, sourceIntegers.Where(i => false).Select(i => i.ToString()).ToList());
Assert.Equal(convertedList, sourceIntegers.Select(i => i.ToString()).Where(s => s != null).ToList());
Assert.Equal(emptyStringsList, sourceIntegers.Select(i => i.ToString()).Where(s => s == null).ToList());
}
[Theory]
[InlineData(new int[] { }, new string[] { })]
[InlineData(new int[] { 1 }, new string[] { "1" })]
[InlineData(new int[] { 1, 2, 3 }, new string[] { "1", "2", "3" })]
public void ToList_ListWhereSelect(int[] sourceIntegers, string[] convertedStrings)
{
var sourceList = new List<int>(sourceIntegers);
var convertedList = new List<string>(convertedStrings);
var emptyIntegersList = new List<int>();
var emptyStringsList = new List<string>();
Assert.Equal(convertedList, sourceList.Select(i => i.ToString()).ToList());
Assert.Equal(sourceList, sourceList.Where(i => true).ToList());
Assert.Equal(emptyIntegersList, sourceList.Where(i => false).ToList());
Assert.Equal(convertedList, sourceList.Where(i => true).Select(i => i.ToString()).ToList());
Assert.Equal(emptyStringsList, sourceList.Where(i => false).Select(i => i.ToString()).ToList());
Assert.Equal(convertedList, sourceList.Select(i => i.ToString()).Where(s => s != null).ToList());
Assert.Equal(emptyStringsList, sourceList.Select(i => i.ToString()).Where(s => s == null).ToList());
}
[Theory]
[InlineData(new int[] { }, new string[] { })]
[InlineData(new int[] { 1 }, new string[] { "1" })]
[InlineData(new int[] { 1, 2, 3 }, new string[] { "1", "2", "3" })]
public void ToList_IListWhereSelect(int[] sourceIntegers, string[] convertedStrings)
{
var sourceList = new ReadOnlyCollection<int>(sourceIntegers);
var convertedList = new ReadOnlyCollection<string>(convertedStrings);
var emptyIntegersList = new ReadOnlyCollection<int>(Array.Empty<int>());
var emptyStringsList = new ReadOnlyCollection<string>(Array.Empty<string>());
Assert.Equal(convertedList, sourceList.Select(i => i.ToString()).ToList());
Assert.Equal(sourceList, sourceList.Where(i => true).ToList());
Assert.Equal(emptyIntegersList, sourceList.Where(i => false).ToList());
Assert.Equal(convertedList, sourceList.Where(i => true).Select(i => i.ToString()).ToList());
Assert.Equal(emptyStringsList, sourceList.Where(i => false).Select(i => i.ToString()).ToList());
Assert.Equal(convertedList, sourceList.Select(i => i.ToString()).Where(s => s != null).ToList());
Assert.Equal(emptyStringsList, sourceList.Select(i => i.ToString()).Where(s => s == null).ToList());
}
[Fact]
public void SameResultsRepeatCallsFromWhereOnIntQuery()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
Assert.Equal(q.ToList(), q.ToList());
}
[Fact]
public void SameResultsRepeatCallsFromWhereOnStringQuery()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x)
select x;
Assert.Equal(q.ToList(), q.ToList());
}
[Fact]
public void SourceIsEmptyICollectionT()
{
int[] source = { };
ICollection<int> collection = source as ICollection<int>;
Assert.Empty(source.ToList());
Assert.Empty(collection.ToList());
}
[Fact]
public void SourceIsICollectionTWithFewElements()
{
int?[] source = { -5, null, 0, 10, 3, -1, null, 4, 9 };
int?[] expected = { -5, null, 0, 10, 3, -1, null, 4, 9 };
ICollection<int?> collection = source as ICollection<int?>;
Assert.Equal(expected, source.ToList());
Assert.Equal(expected, collection.ToList());
}
[Fact]
public void SourceNotICollectionAndIsEmpty()
{
IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(-4, 0);
Assert.Empty(source.ToList());
}
[Fact]
public void SourceNotICollectionAndHasElements()
{
IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(-4, 10);
int[] expected = { -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 };
Assert.Null(source as ICollection<int>);
Assert.Equal(expected, source.ToList());
}
[Fact]
public void SourceNotICollectionAndAllNull()
{
IEnumerable<int?> source = RepeatedNullableNumberGuaranteedNotCollectionType(null, 5);
int?[] expected = { null, null, null, null, null };
Assert.Null(source as ICollection<int>);
Assert.Equal(expected, source.ToList());
}
[Fact]
public void ConstantTimeCountPartitionSelectSameTypeToList()
{
var source = Enumerable.Range(0, 100).Select(i => i * 2).Skip(1).Take(5);
Assert.Equal(new[] { 2, 4, 6, 8, 10 }, source.ToList());
}
[Fact]
public void ConstantTimeCountPartitionSelectDiffTypeToList()
{
var source = Enumerable.Range(0, 100).Select(i => i.ToString()).Skip(1).Take(5);
Assert.Equal(new[] { "1", "2", "3", "4", "5" }, source.ToList());
}
[Fact]
public void ConstantTimeCountEmptyPartitionSelectSameTypeToList()
{
var source = Enumerable.Range(0, 100).Select(i => i * 2).Skip(1000);
Assert.Empty(source.ToList());
}
[Fact]
public void ConstantTimeCountEmptyPartitionSelectDiffTypeToList()
{
var source = Enumerable.Range(0, 100).Select(i => i.ToString()).Skip(1000);
Assert.Empty(source.ToList());
}
[Fact]
public void NonConstantTimeCountPartitionSelectSameTypeToList()
{
var source = NumberRangeGuaranteedNotCollectionType(0, 100).OrderBy(i => i).Select(i => i * 2).Skip(1).Take(5);
Assert.Equal(new[] { 2, 4, 6, 8, 10 }, source.ToList());
}
[Fact]
public void NonConstantTimeCountPartitionSelectDiffTypeToList()
{
var source = NumberRangeGuaranteedNotCollectionType(0, 100).OrderBy(i => i).Select(i => i.ToString()).Skip(1).Take(5);
Assert.Equal(new[] { "1", "2", "3", "4", "5" }, source.ToList());
}
[Fact]
public void NonConstantTimeCountEmptyPartitionSelectSameTypeToList()
{
var source = NumberRangeGuaranteedNotCollectionType(0, 100).OrderBy(i => i).Select(i => i * 2).Skip(1000);
Assert.Empty(source.ToList());
}
[Fact]
public void NonConstantTimeCountEmptyPartitionSelectDiffTypeToList()
{
var source = NumberRangeGuaranteedNotCollectionType(0, 100).OrderBy(i => i).Select(i => i.ToString()).Skip(1000);
Assert.Empty(source.ToList());
}
}
}
| |
// 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;
using System;
using System.Reflection;
using System.Collections.Generic;
namespace System.Reflection.Tests
{
public class TypeInfoDeclaredGenericTypeParameterTests
{
//Interfaces
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters1()
{
VerifyGenericTypeParameters(typeof(Test_I1).Project(), new string[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters2()
{
VerifyGenericTypeParameters(typeof(Test_IG1<>).Project(), new string[] { "TI" }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters3()
{
VerifyGenericTypeParameters(typeof(Test_IG1<int>).Project(), new string[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters4()
{
VerifyGenericTypeParameters(typeof(Test_IG21<,>).Project(), new string[] { "TI", "VI" }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters5()
{
VerifyGenericTypeParameters(typeof(Test_IG21<int, string>).Project(), new string[] { }, null);
}
// For Structs
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters6()
{
VerifyGenericTypeParameters(typeof(Test_S1).Project(), new string[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters7()
{
VerifyGenericTypeParameters(typeof(Test_SG1<>).Project(), new string[] { "TS" }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters8()
{
VerifyGenericTypeParameters(typeof(Test_SG1<int>).Project(), new string[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters9()
{
VerifyGenericTypeParameters(typeof(Test_SG21<,>).Project(), new string[] { "TS", "VS" }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters10()
{
VerifyGenericTypeParameters(typeof(Test_SG21<int, string>).Project(), new string[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters11()
{
VerifyGenericTypeParameters(typeof(Test_SI1).Project(), new string[] { }, new string[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters12()
{
VerifyGenericTypeParameters(typeof(Test_SIG1<>).Project(), new string[] { "TS" }, new string[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters13()
{
VerifyGenericTypeParameters(typeof(Test_SIG1<int>).Project(), new string[] { }, new string[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters14()
{
VerifyGenericTypeParameters(typeof(Test_SIG21<,>).Project(), new string[] { "TS", "VS" }, new string[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters15()
{
VerifyGenericTypeParameters(typeof(Test_SIG21<int, string>).Project(), new string[] { }, new string[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters16()
{
VerifyGenericTypeParameters(typeof(Test_SI_Int1).Project(), new string[] { }, new string[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters17()
{
VerifyGenericTypeParameters(typeof(Test_SIG_Int1<>).Project(), new string[] { "TS" }, new string[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters18()
{
VerifyGenericTypeParameters(typeof(Test_SIG_Int1<string>).Project(), new string[] { }, new string[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters19()
{
VerifyGenericTypeParameters(typeof(Test_SIG_Int_Int1).Project(), new string[] { }, new string[] { });
}
//For classes
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters20()
{
VerifyGenericTypeParameters(typeof(Test_C1).Project(), new string[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters21()
{
VerifyGenericTypeParameters(typeof(Test_CG1<>).Project(), new string[] { "T" }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters22()
{
VerifyGenericTypeParameters(typeof(Test_CG1<int>).Project(), new string[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters23()
{
VerifyGenericTypeParameters(typeof(Test_CG21<,>).Project(), new string[] { "T", "V" }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters24()
{
VerifyGenericTypeParameters(typeof(Test_CG21<int, string>).Project(), new string[] { }, null);
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters25()
{
VerifyGenericTypeParameters(typeof(Test_CI1).Project(), new string[] { }, new string[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters26()
{
VerifyGenericTypeParameters(typeof(Test_CIG1<>).Project(), new string[] { "T" }, new string[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters27()
{
VerifyGenericTypeParameters(typeof(Test_CIG1<int>).Project(), new string[] { }, new string[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters28()
{
VerifyGenericTypeParameters(typeof(Test_CIG21<,>).Project(), new string[] { "T", "V" }, new string[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters29()
{
VerifyGenericTypeParameters(typeof(Test_CIG21<int, string>).Project(), new string[] { }, new string[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters30()
{
VerifyGenericTypeParameters(typeof(Test_CI_Int1).Project(), new string[] { }, new string[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters31()
{
VerifyGenericTypeParameters(typeof(Test_CIG_Int1<>).Project(), new string[] { "T" }, new string[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters32()
{
VerifyGenericTypeParameters(typeof(Test_CIG_Int1<string>).Project(), new string[] { }, new string[] { });
}
// Verify Generic Arguments
[Fact]
public static void TestGenericParameters33()
{
VerifyGenericTypeParameters(typeof(Test_CIG_Int_Int1).Project(), new string[] { }, new string[] { });
}
//private helper methods
private static void VerifyGenericTypeParameters(Type type, string[] expectedGTP, string[] expectedBaseGTP)
{
//Fix to initialize Reflection
string str = typeof(object).Project().Name;
TypeInfo typeInfo = type.GetTypeInfo();
Type[] retGenericTypeParameters = typeInfo.GenericTypeParameters;
Assert.Equal(expectedGTP.Length, retGenericTypeParameters.Length);
for (int i = 0; i < retGenericTypeParameters.Length; i++)
{
Assert.Equal(expectedGTP[i], retGenericTypeParameters[i].Name);
}
Type baseType = typeInfo.BaseType;
if (baseType == null)
return;
if (baseType == typeof(ValueType).Project() || baseType == typeof(object).Project())
{
Type[] interfaces = getInterfaces(typeInfo);
if (interfaces.Length == 0)
return;
baseType = interfaces[0];
}
TypeInfo typeInfoBase = baseType.GetTypeInfo();
retGenericTypeParameters = typeInfoBase.GenericTypeParameters;
Assert.Equal(expectedBaseGTP.Length, retGenericTypeParameters.Length);
for (int i = 0; i < retGenericTypeParameters.Length; i++)
{
Assert.Equal(expectedBaseGTP[i], retGenericTypeParameters[i].Name);
}
}
private static Type[] getInterfaces(TypeInfo ti)
{
List<Type> list = new List<Type>();
IEnumerator<Type> allinterfaces = ti.ImplementedInterfaces.GetEnumerator();
while (allinterfaces.MoveNext())
{
list.Add(allinterfaces.Current);
}
return list.ToArray();
}
}
//Metadata for Reflection
public interface Test_I1 { }
public interface Test_IG1<TI> { }
public interface Test_IG21<TI, VI> { }
public struct Test_S1 { }
public struct Test_SG1<TS> { }
public struct Test_SG21<TS, VS> { }
public struct Test_SI1 : Test_I1 { }
public struct Test_SIG1<TS> : Test_IG1<TS> { }
public struct Test_SIG21<TS, VS> : Test_IG21<TS, VS> { }
public struct Test_SI_Int1 : Test_IG1<int> { }
public struct Test_SIG_Int1<TS> : Test_IG21<TS, int> { }
public struct Test_SIG_Int_Int1 : Test_IG21<int, int> { }
public class Test_C1 { }
public class Test_CG1<T> { }
public class Test_CG21<T, V> { }
public class Test_CI1 : Test_I1 { }
public class Test_CIG1<T> : Test_IG1<T> { }
public class Test_CIG21<T, V> : Test_IG21<T, V> { }
public class Test_CI_Int1 : Test_IG1<int> { }
public class Test_CIG_Int1<T> : Test_CG21<T, int> { }
public class Test_CIG_Int_Int1 : Test_CG21<int, int> { }
}
| |
// 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.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using ILCompiler.DependencyAnalysis;
using ILCompiler.DependencyAnalysis.ReadyToRun;
using Internal.TypeSystem;
namespace ILCompiler.PEWriter
{
/// <summary>
/// Ready-to-run PE builder combines copying the input MSIL PE executable with managed
/// metadata and IL and adding new code and data representing the R2R JITted code and
/// additional runtime structures (R2R header and tables).
/// </summary>
public class R2RPEBuilder : PEBuilder
{
/// <summary>
/// Number of low-order RVA bits that must match file position on Linux.
/// </summary>
const int RVABitsToMatchFilePos = 16;
/// <summary>
/// This structure describes how a particular section moved between the original MSIL
/// and the output PE file. It holds beginning and end RVA of the input (MSIL) section
/// and a delta between the input and output starting RVA of the section.
/// </summary>
struct SectionRVADelta
{
/// <summary>
/// Starting RVA of the section in the input MSIL PE.
/// </summary>
public readonly int StartRVA;
/// <summary>
/// End RVA (one plus the last RVA in the section) of the section in the input MSIL PE.
/// </summary>
public readonly int EndRVA;
/// <summary>
/// Starting RVA of the section in the output PE minus its starting RVA in the input MSIL.
/// </summary>
public readonly int DeltaRVA;
/// <summary>
/// Initialize the section RVA delta information.
/// </summary>
/// <param name="startRVA">Starting RVA of the section in the input MSIL</param>
/// <param name="endRVA">End RVA of the section in the input MSIL</param>
/// <param name="deltaRVA">Output RVA of the section minus input RVA of the section</param>
public SectionRVADelta(int startRVA, int endRVA, int deltaRVA)
{
StartRVA = startRVA;
EndRVA = endRVA;
DeltaRVA = deltaRVA;
}
}
/// <summary>
/// Name of the text section.
/// </summary>
public const string TextSectionName = ".text";
/// <summary>
/// Name of the initialized data section.
/// </summary>
public const string SDataSectionName = ".sdata";
/// <summary>
/// Name of the relocation section.
/// </summary>
public const string RelocSectionName = ".reloc";
/// <summary>
/// Name of the writeable data section.
/// </summary>
public const string DataSectionName = ".data";
/// <summary>
/// Name of the export data section.
/// </summary>
public const string ExportDataSectionName = ".edata";
/// <summary>
/// Compilation target OS and architecture specification.
/// </summary>
private TargetDetails _target;
/// <summary>
/// PE reader representing the input MSIL PE file we're copying to the output composite PE file.
/// </summary>
private PEReader _peReader;
/// <summary>
/// Custom sections explicitly injected by the caller.
/// </summary>
private HashSet<string> _customSections;
/// <summary>
/// Complete list of section names includes the sections present in the input MSIL file
/// (.text, optionally .rsrc and .reloc) and extra questions injected during the R2R PE
/// creation.
/// </summary>
private ImmutableArray<Section> _sections;
/// <summary>
/// Callback to retrieve the runtime function table which needs setting to the
/// ExceptionTable PE directory entry.
/// </summary>
private Func<RuntimeFunctionsTableNode> _getRuntimeFunctionsTable;
/// <summary>
/// For each copied section, we store its initial and end RVA in the source PE file
/// and the RVA difference between the old and new file. We use this table to relocate
/// directory entries in the PE file header.
/// </summary>
private List<SectionRVADelta> _sectionRvaDeltas;
/// <summary>
/// Logical section start RVAs. When emitting R2R PE executables for Linux, we must
/// align RVA's so that their 'RVABitsToMatchFilePos' lowest-order bits match the
/// file position (otherwise memory mapping of the file fails and CoreCLR silently
/// switches over to runtime JIT). PEBuilder doesn't support this today so that we
/// must store the RVA's and post-process the produced PE by patching the section
/// headers in the PE header.
/// </summary>
private int[] _sectionRVAs;
/// <summary>
/// Maximum of virtual and physical size for each section.
/// </summary>
private int[] _sectionRawSizes;
/// <summary>
/// R2R PE section builder & relocator.
/// </summary>
private readonly SectionBuilder _sectionBuilder;
/// <summary>
/// Zero-based index of the CPAOT-generated text section
/// </summary>
private readonly int _textSectionIndex;
/// <summary>
/// Zero-based index of the CPAOT-generated read-write data section
/// </summary>
private readonly int _dataSectionIndex;
/// <summary>
/// True after Write has been called; it's not possible to add further object data items past that point.
/// </summary>
private bool _written;
/// <summary>
/// Constructor initializes the various control structures and combines the section list.
/// </summary>
/// <param name="target">Target environment specifier</param>
/// <param name="peReader">Input MSIL PE file reader</param>
/// <param name="getRuntimeFunctionsTable">Callback to retrieve the runtime functions table</param>
public R2RPEBuilder(
TargetDetails target,
PEReader peReader,
Func<RuntimeFunctionsTableNode> getRuntimeFunctionsTable)
: base(PEHeaderCopier.Copy(peReader.PEHeaders, target), deterministicIdProvider: null)
{
_target = target;
_peReader = peReader;
_getRuntimeFunctionsTable = getRuntimeFunctionsTable;
_sectionRvaDeltas = new List<SectionRVADelta>();
_sectionBuilder = new SectionBuilder(target);
_textSectionIndex = _sectionBuilder.AddSection(TextSectionName, SectionCharacteristics.ContainsCode | SectionCharacteristics.MemExecute | SectionCharacteristics.MemRead, 512);
_dataSectionIndex = _sectionBuilder.AddSection(DataSectionName, SectionCharacteristics.ContainsInitializedData | SectionCharacteristics.MemWrite | SectionCharacteristics.MemRead, 512);
_customSections = new HashSet<string>();
foreach (SectionInfo section in _sectionBuilder.GetSections())
{
_customSections.Add(section.SectionName);
}
if (_sectionBuilder.FindSection(R2RPEBuilder.RelocSectionName) == null)
{
// Always inject the relocation section to the end of section list
_sectionBuilder.AddSection(
R2RPEBuilder.RelocSectionName,
SectionCharacteristics.ContainsInitializedData |
SectionCharacteristics.MemRead |
SectionCharacteristics.MemDiscardable,
peReader.PEHeaders.PEHeader.SectionAlignment);
}
ImmutableArray<Section>.Builder sectionListBuilder = ImmutableArray.CreateBuilder<Section>();
foreach (SectionInfo sectionInfo in _sectionBuilder.GetSections())
{
ILCompiler.PEWriter.Section builderSection = _sectionBuilder.FindSection(sectionInfo.SectionName);
Debug.Assert(builderSection != null);
sectionListBuilder.Add(new Section(builderSection.Name, builderSection.Characteristics));
}
_sections = sectionListBuilder.ToImmutableArray();
_sectionRVAs = new int[_sections.Length];
_sectionRawSizes = new int[_sections.Length];
}
public void SetCorHeader(ISymbolNode symbol, int headerSize)
{
_sectionBuilder.SetCorHeader(symbol, headerSize);
}
public void SetWin32Resources(ISymbolNode symbol, int resourcesSize)
{
_sectionBuilder.SetWin32Resources(symbol, resourcesSize);
}
/// <summary>
/// Emit a single object data item into the output R2R PE file using the section builder.
/// </summary>
/// <param name="objectData">Object data to emit</param>
/// <param name="section">Target section</param>
/// <param name="name">Textual name of the object data for diagnostic purposese</param>
/// <param name="mapFile">Optional map file to output the data item to</param>
public void AddObjectData(ObjectNode.ObjectData objectData, ObjectNodeSection section, string name, TextWriter mapFile)
{
if (_written)
{
throw new InternalCompilerErrorException("Inconsistent upstream behavior - AddObjectData mustn't be called after Write");
}
int targetSectionIndex;
switch (section.Type)
{
case SectionType.ReadOnly:
// We put ReadOnly data into the text section to limit the number of sections.
case SectionType.Executable:
targetSectionIndex = _textSectionIndex;
break;
case SectionType.Writeable:
targetSectionIndex = _dataSectionIndex;
break;
default:
throw new NotImplementedException();
}
_sectionBuilder.AddObjectData(objectData, targetSectionIndex, name, mapFile);
}
/// <summary>
/// Emit built sections into the R2R PE file.
/// </summary>
/// <param name="outputStream">Output stream for the final R2R PE file</param>
public void Write(Stream outputStream)
{
BlobBuilder outputPeFile = new BlobBuilder();
Serialize(outputPeFile);
_sectionBuilder.RelocateOutputFile(
outputPeFile,
_peReader.PEHeaders.PEHeader.ImageBase,
outputStream);
UpdateSectionRVAs(outputStream);
ApplyMachineOSOverride(outputStream);
_written = true;
}
/// <summary>
/// PE header constants copied from System.Reflection.Metadata where they are
/// sadly mostly internal or private.
/// </summary>
const int DosHeaderSize = 0x80;
const int PESignatureSize = sizeof(uint);
const int COFFHeaderSize =
sizeof(short) + // Machine
sizeof(short) + // NumberOfSections
sizeof(int) + // TimeDateStamp:
sizeof(int) + // PointerToSymbolTable
sizeof(int) + // NumberOfSymbols
sizeof(short) + // SizeOfOptionalHeader:
sizeof(ushort); // Characteristics
const int OffsetOfChecksum =
sizeof(short) + // Magic
sizeof(byte) + // MajorLinkerVersion
sizeof(byte) + // MinorLinkerVersion
sizeof(int) + // SizeOfCode
sizeof(int) + // SizeOfInitializedData
sizeof(int) + // SizeOfUninitializedData
sizeof(int) + // AddressOfEntryPoint
sizeof(int) + // BaseOfCode
sizeof(long) + // PE32: BaseOfData (int), ImageBase (int)
// PE32+: ImageBase (long)
sizeof(int) + // SectionAlignment
sizeof(int) + // FileAlignment
sizeof(short) + // MajorOperatingSystemVersion
sizeof(short) + // MinorOperatingSystemVersion
sizeof(short) + // MajorImageVersion
sizeof(short) + // MinorImageVersion
sizeof(short) + // MajorSubsystemVersion
sizeof(short) + // MinorSubsystemVersion
sizeof(int) + // Win32VersionValue
sizeof(int) + // SizeOfImage
sizeof(int); // SizeOfHeaders
const int OffsetOfSizeOfImage = OffsetOfChecksum - 2 * sizeof(int); // SizeOfHeaders, SizeOfImage
const int SectionHeaderNameSize = 8;
const int SectionHeaderRVAOffset = SectionHeaderNameSize + sizeof(int); // skip 8 bytes Name + 4 bytes VirtualSize
const int SectionHeaderSize =
SectionHeaderNameSize +
sizeof(int) + // VirtualSize
sizeof(int) + // VirtualAddress
sizeof(int) + // SizeOfRawData
sizeof(int) + // PointerToRawData
sizeof(int) + // PointerToRelocations
sizeof(int) + // PointerToLineNumbers
sizeof(short) + // NumberOfRelocations
sizeof(short) + // NumberOfLineNumbers
sizeof(int); // SectionCharacteristics
/// <summary>
/// On Linux, we must patch the section headers. This is because the CoreCLR runtime on Linux
/// requires the 12-16 low-order bits of section RVAs (the number of bits corresponds to the page
/// size) to be identical to the file offset, otherwise memory mapping of the file fails.
/// Sadly PEBuilder in System.Reflection.Metadata doesn't support this so we must post-process
/// the EXE by patching section headers with the correct RVA's. To reduce code variations
/// we're performing the same transformation on Windows where it is a no-op.
/// </summary>
/// <param name="outputStream"></param>
private void UpdateSectionRVAs(Stream outputStream)
{
int peHeaderSize =
OffsetOfChecksum +
sizeof(int) + // Checksum
sizeof(short) + // Subsystem
sizeof(short) + // DllCharacteristics
4 * _target.PointerSize + // SizeOfStackReserve, SizeOfStackCommit, SizeOfHeapReserve, SizeOfHeapCommit
sizeof(int) + // LoaderFlags
sizeof(int) + // NumberOfRvaAndSizes
16 * sizeof(long); // directory entries
int sectionHeaderOffset = DosHeaderSize + PESignatureSize + COFFHeaderSize + peHeaderSize;
int sectionCount = _sectionRVAs.Length;
for (int sectionIndex = 0; sectionIndex < sectionCount; sectionIndex++)
{
outputStream.Seek(sectionHeaderOffset + SectionHeaderSize * sectionIndex + SectionHeaderRVAOffset, SeekOrigin.Begin);
byte[] rvaBytes = BitConverter.GetBytes(_sectionRVAs[sectionIndex]);
Debug.Assert(rvaBytes.Length == sizeof(int));
outputStream.Write(rvaBytes, 0, rvaBytes.Length);
}
// Patch SizeOfImage to point past the end of the last section
outputStream.Seek(DosHeaderSize + PESignatureSize + COFFHeaderSize + OffsetOfSizeOfImage, SeekOrigin.Begin);
int sizeOfImage = AlignmentHelper.AlignUp(_sectionRVAs[sectionCount - 1] + _sectionRawSizes[sectionCount - 1], Header.SectionAlignment);
byte[] sizeOfImageBytes = BitConverter.GetBytes(sizeOfImage);
Debug.Assert(sizeOfImageBytes.Length == sizeof(int));
outputStream.Write(sizeOfImageBytes, 0, sizeOfImageBytes.Length);
}
/// <summary>
/// TODO: System.Reflection.Metadata doesn't currently support OS machine overrides.
/// We cannot directly pass the xor-ed target machine to PEHeaderBuilder because it
/// may incorrectly detect 32-bitness and emit wrong OptionalHeader.Magic. Therefore
/// we create the executable using the raw Machine ID and apply the override as the
/// last operation before closing the file.
/// </summary>
/// <param name="outputStream">Output stream representing the R2R PE executable</param>
private void ApplyMachineOSOverride(Stream outputStream)
{
byte[] patchedTargetMachine = BitConverter.GetBytes(
(ushort)unchecked((ushort)Header.Machine ^ (ushort)_target.MachineOSOverrideFromTarget()));
Debug.Assert(patchedTargetMachine.Length == sizeof(ushort));
outputStream.Seek(DosHeaderSize + PESignatureSize, SeekOrigin.Begin);
outputStream.Write(patchedTargetMachine, 0, patchedTargetMachine.Length);
}
/// <summary>
/// Copy all directory entries and the address of entry point, relocating them along the way.
/// </summary>
protected override PEDirectoriesBuilder GetDirectories()
{
PEDirectoriesBuilder builder = new PEDirectoriesBuilder();
_sectionBuilder.UpdateDirectories(builder);
RuntimeFunctionsTableNode runtimeFunctionsTable = _getRuntimeFunctionsTable();
builder.ExceptionTable = new DirectoryEntry(
relativeVirtualAddress: _sectionBuilder.GetSymbolRVA(runtimeFunctionsTable),
size: runtimeFunctionsTable.TableSize);
return builder;
}
/// <summary>
/// Relocate a single directory entry.
/// </summary>
/// <param name="entry">Directory entry to allocate</param>
/// <returns>Relocated directory entry</returns>
public DirectoryEntry RelocateDirectoryEntry(DirectoryEntry entry)
{
return new DirectoryEntry(RelocateRVA(entry.RelativeVirtualAddress), entry.Size);
}
/// <summary>
/// Relocate a given RVA using the section offset table produced during section serialization.
/// </summary>
/// <param name="rva">RVA to relocate</param>
/// <returns>Relocated RVA</returns>
private int RelocateRVA(int rva)
{
if (rva == 0)
{
// Zero RVA is normally used as NULL
return rva;
}
foreach (SectionRVADelta sectionRvaDelta in _sectionRvaDeltas)
{
if (rva >= sectionRvaDelta.StartRVA && rva < sectionRvaDelta.EndRVA)
{
// We found the input section holding the RVA, apply its specific delt (output RVA - input RVA).
return rva + sectionRvaDelta.DeltaRVA;
}
}
Debug.Assert(false, "RVA is not within any of the input sections - output PE may be inconsistent");
return rva;
}
/// <summary>
/// Provide an array of sections for the PEBuilder to use.
/// </summary>
protected override ImmutableArray<Section> CreateSections()
{
return _sections;
}
/// <summary>
/// Output the section with a given name. For sections existent in the source MSIL PE file
/// (.text, optionally .rsrc and .reloc), we first copy the content of the input MSIL PE file
/// and then call the section serialization callback to emit the extra content after the input
/// section content.
/// </summary>
/// <param name="name">Section name</param>
/// <param name="location">RVA and file location where the section will be put</param>
/// <returns>Blob builder representing the section data</returns>
protected override BlobBuilder SerializeSection(string name, SectionLocation location)
{
BlobBuilder sectionDataBuilder = null;
int sectionStartRva = location.RelativeVirtualAddress;
int outputSectionIndex = _sections.Length - 1;
while (outputSectionIndex >= 0 && _sections[outputSectionIndex].Name != name)
{
outputSectionIndex--;
}
if (!_target.IsWindows)
{
if (outputSectionIndex > 0)
{
sectionStartRva = Math.Max(sectionStartRva, _sectionRVAs[outputSectionIndex - 1] + _sectionRawSizes[outputSectionIndex - 1]);
}
const int RVAAlign = 1 << RVABitsToMatchFilePos;
sectionStartRva = AlignmentHelper.AlignUp(sectionStartRva, RVAAlign);
int rvaAdjust = (location.PointerToRawData - sectionStartRva) & (RVAAlign - 1);
sectionStartRva += rvaAdjust;
location = new SectionLocation(sectionStartRva, location.PointerToRawData);
}
if (outputSectionIndex >= 0)
{
_sectionRVAs[outputSectionIndex] = sectionStartRva;
}
BlobBuilder extraData = _sectionBuilder.SerializeSection(name, location);
if (extraData != null)
{
if (sectionDataBuilder == null)
{
// See above - there's a bug due to which LinkSuffix to an empty BlobBuilder screws up the blob content.
sectionDataBuilder = extraData;
}
else
{
sectionDataBuilder.LinkSuffix(extraData);
}
}
// Make sure the section has at least 1 byte, otherwise the PE emitter goes mad,
// messes up the section map and corrups the output executable.
if (sectionDataBuilder == null)
{
sectionDataBuilder = new BlobBuilder();
}
if (sectionDataBuilder.Count == 0)
{
sectionDataBuilder.WriteByte(0);
}
if (outputSectionIndex >= 0)
{
_sectionRawSizes[outputSectionIndex] = sectionDataBuilder.Count;
}
return sectionDataBuilder;
}
}
/// <summary>
/// Simple helper for copying the various global values in the PE header.
/// </summary>
static class PEHeaderCopier
{
/// <summary>
/// Copy PE headers into a PEHeaderBuilder used by PEBuilder.
/// </summary>
/// <param name="peHeaders">Headers to copy</param>
/// <param name="target">Target architecture to set in the header</param>
public static PEHeaderBuilder Copy(PEHeaders peHeaders, TargetDetails target)
{
bool is64BitTarget = target.PointerSize == sizeof(long);
Characteristics imageCharacteristics = peHeaders.CoffHeader.Characteristics;
if (is64BitTarget)
{
imageCharacteristics &= ~Characteristics.Bit32Machine;
imageCharacteristics |= Characteristics.LargeAddressAware;
}
int fileAlignment = 0x200;
if (!target.IsWindows && !is64BitTarget)
{
// To minimize wasted VA space on 32 bit systems align file to page bounaries (presumed to be 4K).
fileAlignment = 0x1000;
}
int sectionAlignment = 0x1000;
if (!target.IsWindows && is64BitTarget)
{
// On Linux, we must match the bottom 12 bits of section RVA's to their file offsets. For this reason
// we need the same alignment for both.
sectionAlignment = fileAlignment;
}
DllCharacteristics dllCharacteristics = DllCharacteristics.DynamicBase | DllCharacteristics.NxCompatible;
if (!is64BitTarget)
{
dllCharacteristics |= DllCharacteristics.NoSeh;
}
// Copy over selected DLL characteristics bits from IL image
dllCharacteristics |= peHeaders.PEHeader.DllCharacteristics &
(DllCharacteristics.TerminalServerAware | DllCharacteristics.AppContainer);
if (is64BitTarget)
{
dllCharacteristics |= DllCharacteristics.HighEntropyVirtualAddressSpace;
}
return new PEHeaderBuilder(
machine: target.MachineFromTarget(),
sectionAlignment: sectionAlignment,
fileAlignment: fileAlignment,
imageBase: peHeaders.PEHeader.ImageBase,
majorLinkerVersion: 11,
minorLinkerVersion: 0,
majorOperatingSystemVersion: 5,
// Win2k = 5.0 for 32-bit images, Win2003 = 5.2 for 64-bit images
minorOperatingSystemVersion: is64BitTarget ? (ushort)2 : (ushort)0,
majorImageVersion: peHeaders.PEHeader.MajorImageVersion,
minorImageVersion: peHeaders.PEHeader.MinorImageVersion,
majorSubsystemVersion: peHeaders.PEHeader.MajorSubsystemVersion,
minorSubsystemVersion: peHeaders.PEHeader.MinorSubsystemVersion,
subsystem: peHeaders.PEHeader.Subsystem,
dllCharacteristics: dllCharacteristics,
imageCharacteristics: imageCharacteristics,
sizeOfStackReserve: peHeaders.PEHeader.SizeOfStackReserve,
sizeOfStackCommit: peHeaders.PEHeader.SizeOfStackCommit,
sizeOfHeapReserve: 0,
sizeOfHeapCommit: 0);
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using LumiSoft.Net;
using LumiSoft.Net.Log;
using LumiSoft.Net.TCP;
namespace LumiSoft.Net.SMTP.Relay
{
#region Delegates
/// <summary>
/// Represents the method that will handle the <b>Relay_Server.SessionCompleted</b> event.
/// </summary>
/// <param name="e">Event data.</param>
public delegate void Relay_SessionCompletedEventHandler(Relay_SessionCompletedEventArgs e);
#endregion
/// <summary>
/// This class implements SMTP relay server. Defined in RFC 2821.
/// </summary>
public class Relay_Server : IDisposable
{
private bool m_IsDisposed = false;
private bool m_IsRunning = false;
private IPBindInfo[] m_pBindings = new IPBindInfo[0];
private bool m_HasBindingsChanged = false;
private Relay_Mode m_RelayMode = Relay_Mode.Dns;
private List<Relay_Queue> m_pQueues = null;
private BalanceMode m_SmartHostsBalanceMode = BalanceMode.LoadBalance;
private CircleCollection<Relay_SmartHost> m_pSmartHosts = null;
private CircleCollection<IPBindInfo> m_pLocalEndPoints = null;
private long m_MaxConnections = 0;
private long m_MaxConnectionsPerIP = 0;
private TCP_SessionCollection<Relay_Session> m_pSessions = null;
private Dictionary<IPAddress,long> m_pConnectionsPerIP = null;
private int m_SessionIdleTimeout = 30;
private Logger m_pLogger = null;
/// <summary>
/// Default constructor.
/// </summary>
public Relay_Server()
{
m_pQueues = new List<Relay_Queue>();
m_pSmartHosts = new CircleCollection<Relay_SmartHost>();
}
#region method Dispose
/// <summary>
/// Cleans up any resources being used.
/// </summary>
public void Dispose()
{
if(m_IsDisposed){
return;
}
try{
if(m_IsRunning){
Stop();
}
}
catch{
}
m_IsDisposed = true;
// Release events.
this.Error = null;
this.SessionCompleted = null;
m_pQueues = null;
m_pSmartHosts = null;
}
#endregion
#region method Start
/// <summary>
/// Starts SMTP relay server.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
public virtual void Start()
{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
if(m_IsRunning){
return;
}
m_IsRunning = true;
m_pLocalEndPoints = new CircleCollection<IPBindInfo>();
m_pSessions = new TCP_SessionCollection<Relay_Session>();
m_pConnectionsPerIP = new Dictionary<IPAddress,long>();
Thread tr1 = new Thread(new ThreadStart(this.Run));
tr1.Start();
Thread tr2 = new Thread(new ThreadStart(this.Run_CheckTimedOutSessions));
tr2.Start();
}
#endregion
#region method Stop
/// <summary>
/// Stops SMTP relay server.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
public virtual void Stop()
{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
if(!m_IsRunning){
return;
}
m_IsRunning = false;
// TODO: We need to send notify to all not processed messages, then they can be Disposed as needed.
// Clean up.
m_pLocalEndPoints = null;
//m_pSessions.Dispose();
m_pSessions = null;
m_pConnectionsPerIP = null;
}
#endregion
#region method Run
/// <summary>
/// Processes relay queue.
/// </summary>
private void Run()
{
while(m_IsRunning){
try{
// Bind info has changed, create new local end points.
if(m_HasBindingsChanged){
m_pLocalEndPoints.Clear();
foreach(IPBindInfo binding in m_pBindings){
if(binding.IP == IPAddress.Any){
foreach(IPAddress ip in System.Net.Dns.GetHostAddresses("")){
if(ip.AddressFamily == AddressFamily.InterNetwork){
IPBindInfo b = new IPBindInfo(binding.HostName,binding.Protocol,ip,25);
if(!m_pLocalEndPoints.Contains(b)){
m_pLocalEndPoints.Add(b);
}
}
}
}
else if(binding.IP == IPAddress.IPv6Any){
foreach(IPAddress ip in System.Net.Dns.GetHostAddresses("")){
if(ip.AddressFamily == AddressFamily.InterNetworkV6){
IPBindInfo b = new IPBindInfo(binding.HostName,binding.Protocol,ip,25);
if(!m_pLocalEndPoints.Contains(b)){
m_pLocalEndPoints.Add(b);
}
}
}
}
else{
IPBindInfo b = new IPBindInfo(binding.HostName,binding.Protocol,binding.IP,25);
if(!m_pLocalEndPoints.Contains(b)){
m_pLocalEndPoints.Add(b);
}
}
}
m_HasBindingsChanged = false;
}
// There are no local end points specified.
if(m_pLocalEndPoints.Count == 0){
Thread.Sleep(10);
}
// Maximum allowed relay sessions exceeded, skip adding new ones.
else if(m_MaxConnections != 0 && m_pSessions.Count >= m_MaxConnections){
Thread.Sleep(10);
}
else{
Relay_QueueItem item = null;
// Get next queued message from highest possible priority queue.
foreach(Relay_Queue queue in m_pQueues){
item = queue.DequeueMessage();
// There is queued message.
if(item != null){
break;
}
// No messages in this queue, see next lower priority queue.
}
// There are no messages in any queue.
if(item == null){
Thread.Sleep(10);
}
// Create new session for queued relay item.
else{
// Get round-robin local end point for that session.
// This ensures if multiple network connections, all will be load balanced.
IPBindInfo localBindInfo = m_pLocalEndPoints.Next();
if(m_RelayMode == Relay_Mode.Dns){
Relay_Session session = new Relay_Session(this,localBindInfo,item);
m_pSessions.Add(session);
ThreadPool.QueueUserWorkItem(new WaitCallback(session.Start));
}
else if(m_RelayMode == Relay_Mode.SmartHost){
// Get smart hosts in balance mode order.
Relay_SmartHost[] smartHosts = null;
if(m_SmartHostsBalanceMode == BalanceMode.FailOver){
smartHosts = m_pSmartHosts.ToArray();
}
else{
smartHosts = m_pSmartHosts.ToCurrentOrderArray();
}
Relay_Session session = new Relay_Session(this,localBindInfo,item,smartHosts);
m_pSessions.Add(session);
ThreadPool.QueueUserWorkItem(new WaitCallback(session.Start));
}
}
}
}
catch(Exception x){
OnError(x);
}
}
}
#endregion
#region method Run_CheckTimedOutSessions
/// <summary>
/// This method checks timed out relay sessions while server is running.
/// </summary>
private void Run_CheckTimedOutSessions()
{
DateTime lastCheck = DateTime.Now;
while(this.IsRunning){
try{
// Check interval reached.
if(m_SessionIdleTimeout > 0 && lastCheck.AddSeconds(30) < DateTime.Now){
foreach(Relay_Session session in this.Sessions.ToArray()){
try{
if(session.LastActivity.AddSeconds(m_SessionIdleTimeout) < DateTime.Now){
session.Dispose(new Exception("Session idle timeout."));
}
}
catch{
}
}
lastCheck = DateTime.Now;
}
// Not check interval yet.
else{
Thread.Sleep(1000);
}
}
catch(Exception x){
OnError(x);
}
}
}
#endregion
#region method AddIpUsage
/// <summary>
/// Increases specified IP address connactions count if maximum allowed connections to
/// the specified IP address isn't exceeded.
/// </summary>
/// <param name="ip">IP address.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null.</exception>
/// <returns>Returns true if specified IP usage increased, false if maximum allowed connections to the specified IP address is exceeded.</returns>
internal bool TryAddIpUsage(IPAddress ip)
{
if(ip == null){
throw new ArgumentNullException("ip");
}
lock(m_pConnectionsPerIP){
long count = 0;
// Specified IP entry exists, increase usage.
if(m_pConnectionsPerIP.TryGetValue(ip,out count)){
// Maximum allowed connections to the specified IP address is exceeded.
if(m_MaxConnectionsPerIP > 0 && count >= m_MaxConnectionsPerIP){
return false;
}
m_pConnectionsPerIP[ip] = count + 1;
}
// Specified IP entry doesn't exist, create new entry and increase usage.
else{
m_pConnectionsPerIP.Add(ip,1);
}
return true;
}
}
#endregion
#region method RemoveIpUsage
/// <summary>
/// Decreases specified IP address connactions count.
/// </summary>
/// <param name="ip">IP address.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null.</exception>
internal void RemoveIpUsage(IPAddress ip)
{
if(ip == null){
throw new ArgumentNullException("ip");
}
lock(m_pConnectionsPerIP){
long count = 0;
// Specified IP entry exists, increase usage.
if(m_pConnectionsPerIP.TryGetValue(ip,out count)){
// This is last usage to that IP, remove that IP entry.
if(count == 1){
m_pConnectionsPerIP.Remove(ip);
}
// Decrease Ip usage.
else{
m_pConnectionsPerIP[ip] = count - 1;
}
}
else{
// No such entry, just skip it.
}
}
}
#endregion
#region method GetIpUsage
/// <summary>
/// Gets how many connections to the specified IP address.
/// </summary>
/// <param name="ip">IP address.</param>
/// <returns>Returns number of connections to the specified IP address.</returns>
/// <exception cref="ArgumentNullException">Is raised when <b>ip</b> is null.</exception>
internal long GetIpUsage(IPAddress ip)
{
if(ip == null){
throw new ArgumentNullException("ip");
}
lock(m_pConnectionsPerIP){
long count = 0;
// Specified IP entry exists, return usage.
if(m_pConnectionsPerIP.TryGetValue(ip,out count)){
return count;
}
// No usage to specified IP.
else{
return 0;
}
}
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets if server is disposed.
/// </summary>
public bool IsDisposed
{
get{ return m_IsDisposed; }
}
/// <summary>
/// Gets if server is running.
/// </summary>
public bool IsRunning
{
get{ return m_IsRunning; }
}
/// <summary>
/// Gets or sets relay server IP bindings.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public IPBindInfo[] Bindings
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
return m_pBindings;
}
set{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
if(value == null){
value = new IPBindInfo[0];
}
//--- See binds has changed --------------
bool changed = false;
if(m_pBindings.Length != value.Length){
changed = true;
}
else{
for(int i=0;i<m_pBindings.Length;i++){
if(!m_pBindings[i].Equals(value[i])){
changed = true;
break;
}
}
}
if(changed){
m_pBindings = value;
m_HasBindingsChanged = true;
}
}
}
/// <summary>
/// Gets or sets relay mode.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public Relay_Mode RelayMode
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
return m_RelayMode;
}
set{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
m_RelayMode = value;
}
}
/// <summary>
/// Gets relay queues. Queue with lower index number has higher priority.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public List<Relay_Queue> Queues
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
return m_pQueues;
}
}
/// <summary>
/// Gets or sets how smart hosts will be balanced.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public BalanceMode SmartHostsBalanceMode
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
return m_SmartHostsBalanceMode;
}
set{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
m_SmartHostsBalanceMode = value;
}
}
/// <summary>
/// Gets or sets smart hosts. Smart hosts must be in priority order, lower index number means higher priority.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
/// <exception cref="ArgumentNullException">Is raised when null value is passed.</exception>
public Relay_SmartHost[] SmartHosts
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
return m_pSmartHosts.ToArray();
}
set{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
if(value == null){
throw new ArgumentNullException("SmartHosts");
}
m_pSmartHosts.Add(value);
}
}
/// <summary>
/// Gets or sets maximum allowed concurent connections. Value 0 means unlimited.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
/// <exception cref="ArgumentException">Is raised when negative value is passed.</exception>
public long MaxConnections
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
return m_MaxConnections;
}
set{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
if(value < 0){
throw new ArgumentException("Property 'MaxConnections' value must be >= 0.");
}
m_MaxConnections = value;
}
}
/// <summary>
/// Gets or sets maximum allowed connections to 1 IP address. Value 0 means unlimited.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public long MaxConnectionsPerIP
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
return m_MaxConnectionsPerIP;
}
set{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
if(m_MaxConnectionsPerIP < 0){
throw new ArgumentException("Property 'MaxConnectionsPerIP' value must be >= 0.");
}
m_MaxConnectionsPerIP = value;
}
}
/// <summary>
/// Gets or sets session idle time in seconds when it will be timed out. Value 0 means unlimited (strongly not recomended).
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
/// <exception cref="ArgumentException">Is raised when invalid value is passed.</exception>
public int SessionIdleTimeout
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
return m_SessionIdleTimeout;
}
set{if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
if(m_SessionIdleTimeout < 0){
throw new ArgumentException("Property 'SessionIdleTimeout' value must be >= 0.");
}
m_SessionIdleTimeout = value;
}
}
/// <summary>
/// Gets active relay sessions.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
/// <exception cref="InvalidOperationException">Is raised when this property is accessed and relay server is not running.</exception>
public TCP_SessionCollection<Relay_Session> Sessions
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
if(!m_IsRunning){
throw new InvalidOperationException("Relay server not running.");
}
return m_pSessions;
}
}
/// <summary>
/// Gets or sets relay logger. Value null means no logging.
/// </summary>
public Logger Logger
{
get{ return m_pLogger; }
set{ m_pLogger = value; }
}
#endregion
#region Events Implementation
/// <summary>
/// This event is raised when relay session processing completes.
/// </summary>
public event Relay_SessionCompletedEventHandler SessionCompleted = null;
#region method OnSessionCompleted
/// <summary>
/// Raises <b>SessionCompleted</b> event.
/// </summary>
/// <param name="session">Session what completed processing.</param>
/// <param name="exception">Exception happened or null if relay completed successfully.</param>
internal protected virtual void OnSessionCompleted(Relay_Session session,Exception exception)
{
if(this.SessionCompleted != null){
this.SessionCompleted(new Relay_SessionCompletedEventArgs(session,exception));
}
}
#endregion
/// <summary>
/// This event is raised when unhandled exception happens.
/// </summary>
public event ErrorEventHandler Error = null;
#region method OnError
/// <summary>
/// Raises <b>Error</b> event.
/// </summary>
/// <param name="x">Exception happned.</param>
internal protected virtual void OnError(Exception x)
{
if(this.Error != null){
this.Error(this,new Error_EventArgs(x,new System.Diagnostics.StackTrace()));
}
}
#endregion
#endregion
}
}
| |
using EncompassRest.Loans.Enums;
namespace EncompassRest.Loans
{
/// <summary>
/// EmDocumentInvestor
/// </summary>
public sealed partial class EmDocumentInvestor : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<string?>? _id;
private DirtyValue<string?>? _invAsgnCty;
private DirtyValue<string?>? _invAsgnJrsdctn;
private DirtyValue<string?>? _invAsgnNm;
private DirtyValue<StringEnumValue<OrgTyp>>? _invAsgnOrgTyp;
private DirtyValue<string?>? _invAsgnStCd;
private DirtyValue<string?>? _invAsgnStreetAddr1;
private DirtyValue<string?>? _invAsgnStreetAddr2;
private DirtyValue<string?>? _invAsgnZip;
private DirtyValue<string?>? _invCty;
private DirtyValue<string?>? _invFaxNum;
private DirtyValue<string?>? _invJrsdctn;
private DirtyValue<string?>? _invLossPayeeAdtlTxt;
private DirtyValue<string?>? _invLossPayeeCntctEmail;
private DirtyValue<string?>? _invLossPayeeCntctFax;
private DirtyValue<string?>? _invLossPayeeCntctNm;
private DirtyValue<string?>? _invLossPayeeCntctPhone;
private DirtyValue<string?>? _invLossPayeeCty;
private DirtyValue<string?>? _invLossPayeeJrsdctn;
private DirtyValue<string?>? _invLossPayeeNm;
private DirtyValue<StringEnumValue<OrgTyp>>? _invLossPayeeOrgTyp;
private DirtyValue<string?>? _invLossPayeeScsrClausTxtDesc;
private DirtyValue<string?>? _invLossPayeeStCd;
private DirtyValue<string?>? _invLossPayeeStreetAddr1;
private DirtyValue<string?>? _invLossPayeeStreetAddr2;
private DirtyValue<string?>? _invLossPayeeZip;
private DirtyValue<string?>? _invNm;
private DirtyValue<StringEnumValue<OrgTyp>>? _invOrgTyp;
private DirtyValue<string?>? _invPhoneNum;
private DirtyValue<string?>? _invPmtCpn2PayToAdtlTxt;
private DirtyValue<string?>? _invPmtCpn2PayToAdtlTxt2;
private DirtyValue<string?>? _invPmtCpn2PayToCty;
private DirtyValue<string?>? _invPmtCpn2PayToNm;
private DirtyValue<string?>? _invPmtCpn2PayToStCd;
private DirtyValue<string?>? _invPmtCpn2PayToStreetAddr1;
private DirtyValue<string?>? _invPmtCpn2PayToStreetAddr2;
private DirtyValue<string?>? _invPmtCpn2PayToZip;
private DirtyValue<string?>? _invPmtCpnLoanTrsfToAdtlTxt;
private DirtyValue<string?>? _invPmtCpnLoanTrsfToCty;
private DirtyValue<string?>? _invPmtCpnLoanTrsfToNm;
private DirtyValue<string?>? _invPmtCpnLoanTrsfToStCd;
private DirtyValue<string?>? _invPmtCpnLoanTrsfToStreetAddr1;
private DirtyValue<string?>? _invPmtCpnLoanTrsfToStreetAddr2;
private DirtyValue<string?>? _invPmtCpnLoanTrsfToSvcAdtlTxt;
private DirtyValue<string?>? _invPmtCpnLoanTrsfToSvcCty;
private DirtyValue<string?>? _invPmtCpnLoanTrsfToSvcNm;
private DirtyValue<string?>? _invPmtCpnLoanTrsfToSvcStCd;
private DirtyValue<string?>? _invPmtCpnLoanTrsfToSvcStreetAddr1;
private DirtyValue<string?>? _invPmtCpnLoanTrsfToSvcStreetAddr2;
private DirtyValue<string?>? _invPmtCpnLoanTrsfToSvcZip;
private DirtyValue<string?>? _invPmtCpnLoanTrsfToZip;
private DirtyValue<string?>? _invPmtCpnPayToAdtlTxt;
private DirtyValue<string?>? _invPmtCpnPayToAdtlTxt2;
private DirtyValue<string?>? _invPmtCpnPayToCty;
private DirtyValue<string?>? _invPmtCpnPayToNm;
private DirtyValue<string?>? _invPmtCpnPayToStCd;
private DirtyValue<string?>? _invPmtCpnPayToStreetAddr1;
private DirtyValue<string?>? _invPmtCpnPayToStreetAddr2;
private DirtyValue<string?>? _invPmtCpnPayToZip;
private DirtyValue<string?>? _invStCd;
private DirtyValue<string?>? _invStreetAddr1;
private DirtyValue<string?>? _invStreetAddr2;
private DirtyValue<string?>? _invSvcrAdtlTxt;
private DirtyValue<string?>? _invSvcrCntctNm;
private DirtyValue<string?>? _invSvcrCntctPhoneNum;
private DirtyValue<string?>? _invSvcrCntctTollFreePhoneNum;
private DirtyValue<string?>? _invSvcrCty;
private DirtyValue<string?>? _invSvcrDayOp;
private DirtyValue<string?>? _invSvcrDayOpAddl;
private DirtyValue<string?>? _invSvcrHrsOp;
private DirtyValue<string?>? _invSvcrHrsOpAddl;
private DirtyValue<string?>? _invSvcrJrsdctn;
private DirtyValue<string?>? _invSvcrNm;
private DirtyValue<StringEnumValue<OrgTyp>>? _invSvcrOrgTyp;
private DirtyValue<string?>? _invSvcrQlfdWrtnRqstMailToAdtlTxt;
private DirtyValue<string?>? _invSvcrQlfdWrtnRqstMailToCty;
private DirtyValue<string?>? _invSvcrQlfdWrtnRqstMailToNm;
private DirtyValue<string?>? _invSvcrQlfdWrtnRqstMailToStCd;
private DirtyValue<string?>? _invSvcrQlfdWrtnRqstMailToStreetAddr1;
private DirtyValue<string?>? _invSvcrQlfdWrtnRqstMailToStreetAddr2;
private DirtyValue<string?>? _invSvcrQlfdWrtnRqstMailToZip;
private DirtyValue<string?>? _invSvcrStCd;
private DirtyValue<string?>? _invSvcrStreetAddr1;
private DirtyValue<string?>? _invSvcrStreetAddr2;
private DirtyValue<string?>? _invSvcrZip;
private DirtyValue<string?>? _invTaxIDNum;
private DirtyValue<string?>? _invTollFreePhoneNum;
private DirtyValue<string?>? _invUrl;
private DirtyValue<string?>? _invZip;
/// <summary>
/// EmDocumentInvestor Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Assignment City [Closing.InvAsgnCty]
/// </summary>
public string? InvAsgnCty { get => _invAsgnCty; set => SetField(ref _invAsgnCty, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Assignment Organized Under the Laws Of Jurisdiction Name [Closing.InvAsgnJrsdctn]
/// </summary>
public string? InvAsgnJrsdctn { get => _invAsgnJrsdctn; set => SetField(ref _invAsgnJrsdctn, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Assignment Name [Closing.InvAsgnNm]
/// </summary>
public string? InvAsgnNm { get => _invAsgnNm; set => SetField(ref _invAsgnNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Assignment Organization Type [Closing.InvAsgnOrgTyp]
/// </summary>
public StringEnumValue<OrgTyp> InvAsgnOrgTyp { get => _invAsgnOrgTyp; set => SetField(ref _invAsgnOrgTyp, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Assignment State Code [Closing.InvAsgnStCd]
/// </summary>
public string? InvAsgnStCd { get => _invAsgnStCd; set => SetField(ref _invAsgnStCd, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Assignment Street Address [Closing.InvAsgnStreetAddr1]
/// </summary>
public string? InvAsgnStreetAddr1 { get => _invAsgnStreetAddr1; set => SetField(ref _invAsgnStreetAddr1, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Assignment Street Address 2 [Closing.InvAsgnStreetAddr2]
/// </summary>
public string? InvAsgnStreetAddr2 { get => _invAsgnStreetAddr2; set => SetField(ref _invAsgnStreetAddr2, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Assignment Postal Code [Closing.InvAsgnZip]
/// </summary>
public string? InvAsgnZip { get => _invAsgnZip; set => SetField(ref _invAsgnZip, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor City [Closing.InvCty]
/// </summary>
public string? InvCty { get => _invCty; set => SetField(ref _invCty, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor FAX Number [Closing.InvFaxNum]
/// </summary>
public string? InvFaxNum { get => _invFaxNum; set => SetField(ref _invFaxNum, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Jurisdiction [Closing.InvJrsdctn]
/// </summary>
public string? InvJrsdctn { get => _invJrsdctn; set => SetField(ref _invJrsdctn, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Loss Payee Additional Text [Closing.InvLossPayeeAdtlTxt]
/// </summary>
public string? InvLossPayeeAdtlTxt { get => _invLossPayeeAdtlTxt; set => SetField(ref _invLossPayeeAdtlTxt, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Loss Payee Contact Email Address [Closing.InvLossPayeeCntctEmail]
/// </summary>
public string? InvLossPayeeCntctEmail { get => _invLossPayeeCntctEmail; set => SetField(ref _invLossPayeeCntctEmail, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Loss Payee Contact Fax Number [Closing.InvLossPayeeCntctFax]
/// </summary>
public string? InvLossPayeeCntctFax { get => _invLossPayeeCntctFax; set => SetField(ref _invLossPayeeCntctFax, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Loss Payee Contact Name [Closing.InvLossPayeeCntctNm]
/// </summary>
public string? InvLossPayeeCntctNm { get => _invLossPayeeCntctNm; set => SetField(ref _invLossPayeeCntctNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Loss Payee Contact Telephone Number [Closing.InvLossPayeeCntctPhone]
/// </summary>
public string? InvLossPayeeCntctPhone { get => _invLossPayeeCntctPhone; set => SetField(ref _invLossPayeeCntctPhone, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Loss Payee City [Closing.InvLossPayeeCty]
/// </summary>
public string? InvLossPayeeCty { get => _invLossPayeeCty; set => SetField(ref _invLossPayeeCty, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Loss Payee Organized Under the Laws Of Jurisdiction Name [Closing.InvLossPayeeJrsdctn]
/// </summary>
public string? InvLossPayeeJrsdctn { get => _invLossPayeeJrsdctn; set => SetField(ref _invLossPayeeJrsdctn, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Loss Payee Name [Closing.InvLossPayeeNm]
/// </summary>
public string? InvLossPayeeNm { get => _invLossPayeeNm; set => SetField(ref _invLossPayeeNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Loss Payee Organization Type [Closing.InvLossPayeeOrgTyp]
/// </summary>
public StringEnumValue<OrgTyp> InvLossPayeeOrgTyp { get => _invLossPayeeOrgTyp; set => SetField(ref _invLossPayeeOrgTyp, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Loss Payee Successor Clause Text Description [Closing.InvLossPayeeScsrClausTxtDesc]
/// </summary>
public string? InvLossPayeeScsrClausTxtDesc { get => _invLossPayeeScsrClausTxtDesc; set => SetField(ref _invLossPayeeScsrClausTxtDesc, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Loss Payee State Code [Closing.InvLossPayeeStCd]
/// </summary>
public string? InvLossPayeeStCd { get => _invLossPayeeStCd; set => SetField(ref _invLossPayeeStCd, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Loss Payee Street Address [Closing.InvLossPayeeStreetAddr1]
/// </summary>
public string? InvLossPayeeStreetAddr1 { get => _invLossPayeeStreetAddr1; set => SetField(ref _invLossPayeeStreetAddr1, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Loss Payee Street Address 2 [Closing.InvLossPayeeStreetAddr2]
/// </summary>
public string? InvLossPayeeStreetAddr2 { get => _invLossPayeeStreetAddr2; set => SetField(ref _invLossPayeeStreetAddr2, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Loss Payee Postal Code [Closing.InvLossPayeeZip]
/// </summary>
public string? InvLossPayeeZip { get => _invLossPayeeZip; set => SetField(ref _invLossPayeeZip, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Name [Closing.InvNm]
/// </summary>
public string? InvNm { get => _invNm; set => SetField(ref _invNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Organization Type [Closing.InvOrgTyp]
/// </summary>
public StringEnumValue<OrgTyp> InvOrgTyp { get => _invOrgTyp; set => SetField(ref _invOrgTyp, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Telephone Number [Closing.InvPhoneNum]
/// </summary>
public string? InvPhoneNum { get => _invPhoneNum; set => SetField(ref _invPhoneNum, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon 2 Pay To Additional Text 1 [Closing.InvPmtCpn2PayToAdtlTxt]
/// </summary>
public string? InvPmtCpn2PayToAdtlTxt { get => _invPmtCpn2PayToAdtlTxt; set => SetField(ref _invPmtCpn2PayToAdtlTxt, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon 2 Pay To Additional Text 2 [Closing.InvPmtCpn2PayToAdtlTxt2]
/// </summary>
public string? InvPmtCpn2PayToAdtlTxt2 { get => _invPmtCpn2PayToAdtlTxt2; set => SetField(ref _invPmtCpn2PayToAdtlTxt2, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon 2 Pay To City [Closing.InvPmtCpn2PayToCty]
/// </summary>
public string? InvPmtCpn2PayToCty { get => _invPmtCpn2PayToCty; set => SetField(ref _invPmtCpn2PayToCty, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon 2 Pay To Name [Closing.InvPmtCpn2PayToNm]
/// </summary>
public string? InvPmtCpn2PayToNm { get => _invPmtCpn2PayToNm; set => SetField(ref _invPmtCpn2PayToNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon 2 Pay To State Code [Closing.InvPmtCpn2PayToStCd]
/// </summary>
public string? InvPmtCpn2PayToStCd { get => _invPmtCpn2PayToStCd; set => SetField(ref _invPmtCpn2PayToStCd, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon 2 Pay To Street Address [Closing.InvPmtCpn2PayToStreetAddr1]
/// </summary>
public string? InvPmtCpn2PayToStreetAddr1 { get => _invPmtCpn2PayToStreetAddr1; set => SetField(ref _invPmtCpn2PayToStreetAddr1, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon 2 Pay To Street Address 2 [Closing.InvPmtCpn2PayToStreetAddr2]
/// </summary>
public string? InvPmtCpn2PayToStreetAddr2 { get => _invPmtCpn2PayToStreetAddr2; set => SetField(ref _invPmtCpn2PayToStreetAddr2, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon 2 Pay To Postal Code [Closing.InvPmtCpn2PayToZip]
/// </summary>
public string? InvPmtCpn2PayToZip { get => _invPmtCpn2PayToZip; set => SetField(ref _invPmtCpn2PayToZip, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon Loan Transfer To Miscellaneous Text Description [Closing.InvPmtCpnLoanTrsfToAdtlTxt]
/// </summary>
public string? InvPmtCpnLoanTrsfToAdtlTxt { get => _invPmtCpnLoanTrsfToAdtlTxt; set => SetField(ref _invPmtCpnLoanTrsfToAdtlTxt, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon Loan Transfer To City [Closing.InvPmtCpnLoanTrsfToCty]
/// </summary>
public string? InvPmtCpnLoanTrsfToCty { get => _invPmtCpnLoanTrsfToCty; set => SetField(ref _invPmtCpnLoanTrsfToCty, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon Loan Transfer To Name [Closing.InvPmtCpnLoanTrsfToNm]
/// </summary>
public string? InvPmtCpnLoanTrsfToNm { get => _invPmtCpnLoanTrsfToNm; set => SetField(ref _invPmtCpnLoanTrsfToNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon Loan Transfer To State Code [Closing.InvPmtCpnLoanTrsfToStCd]
/// </summary>
public string? InvPmtCpnLoanTrsfToStCd { get => _invPmtCpnLoanTrsfToStCd; set => SetField(ref _invPmtCpnLoanTrsfToStCd, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon Loan Transfer To Street Address [Closing.InvPmtCpnLoanTrsfToStreetAddr1]
/// </summary>
public string? InvPmtCpnLoanTrsfToStreetAddr1 { get => _invPmtCpnLoanTrsfToStreetAddr1; set => SetField(ref _invPmtCpnLoanTrsfToStreetAddr1, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon Loan Transfer To Street Address 2 [Closing.InvPmtCpnLoanTrsfToStreetAddr2]
/// </summary>
public string? InvPmtCpnLoanTrsfToStreetAddr2 { get => _invPmtCpnLoanTrsfToStreetAddr2; set => SetField(ref _invPmtCpnLoanTrsfToStreetAddr2, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon Loan Transfer To Servicing Miscellaneous Text Description [Closing.InvPmtCpnLoanTrsfToSvcAdtlTxt]
/// </summary>
public string? InvPmtCpnLoanTrsfToSvcAdtlTxt { get => _invPmtCpnLoanTrsfToSvcAdtlTxt; set => SetField(ref _invPmtCpnLoanTrsfToSvcAdtlTxt, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon Loan Transfer To Servicing City [Closing.InvPmtCpnLoanTrsfToSvcCty]
/// </summary>
public string? InvPmtCpnLoanTrsfToSvcCty { get => _invPmtCpnLoanTrsfToSvcCty; set => SetField(ref _invPmtCpnLoanTrsfToSvcCty, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon Loan Transfer To Servicing Name [Closing.InvPmtCpnLoanTrsfToSvcNm]
/// </summary>
public string? InvPmtCpnLoanTrsfToSvcNm { get => _invPmtCpnLoanTrsfToSvcNm; set => SetField(ref _invPmtCpnLoanTrsfToSvcNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon Loan Transfer To Servicing State Code [Closing.InvPmtCpnLoanTrsfToSvcStCd]
/// </summary>
public string? InvPmtCpnLoanTrsfToSvcStCd { get => _invPmtCpnLoanTrsfToSvcStCd; set => SetField(ref _invPmtCpnLoanTrsfToSvcStCd, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon Loan Transfer To Servicing Street Address [Closing.InvPmtCpnLoanTrsfToSvcStreetAddr1]
/// </summary>
public string? InvPmtCpnLoanTrsfToSvcStreetAddr1 { get => _invPmtCpnLoanTrsfToSvcStreetAddr1; set => SetField(ref _invPmtCpnLoanTrsfToSvcStreetAddr1, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon Loan Transfer To Servicing Street Address 2 [Closing.InvPmtCpnLoanTrsfToSvcStreetAddr2]
/// </summary>
public string? InvPmtCpnLoanTrsfToSvcStreetAddr2 { get => _invPmtCpnLoanTrsfToSvcStreetAddr2; set => SetField(ref _invPmtCpnLoanTrsfToSvcStreetAddr2, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon Loan Transfer To Servicing Postal Code [Closing.InvPmtCpnLoanTrsfToSvcZip]
/// </summary>
public string? InvPmtCpnLoanTrsfToSvcZip { get => _invPmtCpnLoanTrsfToSvcZip; set => SetField(ref _invPmtCpnLoanTrsfToSvcZip, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon Loan Transfer To Postal Code [Closing.InvPmtCpnLoanTrsfToZip]
/// </summary>
public string? InvPmtCpnLoanTrsfToZip { get => _invPmtCpnLoanTrsfToZip; set => SetField(ref _invPmtCpnLoanTrsfToZip, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon 1 Pay To Additional Text 1 [Closing.InvPmtCpnPayToAdtlTxt]
/// </summary>
public string? InvPmtCpnPayToAdtlTxt { get => _invPmtCpnPayToAdtlTxt; set => SetField(ref _invPmtCpnPayToAdtlTxt, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon 1 Pay To Additional Text 2 [Closing.InvPmtCpnPayToAdtlTxt2]
/// </summary>
public string? InvPmtCpnPayToAdtlTxt2 { get => _invPmtCpnPayToAdtlTxt2; set => SetField(ref _invPmtCpnPayToAdtlTxt2, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon 1 Pay To City [Closing.InvPmtCpnPayToCty]
/// </summary>
public string? InvPmtCpnPayToCty { get => _invPmtCpnPayToCty; set => SetField(ref _invPmtCpnPayToCty, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon 1 Pay To Name [Closing.InvPmtCpnPayToNm]
/// </summary>
public string? InvPmtCpnPayToNm { get => _invPmtCpnPayToNm; set => SetField(ref _invPmtCpnPayToNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon 1 Pay To State Code [Closing.InvPmtCpnPayToStCd]
/// </summary>
public string? InvPmtCpnPayToStCd { get => _invPmtCpnPayToStCd; set => SetField(ref _invPmtCpnPayToStCd, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon 1 Pay To Street Address [Closing.InvPmtCpnPayToStreetAddr1]
/// </summary>
public string? InvPmtCpnPayToStreetAddr1 { get => _invPmtCpnPayToStreetAddr1; set => SetField(ref _invPmtCpnPayToStreetAddr1, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon 1 Pay To Street Address 2 [Closing.InvPmtCpnPayToStreetAddr2]
/// </summary>
public string? InvPmtCpnPayToStreetAddr2 { get => _invPmtCpnPayToStreetAddr2; set => SetField(ref _invPmtCpnPayToStreetAddr2, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Payment Coupon 1 Pay To Postal Code [Closing.InvPmtCpnPayToZip]
/// </summary>
public string? InvPmtCpnPayToZip { get => _invPmtCpnPayToZip; set => SetField(ref _invPmtCpnPayToZip, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor State Code [Closing.InvStCd]
/// </summary>
public string? InvStCd { get => _invStCd; set => SetField(ref _invStCd, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Street Address [Closing.InvStreetAddr1]
/// </summary>
public string? InvStreetAddr1 { get => _invStreetAddr1; set => SetField(ref _invStreetAddr1, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Street Address 2 [Closing.InvStreetAddr2]
/// </summary>
public string? InvStreetAddr2 { get => _invStreetAddr2; set => SetField(ref _invStreetAddr2, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Additional Text [Closing.InvSvcrAdtlTxt]
/// </summary>
public string? InvSvcrAdtlTxt { get => _invSvcrAdtlTxt; set => SetField(ref _invSvcrAdtlTxt, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Contact Name [Closing.InvSvcrCntctNm]
/// </summary>
public string? InvSvcrCntctNm { get => _invSvcrCntctNm; set => SetField(ref _invSvcrCntctNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Contact Telephone Number [Closing.InvSvcrCntctPhoneNum]
/// </summary>
public string? InvSvcrCntctPhoneNum { get => _invSvcrCntctPhoneNum; set => SetField(ref _invSvcrCntctPhoneNum, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Contact Toll-Free Telephone Number [Closing.InvSvcrCntctTollFreePhoneNum]
/// </summary>
public string? InvSvcrCntctTollFreePhoneNum { get => _invSvcrCntctTollFreePhoneNum; set => SetField(ref _invSvcrCntctTollFreePhoneNum, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer City [Closing.InvSvcrCty]
/// </summary>
public string? InvSvcrCty { get => _invSvcrCty; set => SetField(ref _invSvcrCty, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Days of Operation [Closing.InvSvcrDayOp]
/// </summary>
public string? InvSvcrDayOp { get => _invSvcrDayOp; set => SetField(ref _invSvcrDayOp, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Days of Operation (Additional) [Closing.InvSvcrDayOpAddl]
/// </summary>
public string? InvSvcrDayOpAddl { get => _invSvcrDayOpAddl; set => SetField(ref _invSvcrDayOpAddl, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Hours of Operation [Closing.InvSvcrHrsOp]
/// </summary>
public string? InvSvcrHrsOp { get => _invSvcrHrsOp; set => SetField(ref _invSvcrHrsOp, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Hours of Operation (Additional) [Closing.InvSvcrHrsOpAddl]
/// </summary>
public string? InvSvcrHrsOpAddl { get => _invSvcrHrsOpAddl; set => SetField(ref _invSvcrHrsOpAddl, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Jurisdiction [Closing.InvSvcrJrsdctn]
/// </summary>
public string? InvSvcrJrsdctn { get => _invSvcrJrsdctn; set => SetField(ref _invSvcrJrsdctn, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Name [Closing.InvSvcrNm]
/// </summary>
public string? InvSvcrNm { get => _invSvcrNm; set => SetField(ref _invSvcrNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Organization Type [Closing.InvSvcrOrgTyp]
/// </summary>
public StringEnumValue<OrgTyp> InvSvcrOrgTyp { get => _invSvcrOrgTyp; set => SetField(ref _invSvcrOrgTyp, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Qualified Written Request Mail To Additional Text [Closing.InvSvcrQlfdWrtnRqstMailToAdtlTxt]
/// </summary>
public string? InvSvcrQlfdWrtnRqstMailToAdtlTxt { get => _invSvcrQlfdWrtnRqstMailToAdtlTxt; set => SetField(ref _invSvcrQlfdWrtnRqstMailToAdtlTxt, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Qualified Written Request Mail To City [Closing.InvSvcrQlfdWrtnRqstMailToCty]
/// </summary>
public string? InvSvcrQlfdWrtnRqstMailToCty { get => _invSvcrQlfdWrtnRqstMailToCty; set => SetField(ref _invSvcrQlfdWrtnRqstMailToCty, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Qualified Written Request Mail To Name [Closing.InvSvcrQlfdWrtnRqstMailToNm]
/// </summary>
public string? InvSvcrQlfdWrtnRqstMailToNm { get => _invSvcrQlfdWrtnRqstMailToNm; set => SetField(ref _invSvcrQlfdWrtnRqstMailToNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Qualified Written Request Mail To State Code [Closing.InvSvcrQlfdWrtnRqstMailToStCd]
/// </summary>
public string? InvSvcrQlfdWrtnRqstMailToStCd { get => _invSvcrQlfdWrtnRqstMailToStCd; set => SetField(ref _invSvcrQlfdWrtnRqstMailToStCd, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Qualified Written Request Mail To Street Address [Closing.InvSvcrQlfdWrtnRqstMailToStreetAddr1]
/// </summary>
public string? InvSvcrQlfdWrtnRqstMailToStreetAddr1 { get => _invSvcrQlfdWrtnRqstMailToStreetAddr1; set => SetField(ref _invSvcrQlfdWrtnRqstMailToStreetAddr1, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Qualified Written Request Mail To Street Address 2 [Closing.InvSvcrQlfdWrtnRqstMailToStreetAddr2]
/// </summary>
public string? InvSvcrQlfdWrtnRqstMailToStreetAddr2 { get => _invSvcrQlfdWrtnRqstMailToStreetAddr2; set => SetField(ref _invSvcrQlfdWrtnRqstMailToStreetAddr2, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Qualified Written Request Mail To Postal Code [Closing.InvSvcrQlfdWrtnRqstMailToZip]
/// </summary>
public string? InvSvcrQlfdWrtnRqstMailToZip { get => _invSvcrQlfdWrtnRqstMailToZip; set => SetField(ref _invSvcrQlfdWrtnRqstMailToZip, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer State Code [Closing.InvSvcrStCd]
/// </summary>
public string? InvSvcrStCd { get => _invSvcrStCd; set => SetField(ref _invSvcrStCd, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Street Address [Closing.InvSvcrStreetAddr1]
/// </summary>
public string? InvSvcrStreetAddr1 { get => _invSvcrStreetAddr1; set => SetField(ref _invSvcrStreetAddr1, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Street Address 2 [Closing.InvSvcrStreetAddr2]
/// </summary>
public string? InvSvcrStreetAddr2 { get => _invSvcrStreetAddr2; set => SetField(ref _invSvcrStreetAddr2, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Servicer Postal Code [Closing.InvSvcrZip]
/// </summary>
public string? InvSvcrZip { get => _invSvcrZip; set => SetField(ref _invSvcrZip, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Tax ID No. [Closing.InvTaxIDNum]
/// </summary>
public string? InvTaxIDNum { get => _invTaxIDNum; set => SetField(ref _invTaxIDNum, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Toll-Free Telephone Number [Closing.InvTollFreePhoneNum]
/// </summary>
public string? InvTollFreePhoneNum { get => _invTollFreePhoneNum; set => SetField(ref _invTollFreePhoneNum, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor URL [Closing.InvUrl]
/// </summary>
public string? InvUrl { get => _invUrl; set => SetField(ref _invUrl, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Investor Postal Code [Closing.InvZip]
/// </summary>
public string? InvZip { get => _invZip; set => SetField(ref _invZip, value); }
}
}
| |
namespace Ioke.Lang {
using System.Collections;
using System.Collections.Generic;
using Ioke.Lang.Util;
public class DefaultMacro : IokeData, Named, Inspectable, AssociatedCode {
string name;
IokeObject code;
public DefaultMacro(string name) {
this.name = name;
}
public DefaultMacro(IokeObject context, IokeObject code) : this((string)null) {
this.code = code;
}
public override void Init(IokeObject obj) {
obj.Kind = "DefaultMacro";
obj.RegisterCell("activatable", obj.runtime.True);
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the name of the macro",
new TypeCheckingNativeMethod.WithNoArguments("name", obj,
(method, on, args, keywords, _context, message) => {
return _context.runtime.NewText(((DefaultMacro)IokeObject.dataOf(on)).name);
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("activates this macro with the arguments given to call",
new NativeMethod("call", DefaultArgumentsDefinition.builder()
.WithRestUnevaluated("arguments")
.Arguments,
(method, _context, message, on, outer) => {
return IokeObject.As(on, _context).Activate(_context, message, _context.RealContext);
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the message chain for this macro",
new TypeCheckingNativeMethod.WithNoArguments("message", obj,
(method, on, args, keywords, _context, message) => {
return ((DefaultMacro)IokeObject.dataOf(on)).Code;
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the code for the argument definition",
new TypeCheckingNativeMethod.WithNoArguments("argumentsCode", obj,
(method, on, args, keywords, _context, message) => {
return _context.runtime.NewText(((AssociatedCode)IokeObject.dataOf(on)).ArgumentsCode);
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a text inspection of the object",
new TypeCheckingNativeMethod.WithNoArguments("inspect", obj,
(method, on, args, keywords, _context, message) => {
return _context.runtime.NewText(DefaultMacro.GetInspect(on));
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a brief text inspection of the object",
new TypeCheckingNativeMethod.WithNoArguments("notice", obj,
(method, on, args, keywords, _context, message) => {
return _context.runtime.NewText(DefaultMacro.GetNotice(on));
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the full code of this macro, as a Text",
new TypeCheckingNativeMethod.WithNoArguments("code", obj,
(method, on, args, keywords, _context, message) => {
IokeData data = IokeObject.dataOf(on);
if(data is DefaultMacro) {
return _context.runtime.NewText(((DefaultMacro)data).CodeString);
} else {
return _context.runtime.NewText(((AliasMethod)data).CodeString);
}
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns idiomatically formatted code for this macro",
new TypeCheckingNativeMethod.WithNoArguments("formattedCode", obj,
(method, on, args, keywords, _context, message) => {
return _context.runtime.NewText(((AssociatedCode)IokeObject.dataOf(on)).FormattedCode(method));
})));
}
public string Name {
get { return this.name; }
set { this.name = value; }
}
public static string GetInspect(object on) {
return ((Inspectable)(IokeObject.dataOf(on))).Inspect(on);
}
public static string GetNotice(object on) {
return ((Inspectable)(IokeObject.dataOf(on))).Notice(on);
}
public string Inspect(object self) {
if(name == null) {
return "macro(" + Message.Code(code) + ")";
} else {
return name + ":macro(" + Message.Code(code) + ")";
}
}
public string Notice(object self) {
if(name == null) {
return "macro(...)";
} else {
return name + ":macro(...)";
}
}
public IokeObject Code {
get { return code; }
}
public string CodeString {
get { return "macro(" + Message.Code(code) + ")"; }
}
public string FormattedCode(object self) {
return "macro(\n " + Message.FormattedCode(code, 2, (IokeObject)self) + ")";
}
public string ArgumentsCode {
get { return "..."; }
}
public override object ActivateWithCallAndData(IokeObject self, IokeObject context, IokeObject message, object on, object call, IDictionary<string, object> data) {
if(code == null) {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(context.runtime.Condition,
message,
context,
"Error",
"Invocation",
"NotActivatable"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("method", self);
condition.SetCell("report", context.runtime.NewText("You tried to activate a method without any code - did you by any chance activate the DefaultMacro kind by referring to it without wrapping it inside a call to cell?"));
context.runtime.ErrorCondition(condition);
return null;
}
IokeObject c = context.runtime.Locals.Mimic(message, context);
c.SetCell("self", on);
c.SetCell("@", on);
c.RegisterMethod(c.runtime.NewNativeMethod("will return the currently executing macro receiver", new NativeMethod.WithNoArguments("@@",
(method, _context, _message, _on, outer) => {
outer.ArgumentsDefinition.GetEvaluatedArguments(_context, _message, _on, new SaneArrayList(), new SaneDictionary<string, object>());
return self;
})));
c.SetCell("currentMessage", message);
c.SetCell("surroundingContext", context);
c.SetCell("call", call);
foreach(var d in data) {
string s = d.Key;
c.SetCell(s.Substring(0, s.Length-1), d.Value);
}
try {
return ((Message)IokeObject.dataOf(code)).EvaluateCompleteWith(code, c, on);
} catch(ControlFlow.Return e) {
if(e.context == c) {
return e.Value;
} else {
throw e;
}
}
}
public override object ActivateWithCall(IokeObject self, IokeObject context, IokeObject message, object on, object call) {
if(code == null) {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(context.runtime.Condition,
message,
context,
"Error",
"Invocation",
"NotActivatable"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("method", self);
condition.SetCell("report", context.runtime.NewText("You tried to activate a method without any code - did you by any chance activate the DefaultMacro kind by referring to it without wrapping it inside a call to cell?"));
context.runtime.ErrorCondition(condition);
return null;
}
IokeObject c = context.runtime.Locals.Mimic(message, context);
c.SetCell("self", on);
c.SetCell("@", on);
c.RegisterMethod(c.runtime.NewNativeMethod("will return the currently executing macro receiver", new NativeMethod.WithNoArguments("@@",
(method, _context, _message, _on, outer) => {
outer.ArgumentsDefinition.GetEvaluatedArguments(_context, _message, _on, new SaneArrayList(), new SaneDictionary<string, object>());
return self;
})));
c.SetCell("currentMessage", message);
c.SetCell("surroundingContext", context);
c.SetCell("call", call);
try {
return ((Message)IokeObject.dataOf(code)).EvaluateCompleteWith(code, c, on);
} catch(ControlFlow.Return e) {
if(e.context == c) {
return e.Value;
} else {
throw e;
}
}
}
public override object Activate(IokeObject self, IokeObject context, IokeObject message, object on) {
if(code == null) {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(context.runtime.Condition,
message,
context,
"Error",
"Invocation",
"NotActivatable"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("method", self);
condition.SetCell("report", context.runtime.NewText("You tried to activate a method without any code - did you by any chance activate the DefaultMacro kind by referring to it without wrapping it inside a call to cell?"));
context.runtime.ErrorCondition(condition);
return null;
}
IokeObject c = context.runtime.Locals.Mimic(message, context);
c.SetCell("self", on);
c.SetCell("@", on);
c.RegisterMethod(c.runtime.NewNativeMethod("will return the currently executing macro receiver", new NativeMethod.WithNoArguments("@@",
(method, _context, _message, _on, outer) => {
outer.ArgumentsDefinition.GetEvaluatedArguments(_context, _message, _on, new SaneArrayList(), new SaneDictionary<string, object>());
return self;
})));
c.SetCell("currentMessage", message);
c.SetCell("surroundingContext", context);
c.SetCell("call", context.runtime.NewCallFrom(c, message, context, IokeObject.As(on, context)));
try {
return ((Message)IokeObject.dataOf(code)).EvaluateCompleteWith(code, c, on);
} catch(ControlFlow.Return e) {
if(e.context == c) {
return e.Value;
} else {
throw e;
}
}
}
public override object ActivateWithData(IokeObject self, IokeObject context, IokeObject message, object on, IDictionary<string, object> data) {
if(code == null) {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(context.runtime.Condition,
message,
context,
"Error",
"Invocation",
"NotActivatable"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("method", self);
condition.SetCell("report", context.runtime.NewText("You tried to activate a method without any code - did you by any chance activate the DefaultMacro kind by referring to it without wrapping it inside a call to cell?"));
context.runtime.ErrorCondition(condition);
return null;
}
IokeObject c = context.runtime.Locals.Mimic(message, context);
c.SetCell("self", on);
c.SetCell("@", on);
c.RegisterMethod(c.runtime.NewNativeMethod("will return the currently executing macro receiver", new NativeMethod.WithNoArguments("@@",
(method, _context, _message, _on, outer) => {
outer.ArgumentsDefinition.GetEvaluatedArguments(_context, _message, _on, new SaneArrayList(), new SaneDictionary<string, object>());
return self;
})));
c.SetCell("currentMessage", message);
c.SetCell("surroundingContext", context);
c.SetCell("call", context.runtime.NewCallFrom(c, message, context, IokeObject.As(on, context)));
foreach(var d in data) {
string s = d.Key;
c.SetCell(s.Substring(0, s.Length-1), d.Value);
}
try {
return ((Message)IokeObject.dataOf(code)).EvaluateCompleteWith(code, c, on);
} catch(ControlFlow.Return e) {
if(e.context == c) {
return e.Value;
} else {
throw e;
}
}
}
}
}
| |
/*
* CP500.cs - IBM EBCDIC (International) code page.
*
* Copyright (c) 2002 Southern Storm Software, Pty Ltd
*
* 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
*/
// Generated from "ibm-500.ucm".
namespace I18N.Rare
{
using System;
using I18N.Common;
public class CP500 : ByteEncoding
{
public CP500()
: base(500, ToChars, "IBM EBCDIC (International)",
"IBM500", "IBM500", "IBM500",
false, false, false, false, 1252)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u009C', '\u0009',
'\u0086', '\u007F', '\u0097', '\u008D', '\u008E', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u009D', '\u0085', '\u0008', '\u0087',
'\u0018', '\u0019', '\u0092', '\u008F', '\u001C', '\u001D',
'\u001E', '\u001F', '\u0080', '\u0081', '\u0082', '\u0083',
'\u0084', '\u000A', '\u0017', '\u001B', '\u0088', '\u0089',
'\u008A', '\u008B', '\u008C', '\u0005', '\u0006', '\u0007',
'\u0090', '\u0091', '\u0016', '\u0093', '\u0094', '\u0095',
'\u0096', '\u0004', '\u0098', '\u0099', '\u009A', '\u009B',
'\u0014', '\u0015', '\u009E', '\u001A', '\u0020', '\u00A0',
'\u00E2', '\u00E4', '\u00E0', '\u00E1', '\u00E3', '\u00E5',
'\u00E7', '\u00F1', '\u005B', '\u002E', '\u003C', '\u0028',
'\u002B', '\u0021', '\u0026', '\u00E9', '\u00EA', '\u00EB',
'\u00E8', '\u00ED', '\u00EE', '\u00EF', '\u00EC', '\u00DF',
'\u005D', '\u0024', '\u002A', '\u0029', '\u003B', '\u005E',
'\u002D', '\u002F', '\u00C2', '\u00C4', '\u00C0', '\u00C1',
'\u00C3', '\u00C5', '\u00C7', '\u00D1', '\u00A6', '\u002C',
'\u0025', '\u005F', '\u003E', '\u003F', '\u00F8', '\u00C9',
'\u00CA', '\u00CB', '\u00C8', '\u00CD', '\u00CE', '\u00CF',
'\u00CC', '\u0060', '\u003A', '\u0023', '\u0040', '\u0027',
'\u003D', '\u0022', '\u00D8', '\u0061', '\u0062', '\u0063',
'\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069',
'\u00AB', '\u00BB', '\u00F0', '\u00FD', '\u00FE', '\u00B1',
'\u00B0', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E',
'\u006F', '\u0070', '\u0071', '\u0072', '\u00AA', '\u00BA',
'\u00E6', '\u00B8', '\u00C6', '\u00A4', '\u00B5', '\u007E',
'\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078',
'\u0079', '\u007A', '\u00A1', '\u00BF', '\u00D0', '\u00DD',
'\u00DE', '\u00AE', '\u00A2', '\u00A3', '\u00A5', '\u00B7',
'\u00A9', '\u00A7', '\u00B6', '\u00BC', '\u00BD', '\u00BE',
'\u00AC', '\u007C', '\u00AF', '\u00A8', '\u00B4', '\u00D7',
'\u007B', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045',
'\u0046', '\u0047', '\u0048', '\u0049', '\u00AD', '\u00F4',
'\u00F6', '\u00F2', '\u00F3', '\u00F5', '\u007D', '\u004A',
'\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050',
'\u0051', '\u0052', '\u00B9', '\u00FB', '\u00FC', '\u00F9',
'\u00FA', '\u00FF', '\u005C', '\u00F7', '\u0053', '\u0054',
'\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A',
'\u00B2', '\u00D4', '\u00D6', '\u00D2', '\u00D3', '\u00D5',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u00B3', '\u00DB',
'\u00DC', '\u00D9', '\u00DA', '\u009F',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 4) switch(ch)
{
case 0x000B:
case 0x000C:
case 0x000D:
case 0x000E:
case 0x000F:
case 0x0010:
case 0x0011:
case 0x0012:
case 0x0013:
case 0x0018:
case 0x0019:
case 0x001C:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x00B6:
break;
case 0x0004: ch = 0x37; break;
case 0x0005: ch = 0x2D; break;
case 0x0006: ch = 0x2E; break;
case 0x0007: ch = 0x2F; break;
case 0x0008: ch = 0x16; break;
case 0x0009: ch = 0x05; break;
case 0x000A: ch = 0x25; break;
case 0x0014: ch = 0x3C; break;
case 0x0015: ch = 0x3D; break;
case 0x0016: ch = 0x32; break;
case 0x0017: ch = 0x26; break;
case 0x001A: ch = 0x3F; break;
case 0x001B: ch = 0x27; break;
case 0x0020: ch = 0x40; break;
case 0x0021: ch = 0x4F; break;
case 0x0022: ch = 0x7F; break;
case 0x0023: ch = 0x7B; break;
case 0x0024: ch = 0x5B; break;
case 0x0025: ch = 0x6C; break;
case 0x0026: ch = 0x50; break;
case 0x0027: ch = 0x7D; break;
case 0x0028: ch = 0x4D; break;
case 0x0029: ch = 0x5D; break;
case 0x002A: ch = 0x5C; break;
case 0x002B: ch = 0x4E; break;
case 0x002C: ch = 0x6B; break;
case 0x002D: ch = 0x60; break;
case 0x002E: ch = 0x4B; break;
case 0x002F: ch = 0x61; break;
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
ch += 0x00C0;
break;
case 0x003A: ch = 0x7A; break;
case 0x003B: ch = 0x5E; break;
case 0x003C: ch = 0x4C; break;
case 0x003D: ch = 0x7E; break;
case 0x003E: ch = 0x6E; break;
case 0x003F: ch = 0x6F; break;
case 0x0040: ch = 0x7C; break;
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
ch += 0x0080;
break;
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
ch += 0x0087;
break;
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
ch += 0x008F;
break;
case 0x005B: ch = 0x4A; break;
case 0x005C: ch = 0xE0; break;
case 0x005D: ch = 0x5A; break;
case 0x005E: ch = 0x5F; break;
case 0x005F: ch = 0x6D; break;
case 0x0060: ch = 0x79; break;
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
ch += 0x0020;
break;
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
ch += 0x0027;
break;
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
ch += 0x002F;
break;
case 0x007B: ch = 0xC0; break;
case 0x007C: ch = 0xBB; break;
case 0x007D: ch = 0xD0; break;
case 0x007E: ch = 0xA1; break;
case 0x007F: ch = 0x07; break;
case 0x0080:
case 0x0081:
case 0x0082:
case 0x0083:
case 0x0084:
ch -= 0x0060;
break;
case 0x0085: ch = 0x15; break;
case 0x0086: ch = 0x06; break;
case 0x0087: ch = 0x17; break;
case 0x0088:
case 0x0089:
case 0x008A:
case 0x008B:
case 0x008C:
ch -= 0x0060;
break;
case 0x008D: ch = 0x09; break;
case 0x008E: ch = 0x0A; break;
case 0x008F: ch = 0x1B; break;
case 0x0090: ch = 0x30; break;
case 0x0091: ch = 0x31; break;
case 0x0092: ch = 0x1A; break;
case 0x0093:
case 0x0094:
case 0x0095:
case 0x0096:
ch -= 0x0060;
break;
case 0x0097: ch = 0x08; break;
case 0x0098:
case 0x0099:
case 0x009A:
case 0x009B:
ch -= 0x0060;
break;
case 0x009C: ch = 0x04; break;
case 0x009D: ch = 0x14; break;
case 0x009E: ch = 0x3E; break;
case 0x009F: ch = 0xFF; break;
case 0x00A0: ch = 0x41; break;
case 0x00A1: ch = 0xAA; break;
case 0x00A2: ch = 0xB0; break;
case 0x00A3: ch = 0xB1; break;
case 0x00A4: ch = 0x9F; break;
case 0x00A5: ch = 0xB2; break;
case 0x00A6: ch = 0x6A; break;
case 0x00A7: ch = 0xB5; break;
case 0x00A8: ch = 0xBD; break;
case 0x00A9: ch = 0xB4; break;
case 0x00AA: ch = 0x9A; break;
case 0x00AB: ch = 0x8A; break;
case 0x00AC: ch = 0xBA; break;
case 0x00AD: ch = 0xCA; break;
case 0x00AE: ch = 0xAF; break;
case 0x00AF: ch = 0xBC; break;
case 0x00B0: ch = 0x90; break;
case 0x00B1: ch = 0x8F; break;
case 0x00B2: ch = 0xEA; break;
case 0x00B3: ch = 0xFA; break;
case 0x00B4: ch = 0xBE; break;
case 0x00B5: ch = 0xA0; break;
case 0x00B7: ch = 0xB3; break;
case 0x00B8: ch = 0x9D; break;
case 0x00B9: ch = 0xDA; break;
case 0x00BA: ch = 0x9B; break;
case 0x00BB: ch = 0x8B; break;
case 0x00BC: ch = 0xB7; break;
case 0x00BD: ch = 0xB8; break;
case 0x00BE: ch = 0xB9; break;
case 0x00BF: ch = 0xAB; break;
case 0x00C0: ch = 0x64; break;
case 0x00C1: ch = 0x65; break;
case 0x00C2: ch = 0x62; break;
case 0x00C3: ch = 0x66; break;
case 0x00C4: ch = 0x63; break;
case 0x00C5: ch = 0x67; break;
case 0x00C6: ch = 0x9E; break;
case 0x00C7: ch = 0x68; break;
case 0x00C8: ch = 0x74; break;
case 0x00C9: ch = 0x71; break;
case 0x00CA: ch = 0x72; break;
case 0x00CB: ch = 0x73; break;
case 0x00CC: ch = 0x78; break;
case 0x00CD: ch = 0x75; break;
case 0x00CE: ch = 0x76; break;
case 0x00CF: ch = 0x77; break;
case 0x00D0: ch = 0xAC; break;
case 0x00D1: ch = 0x69; break;
case 0x00D2: ch = 0xED; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEB; break;
case 0x00D5: ch = 0xEF; break;
case 0x00D6: ch = 0xEC; break;
case 0x00D7: ch = 0xBF; break;
case 0x00D8: ch = 0x80; break;
case 0x00D9: ch = 0xFD; break;
case 0x00DA: ch = 0xFE; break;
case 0x00DB: ch = 0xFB; break;
case 0x00DC: ch = 0xFC; break;
case 0x00DD: ch = 0xAD; break;
case 0x00DE: ch = 0xAE; break;
case 0x00DF: ch = 0x59; break;
case 0x00E0: ch = 0x44; break;
case 0x00E1: ch = 0x45; break;
case 0x00E2: ch = 0x42; break;
case 0x00E3: ch = 0x46; break;
case 0x00E4: ch = 0x43; break;
case 0x00E5: ch = 0x47; break;
case 0x00E6: ch = 0x9C; break;
case 0x00E7: ch = 0x48; break;
case 0x00E8: ch = 0x54; break;
case 0x00E9: ch = 0x51; break;
case 0x00EA: ch = 0x52; break;
case 0x00EB: ch = 0x53; break;
case 0x00EC: ch = 0x58; break;
case 0x00ED: ch = 0x55; break;
case 0x00EE: ch = 0x56; break;
case 0x00EF: ch = 0x57; break;
case 0x00F0: ch = 0x8C; break;
case 0x00F1: ch = 0x49; break;
case 0x00F2: ch = 0xCD; break;
case 0x00F3: ch = 0xCE; break;
case 0x00F4: ch = 0xCB; break;
case 0x00F5: ch = 0xCF; break;
case 0x00F6: ch = 0xCC; break;
case 0x00F7: ch = 0xE1; break;
case 0x00F8: ch = 0x70; break;
case 0x00F9: ch = 0xDD; break;
case 0x00FA: ch = 0xDE; break;
case 0x00FB: ch = 0xDB; break;
case 0x00FC: ch = 0xDC; break;
case 0x00FD: ch = 0x8D; break;
case 0x00FE: ch = 0x8E; break;
case 0x00FF: ch = 0xDF; break;
case 0x0110: ch = 0xAC; break;
case 0x203E: ch = 0xBC; break;
case 0xFF01: ch = 0x4F; break;
case 0xFF02: ch = 0x7F; break;
case 0xFF03: ch = 0x7B; break;
case 0xFF04: ch = 0x5B; break;
case 0xFF05: ch = 0x6C; break;
case 0xFF06: ch = 0x50; break;
case 0xFF07: ch = 0x7D; break;
case 0xFF08: ch = 0x4D; break;
case 0xFF09: ch = 0x5D; break;
case 0xFF0A: ch = 0x5C; break;
case 0xFF0B: ch = 0x4E; break;
case 0xFF0C: ch = 0x6B; break;
case 0xFF0D: ch = 0x60; break;
case 0xFF0E: ch = 0x4B; break;
case 0xFF0F: ch = 0x61; break;
case 0xFF10:
case 0xFF11:
case 0xFF12:
case 0xFF13:
case 0xFF14:
case 0xFF15:
case 0xFF16:
case 0xFF17:
case 0xFF18:
case 0xFF19:
ch -= 0xFE20;
break;
case 0xFF1A: ch = 0x7A; break;
case 0xFF1B: ch = 0x5E; break;
case 0xFF1C: ch = 0x4C; break;
case 0xFF1D: ch = 0x7E; break;
case 0xFF1E: ch = 0x6E; break;
case 0xFF1F: ch = 0x6F; break;
case 0xFF20: ch = 0x7C; break;
case 0xFF21:
case 0xFF22:
case 0xFF23:
case 0xFF24:
case 0xFF25:
case 0xFF26:
case 0xFF27:
case 0xFF28:
case 0xFF29:
ch -= 0xFE60;
break;
case 0xFF2A:
case 0xFF2B:
case 0xFF2C:
case 0xFF2D:
case 0xFF2E:
case 0xFF2F:
case 0xFF30:
case 0xFF31:
case 0xFF32:
ch -= 0xFE59;
break;
case 0xFF33:
case 0xFF34:
case 0xFF35:
case 0xFF36:
case 0xFF37:
case 0xFF38:
case 0xFF39:
case 0xFF3A:
ch -= 0xFE51;
break;
case 0xFF3B: ch = 0x4A; break;
case 0xFF3C: ch = 0xE0; break;
case 0xFF3D: ch = 0x5A; break;
case 0xFF3E: ch = 0x5F; break;
case 0xFF3F: ch = 0x6D; break;
case 0xFF40: ch = 0x79; break;
case 0xFF41:
case 0xFF42:
case 0xFF43:
case 0xFF44:
case 0xFF45:
case 0xFF46:
case 0xFF47:
case 0xFF48:
case 0xFF49:
ch -= 0xFEC0;
break;
case 0xFF4A:
case 0xFF4B:
case 0xFF4C:
case 0xFF4D:
case 0xFF4E:
case 0xFF4F:
case 0xFF50:
case 0xFF51:
case 0xFF52:
ch -= 0xFEB9;
break;
case 0xFF53:
case 0xFF54:
case 0xFF55:
case 0xFF56:
case 0xFF57:
case 0xFF58:
case 0xFF59:
case 0xFF5A:
ch -= 0xFEB1;
break;
case 0xFF5B: ch = 0xC0; break;
case 0xFF5C: ch = 0xBB; break;
case 0xFF5D: ch = 0xD0; break;
case 0xFF5E: ch = 0xA1; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 4) switch(ch)
{
case 0x000B:
case 0x000C:
case 0x000D:
case 0x000E:
case 0x000F:
case 0x0010:
case 0x0011:
case 0x0012:
case 0x0013:
case 0x0018:
case 0x0019:
case 0x001C:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x00B6:
break;
case 0x0004: ch = 0x37; break;
case 0x0005: ch = 0x2D; break;
case 0x0006: ch = 0x2E; break;
case 0x0007: ch = 0x2F; break;
case 0x0008: ch = 0x16; break;
case 0x0009: ch = 0x05; break;
case 0x000A: ch = 0x25; break;
case 0x0014: ch = 0x3C; break;
case 0x0015: ch = 0x3D; break;
case 0x0016: ch = 0x32; break;
case 0x0017: ch = 0x26; break;
case 0x001A: ch = 0x3F; break;
case 0x001B: ch = 0x27; break;
case 0x0020: ch = 0x40; break;
case 0x0021: ch = 0x4F; break;
case 0x0022: ch = 0x7F; break;
case 0x0023: ch = 0x7B; break;
case 0x0024: ch = 0x5B; break;
case 0x0025: ch = 0x6C; break;
case 0x0026: ch = 0x50; break;
case 0x0027: ch = 0x7D; break;
case 0x0028: ch = 0x4D; break;
case 0x0029: ch = 0x5D; break;
case 0x002A: ch = 0x5C; break;
case 0x002B: ch = 0x4E; break;
case 0x002C: ch = 0x6B; break;
case 0x002D: ch = 0x60; break;
case 0x002E: ch = 0x4B; break;
case 0x002F: ch = 0x61; break;
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
ch += 0x00C0;
break;
case 0x003A: ch = 0x7A; break;
case 0x003B: ch = 0x5E; break;
case 0x003C: ch = 0x4C; break;
case 0x003D: ch = 0x7E; break;
case 0x003E: ch = 0x6E; break;
case 0x003F: ch = 0x6F; break;
case 0x0040: ch = 0x7C; break;
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
ch += 0x0080;
break;
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
ch += 0x0087;
break;
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
ch += 0x008F;
break;
case 0x005B: ch = 0x4A; break;
case 0x005C: ch = 0xE0; break;
case 0x005D: ch = 0x5A; break;
case 0x005E: ch = 0x5F; break;
case 0x005F: ch = 0x6D; break;
case 0x0060: ch = 0x79; break;
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
ch += 0x0020;
break;
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
ch += 0x0027;
break;
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
ch += 0x002F;
break;
case 0x007B: ch = 0xC0; break;
case 0x007C: ch = 0xBB; break;
case 0x007D: ch = 0xD0; break;
case 0x007E: ch = 0xA1; break;
case 0x007F: ch = 0x07; break;
case 0x0080:
case 0x0081:
case 0x0082:
case 0x0083:
case 0x0084:
ch -= 0x0060;
break;
case 0x0085: ch = 0x15; break;
case 0x0086: ch = 0x06; break;
case 0x0087: ch = 0x17; break;
case 0x0088:
case 0x0089:
case 0x008A:
case 0x008B:
case 0x008C:
ch -= 0x0060;
break;
case 0x008D: ch = 0x09; break;
case 0x008E: ch = 0x0A; break;
case 0x008F: ch = 0x1B; break;
case 0x0090: ch = 0x30; break;
case 0x0091: ch = 0x31; break;
case 0x0092: ch = 0x1A; break;
case 0x0093:
case 0x0094:
case 0x0095:
case 0x0096:
ch -= 0x0060;
break;
case 0x0097: ch = 0x08; break;
case 0x0098:
case 0x0099:
case 0x009A:
case 0x009B:
ch -= 0x0060;
break;
case 0x009C: ch = 0x04; break;
case 0x009D: ch = 0x14; break;
case 0x009E: ch = 0x3E; break;
case 0x009F: ch = 0xFF; break;
case 0x00A0: ch = 0x41; break;
case 0x00A1: ch = 0xAA; break;
case 0x00A2: ch = 0xB0; break;
case 0x00A3: ch = 0xB1; break;
case 0x00A4: ch = 0x9F; break;
case 0x00A5: ch = 0xB2; break;
case 0x00A6: ch = 0x6A; break;
case 0x00A7: ch = 0xB5; break;
case 0x00A8: ch = 0xBD; break;
case 0x00A9: ch = 0xB4; break;
case 0x00AA: ch = 0x9A; break;
case 0x00AB: ch = 0x8A; break;
case 0x00AC: ch = 0xBA; break;
case 0x00AD: ch = 0xCA; break;
case 0x00AE: ch = 0xAF; break;
case 0x00AF: ch = 0xBC; break;
case 0x00B0: ch = 0x90; break;
case 0x00B1: ch = 0x8F; break;
case 0x00B2: ch = 0xEA; break;
case 0x00B3: ch = 0xFA; break;
case 0x00B4: ch = 0xBE; break;
case 0x00B5: ch = 0xA0; break;
case 0x00B7: ch = 0xB3; break;
case 0x00B8: ch = 0x9D; break;
case 0x00B9: ch = 0xDA; break;
case 0x00BA: ch = 0x9B; break;
case 0x00BB: ch = 0x8B; break;
case 0x00BC: ch = 0xB7; break;
case 0x00BD: ch = 0xB8; break;
case 0x00BE: ch = 0xB9; break;
case 0x00BF: ch = 0xAB; break;
case 0x00C0: ch = 0x64; break;
case 0x00C1: ch = 0x65; break;
case 0x00C2: ch = 0x62; break;
case 0x00C3: ch = 0x66; break;
case 0x00C4: ch = 0x63; break;
case 0x00C5: ch = 0x67; break;
case 0x00C6: ch = 0x9E; break;
case 0x00C7: ch = 0x68; break;
case 0x00C8: ch = 0x74; break;
case 0x00C9: ch = 0x71; break;
case 0x00CA: ch = 0x72; break;
case 0x00CB: ch = 0x73; break;
case 0x00CC: ch = 0x78; break;
case 0x00CD: ch = 0x75; break;
case 0x00CE: ch = 0x76; break;
case 0x00CF: ch = 0x77; break;
case 0x00D0: ch = 0xAC; break;
case 0x00D1: ch = 0x69; break;
case 0x00D2: ch = 0xED; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEB; break;
case 0x00D5: ch = 0xEF; break;
case 0x00D6: ch = 0xEC; break;
case 0x00D7: ch = 0xBF; break;
case 0x00D8: ch = 0x80; break;
case 0x00D9: ch = 0xFD; break;
case 0x00DA: ch = 0xFE; break;
case 0x00DB: ch = 0xFB; break;
case 0x00DC: ch = 0xFC; break;
case 0x00DD: ch = 0xAD; break;
case 0x00DE: ch = 0xAE; break;
case 0x00DF: ch = 0x59; break;
case 0x00E0: ch = 0x44; break;
case 0x00E1: ch = 0x45; break;
case 0x00E2: ch = 0x42; break;
case 0x00E3: ch = 0x46; break;
case 0x00E4: ch = 0x43; break;
case 0x00E5: ch = 0x47; break;
case 0x00E6: ch = 0x9C; break;
case 0x00E7: ch = 0x48; break;
case 0x00E8: ch = 0x54; break;
case 0x00E9: ch = 0x51; break;
case 0x00EA: ch = 0x52; break;
case 0x00EB: ch = 0x53; break;
case 0x00EC: ch = 0x58; break;
case 0x00ED: ch = 0x55; break;
case 0x00EE: ch = 0x56; break;
case 0x00EF: ch = 0x57; break;
case 0x00F0: ch = 0x8C; break;
case 0x00F1: ch = 0x49; break;
case 0x00F2: ch = 0xCD; break;
case 0x00F3: ch = 0xCE; break;
case 0x00F4: ch = 0xCB; break;
case 0x00F5: ch = 0xCF; break;
case 0x00F6: ch = 0xCC; break;
case 0x00F7: ch = 0xE1; break;
case 0x00F8: ch = 0x70; break;
case 0x00F9: ch = 0xDD; break;
case 0x00FA: ch = 0xDE; break;
case 0x00FB: ch = 0xDB; break;
case 0x00FC: ch = 0xDC; break;
case 0x00FD: ch = 0x8D; break;
case 0x00FE: ch = 0x8E; break;
case 0x00FF: ch = 0xDF; break;
case 0x0110: ch = 0xAC; break;
case 0x203E: ch = 0xBC; break;
case 0xFF01: ch = 0x4F; break;
case 0xFF02: ch = 0x7F; break;
case 0xFF03: ch = 0x7B; break;
case 0xFF04: ch = 0x5B; break;
case 0xFF05: ch = 0x6C; break;
case 0xFF06: ch = 0x50; break;
case 0xFF07: ch = 0x7D; break;
case 0xFF08: ch = 0x4D; break;
case 0xFF09: ch = 0x5D; break;
case 0xFF0A: ch = 0x5C; break;
case 0xFF0B: ch = 0x4E; break;
case 0xFF0C: ch = 0x6B; break;
case 0xFF0D: ch = 0x60; break;
case 0xFF0E: ch = 0x4B; break;
case 0xFF0F: ch = 0x61; break;
case 0xFF10:
case 0xFF11:
case 0xFF12:
case 0xFF13:
case 0xFF14:
case 0xFF15:
case 0xFF16:
case 0xFF17:
case 0xFF18:
case 0xFF19:
ch -= 0xFE20;
break;
case 0xFF1A: ch = 0x7A; break;
case 0xFF1B: ch = 0x5E; break;
case 0xFF1C: ch = 0x4C; break;
case 0xFF1D: ch = 0x7E; break;
case 0xFF1E: ch = 0x6E; break;
case 0xFF1F: ch = 0x6F; break;
case 0xFF20: ch = 0x7C; break;
case 0xFF21:
case 0xFF22:
case 0xFF23:
case 0xFF24:
case 0xFF25:
case 0xFF26:
case 0xFF27:
case 0xFF28:
case 0xFF29:
ch -= 0xFE60;
break;
case 0xFF2A:
case 0xFF2B:
case 0xFF2C:
case 0xFF2D:
case 0xFF2E:
case 0xFF2F:
case 0xFF30:
case 0xFF31:
case 0xFF32:
ch -= 0xFE59;
break;
case 0xFF33:
case 0xFF34:
case 0xFF35:
case 0xFF36:
case 0xFF37:
case 0xFF38:
case 0xFF39:
case 0xFF3A:
ch -= 0xFE51;
break;
case 0xFF3B: ch = 0x4A; break;
case 0xFF3C: ch = 0xE0; break;
case 0xFF3D: ch = 0x5A; break;
case 0xFF3E: ch = 0x5F; break;
case 0xFF3F: ch = 0x6D; break;
case 0xFF40: ch = 0x79; break;
case 0xFF41:
case 0xFF42:
case 0xFF43:
case 0xFF44:
case 0xFF45:
case 0xFF46:
case 0xFF47:
case 0xFF48:
case 0xFF49:
ch -= 0xFEC0;
break;
case 0xFF4A:
case 0xFF4B:
case 0xFF4C:
case 0xFF4D:
case 0xFF4E:
case 0xFF4F:
case 0xFF50:
case 0xFF51:
case 0xFF52:
ch -= 0xFEB9;
break;
case 0xFF53:
case 0xFF54:
case 0xFF55:
case 0xFF56:
case 0xFF57:
case 0xFF58:
case 0xFF59:
case 0xFF5A:
ch -= 0xFEB1;
break;
case 0xFF5B: ch = 0xC0; break;
case 0xFF5C: ch = 0xBB; break;
case 0xFF5D: ch = 0xD0; break;
case 0xFF5E: ch = 0xA1; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP500
public class ENCibm500 : CP500
{
public ENCibm500() : base() {}
}; // class ENCibm500
}; // namespace I18N.Rare
| |
////////////////////////////////////////////////////////////////
// //
// Neoforce Controls //
// //
////////////////////////////////////////////////////////////////
// //
// File: Window.cs //
// //
// Version: 0.7 //
// //
// Date: 11/09/2010 //
// //
// Author: Tom Shane //
// //
////////////////////////////////////////////////////////////////
// //
// Copyright (c) by Tom Shane //
// //
////////////////////////////////////////////////////////////////
#region //// Using /////////////
////////////////////////////////////////////////////////////////////////////
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
////////////////////////////////////////////////////////////////////////////
#endregion
namespace TomShane.Neoforce.Controls
{
#region //// Classes ///////////
////////////////////////////////////////////////////////////////////////////
public class WindowGamePadActions: GamePadActions
{
public GamePadButton Accept = GamePadButton.Start;
public GamePadButton Cancel = GamePadButton.Back;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
/// <include file='Documents/Window.xml' path='Window/Class[@name="Window"]/*' />
public class Window: ModalContainer
{
#region //// Consts ////////////
////////////////////////////////////////////////////////////////////////////
private const string skWindow = "Window";
private const string lrWindow = "Control";
private const string lrCaption = "Caption";
private const string lrFrameTop = "FrameTop";
private const string lrFrameLeft = "FrameLeft";
private const string lrFrameRight = "FrameRight";
private const string lrFrameBottom = "FrameBottom";
private const string lrIcon = "Icon";
private const string skButton = "Window.CloseButton";
private const string lrButton = "Control";
private const string skShadow = "Window.Shadow";
private const string lrShadow = "Control";
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Fields ////////////
////////////////////////////////////////////////////////////////////////////
private Button btnClose;
private bool closeButtonVisible = true;
private bool iconVisible = true;
private Texture2D icon = null;
private bool shadow = true;
private bool captionVisible = true;
private bool borderVisible = true;
private byte oldAlpha = 255;
private byte dragAlpha = 200;
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Events ////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Properties ////////
////////////////////////////////////////////////////////////////////////////
public virtual Texture2D Icon
{
get { return icon; }
set { icon = value; }
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public virtual bool Shadow
{
get { return shadow; }
set { shadow = value; }
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public virtual bool CloseButtonVisible
{
get
{
return closeButtonVisible;
}
set
{
closeButtonVisible = value;
if (btnClose != null) btnClose.Visible = value;
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public virtual bool IconVisible
{
get
{
return iconVisible;
}
set
{
iconVisible = value;
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public virtual bool CaptionVisible
{
get { return captionVisible; }
set
{
captionVisible = value;
AdjustMargins();
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public virtual bool BorderVisible
{
get { return borderVisible; }
set
{
borderVisible = value;
AdjustMargins();
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public virtual byte DragAlpha
{
get { return dragAlpha; }
set { dragAlpha = value; }
}
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Constructors //////
////////////////////////////////////////////////////////////////////////////
public Window(Manager manager): base(manager)
{
CheckLayer(Skin, lrWindow);
CheckLayer(Skin, lrCaption);
CheckLayer(Skin, lrFrameTop);
CheckLayer(Skin, lrFrameLeft);
CheckLayer(Skin, lrFrameRight);
CheckLayer(Skin, lrFrameBottom);
CheckLayer(Manager.Skin.Controls[skButton], lrButton);
CheckLayer(Manager.Skin.Controls[skShadow], lrShadow);
SetDefaultSize(640, 480);
SetMinimumSize(100, 75);
btnClose = new Button(manager);
btnClose.Skin = new SkinControl(Manager.Skin.Controls[skButton]);
btnClose.Init();
btnClose.Detached = true;
btnClose.CanFocus = false;
btnClose.Text = null;
btnClose.Click += new EventHandler(btnClose_Click);
btnClose.SkinChanged += new EventHandler(btnClose_SkinChanged);
AdjustMargins();
AutoScroll = true;
Movable = true;
Resizable = true;
Center();
Add(btnClose, false);
oldAlpha = Alpha;
}
////////////////////////////////////////////////////////////////////////////
#endregion
////////////////////////////////////////////////////////////////////////////
protected override void Dispose(bool disposing)
{
if (disposing)
{
}
base.Dispose(disposing);
}
////////////////////////////////////////////////////////////////////////////
#region //// Methods ///////////
////////////////////////////////////////////////////////////////////////////
public override void Init()
{
base.Init();
SkinLayer l = btnClose.Skin.Layers[lrButton];
btnClose.Width = l.Width - btnClose.Skin.OriginMargins.Horizontal;
btnClose.Height = l.Height - btnClose.Skin.OriginMargins.Vertical;
btnClose.Left = OriginWidth - Skin.OriginMargins.Right - btnClose.Width + l.OffsetX;
btnClose.Top = Skin.OriginMargins.Top + l.OffsetY;
btnClose.Anchor = Anchors.Top | Anchors.Right;
//SkinControl sc = new SkinControl(ClientArea.Skin);
//sc.Layers[0] = Skin.Layers[lrWindow];
//ClientArea.Color = Color.Transparent;
//ClientArea.BackColor = Color.Transparent;
//ClientArea.Skin = sc;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected internal override void InitSkin()
{
base.InitSkin();
Skin = new SkinControl(Manager.Skin.Controls[skWindow]);
AdjustMargins();
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
void btnClose_SkinChanged(object sender, EventArgs e)
{
btnClose.Skin = new SkinControl(Manager.Skin.Controls[skButton]);
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
internal override void Render(Renderer renderer, GameTime gameTime)
{
if (Visible && Shadow)
{
SkinControl c = Manager.Skin.Controls[skShadow];
SkinLayer l = c.Layers[lrShadow];
Color cl = Color.FromNonPremultiplied(l.States.Enabled.Color.R, l.States.Enabled.Color.G, l.States.Enabled.Color.B, Alpha);
renderer.Begin(BlendingMode.Default);
renderer.DrawLayer(l, new Rectangle(Left - c.OriginMargins.Left, Top - c.OriginMargins.Top, Width + c.OriginMargins.Horizontal, Height + c.OriginMargins.Vertical), cl, 0);
renderer.End();
}
base.Render(renderer, gameTime);
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private Rectangle GetIconRect()
{
SkinLayer l1 = Skin.Layers[lrCaption];
SkinLayer l5 = Skin.Layers[lrIcon];
int s = l1.Height - l1.ContentMargins.Vertical;
return new Rectangle(DrawingRect.Left + l1.ContentMargins.Left + l5.OffsetX,
DrawingRect.Top + l1.ContentMargins.Top + l5.OffsetY,
s, s);
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected override void DrawControl(Renderer renderer, Rectangle rect, GameTime gameTime)
{
SkinLayer l1 = captionVisible ? Skin.Layers[lrCaption] : Skin.Layers[lrFrameTop];
SkinLayer l2 = Skin.Layers[lrFrameLeft];
SkinLayer l3 = Skin.Layers[lrFrameRight];
SkinLayer l4 = Skin.Layers[lrFrameBottom];
SkinLayer l5 = Skin.Layers[lrIcon];
LayerStates s1, s2, s3, s4;
SpriteFont f1 = l1.Text.Font.Resource;
Color c1 = l1.Text.Colors.Enabled;
if ((Focused || (Manager.FocusedControl != null && Manager.FocusedControl.Root == this.Root)) && ControlState != ControlState.Disabled)
{
s1 = l1.States.Focused;
s2 = l2.States.Focused;
s3 = l3.States.Focused;
s4 = l4.States.Focused;
c1 = l1.Text.Colors.Focused;
}
else if (ControlState == ControlState.Disabled)
{
s1 = l1.States.Disabled;
s2 = l2.States.Disabled;
s3 = l3.States.Disabled;
s4 = l4.States.Disabled;
c1 = l1.Text.Colors.Disabled;
}
else
{
s1 = l1.States.Enabled;
s2 = l2.States.Enabled;
s3 = l3.States.Enabled;
s4 = l4.States.Enabled;
c1 = l1.Text.Colors.Enabled;
}
renderer.DrawLayer(Skin.Layers[lrWindow], rect, Skin.Layers[lrWindow].States.Enabled.Color, Skin.Layers[lrWindow].States.Enabled.Index);
if (borderVisible)
{
renderer.DrawLayer(l1, new Rectangle(rect.Left, rect.Top, rect.Width, l1.Height), s1.Color, s1.Index);
renderer.DrawLayer(l2, new Rectangle(rect.Left, rect.Top + l1.Height, l2.Width, rect.Height - l1.Height - l4.Height), s2.Color, s2.Index);
renderer.DrawLayer(l3, new Rectangle(rect.Right - l3.Width, rect.Top + l1.Height, l3.Width, rect.Height - l1.Height - l4.Height), s3.Color, s3.Index);
renderer.DrawLayer(l4, new Rectangle(rect.Left, rect.Bottom - l4.Height, rect.Width, l4.Height), s4.Color, s4.Index);
if (iconVisible && (icon != null || l5 != null) && captionVisible)
{
Texture2D i = (icon != null) ? icon : l5.Image.Resource;
renderer.Draw(i, GetIconRect(), Color.White);
}
int icosize = 0;
if (l5 != null && iconVisible && captionVisible)
{
icosize = l1.Height - l1.ContentMargins.Vertical + 4 + l5.OffsetX;
}
int closesize = 0;
if (btnClose.Visible)
{
closesize = btnClose.Width - (btnClose.Skin.Layers[lrButton].OffsetX);
}
Rectangle r = new Rectangle(rect.Left + l1.ContentMargins.Left + icosize,
rect.Top + l1.ContentMargins.Top,
rect.Width - l1.ContentMargins.Horizontal - closesize - icosize,
l1.Height - l1.ContentMargins.Top - l1.ContentMargins.Bottom);
int ox = l1.Text.OffsetX;
int oy = l1.Text.OffsetY;
renderer.DrawString(f1, Text, r, c1, l1.Text.Alignment, ox, oy, true);
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
void btnClose_Click(object sender, EventArgs e)
{
Close(ModalResult = ModalResult.Cancel);
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public virtual void Center()
{
Left = (Manager.ScreenWidth / 2) - (Width / 2);
Top = (Manager.ScreenHeight - Height) / 2;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected override void OnResize(ResizeEventArgs e)
{
SetMovableArea();
base.OnResize(e);
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected override void OnMoveBegin(EventArgs e)
{
base.OnMoveBegin(e);
try
{
oldAlpha = Alpha;
Alpha = dragAlpha;
}
catch
{
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected override void OnMoveEnd(EventArgs e)
{
base.OnMoveEnd(e);
try
{
Alpha = oldAlpha;
}
catch
{
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected override void OnDoubleClick(EventArgs e)
{
base.OnDoubleClick(e);
MouseEventArgs ex = (e is MouseEventArgs) ? (MouseEventArgs) e : new MouseEventArgs();
if (IconVisible && ex.Button == MouseButton.Left)
{
Rectangle r = GetIconRect();
r.Offset(AbsoluteLeft, AbsoluteTop);
if (r.Contains(ex.Position))
{
Close();
}
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected override void AdjustMargins()
{
if (captionVisible && borderVisible)
{
ClientMargins = new Margins(Skin.ClientMargins.Left, Skin.Layers[lrCaption].Height, Skin.ClientMargins.Right, Skin.ClientMargins.Bottom);
}
else if (!captionVisible && borderVisible)
{
ClientMargins = new Margins(Skin.ClientMargins.Left, Skin.ClientMargins.Top, Skin.ClientMargins.Right, Skin.ClientMargins.Bottom);
}
else if (!borderVisible)
{
ClientMargins = new Margins(0, 0, 0, 0);
}
if (btnClose != null)
{
btnClose.Visible = closeButtonVisible && captionVisible && borderVisible;
}
SetMovableArea();
base.AdjustMargins();
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void SetMovableArea()
{
if (captionVisible && borderVisible)
{
MovableArea = new Rectangle(Skin.OriginMargins.Left, Skin.OriginMargins.Top, Width, Skin.Layers[lrCaption].Height - Skin.OriginMargins.Top);
}
else if (!captionVisible)
{
MovableArea = new Rectangle(0, 0, Width, Height);
}
}
////////////////////////////////////////////////////////////////////////////
#endregion
}
////////////////////////////////////////////////////////////////////////////
#endregion
}
| |
// 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;
using System.Data;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
namespace System.Data.Common
{
public abstract class DbDataReader :
IDisposable,
IEnumerable
{
protected DbDataReader() : base()
{
}
abstract public int Depth
{
get;
}
abstract public int FieldCount
{
get;
}
abstract public bool HasRows
{
get;
}
abstract public bool IsClosed
{
get;
}
abstract public int RecordsAffected
{
get;
}
virtual public int VisibleFieldCount
{
get
{
return FieldCount;
}
}
abstract public object this[int ordinal]
{
get;
}
abstract public object this[string name]
{
get;
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
}
}
abstract public string GetDataTypeName(int ordinal);
abstract public IEnumerator GetEnumerator();
abstract public Type GetFieldType(int ordinal);
abstract public string GetName(int ordinal);
abstract public int GetOrdinal(string name);
abstract public bool GetBoolean(int ordinal);
abstract public byte GetByte(int ordinal);
abstract public long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length);
abstract public char GetChar(int ordinal);
abstract public long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length);
public DbDataReader GetData(int ordinal)
{
return GetDbDataReader(ordinal);
}
virtual protected DbDataReader GetDbDataReader(int ordinal)
{
throw ADP.NotSupported();
}
abstract public DateTime GetDateTime(int ordinal);
abstract public Decimal GetDecimal(int ordinal);
abstract public double GetDouble(int ordinal);
abstract public float GetFloat(int ordinal);
abstract public Guid GetGuid(int ordinal);
abstract public Int16 GetInt16(int ordinal);
abstract public Int32 GetInt32(int ordinal);
abstract public Int64 GetInt64(int ordinal);
virtual public Type GetProviderSpecificFieldType(int ordinal)
{
return GetFieldType(ordinal);
}
virtual public Object GetProviderSpecificValue(int ordinal)
{
return GetValue(ordinal);
}
virtual public int GetProviderSpecificValues(object[] values)
{
return GetValues(values);
}
abstract public String GetString(int ordinal);
virtual public Stream GetStream(int ordinal)
{
using (MemoryStream bufferStream = new MemoryStream())
{
long bytesRead = 0;
long bytesReadTotal = 0;
byte[] buffer = new byte[4096];
do
{
bytesRead = GetBytes(ordinal, bytesReadTotal, buffer, 0, buffer.Length);
bufferStream.Write(buffer, 0, (int)bytesRead);
bytesReadTotal += bytesRead;
} while (bytesRead > 0);
return new MemoryStream(bufferStream.ToArray(), false);
}
}
virtual public TextReader GetTextReader(int ordinal)
{
if (IsDBNull(ordinal))
{
return new StringReader(String.Empty);
}
else
{
return new StringReader(GetString(ordinal));
}
}
abstract public Object GetValue(int ordinal);
virtual public T GetFieldValue<T>(int ordinal)
{
return (T)GetValue(ordinal);
}
public Task<T> GetFieldValueAsync<T>(int ordinal)
{
return GetFieldValueAsync<T>(ordinal, CancellationToken.None);
}
virtual public Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
var taskFactory = new TaskFactory();
return taskFactory.FromCancellation<T>(cancellationToken);
}
else
{
try
{
return Task.FromResult<T>(GetFieldValue<T>(ordinal));
}
catch (Exception e)
{
var taskFactory = new TaskFactory();
return taskFactory.FromException<T>(e);
}
}
}
abstract public int GetValues(object[] values);
abstract public bool IsDBNull(int ordinal);
public Task<bool> IsDBNullAsync(int ordinal)
{
return IsDBNullAsync(ordinal, CancellationToken.None);
}
virtual public Task<bool> IsDBNullAsync(int ordinal, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
var taskFactory = new TaskFactory();
return taskFactory.FromCancellation<bool>(cancellationToken);
}
else
{
try
{
return IsDBNull(ordinal) ? ADP.TrueTask : ADP.FalseTask;
}
catch (Exception e)
{
var taskFactory = new TaskFactory();
return taskFactory.FromException<bool>(e);
}
}
}
abstract public bool NextResult();
abstract public bool Read();
public Task<bool> ReadAsync()
{
return ReadAsync(CancellationToken.None);
}
virtual public Task<bool> ReadAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
var taskFactory = new TaskFactory();
return taskFactory.FromCancellation<bool>(cancellationToken);
}
else
{
try
{
return Read() ? ADP.TrueTask : ADP.FalseTask;
}
catch (Exception e)
{
var taskFactory = new TaskFactory();
return taskFactory.FromException<bool>(e);
}
}
}
public Task<bool> NextResultAsync()
{
return NextResultAsync(CancellationToken.None);
}
virtual public Task<bool> NextResultAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
var taskFactory = new TaskFactory();
return taskFactory.FromCancellation<bool>(cancellationToken);
}
else
{
try
{
return NextResult() ? ADP.TrueTask : ADP.FalseTask;
}
catch (Exception e)
{
var taskFactory = new TaskFactory();
return taskFactory.FromException<bool>(e);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using static NeedyComponent;
public class TwitchModule : MonoBehaviour
{
#region Public Fields
public CanvasGroup CanvasGroupMultiDecker { get => _data.canvasGroupMultiDecker; set => _data.canvasGroupMultiDecker = value; }
public CanvasGroup CanvasGroupUnsupported { get => _data.canvasGroupUnsupported; set => _data.canvasGroupUnsupported = value; }
public Text IDTextMultiDecker { get => _data.idTextMultiDecker; set => _data.idTextMultiDecker = value; }
public Text IDTextUnsupported { get => _data.idTextUnsupported; set => _data.idTextUnsupported = value; }
public Image ClaimedUserMultiDecker { get => _data.claimedUserMultiDecker; set => _data.claimedUserMultiDecker = value; }
public Color ClaimedBackgroundColour { get => _data.claimedBackgroundColour; set => _data.claimedBackgroundColour = value; }
public Color SolvedBackgroundColor { get => _data.solvedBackgroundColor; set => _data.solvedBackgroundColor = value; }
public Color MarkedBackgroundColor { get => _data.markedBackgroundColor; set => _data.markedBackgroundColor = value; }
public AudioSource TakeModuleSound { get => _data.takeModuleSound; set => _data.takeModuleSound = value; }
[HideInInspector]
public TwitchBomb Bomb;
[HideInInspector]
public BombComponent BombComponent;
[HideInInspector]
public Vector3 BasePosition = Vector3.zero;
[HideInInspector]
public Vector3 IdealHandlePositionOffset = Vector3.zero;
[HideInInspector]
public bool Claimed => PlayerName != null;
[HideInInspector]
public int BombID;
public bool Solved => BombComponent.IsSolved;
[HideInInspector]
public bool Unsupported;
[HideInInspector]
public List<Tuple<string, double, bool, bool>> ClaimQueue = new List<Tuple<string, double, bool, bool>>();
public string Code { get; set; }
public bool IsKey { get; set; }
public CameraPriority CameraPriority
{
get => _cameraPriority;
set
{
_cameraPriority = value;
TwitchGame.ModuleCameras.TryViewModule(this);
}
}
public DateTime LastUsed; // when the module was last viewed or received a command
private CameraPriority _cameraPriority = CameraPriority.Unviewed;
public void ViewPin(string user, bool pin)
{
if (Solved && !TwitchPlaySettings.data.AnarchyMode) return;
CameraPriority =
pin && (UserAccess.HasAccess(user, AccessLevel.Mod, true) || Solver.ModInfo.CameraPinningAlwaysAllowed || TwitchPlaySettings.data.AnarchyMode)
? CameraPriority.Pinned
: CameraPriority.Viewed;
LastUsed = DateTime.UtcNow;
}
public ComponentSolver Solver { get; private set; } = null;
public bool IsMod => BombComponent is ModBombComponent || BombComponent is ModNeedyComponent;
public static bool ClaimsEnabled = true;
private string _headerText;
public string HeaderText
{
get => _headerText ?? (BombComponent != null ? BombComponent.GetModuleDisplayName() ?? string.Empty : string.Empty);
set => _headerText = value;
}
public IEnumerator TakeInProgress;
public static List<string> ClaimedList = new List<string>();
#endregion
#region Private Fields
public Color unclaimedBackgroundColor = new Color(0, 0, 0);
private TwitchModuleData _data;
private bool _claimCooldown = true;
private bool _statusLightLeft;
private bool _statusLightDown;
private Vector3 _originalIDPosition = Vector3.zero;
private bool _anarchyMode;
private readonly Dictionary<Transform, int> _originalLayers = new Dictionary<Transform, int>();
private int? _currentLayer;
#endregion
#region Private Statics
private static readonly List<TwitchModule> UnsupportedComponents = new List<TwitchModule>();
#endregion
#region Unity Lifecycle
private void Update()
{
if (_anarchyMode != TwitchPlaySettings.data.AnarchyMode)
{
_anarchyMode = TwitchPlaySettings.data.AnarchyMode;
if (_anarchyMode)
{
CanvasGroupMultiDecker.alpha = Solved ? 0.5f : 1.0f;
SetBannerColor(unclaimedBackgroundColor);
}
else
{
CanvasGroupMultiDecker.alpha = Solved ? 0.0f : 1.0f;
SetBannerColor(Claimed && !Solved ? ClaimedBackgroundColour : unclaimedBackgroundColor);
}
}
if (_originalIDPosition == Vector3.zero) return;
if (Solver.ModInfo.statusLightLeft != _statusLightLeft || Solver.ModInfo.statusLightDown != _statusLightDown)
{
Vector3 pos = _originalIDPosition;
CanvasGroupMultiDecker.transform.localPosition = new Vector3(Solver.ModInfo.statusLightLeft ? -pos.x : pos.x, pos.y, Solver.ModInfo.statusLightDown ? -pos.z : pos.z);
_statusLightLeft = Solver.ModInfo.statusLightLeft;
_statusLightDown = Solver.ModInfo.statusLightDown;
}
if (Solver.ModInfo.ShouldSerializeunclaimedColor() && unclaimedBackgroundColor != Solver.ModInfo.unclaimedColor)
{
unclaimedBackgroundColor = Solver.ModInfo.unclaimedColor;
if (!Claimed || Solved) SetBannerColor(unclaimedBackgroundColor);
}
if (!Solver.ModInfo.ShouldSerializeunclaimedColor() && unclaimedBackgroundColor != TwitchPlaySettings.data.UnclaimedColor && !(TwitchPlaySettings.data.ShowModuleType || TwitchPlaySettings.data.ShowModuleDifficulty))
{
unclaimedBackgroundColor = TwitchPlaySettings.data.UnclaimedColor;
if (!Claimed || Solved) SetBannerColor(unclaimedBackgroundColor);
}
}
private void Awake() => _data = GetComponent<TwitchModuleData>();
private void Start()
{
_anarchyMode = TwitchPlaySettings.data.AnarchyMode;
IDTextMultiDecker.text = Code;
CanvasGroupMultiDecker.alpha = 1.0f;
unclaimedBackgroundColor = TwitchPlaySettings.data.UnclaimedColor;
try
{
Solver = ComponentSolverFactory.CreateSolver(this);
if (Solver != null)
{
if (Solver.ModInfo.ShouldSerializeunclaimedColor()) unclaimedBackgroundColor = Solver.ModInfo.unclaimedColor;
else if (TwitchPlaySettings.data.ShowModuleType || TwitchPlaySettings.data.ShowModuleDifficulty)
{
float difficulty = (float) Solver.ModInfo.moduleScore / ComponentSolverFactory.GetModuleInformation().Max(modInfo => modInfo.moduleScore);
unclaimedBackgroundColor = Color.HSVToRGB(
TwitchPlaySettings.data.ShowModuleType ? BombComponent.ComponentType.ToString().EndsWith("Mod") ? 0.6f : 0.3f : 0.725f,
1,
TwitchPlaySettings.data.ShowModuleDifficulty ? Mathf.Lerp(0.95f, 0.30f, difficulty) : 0.637f
);
}
Solver.Code = Code;
Vector3 pos = CanvasGroupMultiDecker.transform.localPosition;
// This sets the Y position of ID tag to be right above the status light forfor modules where the status light has been moved.
// Which is done by getting the status light's position in world space, converting it to the tag's local space, taking the Y and adding 0.03514.
StatusLightParent statusLightParent = BombComponent.GetComponentInChildren<StatusLightParent>();
if (statusLightParent != null)
pos.y = CanvasGroupMultiDecker.transform.parent.InverseTransformPoint(statusLightParent.transform.position).y + 0.03514f;
_originalIDPosition = pos;
CanvasGroupMultiDecker.transform.localPosition = new Vector3(Solver.ModInfo.statusLightLeft ? -pos.x : pos.x, pos.y, Solver.ModInfo.statusLightDown ? -pos.z : pos.z);
_statusLightLeft = Solver.ModInfo.statusLightLeft;
_statusLightDown = Solver.ModInfo.statusLightDown;
RectTransform rectTransform = ClaimedUserMultiDecker.rectTransform;
rectTransform.anchorMax = rectTransform.anchorMin = new Vector2(Solver.ModInfo.statusLightLeft ? 1 : 0, Solver.ModInfo.statusLightDown ? 0 : 1);
rectTransform.pivot = new Vector2(Solver.ModInfo.statusLightLeft ? 0 : 1, Solver.ModInfo.statusLightDown ? 0 : 1);
CanvasGroupUnsupported.gameObject.SetActive(Solver.UnsupportedModule);
IDTextUnsupported.text = BombComponent is ModBombComponent
? $"To solve this\nmodule, use\n!{Code} solve"
: $"To disarm this\nneedy, use\n!{Code} solve";
if (Solver.UnsupportedModule)
UnsupportedComponents.Add(this);
StartCoroutine(AutoAssignModule());
if (BombComponent.GetComponent<NeedyComponent>() != null) StartCoroutine(TrackNeedyModule());
}
}
catch (Exception e)
{
DebugHelper.LogException(e);
CanvasGroupMultiDecker.alpha = 0.0f;
UnsupportedComponents.Add(this);
Solver = null;
CanvasGroupUnsupported.gameObject.SetActive(true);
IDTextUnsupported.gameObject.SetActive(false);
if (TwitchPlaySettings.data.EnableTwitchPlaysMode && !TwitchPlaySettings.data.EnableInteractiveMode)
{
DebugHelper.Log("An unimplemented module was added to a bomb, solving module.");
}
if (BombComponent != null)
{
if (BombComponent.GetComponent<KMBombModule>() != null)
{
KMBombModule module = BombComponent.GetComponent<KMBombModule>();
module.OnPass += delegate
{
TwitchGame.ModuleCameras?.UpdateSolves();
OnPass(null);
TwitchGame.ModuleCameras?.UnviewModule(this);
return false;
};
module.OnStrike += delegate
{
TwitchGame.ModuleCameras?.UpdateStrikes();
return false;
};
}
else if (BombComponent.GetComponent<KMNeedyModule>() != null)
{
BombComponent.GetComponent<KMNeedyModule>().OnStrike += delegate
{
TwitchGame.ModuleCameras?.UpdateStrikes();
return false;
};
}
}
}
SetBannerColor(unclaimedBackgroundColor);
}
public static void DeactivateNeedyModule(TwitchModule handle)
{
IRCConnection.SendMessage(TwitchPlaySettings.data.UnsupportedNeedyWarning);
KMNeedyModule needyModule = handle.BombComponent.GetComponent<KMNeedyModule>();
needyModule.OnNeedyActivation = () => { needyModule.StopAllCoroutines(); needyModule.gameObject.SetActive(false); needyModule.HandlePass(); needyModule.gameObject.SetActive(true); };
needyModule.OnNeedyDeactivation = () => { needyModule.StopAllCoroutines(); needyModule.gameObject.SetActive(false); needyModule.HandlePass(); needyModule.gameObject.SetActive(true); };
needyModule.OnTimerExpired = () => { needyModule.StopAllCoroutines(); needyModule.gameObject.SetActive(false); needyModule.HandlePass(); needyModule.gameObject.SetActive(true); };
needyModule.WarnAtFiveSeconds = false;
}
public class NeedyStats
{
public int Solves;
public float ActiveTime;
}
public Dictionary<string, NeedyStats> PlayerNeedyStats = new Dictionary<string, NeedyStats>();
public IEnumerator TrackNeedyModule()
{
NeedyComponent needyModule = BombComponent.GetComponent<NeedyComponent>();
NeedyStateEnum lastState = needyModule.State;
float lastTime = Time.time;
while (true)
{
if (Claimed)
{
switch (needyModule.State)
{
case NeedyStateEnum.BombComplete:
case NeedyStateEnum.Terminated:
yield break;
case NeedyStateEnum.Cooldown when lastState == NeedyStateEnum.Running:
if (!PlayerNeedyStats.ContainsKey(PlayerName))
PlayerNeedyStats[PlayerName] = new NeedyStats();
PlayerNeedyStats[PlayerName].Solves++;
break;
case NeedyStateEnum.Running:
if (!PlayerNeedyStats.ContainsKey(PlayerName))
PlayerNeedyStats[PlayerName] = new NeedyStats();
PlayerNeedyStats[PlayerName].ActiveTime += Time.time - lastTime;
break;
}
}
lastState = needyModule.State;
lastTime = Time.time;
yield return new WaitForSeconds(0.1f);
}
}
public static bool UnsupportedModulesPresent() => UnsupportedComponents.Any(x => x.Solver == null || !x.Solved);
public static bool SolveUnsupportedModules(bool bombStartup = false)
{
List<TwitchModule> componentsToRemove = bombStartup
? UnsupportedComponents.Where(x => x.Solver == null).ToList()
: UnsupportedComponents.Where(x => x.Solver == null || !x.Solved).ToList();
if (componentsToRemove.Count == 0) return false;
foreach (TwitchModule handle in componentsToRemove)
{
if (handle.BombComponent.GetComponent<KMNeedyModule>() != null)
{
DeactivateNeedyModule(handle);
}
handle.SolveSilently();
}
// Forget Me Not and Forget Everything become unsolvable if more than one module is solved at once.
if (componentsToRemove.Count > 1)
TwitchGame.Instance.RemoveSolveBasedModules();
UnsupportedComponents.Clear();
return true;
}
public void SolveSilently() => Solver.SolveSilently();
public static void ClearUnsupportedModules() => UnsupportedComponents.Clear();
public void OnPass(string userNickname)
{
CanvasGroupMultiDecker.alpha = TwitchPlaySettings.data.AnarchyMode ? 0.5f : 0.0f;
if (PlayerName == null)
{
PlayerName = userNickname;
CanClaimNow(userNickname, true, true);
}
if (TakeInProgress != null)
{
StopCoroutine(TakeInProgress);
TakeInProgress = null;
}
if (PlayerName == null) return;
}
private void OnDestroy() => StopAllCoroutines();
#endregion
#region Public Methods
public IEnumerator TakeModule()
{
if (TakeModuleSound != null)
{
TakeModuleSound.time = 0.0f;
TakeModuleSound.Play();
}
yield return new WaitForSecondsRealtime(60.0f);
SetBannerColor(unclaimedBackgroundColor);
if (PlayerName != null)
{
IRCConnection.SendMessageFormat(TwitchPlaySettings.data.ModuleAbandoned, Code, PlayerName, HeaderText);
PlayerName = null;
TakeInProgress = null;
}
}
public IEnumerator EndClaimCooldown()
{
if (TwitchPlaySettings.data.InstantModuleClaimCooldown > 0)
{
yield return new WaitForSeconds(TwitchPlaySettings.data.InstantModuleClaimCooldown);
}
_claimCooldown = false;
}
public Tuple<bool, double> CanClaimNow(string userNickName, bool updatePreviousClaim, bool force = false)
{
if (TwitchPlaySettings.data.AnarchyMode) return new Tuple<bool, double>(false, DateTime.Now.TotalSeconds());
if (string.IsNullOrEmpty(userNickName)) return new Tuple<bool, double>(false, DateTime.Now.TotalSeconds());
if (TwitchGame.Instance.LastClaimedModule == null)
{
TwitchGame.Instance.LastClaimedModule = new Dictionary<string, Dictionary<string, double>>();
}
if (!TwitchGame.Instance.LastClaimedModule.TryGetValue(Solver.ModInfo.moduleID, out Dictionary<string, double> value) || value == null)
{
value = new Dictionary<string, double>();
TwitchGame.Instance.LastClaimedModule[Solver.ModInfo.moduleID] = value;
}
if (_claimCooldown && !force && value.TryGetValue(userNickName, out double seconds) &&
(DateTime.Now.TotalSeconds() - seconds) < TwitchPlaySettings.data.InstantModuleClaimCooldownExpiry)
{
return new Tuple<bool, double>(false, seconds + TwitchPlaySettings.data.InstantModuleClaimCooldownExpiry);
}
if (updatePreviousClaim || force)
{
value[userNickName] = DateTime.Now.TotalSeconds();
}
return new Tuple<bool, double>(true, DateTime.Now.TotalSeconds());
}
public void AddToClaimQueue(string userNickname, bool viewRequested = false, bool viewPinRequested = false)
{
double seconds = CanClaimNow(userNickname, false).Second;
if (ClaimQueue.Any(x => x.First.Equals(userNickname, StringComparison.InvariantCultureIgnoreCase))) return;
for (int i = 0; i < ClaimQueue.Count; i++)
{
if (ClaimQueue[i].Second < seconds) continue;
ClaimQueue.Insert(i, new Tuple<string, double, bool, bool>(userNickname, seconds, viewRequested, viewPinRequested));
return;
}
ClaimQueue.Add(new Tuple<string, double, bool, bool>(userNickname, seconds, viewRequested, viewPinRequested));
}
public void RemoveFromClaimQueue(string userNickname) => ClaimQueue.RemoveAll(x => x.First.Equals(userNickname, StringComparison.InvariantCultureIgnoreCase));
public IEnumerator AutoAssignModule()
{
StartCoroutine(EndClaimCooldown());
while (!Solved && !Solver.AttemptedForcedSolve)
{
yield return new WaitForSeconds(0.1f);
if (PlayerName != null || ClaimQueue.Count == 0) continue;
for (int i = 0; i < ClaimQueue.Count; i++)
{
Tuple<bool, string> claim = ClaimModule(ClaimQueue[i].First, ClaimQueue[i].Third, ClaimQueue[i].Fourth);
if (!claim.First) continue;
IRCConnection.SendMessage(claim.Second);
if (ClaimQueue[i].Third)
ViewPin(user: ClaimQueue[i].First, pin: ClaimQueue[i].Fourth);
ClaimQueue.RemoveAt(i);
break;
}
}
}
public Tuple<bool, string> ClaimModule(string userNickName, bool viewRequested = false, bool viewPinRequested = false)
{
if (Solver.AttemptedForcedSolve)
{
return new Tuple<bool, string>(false, string.Format("Sorry @{1}, module ID {0} ({2}) is being solved automatically.", Code, userNickName, HeaderText));
}
if (TwitchPlaySettings.data.AnarchyMode)
{
return new Tuple<bool, string>(false, $"Sorry {userNickName}, claiming modules is not allowed in anarchy mode.");
}
if (!ClaimsEnabled && !UserAccess.HasAccess(userNickName, AccessLevel.Admin, true))
{
return new Tuple<bool, string>(false, $"Sorry {userNickName}, claims have been disabled.");
}
if (PlayerName != null)
{
if (!PlayerName.Equals(userNickName))
AddToClaimQueue(userNickName, viewRequested, viewPinRequested);
return new Tuple<bool, string>(false, string.Format(TwitchPlaySettings.data.AlreadyClaimed, Code, PlayerName, userNickName, HeaderText));
}
if (TwitchGame.Instance.Modules.Count(md => md.PlayerName != null && md.PlayerName.EqualsIgnoreCase(userNickName) && !md.Solved) >= TwitchPlaySettings.data.ModuleClaimLimit && !Solved && (!UserAccess.HasAccess(userNickName, AccessLevel.SuperUser, true) || !TwitchPlaySettings.data.SuperStreamerIgnoreClaimLimit))
{
AddToClaimQueue(userNickName, viewRequested, viewPinRequested);
return new Tuple<bool, string>(false, string.Format(TwitchPlaySettings.data.TooManyClaimed, userNickName, TwitchPlaySettings.data.ModuleClaimLimit));
}
else
{
Tuple<bool, double> claim = CanClaimNow(userNickName, true);
if (!claim.First)
{
AddToClaimQueue(userNickName, viewRequested, viewPinRequested);
return new Tuple<bool, string>(false, string.Format(TwitchPlaySettings.data.ClaimCooldown, Code, TwitchPlaySettings.data.InstantModuleClaimCooldown, userNickName, HeaderText));
}
SetBannerColor(ClaimedBackgroundColour);
PlayerName = userNickName;
if (CameraPriority < CameraPriority.Claimed)
CameraPriority = CameraPriority.Claimed;
return new Tuple<bool, string>(true, string.Format(TwitchPlaySettings.data.ModuleClaimed, Code, PlayerName, HeaderText));
}
}
public Tuple<bool, string> UnclaimModule(string userNickName)
{
if (Solved)
return new Tuple<bool, string>(false, string.Format(TwitchPlaySettings.data.AlreadySolved, Code, PlayerName, userNickName, BombComponent.GetModuleDisplayName()));
if (PlayerName == null)
{
bool wasQueued = ClaimQueue.Any(x => x.First == userNickName);
if (wasQueued) RemoveFromClaimQueue(userNickName);
return new Tuple<bool, string>(false, !wasQueued ? string.Format(TwitchPlaySettings.data.ModuleNotClaimed, userNickName, Code, HeaderText) : null);
}
RemoveFromClaimQueue(userNickName);
if (PlayerName.Equals(userNickName, StringComparison.InvariantCultureIgnoreCase) || UserAccess.HasAccess(userNickName, AccessLevel.Mod, true))
{
RemoveFromClaimQueue(PlayerName);
if (TakeInProgress != null)
{
StopCoroutine(TakeInProgress);
TakeInProgress = null;
}
SetBannerColor(unclaimedBackgroundColor);
string messageOut = string.Format(TwitchPlaySettings.data.ModuleUnclaimed, Code, PlayerName, HeaderText);
PlayerName = null;
if (CameraPriority > CameraPriority.Interacted)
CameraPriority = CameraPriority.Interacted;
return new Tuple<bool, string>(true, messageOut);
}
else
{
return new Tuple<bool, string>(false, string.Format(TwitchPlaySettings.data.AlreadyClaimed, Code, PlayerName, userNickName, HeaderText));
}
}
public void CommandError(string userNickName, string message) => IRCConnection.SendMessageFormat(TwitchPlaySettings.data.CommandError, userNickName, Code, HeaderText, message);
public void CommandInvalid(string userNickName) => IRCConnection.SendMessageFormat(TwitchPlaySettings.data.InvalidCommand, userNickName, Code, HeaderText);
public void UpdateLayerData()
{
foreach (var trans in BombComponent.gameObject.GetComponentsInChildren<Transform>(true))
{
if (_originalLayers.ContainsKey(trans))
continue;
_originalLayers.Add(trans, trans.gameObject.layer);
try
{
if (_currentLayer != null)
trans.gameObject.layer = _currentLayer.Value;
}
catch
{
//continue;
}
}
foreach (var trans in gameObject.GetComponentsInChildren<Transform>(true))
{
if (_originalLayers.ContainsKey(trans))
continue;
_originalLayers.Add(trans, trans.gameObject.layer);
try
{
if (_currentLayer != null)
trans.gameObject.layer = _currentLayer.Value;
}
catch
{
//continue;
}
}
}
public void SetRenderLayer(int? layer)
{
_currentLayer = layer;
foreach (var kvp in _originalLayers)
{
try
{
var setToLayer = _currentLayer ?? kvp.Value;
if (kvp.Key.gameObject.layer != setToLayer)
kvp.Key.gameObject.layer = setToLayer;
}
catch
{
//continue;
}
}
Light[] lights = BombComponent.GetComponentsInChildren<Light>(true);
if (lights == null)
return;
foreach (var light in lights)
{
light.enabled = !light.enabled;
light.enabled = !light.enabled;
}
}
#endregion
#region Private Methods
public void SetBannerColor(Color color)
{
CanvasGroupMultiDecker.GetComponent<Image>().color = color;
ClaimedUserMultiDecker.color = color;
}
#endregion
#region Properties
private string _playerName;
public string PlayerName
{
set
{
_playerName = value;
Image claimedDisplay = ClaimedUserMultiDecker;
if (value != null) claimedDisplay.transform.Find("Username").GetComponent<Text>().text = value;
claimedDisplay.gameObject.SetActive(value != null);
}
get => _playerName;
}
public Selectable Selectable => BombComponent.GetComponent<Selectable>();
public float FocusDistance => Selectable.GetFocusDistance();
public bool FrontFace
{
get
{
Vector3 componentUp = transform.up;
Vector3 bombUp = Bomb.Bomb.transform.up;
float angleBetween = Vector3.Angle(componentUp, bombUp);
return angleBetween < 90.0f;
}
}
#endregion
}
| |
using RootSystem = System;
using System.Linq;
using System.Collections.Generic;
namespace Microsoft.Kinect.Face
{
//
// Microsoft.Kinect.Face.FaceFrame
//
public sealed partial class FaceFrame : RootSystem.IDisposable, Helper.INativeWrapper
{
internal RootSystem.IntPtr _pNative;
RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } }
// Constructors and Finalizers
internal FaceFrame(RootSystem.IntPtr pNative)
{
_pNative = pNative;
Microsoft_Kinect_Face_FaceFrame_AddRefObject(ref _pNative);
}
~FaceFrame()
{
Dispose(false);
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_Face_FaceFrame_ReleaseObject(ref RootSystem.IntPtr pNative);
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_Face_FaceFrame_AddRefObject(ref RootSystem.IntPtr pNative);
private void Dispose(bool disposing)
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
__EventCleanup();
Helper.NativeObjectCache.RemoveObject<FaceFrame>(_pNative);
if (disposing)
{
Microsoft_Kinect_Face_FaceFrame_Dispose(_pNative);
}
Microsoft_Kinect_Face_FaceFrame_ReleaseObject(ref _pNative);
_pNative = RootSystem.IntPtr.Zero;
}
// Public Properties
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern RootSystem.IntPtr Microsoft_Kinect_Face_FaceFrame_get_BodyFrameReference(RootSystem.IntPtr pNative);
public Windows.Kinect.BodyFrameReference BodyFrameReference
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("FaceFrame");
}
RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_FaceFrame_get_BodyFrameReference(_pNative);
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.BodyFrameReference>(objectPointer, n => new Windows.Kinect.BodyFrameReference(n));
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern RootSystem.IntPtr Microsoft_Kinect_Face_FaceFrame_get_ColorFrameReference(RootSystem.IntPtr pNative);
public Windows.Kinect.ColorFrameReference ColorFrameReference
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("FaceFrame");
}
RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_FaceFrame_get_ColorFrameReference(_pNative);
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.ColorFrameReference>(objectPointer, n => new Windows.Kinect.ColorFrameReference(n));
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern RootSystem.IntPtr Microsoft_Kinect_Face_FaceFrame_get_DepthFrameReference(RootSystem.IntPtr pNative);
public Windows.Kinect.DepthFrameReference DepthFrameReference
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("FaceFrame");
}
RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_FaceFrame_get_DepthFrameReference(_pNative);
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.DepthFrameReference>(objectPointer, n => new Windows.Kinect.DepthFrameReference(n));
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern RootSystem.IntPtr Microsoft_Kinect_Face_FaceFrame_get_FaceFrameResult(RootSystem.IntPtr pNative);
public Microsoft.Kinect.Face.FaceFrameResult FaceFrameResult
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("FaceFrame");
}
RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_FaceFrame_get_FaceFrameResult(_pNative);
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Microsoft.Kinect.Face.FaceFrameResult>(objectPointer, n => new Microsoft.Kinect.Face.FaceFrameResult(n));
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern RootSystem.IntPtr Microsoft_Kinect_Face_FaceFrame_get_FaceFrameSource(RootSystem.IntPtr pNative);
public Microsoft.Kinect.Face.FaceFrameSource FaceFrameSource
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("FaceFrame");
}
RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_FaceFrame_get_FaceFrameSource(_pNative);
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Microsoft.Kinect.Face.FaceFrameSource>(objectPointer, n => new Microsoft.Kinect.Face.FaceFrameSource(n));
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern RootSystem.IntPtr Microsoft_Kinect_Face_FaceFrame_get_InfraredFrameReference(RootSystem.IntPtr pNative);
public Windows.Kinect.InfraredFrameReference InfraredFrameReference
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("FaceFrame");
}
RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_FaceFrame_get_InfraredFrameReference(_pNative);
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.InfraredFrameReference>(objectPointer, n => new Windows.Kinect.InfraredFrameReference(n));
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern bool Microsoft_Kinect_Face_FaceFrame_get_IsTrackingIdValid(RootSystem.IntPtr pNative);
public bool IsTrackingIdValid
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("FaceFrame");
}
return Microsoft_Kinect_Face_FaceFrame_get_IsTrackingIdValid(_pNative);
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern long Microsoft_Kinect_Face_FaceFrame_get_RelativeTime(RootSystem.IntPtr pNative);
public RootSystem.TimeSpan RelativeTime
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("FaceFrame");
}
return RootSystem.TimeSpan.FromMilliseconds(Microsoft_Kinect_Face_FaceFrame_get_RelativeTime(_pNative));
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern ulong Microsoft_Kinect_Face_FaceFrame_get_TrackingId(RootSystem.IntPtr pNative);
public ulong TrackingId
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("FaceFrame");
}
return Microsoft_Kinect_Face_FaceFrame_get_TrackingId(_pNative);
}
}
// Public Methods
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_Face_FaceFrame_Dispose(RootSystem.IntPtr pNative);
public void Dispose()
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Dispose(true);
RootSystem.GC.SuppressFinalize(this);
}
private void __EventCleanup()
{
}
}
}
| |
//
// This file was generated by the BinaryNotes compiler.
// See http://bnotes.sourceforge.net
// Any modifications to this file will be lost upon recompilation of the source ASN.1.
//
using System.Collections.Generic;
using GSF.ASN1;
using GSF.ASN1.Attributes;
using GSF.ASN1.Coders;
using GSF.ASN1.Types;
namespace GSF.MMS.Model
{
[ASN1PreparedElement]
[ASN1Sequence(Name = "Semaphore_instance", IsSet = false)]
public class Semaphore_instance : IASN1PreparedElement
{
private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(Semaphore_instance));
private DefinitionChoiceType definition_;
private Identifier name_;
[ASN1Element(Name = "name", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public Identifier Name
{
get
{
return name_;
}
set
{
name_ = value;
}
}
[ASN1Element(Name = "definition", IsOptional = false, HasTag = false, HasDefaultValue = false)]
public DefinitionChoiceType Definition
{
get
{
return definition_;
}
set
{
definition_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
[ASN1PreparedElement]
[ASN1Choice(Name = "definition")]
public class DefinitionChoiceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DefinitionChoiceType));
private DetailsSequenceType details_;
private bool details_selected;
private ObjectIdentifier reference_;
private bool reference_selected;
[ASN1ObjectIdentifier(Name = "")]
[ASN1Element(Name = "reference", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public ObjectIdentifier Reference
{
get
{
return reference_;
}
set
{
selectReference(value);
}
}
[ASN1Element(Name = "details", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)]
public DetailsSequenceType Details
{
get
{
return details_;
}
set
{
selectDetails(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isReferenceSelected()
{
return reference_selected;
}
public void selectReference(ObjectIdentifier val)
{
reference_ = val;
reference_selected = true;
details_selected = false;
}
public bool isDetailsSelected()
{
return details_selected;
}
public void selectDetails(DetailsSequenceType val)
{
details_ = val;
details_selected = true;
reference_selected = false;
}
[ASN1PreparedElement]
[ASN1Sequence(Name = "details", IsSet = false)]
public class DetailsSequenceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DetailsSequenceType));
private Access_Control_List_instance accessControl_;
private ClassEnumType class__;
private Event_Condition_instance eventCondition_;
private ICollection<string> namedTokens_;
private bool namedTokens_present;
private long numberOfTokens_;
private bool numberOfTokens_present;
[ASN1Element(Name = "accessControl", IsOptional = false, HasTag = true, Tag = 3, HasDefaultValue = false)]
public Access_Control_List_instance AccessControl
{
get
{
return accessControl_;
}
set
{
accessControl_ = value;
}
}
[ASN1Element(Name = "class", IsOptional = false, HasTag = true, Tag = 4, HasDefaultValue = false)]
public ClassEnumType Class_
{
get
{
return class__;
}
set
{
class__ = value;
}
}
[ASN1Integer(Name = "")]
[ASN1Element(Name = "numberOfTokens", IsOptional = true, HasTag = true, Tag = 5, HasDefaultValue = false)]
public long NumberOfTokens
{
get
{
return numberOfTokens_;
}
set
{
numberOfTokens_ = value;
numberOfTokens_present = true;
}
}
[ASN1String(Name = "",
StringType = UniversalTags.VisibleString, IsUCS = false)]
[ASN1SequenceOf(Name = "namedTokens", IsSetOf = false)]
[ASN1Element(Name = "namedTokens", IsOptional = true, HasTag = true, Tag = 6, HasDefaultValue = false)]
public ICollection<string> NamedTokens
{
get
{
return namedTokens_;
}
set
{
namedTokens_ = value;
namedTokens_present = true;
}
}
[ASN1Element(Name = "eventCondition", IsOptional = false, HasTag = true, Tag = 7, HasDefaultValue = false)]
public Event_Condition_instance EventCondition
{
get
{
return eventCondition_;
}
set
{
eventCondition_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isNumberOfTokensPresent()
{
return numberOfTokens_present;
}
public bool isNamedTokensPresent()
{
return namedTokens_present;
}
[ASN1PreparedElement]
[ASN1Enum(Name = "ClassEnumType")]
public class ClassEnumType : IASN1PreparedElement
{
public enum EnumType
{
[ASN1EnumItem(Name = "token", HasTag = true, Tag = 0)]
token,
[ASN1EnumItem(Name = "pool", HasTag = true, Tag = 1)]
pool,
}
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(ClassEnumType));
private EnumType val;
public EnumType Value
{
get
{
return val;
}
set
{
val = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace LearningAzure.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//
// System.Web.SessionState.HttpSessionState
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Web;
namespace System.Web.SessionState {
public sealed class HttpSessionState : ICollection, IEnumerable
{
private string _id;
private SessionDictionary _dict;
private HttpStaticObjectsCollection _staticObjects;
private int _timeout;
private bool _newSession;
private bool _isCookieless;
private SessionStateMode _mode;
private bool _isReadonly;
internal bool _abandoned;
internal HttpSessionState (string id,
SessionDictionary dict,
HttpStaticObjectsCollection staticObjects,
int timeout,
bool newSession,
bool isCookieless,
SessionStateMode mode,
bool isReadonly)
{
_id = id;
_dict = dict;
_staticObjects = staticObjects.Clone ();
_timeout = timeout;
_newSession = newSession;
_isCookieless = isCookieless;
_mode = mode;
_isReadonly = isReadonly;
}
internal HttpSessionState Clone ()
{
return new HttpSessionState (_id, _dict.Clone (), _staticObjects, _timeout, _newSession,
_isCookieless, _mode, _isReadonly);
}
public int CodePage {
get {
HttpContext current = HttpContext.Current;
if (current == null)
return Encoding.Default.CodePage;
return current.Response.ContentEncoding.CodePage;
}
set {
HttpContext current = HttpContext.Current;
if (current != null)
current.Response.ContentEncoding = Encoding.GetEncoding (value);
}
}
public HttpSessionState Contents {
get { return this; }
}
public int Count {
get { return _dict.Count; }
}
internal bool IsAbandoned {
get { return _abandoned; }
}
public bool IsCookieless {
get { return _isCookieless; }
}
public bool IsNewSession {
get { return _newSession; }
}
public bool IsReadOnly {
get { return _isReadonly; }
}
public bool IsSynchronized {
get { return false; }
}
public object this [string key] {
get { return _dict [key]; }
set { _dict [key] = value; }
}
public object this [int index] {
get { return _dict [index]; }
set { _dict [index] = value; }
}
public NameObjectCollectionBase.KeysCollection Keys {
get { return _dict.Keys; }
}
public int LCID {
get { return Thread.CurrentThread.CurrentCulture.LCID; }
set { Thread.CurrentThread.CurrentCulture = new CultureInfo(value); }
}
public SessionStateMode Mode {
get { return _mode; }
}
public string SessionID {
get { return _id; }
}
public HttpStaticObjectsCollection StaticObjects {
get { return _staticObjects; }
}
public object SyncRoot {
get { return this; }
}
public int Timeout {
get { return _timeout; }
set {
if (value < 1)
throw new ArgumentException ("The argument to SetTimeout must be greater than 0.");
_timeout = value;
}
}
internal SessionDictionary SessionDictionary {
get { return _dict; }
}
internal void SetNewSession (bool value)
{
_newSession = value;
}
public void Abandon ()
{
_abandoned = true;
}
public void Add (string name, object value)
{
_dict [name] = value;
}
public void Clear ()
{
if (_dict != null)
_dict.Clear ();
}
public void CopyTo (Array array, int index)
{
NameObjectCollectionBase.KeysCollection all = Keys;
for (int i = 0; i < all.Count; i++)
array.SetValue (all.Get(i), i + index);
}
public IEnumerator GetEnumerator ()
{
return _dict.GetEnumerator ();
}
public void Remove (string name)
{
_dict.Remove (name);
}
public void RemoveAll ()
{
_dict.Clear ();
}
public void RemoveAt (int index)
{
_dict.RemoveAt (index);
}
}
}
| |
// 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;
using System;
using System.Collections;
using System.Collections.Specialized;
namespace System.Collections.Specialized.Tests
{
public class CtorIntNvcTests
{
[Fact]
public void Test01()
{
NameValueCollection nvc;
NameValueCollection nvc1; // argument NameValueCollection
// simple string values
string[] values =
{
"",
" ",
"a",
"aa",
"tExt",
" SPaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// names(keys) for simple string values
string[] names =
{
"zero",
"oNe",
" ",
"",
"aA",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
// [] NameValueCollection is constructed as expected
//-----------------------------------------------------------------
nvc1 = new NameValueCollection(10);
//
// [] Create w/o capacity from empty w capacity
//
nvc = new NameValueCollection(nvc1);
if (nvc == null)
{
Assert.False(true, "Error, collection is null");
}
if (nvc.Count != 0)
{
Assert.False(true, string.Format("Error, Count = {0} ", nvc.Count));
}
// [] Create w capacity from empty w same capacity
nvc = new NameValueCollection(10, nvc1);
if (nvc == null)
{
Assert.False(true, "Error, collection is null");
}
if (nvc.Count != 0)
{
Assert.False(true, string.Format("Error, Count = {0} ", nvc.Count));
}
//
//
// [] Create w capacity from empty w greater capacity
nvc = new NameValueCollection(5, nvc1);
if (nvc == null)
{
Assert.False(true, "Error, collection is null");
}
if (nvc.Count != 0)
{
Assert.False(true, string.Format("Error, Count = {0} ", nvc.Count));
}
// [] Create w capacity from empty w smaller capacity
nvc = new NameValueCollection(50, nvc1);
if (nvc == null)
{
Assert.False(true, "Error, collection is null");
}
if (nvc.Count != 0)
{
Assert.False(true, string.Format("Error, Count = {0} ", nvc.Count));
}
///////////////////////////////////////////////////////////////
//
// create from filled collection
// [] Create from filled collection - smaller capacity
//
int len = values.Length;
for (int i = 0; i < len; i++)
{
nvc1.Add(names[i], values[i]);
}
if (nvc1.Count != len)
{
Assert.False(true, string.Format("Error, Count = {0} after instead of {1}", nvc.Count, len));
}
nvc = new NameValueCollection(len / 2, nvc1);
if (nvc.Count != nvc1.Count)
{
Assert.False(true, string.Format("Error, Count = {0} instead of {1}", nvc.Count, nvc1.Count));
}
string[] keys1 = nvc1.AllKeys;
string[] keys = nvc.AllKeys;
if (keys1.Length != keys.Length)
{
Assert.False(true, string.Format("Error, new collection Keys.Length is {0} instead of {1}", keys.Length, keys1.Length));
}
else
{
for (int i = 0; i < keys1.Length; i++)
{
if (Array.IndexOf(keys, keys1[i]) < 0)
{
Assert.False(true, string.Format("Error, no key \"{1}\" in AllKeys", i, keys1[i]));
}
}
}
for (int i = 0; i < keys.Length; i++)
{
string[] val = nvc.GetValues(keys[i]);
if ((val.Length != 1) || String.Compare(val[0], (nvc1.GetValues(keys[i]))[0]) != 0)
{
Assert.False(true, string.Format("Error, unexpected value at key \"{1}\"", i, keys1[i]));
}
}
//
// [] Create from filled collection - count capacity
//
len = values.Length;
nvc = new NameValueCollection(len, nvc1);
if (nvc.Count != nvc1.Count)
{
Assert.False(true, string.Format("Error, Count = {0} instead of {1}", nvc.Count, nvc1.Count));
}
keys1 = nvc1.AllKeys;
keys = nvc.AllKeys;
if (keys1.Length != keys.Length)
{
Assert.False(true, string.Format("Error, new collection Keys.Length is {0} instead of {1}", keys.Length, keys1.Length));
}
else
{
for (int i = 0; i < keys1.Length; i++)
{
if (Array.IndexOf(keys, keys1[i]) < 0)
{
Assert.False(true, string.Format("Error, no key \"{1}\" in AllKeys", i, keys1[i]));
}
}
}
for (int i = 0; i < keys.Length; i++)
{
string[] val = nvc.GetValues(keys[i]);
if ((val.Length != 1) || String.Compare(val[0], (nvc1.GetValues(keys[i]))[0]) != 0)
{
Assert.False(true, string.Format("Error, unexpected value at key \"{1}\"", i, keys1[i]));
}
}
//
// [] Create from filled collection - greater capacity
//
len = values.Length;
nvc = new NameValueCollection(len * 2, nvc1);
if (nvc.Count != nvc1.Count)
{
Assert.False(true, string.Format("Error, Count = {0} instead of {1}", nvc.Count, nvc1.Count));
}
keys1 = nvc1.AllKeys;
keys = nvc.AllKeys;
if (keys1.Length != keys.Length)
{
Assert.False(true, string.Format("Error, new collection Keys.Length is {0} instead of {1}", keys.Length, keys1.Length));
}
else
{
for (int i = 0; i < keys1.Length; i++)
{
if (Array.IndexOf(keys, keys1[i]) < 0)
{
Assert.False(true, string.Format("Error, no key \"{1}\" in AllKeys", i, keys1[i]));
}
}
}
for (int i = 0; i < keys.Length; i++)
{
string[] val = nvc.GetValues(keys[i]);
if ((val.Length != 1) || String.Compare(val[0], (nvc1.GetValues(keys[i]))[0]) != 0)
{
Assert.False(true, string.Format("Error, unexpected value at key \"{1}\"", i, keys1[i]));
}
}
//
// [] change argument collection
//
string toChange = keys1[0];
string init = nvc1[toChange];
//
// Change element
//
nvc1[toChange] = "new Value";
if (String.Compare(nvc1[toChange], "new Value") != 0)
{
Assert.False(true, "Error, failed to change element");
}
if (String.Compare(nvc[toChange], init) != 0)
{
Assert.False(true, "Error, changed element in new collection");
}
//
// Remove element
//
nvc1.Remove(toChange);
if (nvc1.Count != len - 1)
{
Assert.False(true, "Error, failed to remove element");
}
if (nvc.Count != len)
{
Assert.False(true, "Error, collection changed after argument change - removed element");
}
keys = nvc.AllKeys;
if (Array.IndexOf(keys, toChange) < 0)
{
Assert.False(true, "Error, collection changed after argument change - no key");
}
//
// [] invalid parameter - negative capacity
//
Assert.Throws<ArgumentOutOfRangeException>(() => { nvc = new NameValueCollection(-1, nvc1); });
//
// [] invalid parameter - null collection
//
Assert.Throws<ArgumentNullException>(() => { nvc = new NameValueCollection(10, (NameValueCollection)null); });
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type float with 2 columns and 2 rows.
/// </summary>
[Serializable]
[DataContract(Namespace = "mat")]
[StructLayout(LayoutKind.Sequential)]
public struct mat2 : IReadOnlyList<float>, IEquatable<mat2>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
[DataMember]
public float m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
[DataMember]
public float m01;
/// <summary>
/// Column 1, Rows 0
/// </summary>
[DataMember]
public float m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
[DataMember]
public float m11;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public mat2(float m00, float m01, float m10, float m11)
{
this.m00 = m00;
this.m01 = m01;
this.m10 = m10;
this.m11 = m11;
}
/// <summary>
/// Constructs this matrix from a mat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2(mat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a mat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2(mat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a mat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2(mat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a mat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2(mat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a mat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2(mat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a mat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2(mat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a mat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2(mat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a mat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2(mat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a mat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2(mat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2(vec2 c0, vec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m10 = c1.x;
this.m11 = c1.y;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public float[,] Values => new[,] { { m00, m01 }, { m10, m11 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public float[] Values1D => new[] { m00, m01, m10, m11 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public vec2 Column0
{
get
{
return new vec2(m00, m01);
}
set
{
m00 = value.x;
m01 = value.y;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public vec2 Column1
{
get
{
return new vec2(m10, m11);
}
set
{
m10 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public vec2 Row0
{
get
{
return new vec2(m00, m10);
}
set
{
m00 = value.x;
m10 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public vec2 Row1
{
get
{
return new vec2(m01, m11);
}
set
{
m01 = value.x;
m11 = value.y;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static mat2 Zero { get; } = new mat2(0f, 0f, 0f, 0f);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static mat2 Ones { get; } = new mat2(1f, 1f, 1f, 1f);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static mat2 Identity { get; } = new mat2(1f, 0f, 0f, 1f);
/// <summary>
/// Predefined all-MaxValue matrix
/// </summary>
public static mat2 AllMaxValue { get; } = new mat2(float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue);
/// <summary>
/// Predefined diagonal-MaxValue matrix
/// </summary>
public static mat2 DiagonalMaxValue { get; } = new mat2(float.MaxValue, 0f, 0f, float.MaxValue);
/// <summary>
/// Predefined all-MinValue matrix
/// </summary>
public static mat2 AllMinValue { get; } = new mat2(float.MinValue, float.MinValue, float.MinValue, float.MinValue);
/// <summary>
/// Predefined diagonal-MinValue matrix
/// </summary>
public static mat2 DiagonalMinValue { get; } = new mat2(float.MinValue, 0f, 0f, float.MinValue);
/// <summary>
/// Predefined all-Epsilon matrix
/// </summary>
public static mat2 AllEpsilon { get; } = new mat2(float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon);
/// <summary>
/// Predefined diagonal-Epsilon matrix
/// </summary>
public static mat2 DiagonalEpsilon { get; } = new mat2(float.Epsilon, 0f, 0f, float.Epsilon);
/// <summary>
/// Predefined all-NaN matrix
/// </summary>
public static mat2 AllNaN { get; } = new mat2(float.NaN, float.NaN, float.NaN, float.NaN);
/// <summary>
/// Predefined diagonal-NaN matrix
/// </summary>
public static mat2 DiagonalNaN { get; } = new mat2(float.NaN, 0f, 0f, float.NaN);
/// <summary>
/// Predefined all-NegativeInfinity matrix
/// </summary>
public static mat2 AllNegativeInfinity { get; } = new mat2(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity);
/// <summary>
/// Predefined diagonal-NegativeInfinity matrix
/// </summary>
public static mat2 DiagonalNegativeInfinity { get; } = new mat2(float.NegativeInfinity, 0f, 0f, float.NegativeInfinity);
/// <summary>
/// Predefined all-PositiveInfinity matrix
/// </summary>
public static mat2 AllPositiveInfinity { get; } = new mat2(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
/// <summary>
/// Predefined diagonal-PositiveInfinity matrix
/// </summary>
public static mat2 DiagonalPositiveInfinity { get; } = new mat2(float.PositiveInfinity, 0f, 0f, float.PositiveInfinity);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<float> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m10;
yield return m11;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (2 x 2 = 4).
/// </summary>
public int Count => 4;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public float this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m10;
case 3: return m11;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m10 = value; break;
case 3: this.m11 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public float this[int col, int row]
{
get
{
return this[col * 2 + row];
}
set
{
this[col * 2 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(mat2 rhs) => ((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m10.Equals(rhs.m10) && m11.Equals(rhs.m11)));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is mat2 && Equals((mat2) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(mat2 lhs, mat2 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(mat2 lhs, mat2 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public mat2 Transposed => new mat2(m00, m10, m01, m11);
/// <summary>
/// Returns the minimal component of this matrix.
/// </summary>
public float MinElement => Math.Min(Math.Min(Math.Min(m00, m01), m10), m11);
/// <summary>
/// Returns the maximal component of this matrix.
/// </summary>
public float MaxElement => Math.Max(Math.Max(Math.Max(m00, m01), m10), m11);
/// <summary>
/// Returns the euclidean length of this matrix.
/// </summary>
public float Length => (float)Math.Sqrt(((m00*m00 + m01*m01) + (m10*m10 + m11*m11)));
/// <summary>
/// Returns the squared euclidean length of this matrix.
/// </summary>
public float LengthSqr => ((m00*m00 + m01*m01) + (m10*m10 + m11*m11));
/// <summary>
/// Returns the sum of all fields.
/// </summary>
public float Sum => ((m00 + m01) + (m10 + m11));
/// <summary>
/// Returns the euclidean norm of this matrix.
/// </summary>
public float Norm => (float)Math.Sqrt(((m00*m00 + m01*m01) + (m10*m10 + m11*m11)));
/// <summary>
/// Returns the one-norm of this matrix.
/// </summary>
public float Norm1 => ((Math.Abs(m00) + Math.Abs(m01)) + (Math.Abs(m10) + Math.Abs(m11)));
/// <summary>
/// Returns the two-norm of this matrix.
/// </summary>
public float Norm2 => (float)Math.Sqrt(((m00*m00 + m01*m01) + (m10*m10 + m11*m11)));
/// <summary>
/// Returns the max-norm of this matrix.
/// </summary>
public float NormMax => Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m10)), Math.Abs(m11));
/// <summary>
/// Returns the p-norm of this matrix.
/// </summary>
public double NormP(double p) => Math.Pow(((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + (Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p))), 1 / p);
/// <summary>
/// Returns determinant of this matrix.
/// </summary>
public float Determinant => m00 * m11 - m10 * m01;
/// <summary>
/// Returns the adjunct of this matrix.
/// </summary>
public mat2 Adjugate => new mat2(m11, -m01, -m10, m00);
/// <summary>
/// Returns the inverse of this matrix (use with caution).
/// </summary>
public mat2 Inverse => Adjugate / Determinant;
/// <summary>
/// Executes a matrix-matrix-multiplication mat2 * mat2 -> mat2.
/// </summary>
public static mat2 operator*(mat2 lhs, mat2 rhs) => new mat2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11));
/// <summary>
/// Executes a matrix-matrix-multiplication mat2 * mat3x2 -> mat3x2.
/// </summary>
public static mat3x2 operator*(mat2 lhs, mat3x2 rhs) => new mat3x2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21));
/// <summary>
/// Executes a matrix-matrix-multiplication mat2 * mat4x2 -> mat4x2.
/// </summary>
public static mat4x2 operator*(mat2 lhs, mat4x2 rhs) => new mat4x2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31));
/// <summary>
/// Executes a matrix-vector-multiplication.
/// </summary>
public static vec2 operator*(mat2 m, vec2 v) => new vec2((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y));
/// <summary>
/// Executes a matrix-matrix-divison A / B == A * B^-1 (use with caution).
/// </summary>
public static mat2 operator/(mat2 A, mat2 B) => A * B.Inverse;
/// <summary>
/// Executes a component-wise * (multiply).
/// </summary>
public static mat2 CompMul(mat2 A, mat2 B) => new mat2(A.m00 * B.m00, A.m01 * B.m01, A.m10 * B.m10, A.m11 * B.m11);
/// <summary>
/// Executes a component-wise / (divide).
/// </summary>
public static mat2 CompDiv(mat2 A, mat2 B) => new mat2(A.m00 / B.m00, A.m01 / B.m01, A.m10 / B.m10, A.m11 / B.m11);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static mat2 CompAdd(mat2 A, mat2 B) => new mat2(A.m00 + B.m00, A.m01 + B.m01, A.m10 + B.m10, A.m11 + B.m11);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static mat2 CompSub(mat2 A, mat2 B) => new mat2(A.m00 - B.m00, A.m01 - B.m01, A.m10 - B.m10, A.m11 - B.m11);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static mat2 operator+(mat2 lhs, mat2 rhs) => new mat2(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static mat2 operator+(mat2 lhs, float rhs) => new mat2(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m10 + rhs, lhs.m11 + rhs);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static mat2 operator+(float lhs, mat2 rhs) => new mat2(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m10, lhs + rhs.m11);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static mat2 operator-(mat2 lhs, mat2 rhs) => new mat2(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static mat2 operator-(mat2 lhs, float rhs) => new mat2(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m10 - rhs, lhs.m11 - rhs);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static mat2 operator-(float lhs, mat2 rhs) => new mat2(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m10, lhs - rhs.m11);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static mat2 operator/(mat2 lhs, float rhs) => new mat2(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m10 / rhs, lhs.m11 / rhs);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static mat2 operator/(float lhs, mat2 rhs) => new mat2(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m10, lhs / rhs.m11);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static mat2 operator*(mat2 lhs, float rhs) => new mat2(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m10 * rhs, lhs.m11 * rhs);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static mat2 operator*(float lhs, mat2 rhs) => new mat2(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m10, lhs * rhs.m11);
/// <summary>
/// Executes a component-wise lesser-than comparison.
/// </summary>
public static bmat2 operator<(mat2 lhs, mat2 rhs) => new bmat2(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2 operator<(mat2 lhs, float rhs) => new bmat2(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m10 < rhs, lhs.m11 < rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2 operator<(float lhs, mat2 rhs) => new bmat2(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m10, lhs < rhs.m11);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison.
/// </summary>
public static bmat2 operator<=(mat2 lhs, mat2 rhs) => new bmat2(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2 operator<=(mat2 lhs, float rhs) => new bmat2(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2 operator<=(float lhs, mat2 rhs) => new bmat2(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m10, lhs <= rhs.m11);
/// <summary>
/// Executes a component-wise greater-than comparison.
/// </summary>
public static bmat2 operator>(mat2 lhs, mat2 rhs) => new bmat2(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2 operator>(mat2 lhs, float rhs) => new bmat2(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m10 > rhs, lhs.m11 > rhs);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2 operator>(float lhs, mat2 rhs) => new bmat2(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m10, lhs > rhs.m11);
/// <summary>
/// Executes a component-wise greater-or-equal comparison.
/// </summary>
public static bmat2 operator>=(mat2 lhs, mat2 rhs) => new bmat2(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2 operator>=(mat2 lhs, float rhs) => new bmat2(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2 operator>=(float lhs, mat2 rhs) => new bmat2(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m10, lhs >= rhs.m11);
}
}
| |
namespace Fixtures.SwaggerBatBodyBoolean
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
internal partial class BoolModel : IServiceOperations<AutoRestBoolTestService>, IBoolModel
{
/// <summary>
/// Initializes a new instance of the BoolModel class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal BoolModel(AutoRestBoolTestService client)
{
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestBoolTestService
/// </summary>
public AutoRestBoolTestService Client { get; private set; }
/// <summary>
/// Get true Boolean value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<bool?>> GetTrueWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetTrue", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//bool/true";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<bool?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<bool?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Set Boolean value true
/// </summary>
/// <param name='boolBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutTrueWithHttpMessagesAsync(bool? boolBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (boolBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "boolBody");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("boolBody", boolBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutTrue", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//bool/true";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get false Boolean value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<bool?>> GetFalseWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetFalse", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//bool/false";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<bool?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<bool?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Set Boolean value false
/// </summary>
/// <param name='boolBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutFalseWithHttpMessagesAsync(bool? boolBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (boolBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "boolBody");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("boolBody", boolBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutFalse", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//bool/false";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get null Boolean value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<bool?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//bool/null";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<bool?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<bool?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get invalid Boolean value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<bool?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//bool/invalid";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<bool?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<bool?>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using OpenQA.Selenium.Environment;
namespace OpenQA.Selenium
{
[TestFixture]
public class PageLoadingTest : DriverTestFixture
{
[Test]
public void ShouldWaitForDocumentToBeLoaded()
{
driver.Url = simpleTestPage;
Assert.AreEqual(driver.Title, "Hello WebDriver");
}
[Test]
public void ShouldFollowRedirectsSentInTheHttpResponseHeaders()
{
driver.Url = redirectPage;
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldFollowMetaRedirects()
{
driver.Url = metaRedirectPage;
WaitFor(() => { return driver.Title == "We Arrive Here"; });
Assert.AreEqual(driver.Title, "We Arrive Here");
}
[Test]
public void ShouldBeAbleToGetAFragmentOnTheCurrentPage()
{
driver.Url = xhtmlTestPage;
driver.Url = xhtmlTestPage + "#text";
driver.FindElement(By.Id("id1"));
}
[Test]
[IgnoreBrowser(Browser.Safari, "Hangs Safari driver")]
public void ShouldReturnWhenGettingAUrlThatDoesNotResolve()
{
try
{
// Of course, we're up the creek if this ever does get registered
driver.Url = "http://www.thisurldoesnotexist.comx/";
}
catch (Exception e)
{
if (!IsIeDriverTimedOutException(e))
{
throw e;
}
}
}
[Test]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Safari, "Hangs Safari driver")]
public void ShouldReturnWhenGettingAUrlThatDoesNotConnect()
{
// Here's hoping that there's nothing here. There shouldn't be
driver.Url = "http://localhost:3001";
}
[Test]
public void ShouldBeAbleToLoadAPageWithFramesetsAndWaitUntilAllFramesAreLoaded()
{
driver.Url = framesetPage;
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMilliseconds(500));
driver.SwitchTo().Frame(0);
IWebElement pageNumber = driver.FindElement(By.XPath("//span[@id='pageNumber']"));
Assert.AreEqual(pageNumber.Text.Trim(), "1");
driver.SwitchTo().DefaultContent().SwitchTo().Frame(1);
pageNumber = driver.FindElement(By.XPath("//span[@id='pageNumber']"));
Assert.AreEqual(pageNumber.Text.Trim(), "2");
}
[Test]
[IgnoreBrowser(Browser.IPhone)]
[NeedsFreshDriver(BeforeTest = true)]
public void ShouldDoNothingIfThereIsNothingToGoBackTo()
{
string originalTitle = driver.Title;
driver.Url = formsPage;
driver.Navigate().Back();
// We may have returned to the browser's home page
Assert.IsTrue(driver.Title == originalTitle || driver.Title == "We Leave From Here");
if (driver.Title == originalTitle)
{
driver.Navigate().Back();
Assert.AreEqual(originalTitle, driver.Title);
}
}
[Test]
public void ShouldBeAbleToNavigateBackInTheBrowserHistory()
{
driver.Url = formsPage;
driver.FindElement(By.Id("imageButton")).Submit();
WaitFor(TitleToBeEqualTo("We Arrive Here"));
Assert.AreEqual(driver.Title, "We Arrive Here");
driver.Navigate().Back();
WaitFor(TitleToBeEqualTo("We Leave From Here"));
Assert.AreEqual(driver.Title, "We Leave From Here");
}
[Test]
public void ShouldBeAbleToNavigateBackInTheBrowserHistoryInPresenceOfIframes()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.Name("sameWindow")).Click();
WaitFor(TitleToBeEqualTo("This page has iframes"));
Assert.AreEqual(driver.Title, "This page has iframes");
driver.Navigate().Back();
WaitFor(TitleToBeEqualTo("XHTML Test Page"));
Assert.AreEqual(driver.Title, "XHTML Test Page");
}
[Test]
public void ShouldBeAbleToNavigateForwardsInTheBrowserHistory()
{
driver.Url = formsPage;
driver.FindElement(By.Id("imageButton")).Submit();
WaitFor(TitleToBeEqualTo("We Arrive Here"));
Assert.AreEqual(driver.Title, "We Arrive Here");
driver.Navigate().Back();
WaitFor(TitleToBeEqualTo("We Leave From Here"));
Assert.AreEqual(driver.Title, "We Leave From Here");
driver.Navigate().Forward();
WaitFor(TitleToBeEqualTo("We Arrive Here"));
Assert.AreEqual(driver.Title, "We Arrive Here");
}
//TODO (jimevan): Implement SSL secure http function
//[Test]
//[IgnoreBrowser(Browser.Chrome)]
//[IgnoreBrowser(Browser.IE)]
//public void ShouldBeAbleToAccessPagesWithAnInsecureSslCertificate()
//{
// String url = GlobalTestEnvironment.get().getAppServer().whereIsSecure("simpleTest.html");
// driver.Url = url;
// // This should work
// Assert.AreEqual(driver.Title, "Hello WebDriver");
//}
[Test]
public void ShouldBeAbleToRefreshAPage()
{
driver.Url = xhtmlTestPage;
driver.Navigate().Refresh();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMilliseconds(3000));
Assert.AreEqual(driver.Title, "XHTML Test Page");
}
/// <summary>
/// see <a href="http://code.google.com/p/selenium/issues/detail?id=208">Issue 208</a>
/// </summary>
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.IE, "Browser does, in fact, hang in this case.")]
[IgnoreBrowser(Browser.IPhone, "Untested user-agent")]
public void ShouldNotHangIfDocumentOpenCallIsNeverFollowedByDocumentCloseCall()
{
driver.Url = documentWrite;
// If this command succeeds, then all is well.
driver.FindElement(By.XPath("//body"));
}
[Test]
[IgnoreBrowser(Browser.Android, "Not implemented for browser")]
[IgnoreBrowser(Browser.Chrome, "Not implemented for browser")]
[IgnoreBrowser(Browser.HtmlUnit, "Not implemented for browser")]
[IgnoreBrowser(Browser.IPhone, "Not implemented for browser")]
[IgnoreBrowser(Browser.PhantomJS, "Not implemented for browser")]
[IgnoreBrowser(Browser.Opera, "Not implemented for browser")]
public void ShouldTimeoutIfAPageTakesTooLongToLoad()
{
driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(2));
try
{
// Get the sleeping servlet with a pause of 5 seconds
string slowPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("sleep?time=5");
driver.Url = slowPage;
Assert.Fail("I should have timed out");
}
catch (WebDriverTimeoutException)
{
}
finally
{
driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.MinValue);
}
}
private Func<bool> TitleToBeEqualTo(string expectedTitle)
{
return () => { return driver.Title == expectedTitle; };
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using ICSharpCode.NRefactory.TypeSystem;
using Saltarelle.Compiler;
using Saltarelle.Compiler.Compiler;
using Saltarelle.Compiler.JSModel.Expressions;
using Saltarelle.Compiler.JSModel.ExtensionMethods;
using Saltarelle.Compiler.ScriptSemantics;
namespace CoreLib.Plugin {
public class MetadataImporter : IMetadataImporter {
private static readonly ReadOnlySet<string> _unusableStaticFieldNames = new ReadOnlySet<string>(new HashSet<string>(new[] { "__defineGetter__", "__defineSetter__", "apply", "arguments", "bind", "call", "caller", "constructor", "hasOwnProperty", "isPrototypeOf", "length", "name", "propertyIsEnumerable", "prototype", "toLocaleString", "valueOf" }.Concat(Saltarelle.Compiler.JSModel.Utils.AllKeywords)));
private static readonly ReadOnlySet<string> _unusableInstanceFieldNames = new ReadOnlySet<string>(new HashSet<string>(new[] { "__defineGetter__", "__defineSetter__", "constructor", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "toLocaleString", "valueOf" }.Concat(Saltarelle.Compiler.JSModel.Utils.AllKeywords)));
private class TypeSemantics {
public TypeScriptSemantics Semantics { get; private set; }
public bool IsSerializable { get; private set; }
public bool IsNamedValues { get; private set; }
public bool IsImported { get; private set; }
public TypeSemantics(TypeScriptSemantics semantics, bool isSerializable, bool isNamedValues, bool isImported) {
Semantics = semantics;
IsSerializable = isSerializable;
IsNamedValues = isNamedValues;
IsImported = isImported;
}
}
private readonly Dictionary<ITypeDefinition, TypeSemantics> _typeSemantics;
private readonly Dictionary<ITypeDefinition, DelegateScriptSemantics> _delegateSemantics;
private readonly Dictionary<ITypeDefinition, HashSet<string>> _instanceMemberNamesByType;
private readonly Dictionary<ITypeDefinition, HashSet<string>> _staticMemberNamesByType;
private readonly Dictionary<IMethod, MethodScriptSemantics> _methodSemantics;
private readonly Dictionary<IProperty, PropertyScriptSemantics> _propertySemantics;
private readonly Dictionary<IField, FieldScriptSemantics> _fieldSemantics;
private readonly Dictionary<IEvent, EventScriptSemantics> _eventSemantics;
private readonly Dictionary<IMethod, ConstructorScriptSemantics> _constructorSemantics;
private readonly Dictionary<IProperty, string> _propertyBackingFieldNames;
private readonly Dictionary<IEvent, string> _eventBackingFieldNames;
private readonly Dictionary<ITypeDefinition, int> _backingFieldCountPerType;
private readonly Dictionary<Tuple<IAssembly, string>, int> _internalTypeCountPerAssemblyAndNamespace;
private readonly HashSet<IMember> _ignoredMembers;
private readonly IErrorReporter _errorReporter;
private readonly IType _systemObject;
private readonly ICompilation _compilation;
private readonly bool _minimizeNames;
public MetadataImporter(IErrorReporter errorReporter, ICompilation compilation, CompilerOptions options) {
_errorReporter = errorReporter;
_compilation = compilation;
_minimizeNames = options.MinimizeScript;
_systemObject = compilation.MainAssembly.Compilation.FindType(KnownTypeCode.Object);
_typeSemantics = new Dictionary<ITypeDefinition, TypeSemantics>();
_delegateSemantics = new Dictionary<ITypeDefinition, DelegateScriptSemantics>();
_instanceMemberNamesByType = new Dictionary<ITypeDefinition, HashSet<string>>();
_staticMemberNamesByType = new Dictionary<ITypeDefinition, HashSet<string>>();
_methodSemantics = new Dictionary<IMethod, MethodScriptSemantics>();
_propertySemantics = new Dictionary<IProperty, PropertyScriptSemantics>();
_fieldSemantics = new Dictionary<IField, FieldScriptSemantics>();
_eventSemantics = new Dictionary<IEvent, EventScriptSemantics>();
_constructorSemantics = new Dictionary<IMethod, ConstructorScriptSemantics>();
_propertyBackingFieldNames = new Dictionary<IProperty, string>();
_eventBackingFieldNames = new Dictionary<IEvent, string>();
_backingFieldCountPerType = new Dictionary<ITypeDefinition, int>();
_internalTypeCountPerAssemblyAndNamespace = new Dictionary<Tuple<IAssembly, string>, int>();
_ignoredMembers = new HashSet<IMember>();
var sna = compilation.MainAssembly.AssemblyAttributes.SingleOrDefault(a => a.AttributeType.FullName == typeof(ScriptNamespaceAttribute).FullName);
if (sna != null) {
var data = AttributeReader.ReadAttribute<ScriptNamespaceAttribute>(sna);
if (data.Name == null || (data.Name != "" && !data.Name.IsValidNestedJavaScriptIdentifier())) {
Message(Messages._7002, sna.Region, "assembly");
}
}
}
private void Message(Tuple<int, MessageSeverity, string> message, DomRegion r, params object[] additionalArgs) {
_errorReporter.Region = r;
_errorReporter.Message(message, additionalArgs);
}
private void Message(Tuple<int, MessageSeverity, string> message, IEntity e, params object[] additionalArgs) {
var name = (e is IMethod && ((IMethod)e).IsConstructor ? e.DeclaringType.FullName : e.FullName);
_errorReporter.Region = e.Region;
_errorReporter.Message(message, new object[] { name }.Concat(additionalArgs).ToArray());
}
private string GetDefaultTypeName(ITypeDefinition def, bool ignoreGenericArguments) {
if (ignoreGenericArguments) {
return def.Name;
}
else {
int outerCount = (def.DeclaringTypeDefinition != null ? def.DeclaringTypeDefinition.TypeParameters.Count : 0);
return def.Name + (def.TypeParameterCount != outerCount ? "$" + (def.TypeParameterCount - outerCount).ToString(CultureInfo.InvariantCulture) : "");
}
}
private bool? IsAutoProperty(IProperty property) {
if (property.Region == default(DomRegion))
return null;
return property.Getter != null && property.Setter != null && property.Getter.BodyRegion == default(DomRegion) && property.Setter.BodyRegion == default(DomRegion);
}
private string DetermineNamespace(ITypeDefinition typeDefinition) {
while (typeDefinition.DeclaringTypeDefinition != null) {
typeDefinition = typeDefinition.DeclaringTypeDefinition;
}
var ina = AttributeReader.ReadAttribute<IgnoreNamespaceAttribute>(typeDefinition);
var sna = AttributeReader.ReadAttribute<ScriptNamespaceAttribute>(typeDefinition);
if (ina != null) {
if (sna != null) {
Message(Messages._7001, typeDefinition);
return typeDefinition.FullName;
}
else {
return "";
}
}
else {
if (sna != null) {
if (sna.Name == null || (sna.Name != "" && !sna.Name.IsValidNestedJavaScriptIdentifier()))
Message(Messages._7002, typeDefinition);
return sna.Name;
}
else {
var asna = AttributeReader.ReadAttribute<ScriptNamespaceAttribute>(typeDefinition.ParentAssembly.AssemblyAttributes);
if (asna != null) {
if (asna.Name != null && (asna.Name == "" || asna.Name.IsValidNestedJavaScriptIdentifier()))
return asna.Name;
}
return typeDefinition.Namespace;
}
}
}
private Tuple<string, string> SplitNamespacedName(string fullName) {
string nmspace;
string name;
int dot = fullName.IndexOf('.');
if (dot >= 0) {
nmspace = fullName.Substring(0, dot);
name = fullName.Substring(dot + 1 );
}
else {
nmspace = "";
name = fullName;
}
return Tuple.Create(nmspace, name);
}
private void ProcessDelegate(ITypeDefinition delegateDefinition) {
bool bindThisToFirstParameter = AttributeReader.HasAttribute<BindThisToFirstParameterAttribute>(delegateDefinition);
bool expandParams = AttributeReader.HasAttribute<ExpandParamsAttribute>(delegateDefinition);
if (bindThisToFirstParameter && delegateDefinition.GetDelegateInvokeMethod().Parameters.Count == 0) {
Message(Messages._7147, delegateDefinition, delegateDefinition.FullName);
bindThisToFirstParameter = false;
}
if (expandParams && !delegateDefinition.GetDelegateInvokeMethod().Parameters.Any(p => p.IsParams)) {
Message(Messages._7148, delegateDefinition, delegateDefinition.FullName);
expandParams = false;
}
_delegateSemantics[delegateDefinition] = new DelegateScriptSemantics(expandParams: expandParams, bindThisToFirstParameter: bindThisToFirstParameter);
}
private void ProcessType(ITypeDefinition typeDefinition) {
if (typeDefinition.Kind == TypeKind.Delegate) {
ProcessDelegate(typeDefinition);
return;
}
if (AttributeReader.HasAttribute<NonScriptableAttribute>(typeDefinition) || typeDefinition.DeclaringTypeDefinition != null && GetTypeSemantics(typeDefinition.DeclaringTypeDefinition).Type == TypeScriptSemantics.ImplType.NotUsableFromScript) {
_typeSemantics[typeDefinition] = new TypeSemantics(TypeScriptSemantics.NotUsableFromScript(), false, false, false);
return;
}
var scriptNameAttr = AttributeReader.ReadAttribute<ScriptNameAttribute>(typeDefinition);
var importedAttr = AttributeReader.ReadAttribute<ImportedAttribute>(typeDefinition.Attributes);
bool preserveName = importedAttr != null || AttributeReader.HasAttribute<PreserveNameAttribute>(typeDefinition);
bool? includeGenericArguments = typeDefinition.TypeParameterCount > 0 ? MetadataUtils.ShouldGenericArgumentsBeIncluded(typeDefinition) : false;
if (includeGenericArguments == null) {
_errorReporter.Region = typeDefinition.Region;
Message(Messages._7026, typeDefinition);
includeGenericArguments = true;
}
if (AttributeReader.HasAttribute<ResourcesAttribute>(typeDefinition)) {
if (!typeDefinition.IsStatic) {
Message(Messages._7003, typeDefinition);
}
else if (typeDefinition.TypeParameterCount > 0) {
Message(Messages._7004, typeDefinition);
}
else if (typeDefinition.Members.Any(m => !(m is IField && ((IField)m).IsConst))) {
Message(Messages._7005, typeDefinition);
}
}
string typeName, nmspace;
if (scriptNameAttr != null && scriptNameAttr.Name != null && scriptNameAttr.Name.IsValidJavaScriptIdentifier()) {
typeName = scriptNameAttr.Name;
nmspace = DetermineNamespace(typeDefinition);
}
else if (scriptNameAttr != null && string.IsNullOrEmpty(scriptNameAttr.Name) && !string.IsNullOrEmpty(MetadataUtils.GetModuleName(typeDefinition))) {
typeName = "";
nmspace = "";
}
else {
if (scriptNameAttr != null) {
Message(Messages._7006, typeDefinition);
}
if (_minimizeNames && MetadataUtils.CanBeMinimized(typeDefinition) && !preserveName) {
nmspace = DetermineNamespace(typeDefinition);
var key = Tuple.Create(typeDefinition.ParentAssembly, nmspace);
int index;
_internalTypeCountPerAssemblyAndNamespace.TryGetValue(key, out index);
_internalTypeCountPerAssemblyAndNamespace[key] = index + 1;
typeName = "$" + index.ToString(CultureInfo.InvariantCulture);
}
else {
typeName = GetDefaultTypeName(typeDefinition, !includeGenericArguments.Value);
if (typeDefinition.DeclaringTypeDefinition != null) {
if (AttributeReader.HasAttribute<IgnoreNamespaceAttribute>(typeDefinition) || AttributeReader.HasAttribute<ScriptNamespaceAttribute>(typeDefinition)) {
Message(Messages._7007, typeDefinition);
}
var declaringName = SplitNamespacedName(GetTypeSemantics(typeDefinition.DeclaringTypeDefinition).Name);
nmspace = declaringName.Item1;
typeName = declaringName.Item2 + "$" + typeName;
}
else {
nmspace = DetermineNamespace(typeDefinition);
}
if (MetadataUtils.CanBeMinimized(typeDefinition) && !preserveName && !typeName.StartsWith("$")) {
typeName = "$" + typeName;
}
}
}
bool isSerializable = MetadataUtils.IsSerializable(typeDefinition);
if (isSerializable) {
var baseClass = typeDefinition.DirectBaseTypes.Single(c => c.Kind == TypeKind.Class).GetDefinition();
if (!baseClass.Equals(_systemObject) && baseClass.FullName != "System.Record" && !GetTypeSemanticsInternal(baseClass).IsSerializable) {
Message(Messages._7009, typeDefinition);
}
foreach (var i in typeDefinition.DirectBaseTypes.Where(b => b.Kind == TypeKind.Interface && !GetTypeSemanticsInternal(b.GetDefinition()).IsSerializable)) {
Message(Messages._7010, typeDefinition, i.FullName);
}
if (typeDefinition.Events.Any(evt => !evt.IsStatic)) {
Message(Messages._7011, typeDefinition);
}
foreach (var m in typeDefinition.Members.Where(m => m.IsVirtual)) {
Message(Messages._7023, typeDefinition, m.Name);
}
foreach (var m in typeDefinition.Members.Where(m => m.IsOverride)) {
Message(Messages._7024, typeDefinition, m.Name);
}
if (typeDefinition.Kind == TypeKind.Interface && typeDefinition.Methods.Any()) {
Message(Messages._7155, typeDefinition);
}
}
else {
var globalMethodsAttr = AttributeReader.ReadAttribute<GlobalMethodsAttribute>(typeDefinition);
var mixinAttr = AttributeReader.ReadAttribute<MixinAttribute>(typeDefinition);
if (mixinAttr != null) {
if (!typeDefinition.IsStatic) {
Message(Messages._7012, typeDefinition);
}
else if (typeDefinition.Members.Any(m => !AttributeReader.HasAttribute<CompilerGeneratedAttribute>(m) && (!(m is IMethod) || ((IMethod)m).IsConstructor))) {
Message(Messages._7013, typeDefinition);
}
else if (typeDefinition.TypeParameterCount > 0) {
Message(Messages._7014, typeDefinition);
}
else if (string.IsNullOrEmpty(mixinAttr.Expression)) {
Message(Messages._7025, typeDefinition);
}
else {
var split = SplitNamespacedName(mixinAttr.Expression);
nmspace = split.Item1;
typeName = split.Item2;
}
}
else if (globalMethodsAttr != null) {
if (!typeDefinition.IsStatic) {
Message(Messages._7015, typeDefinition);
}
else if (typeDefinition.TypeParameterCount > 0) {
Message(Messages._7017, typeDefinition);
}
else {
nmspace = "";
typeName = "";
}
}
}
if (importedAttr != null) {
if (!string.IsNullOrEmpty(importedAttr.TypeCheckCode)) {
if (importedAttr.ObeysTypeSystem) {
Message(Messages._7158, typeDefinition);
}
ValidateInlineCode(MetadataUtils.CreateTypeCheckMethod(typeDefinition, _compilation), typeDefinition, importedAttr.TypeCheckCode, Messages._7157);
}
if (!string.IsNullOrEmpty(MetadataUtils.GetSerializableTypeCheckCode(typeDefinition))) {
Message(Messages._7159, typeDefinition);
}
}
_typeSemantics[typeDefinition] = new TypeSemantics(TypeScriptSemantics.NormalType(!string.IsNullOrEmpty(nmspace) ? nmspace + "." + typeName : typeName, ignoreGenericArguments: !includeGenericArguments.Value, generateCode: importedAttr == null), isSerializable: isSerializable, isNamedValues: MetadataUtils.IsNamedValues(typeDefinition), isImported: importedAttr != null);
}
private HashSet<string> GetInstanceMemberNames(ITypeDefinition typeDefinition) {
HashSet<string> result;
if (!_instanceMemberNamesByType.TryGetValue(typeDefinition, out result))
throw new ArgumentException("Error getting instance member names: type " + typeDefinition.FullName + " has not yet been processed.");
return result;
}
private Tuple<string, bool> DeterminePreferredMemberName(IMember member) {
var asa = AttributeReader.ReadAttribute<AlternateSignatureAttribute>(member);
if (asa != null) {
var otherMembers = member.DeclaringTypeDefinition.Methods.Where(m => m.Name == member.Name && !AttributeReader.HasAttribute<AlternateSignatureAttribute>(m) && !AttributeReader.HasAttribute<NonScriptableAttribute>(m) && !AttributeReader.HasAttribute<InlineCodeAttribute>(m)).ToList();
if (otherMembers.Count != 1) {
Message(Messages._7100, member);
return Tuple.Create(member.Name, false);
}
}
return MetadataUtils.DeterminePreferredMemberName(member, _minimizeNames);
}
private void ProcessTypeMembers(ITypeDefinition typeDefinition) {
if (typeDefinition.Kind == TypeKind.Delegate)
return;
var baseMembersByType = typeDefinition.GetAllBaseTypeDefinitions().Where(x => x != typeDefinition).Select(t => new { Type = t, MemberNames = GetInstanceMemberNames(t) }).ToList();
for (int i = 0; i < baseMembersByType.Count; i++) {
var b = baseMembersByType[i];
for (int j = i + 1; j < baseMembersByType.Count; j++) {
var b2 = baseMembersByType[j];
if (!b.Type.GetAllBaseTypeDefinitions().Contains(b2.Type) && !b2.Type.GetAllBaseTypeDefinitions().Contains(b.Type)) {
foreach (var dup in b.MemberNames.Where(b2.MemberNames.Contains)) {
Message(Messages._7018, typeDefinition, b.Type.FullName, b2.Type.FullName, dup);
}
}
}
}
var instanceMembers = baseMembersByType.SelectMany(m => m.MemberNames).Distinct().ToDictionary(m => m, m => false);
if (_instanceMemberNamesByType.ContainsKey(typeDefinition))
_instanceMemberNamesByType[typeDefinition].ForEach(s => instanceMembers[s] = true);
_unusableInstanceFieldNames.ForEach(n => instanceMembers[n] = false);
var staticMembers = _unusableStaticFieldNames.ToDictionary(n => n, n => false);
if (_staticMemberNamesByType.ContainsKey(typeDefinition))
_staticMemberNamesByType[typeDefinition].ForEach(s => staticMembers[s] = true);
var membersByName = from m in typeDefinition.GetMembers(options: GetMemberOptions.IgnoreInheritedMembers)
where !_ignoredMembers.Contains(m)
let name = DeterminePreferredMemberName(m)
group new { m, name } by name.Item1 into g
select new { Name = g.Key, Members = g.Select(x => new { Member = x.m, NameSpecified = x.name.Item2 }).ToList() };
bool isSerializable = GetTypeSemanticsInternal(typeDefinition).IsSerializable;
foreach (var current in membersByName) {
foreach (var m in current.Members.OrderByDescending(x => x.NameSpecified).ThenBy(x => x.Member, MemberOrderer.Instance)) {
if (m.Member is IMethod) {
var method = (IMethod)m.Member;
if (method.IsConstructor) {
ProcessConstructor(method, current.Name, m.NameSpecified, staticMembers);
}
else {
ProcessMethod(method, current.Name, m.NameSpecified, m.Member.IsStatic || isSerializable ? staticMembers : instanceMembers);
}
}
else if (m.Member is IProperty) {
var p = (IProperty)m.Member;
ProcessProperty(p, current.Name, m.NameSpecified, m.Member.IsStatic ? staticMembers : instanceMembers);
var ps = GetPropertySemantics(p);
if (p.CanGet)
_methodSemantics[p.Getter] = ps.Type == PropertyScriptSemantics.ImplType.GetAndSetMethods ? ps.GetMethod : MethodScriptSemantics.NotUsableFromScript();
if (p.CanSet)
_methodSemantics[p.Setter] = ps.Type == PropertyScriptSemantics.ImplType.GetAndSetMethods ? ps.SetMethod : MethodScriptSemantics.NotUsableFromScript();
}
else if (m.Member is IField) {
ProcessField((IField)m.Member, current.Name, m.NameSpecified, m.Member.IsStatic ? staticMembers : instanceMembers);
}
else if (m.Member is IEvent) {
var e = (IEvent)m.Member;
ProcessEvent((IEvent)m.Member, current.Name, m.NameSpecified, m.Member.IsStatic ? staticMembers : instanceMembers);
var es = GetEventSemantics(e);
_methodSemantics[e.AddAccessor] = es.Type == EventScriptSemantics.ImplType.AddAndRemoveMethods ? es.AddMethod : MethodScriptSemantics.NotUsableFromScript();
_methodSemantics[e.RemoveAccessor] = es.Type == EventScriptSemantics.ImplType.AddAndRemoveMethods ? es.RemoveMethod : MethodScriptSemantics.NotUsableFromScript();
}
}
}
_instanceMemberNamesByType[typeDefinition] = new HashSet<string>(instanceMembers.Where(kvp => kvp.Value).Select(kvp => kvp.Key));
_staticMemberNamesByType[typeDefinition] = new HashSet<string>(staticMembers.Where(kvp => kvp.Value).Select(kvp => kvp.Key));
}
private string GetUniqueName(string preferredName, Dictionary<string, bool> usedNames) {
return MetadataUtils.GetUniqueName(preferredName, n => !usedNames.ContainsKey(n));
}
private bool ValidateInlineCode(IMethod method, IEntity errorEntity, string code, Tuple<int, MessageSeverity, string> errorTemplate) {
var typeErrors = new List<string>();
IList<string> errors;
Func<string, JsExpression> resolveType = n => {
var type = ReflectionHelper.ParseReflectionName(n).Resolve(_compilation);
if (type.Kind == TypeKind.Unknown) {
typeErrors.Add("Unknown type '" + n + "' specified in inline implementation");
}
return JsExpression.Null;
};
if (method.ReturnType.Kind == TypeKind.Void && !method.IsConstructor) {
errors = InlineCodeMethodCompiler.ValidateStatementListLiteralCode(method, code, resolveType, t => JsExpression.Null);
}
else {
errors = InlineCodeMethodCompiler.ValidateExpressionLiteralCode(method, code, resolveType, t => JsExpression.Null);
}
if (errors.Count > 0 || typeErrors.Count > 0) {
Message(errorTemplate, errorEntity, string.Join(", ", errors.Concat(typeErrors)));
return false;
}
return true;
}
private void ProcessConstructor(IMethod constructor, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) {
if (constructor.Parameters.Count == 1 && constructor.Parameters[0].Type.FullName == typeof(DummyTypeUsedToAddAttributeToDefaultValueTypeConstructor).FullName) {
_constructorSemantics[constructor] = ConstructorScriptSemantics.NotUsableFromScript();
return;
}
var source = (IMethod)MetadataUtils.UnwrapValueTypeConstructor(constructor);
var nsa = AttributeReader.ReadAttribute<NonScriptableAttribute>(source);
var asa = AttributeReader.ReadAttribute<AlternateSignatureAttribute>(source);
var epa = AttributeReader.ReadAttribute<ExpandParamsAttribute>(source);
var ola = AttributeReader.ReadAttribute<ObjectLiteralAttribute>(source);
if (nsa != null || GetTypeSemanticsInternal(source.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript) {
_constructorSemantics[constructor] = ConstructorScriptSemantics.NotUsableFromScript();
return;
}
if (source.IsStatic) {
_constructorSemantics[constructor] = ConstructorScriptSemantics.Unnamed(); // Whatever, it is not really used.
return;
}
if (epa != null && !source.Parameters.Any(p => p.IsParams)) {
Message(Messages._7102, constructor);
}
bool isSerializable = GetTypeSemanticsInternal(source.DeclaringTypeDefinition).IsSerializable;
bool isImported = GetTypeSemanticsInternal(source.DeclaringTypeDefinition).IsImported;
bool skipInInitializer = AttributeReader.HasAttribute<ScriptSkipAttribute>(constructor);
var ica = AttributeReader.ReadAttribute<InlineCodeAttribute>(source);
if (ica != null) {
if (!ValidateInlineCode(source, source, ica.Code, Messages._7103)) {
_constructorSemantics[constructor] = ConstructorScriptSemantics.Unnamed();
return;
}
if (ica.NonExpandedFormCode != null && !ValidateInlineCode(source, source, ica.NonExpandedFormCode, Messages._7103)) {
_constructorSemantics[constructor] = ConstructorScriptSemantics.Unnamed();
return;
}
if (ica.NonExpandedFormCode != null && !constructor.Parameters.Any(p => p.IsParams)) {
Message(Messages._7029, constructor.Region, "constructor", constructor.DeclaringType.FullName);
_constructorSemantics[constructor] = ConstructorScriptSemantics.Unnamed();
return;
}
_constructorSemantics[constructor] = ConstructorScriptSemantics.InlineCode(ica.Code, skipInInitializer: skipInInitializer, nonExpandedFormLiteralCode: ica.NonExpandedFormCode);
return;
}
else if (asa != null) {
_constructorSemantics[constructor] = preferredName == "$ctor" ? ConstructorScriptSemantics.Unnamed(generateCode: false, expandParams: epa != null, skipInInitializer: skipInInitializer) : ConstructorScriptSemantics.Named(preferredName, generateCode: false, expandParams: epa != null, skipInInitializer: skipInInitializer);
return;
}
else if (ola != null || (isSerializable && GetTypeSemanticsInternal(source.DeclaringTypeDefinition).IsImported)) {
if (isSerializable) {
bool hasError = false;
var members = source.DeclaringTypeDefinition.Members.Where(m => m.SymbolKind == SymbolKind.Property || m.SymbolKind == SymbolKind.Field).ToDictionary(m => m.Name.ToLowerInvariant());
var parameterToMemberMap = new List<IMember>();
foreach (var p in source.Parameters) {
IMember member;
if (p.IsOut || p.IsRef) {
Message(Messages._7145, p.Region, p.Name);
hasError = true;
}
else if (members.TryGetValue(p.Name.ToLowerInvariant(), out member)) {
if (p.Type.GetAllBaseTypes().Any(b => b.Equals(member.ReturnType)) || (member.ReturnType.IsKnownType(KnownTypeCode.NullableOfT) && member.ReturnType.TypeArguments[0].Equals(p.Type))) {
parameterToMemberMap.Add(member);
}
else {
Message(Messages._7144, p.Region, p.Name, p.Type.FullName, member.ReturnType.FullName);
hasError = true;
}
}
else {
Message(Messages._7143, p.Region, source.DeclaringTypeDefinition.FullName, p.Name);
hasError = true;
}
}
_constructorSemantics[constructor] = hasError ? ConstructorScriptSemantics.Unnamed() : ConstructorScriptSemantics.Json(parameterToMemberMap, skipInInitializer: skipInInitializer || constructor.Parameters.Count == 0);
}
else {
Message(Messages._7146, constructor.Region, source.DeclaringTypeDefinition.FullName);
_constructorSemantics[constructor] = ConstructorScriptSemantics.Unnamed();
}
return;
}
else if (source.Parameters.Count == 1 && source.Parameters[0].Type is ArrayType && ((ArrayType)source.Parameters[0].Type).ElementType.IsKnownType(KnownTypeCode.Object) && source.Parameters[0].IsParams && isImported) {
_constructorSemantics[constructor] = ConstructorScriptSemantics.InlineCode("ss.mkdict({" + source.Parameters[0].Name + "})", skipInInitializer: skipInInitializer);
return;
}
else if (nameSpecified) {
if (isSerializable)
_constructorSemantics[constructor] = ConstructorScriptSemantics.StaticMethod(preferredName, expandParams: epa != null, skipInInitializer: skipInInitializer);
else
_constructorSemantics[constructor] = preferredName == "$ctor" ? ConstructorScriptSemantics.Unnamed(expandParams: epa != null, skipInInitializer: skipInInitializer) : ConstructorScriptSemantics.Named(preferredName, expandParams: epa != null, skipInInitializer: skipInInitializer);
usedNames[preferredName] = true;
return;
}
else {
if (!usedNames.ContainsKey("$ctor") && !(isSerializable && _minimizeNames && MetadataUtils.CanBeMinimized(source))) { // The last part ensures that the first constructor of a serializable type can have its name minimized.
_constructorSemantics[constructor] = isSerializable ? ConstructorScriptSemantics.StaticMethod("$ctor", expandParams: epa != null, skipInInitializer: skipInInitializer) : ConstructorScriptSemantics.Unnamed(expandParams: epa != null, skipInInitializer: skipInInitializer);
usedNames["$ctor"] = true;
return;
}
else {
string name;
if (_minimizeNames && MetadataUtils.CanBeMinimized(source)) {
name = GetUniqueName(null, usedNames);
}
else {
int i = 1;
do {
name = "$ctor" + MetadataUtils.EncodeNumber(i, false);
i++;
} while (usedNames.ContainsKey(name));
}
_constructorSemantics[constructor] = isSerializable ? ConstructorScriptSemantics.StaticMethod(name, expandParams: epa != null, skipInInitializer: skipInInitializer) : ConstructorScriptSemantics.Named(name, expandParams: epa != null, skipInInitializer: skipInInitializer);
usedNames[name] = true;
return;
}
}
}
private void ProcessProperty(IProperty property, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) {
if (GetTypeSemanticsInternal(property.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript || AttributeReader.HasAttribute<NonScriptableAttribute>(property)) {
_propertySemantics[property] = PropertyScriptSemantics.NotUsableFromScript();
return;
}
else if (preferredName == "") {
Message(property.IsIndexer ? Messages._7104 : Messages._7105, property);
_propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(property.CanGet ? MethodScriptSemantics.NormalMethod("get") : null, property.CanSet ? MethodScriptSemantics.NormalMethod("set") : null);
return;
}
else if (GetTypeSemanticsInternal(property.DeclaringTypeDefinition).IsSerializable && !property.IsStatic) {
var getica = property.Getter != null ? AttributeReader.ReadAttribute<InlineCodeAttribute>(property.Getter) : null;
var setica = property.Setter != null ? AttributeReader.ReadAttribute<InlineCodeAttribute>(property.Setter) : null;
if (property.Getter != null && property.Setter != null && (getica != null) != (setica != null)) {
Message(Messages._7028, property);
}
else if (getica != null || setica != null) {
bool hasError = false;
if (property.Getter != null && !ValidateInlineCode(property.Getter, property.Getter, getica.Code, Messages._7130)) {
hasError = true;
}
if (property.Setter != null && !ValidateInlineCode(property.Setter, property.Setter, setica.Code, Messages._7130)) {
hasError = true;
}
if (!hasError) {
_propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(getica != null ? MethodScriptSemantics.InlineCode(getica.Code) : null, setica != null ? MethodScriptSemantics.InlineCode(setica.Code) : null);
return;
}
}
if (property.IsIndexer) {
if (property.DeclaringType.Kind == TypeKind.Interface) {
Message(Messages._7161, property.Region);
_propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(property.Getter != null ? MethodScriptSemantics.NormalMethod("X", generateCode: false) : null, property.Setter != null ? MethodScriptSemantics.NormalMethod("X", generateCode: false) : null);
}
else if (property.Parameters.Count == 1) {
_propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(property.Getter != null ? MethodScriptSemantics.NativeIndexer() : null, property.Setter != null ? MethodScriptSemantics.NativeIndexer() : null);
}
else {
Message(Messages._7116, property.Region);
_propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(property.Getter != null ? MethodScriptSemantics.NormalMethod("X", generateCode: false) : null, property.Setter != null ? MethodScriptSemantics.NormalMethod("X", generateCode: false) : null);
}
}
else {
usedNames[preferredName] = true;
_propertySemantics[property] = PropertyScriptSemantics.Field(preferredName);
}
return;
}
var saa = AttributeReader.ReadAttribute<ScriptAliasAttribute>(property);
if (saa != null) {
if (property.IsIndexer) {
Message(Messages._7106, property.Region);
}
else if (!property.IsStatic) {
Message(Messages._7107, property);
}
else {
_propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(property.CanGet ? MethodScriptSemantics.InlineCode(saa.Alias) : null, property.CanSet ? MethodScriptSemantics.InlineCode(saa.Alias + " = {value}") : null);
return;
}
}
if (AttributeReader.HasAttribute<IntrinsicPropertyAttribute>(property)) {
if (property.DeclaringType.Kind == TypeKind.Interface) {
if (property.IsIndexer)
Message(Messages._7108, property.Region);
else
Message(Messages._7109, property);
}
else if (property.IsOverride && GetPropertySemantics((IProperty)InheritanceHelper.GetBaseMember(property).MemberDefinition).Type != PropertyScriptSemantics.ImplType.NotUsableFromScript) {
if (property.IsIndexer)
Message(Messages._7110, property.Region);
else
Message(Messages._7111, property);
}
else if (property.IsOverridable) {
if (property.IsIndexer)
Message(Messages._7112, property.Region);
else
Message(Messages._7113, property);
}
else if (property.IsExplicitInterfaceImplementation || property.ImplementedInterfaceMembers.Any(m => GetPropertySemantics((IProperty)m.MemberDefinition).Type != PropertyScriptSemantics.ImplType.NotUsableFromScript)) {
if (property.IsIndexer)
Message(Messages._7114, property.Region);
else
Message(Messages._7115, property);
}
else if (property.IsIndexer) {
if (property.Parameters.Count == 1) {
_propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(property.CanGet ? MethodScriptSemantics.NativeIndexer() : null, property.CanSet ? MethodScriptSemantics.NativeIndexer() : null);
return;
}
else {
Message(Messages._7116, property.Region);
}
}
else {
usedNames[preferredName] = true;
_propertySemantics[property] = PropertyScriptSemantics.Field(preferredName);
return;
}
}
if (property.IsExplicitInterfaceImplementation && property.ImplementedInterfaceMembers.Any(m => GetPropertySemantics((IProperty)m.MemberDefinition).Type == PropertyScriptSemantics.ImplType.NotUsableFromScript)) {
// Inherit [NonScriptable] for explicit interface implementations.
_propertySemantics[property] = PropertyScriptSemantics.NotUsableFromScript();
return;
}
if (property.ImplementedInterfaceMembers.Count > 0) {
var bases = property.ImplementedInterfaceMembers.Where(b => GetPropertySemantics((IProperty)b).Type != PropertyScriptSemantics.ImplType.NotUsableFromScript).ToList();
var firstField = bases.FirstOrDefault(b => GetPropertySemantics((IProperty)b).Type == PropertyScriptSemantics.ImplType.Field);
if (firstField != null) {
var firstFieldSemantics = GetPropertySemantics((IProperty)firstField);
if (property.IsOverride) {
Message(Messages._7154, property, firstField.FullName);
}
else if (property.IsOverridable) {
Message(Messages._7153, property, firstField.FullName);
}
if (IsAutoProperty(property) == false) {
Message(Messages._7156, property, firstField.FullName);
}
_propertySemantics[property] = firstFieldSemantics;
return;
}
}
MethodScriptSemantics getter, setter;
if (property.CanGet) {
var getterName = DeterminePreferredMemberName(property.Getter);
if (!getterName.Item2)
getterName = Tuple.Create(!nameSpecified && _minimizeNames && property.DeclaringType.Kind != TypeKind.Interface && MetadataUtils.CanBeMinimized(property) ? null : (nameSpecified ? "get_" + preferredName : GetUniqueName("get_" + preferredName, usedNames)), false); // If the name was not specified, generate one.
ProcessMethod(property.Getter, getterName.Item1, getterName.Item2, usedNames);
getter = GetMethodSemanticsInternal(property.Getter);
}
else {
getter = null;
}
if (property.CanSet) {
var setterName = DeterminePreferredMemberName(property.Setter);
if (!setterName.Item2)
setterName = Tuple.Create(!nameSpecified && _minimizeNames && property.DeclaringType.Kind != TypeKind.Interface && MetadataUtils.CanBeMinimized(property) ? null : (nameSpecified ? "set_" + preferredName : GetUniqueName("set_" + preferredName, usedNames)), false); // If the name was not specified, generate one.
ProcessMethod(property.Setter, setterName.Item1, setterName.Item2, usedNames);
setter = GetMethodSemanticsInternal(property.Setter);
}
else {
setter = null;
}
_propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(getter, setter);
}
private void ProcessMethod(IMethod method, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) {
var eaa = AttributeReader.ReadAttribute<EnumerateAsArrayAttribute>(method);
var ssa = AttributeReader.ReadAttribute<ScriptSkipAttribute>(method);
var saa = AttributeReader.ReadAttribute<ScriptAliasAttribute>(method);
var ica = AttributeReader.ReadAttribute<InlineCodeAttribute>(method);
var ifa = AttributeReader.ReadAttribute<InstanceMethodOnFirstArgumentAttribute>(method);
var nsa = AttributeReader.ReadAttribute<NonScriptableAttribute>(method);
var ioa = AttributeReader.ReadAttribute<IntrinsicOperatorAttribute>(method);
var epa = AttributeReader.ReadAttribute<ExpandParamsAttribute>(method);
var asa = AttributeReader.ReadAttribute<AlternateSignatureAttribute>(method);
bool? includeGenericArguments = method.TypeParameters.Count > 0 ? MetadataUtils.ShouldGenericArgumentsBeIncluded(method) : false;
if (eaa != null && (method.Name != "GetEnumerator" || method.IsStatic || method.TypeParameters.Count > 0 || method.Parameters.Count > 0)) {
Message(Messages._7151, method);
eaa = null;
}
if (nsa != null || GetTypeSemanticsInternal(method.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript) {
_methodSemantics[method] = MethodScriptSemantics.NotUsableFromScript();
return;
}
if (ioa != null) {
if (!method.IsOperator) {
Message(Messages._7117, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
}
if (method.Name == "op_Implicit" || method.Name == "op_Explicit") {
Message(Messages._7118, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
}
else {
_methodSemantics[method] = MethodScriptSemantics.NativeOperator();
}
return;
}
else {
var interfaceImplementations = method.ImplementedInterfaceMembers.Where(m => method.IsExplicitInterfaceImplementation || _methodSemantics[(IMethod)m.MemberDefinition].Type != MethodScriptSemantics.ImplType.NotUsableFromScript).ToList();
if (ssa != null) {
// [ScriptSkip] - Skip invocation of the method entirely.
if (method.DeclaringTypeDefinition.Kind == TypeKind.Interface) {
Message(Messages._7119, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else if (method.IsOverride && GetMethodSemanticsInternal((IMethod)InheritanceHelper.GetBaseMember(method).MemberDefinition).Type != MethodScriptSemantics.ImplType.NotUsableFromScript) {
Message(Messages._7120, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else if (method.IsOverridable) {
Message(Messages._7121, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else if (interfaceImplementations.Count > 0) {
Message(Messages._7122, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else {
if (method.IsStatic) {
if (method.Parameters.Count != 1) {
Message(Messages._7123, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
_methodSemantics[method] = MethodScriptSemantics.InlineCode("{" + method.Parameters[0].Name + "}", enumerateAsArray: eaa != null);
return;
}
else {
if (method.Parameters.Count != 0)
Message(Messages._7124, method);
_methodSemantics[method] = MethodScriptSemantics.InlineCode("{this}", enumerateAsArray: eaa != null);
return;
}
}
}
else if (saa != null) {
if (method.IsStatic) {
_methodSemantics[method] = MethodScriptSemantics.InlineCode(saa.Alias + "(" + string.Join(", ", method.Parameters.Select(p => "{" + p.Name + "}")) + ")");
return;
}
else {
Message(Messages._7125, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
}
else if (ica != null) {
string code = ica.Code ?? "", nonVirtualCode = ica.NonVirtualCode, nonExpandedFormCode = ica.NonExpandedFormCode;
if (method.DeclaringTypeDefinition.Kind == TypeKind.Interface && string.IsNullOrEmpty(ica.GeneratedMethodName)) {
Message(Messages._7126, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else if (method.IsOverride && GetMethodSemanticsInternal((IMethod)InheritanceHelper.GetBaseMember(method).MemberDefinition).Type != MethodScriptSemantics.ImplType.NotUsableFromScript) {
Message(Messages._7127, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else if (method.IsOverridable && string.IsNullOrEmpty(ica.GeneratedMethodName)) {
Message(Messages._7128, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else {
if (!ValidateInlineCode(method, method, code, Messages._7130)) {
code = nonVirtualCode = nonExpandedFormCode = "X";
}
if (!string.IsNullOrEmpty(ica.NonVirtualCode) && !ValidateInlineCode(method, method, ica.NonVirtualCode, Messages._7130)) {
code = nonVirtualCode = nonExpandedFormCode = "X";
}
if (!string.IsNullOrEmpty(ica.NonExpandedFormCode)) {
if (!method.Parameters.Any(p => p.IsParams)) {
Message(Messages._7029, method.Region, "method", method.FullName);
code = nonVirtualCode = nonExpandedFormCode = "X";
}
if (!ValidateInlineCode(method, method, ica.NonExpandedFormCode, Messages._7130)) {
code = nonVirtualCode = nonExpandedFormCode = "X";
}
}
_methodSemantics[method] = MethodScriptSemantics.InlineCode(code, enumerateAsArray: eaa != null, generatedMethodName: !string.IsNullOrEmpty(ica.GeneratedMethodName) ? ica.GeneratedMethodName : null, nonVirtualInvocationLiteralCode: nonVirtualCode, nonExpandedFormLiteralCode: nonExpandedFormCode);
if (!string.IsNullOrEmpty(ica.GeneratedMethodName))
usedNames[ica.GeneratedMethodName] = true;
return;
}
}
else if (ifa != null) {
if (method.IsStatic) {
if (epa != null && !method.Parameters.Any(p => p.IsParams)) {
Message(Messages._7137, method);
}
if (method.Parameters.Count == 0) {
Message(Messages._7149, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else if (method.Parameters[0].IsParams) {
Message(Messages._7150, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else {
var sb = new StringBuilder();
sb.Append("{" + method.Parameters[0].Name + "}." + preferredName + "(");
for (int i = 1; i < method.Parameters.Count; i++) {
var p = method.Parameters[i];
if (i > 1)
sb.Append(", ");
sb.Append((epa != null && p.IsParams ? "{*" : "{") + p.Name + "}");
}
sb.Append(")");
_methodSemantics[method] = MethodScriptSemantics.InlineCode(sb.ToString());
return;
}
}
else {
Message(Messages._7131, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
}
else {
if (method.IsOverride && GetMethodSemanticsInternal((IMethod)InheritanceHelper.GetBaseMember(method).MemberDefinition).Type != MethodScriptSemantics.ImplType.NotUsableFromScript) {
if (nameSpecified) {
Message(Messages._7132, method);
}
if (AttributeReader.HasAttribute<IncludeGenericArgumentsAttribute>(method)) {
Message(Messages._7133, method);
}
var semantics = GetMethodSemanticsInternal((IMethod)InheritanceHelper.GetBaseMember(method).MemberDefinition);
if (semantics.Type == MethodScriptSemantics.ImplType.InlineCode && semantics.GeneratedMethodName != null)
semantics = MethodScriptSemantics.NormalMethod(semantics.GeneratedMethodName, ignoreGenericArguments: semantics.IgnoreGenericArguments, expandParams: semantics.ExpandParams); // Methods derived from methods with [InlineCode(..., GeneratedMethodName = "Something")] are treated as normal methods.
if (eaa != null)
semantics = semantics.WithEnumerateAsArray();
if (semantics.Type == MethodScriptSemantics.ImplType.NormalMethod) {
var errorMethod = interfaceImplementations.FirstOrDefault(im => GetMethodSemanticsInternal((IMethod)im.MemberDefinition).Name != semantics.Name);
if (errorMethod != null) {
Message(Messages._7134, method, errorMethod.FullName);
}
}
_methodSemantics[method] = semantics;
return;
}
else if (interfaceImplementations.Count > 0) {
if (nameSpecified) {
Message(Messages._7135, method);
}
var candidateNames = interfaceImplementations
.Select(im => GetMethodSemanticsInternal((IMethod)im.MemberDefinition))
.Select(s => s.Type == MethodScriptSemantics.ImplType.NormalMethod ? s.Name : (s.Type == MethodScriptSemantics.ImplType.InlineCode ? s.GeneratedMethodName : null))
.Where(name => name != null)
.Distinct();
if (candidateNames.Count() > 1) {
Message(Messages._7136, method);
}
// If the method implements more than one interface member, prefer to take the implementation from one that is not unusable.
var sem = interfaceImplementations.Select(im => GetMethodSemanticsInternal((IMethod)im.MemberDefinition)).FirstOrDefault() ?? MethodScriptSemantics.NotUsableFromScript();
if (sem.Type == MethodScriptSemantics.ImplType.InlineCode && sem.GeneratedMethodName != null)
sem = MethodScriptSemantics.NormalMethod(sem.GeneratedMethodName, ignoreGenericArguments: sem.IgnoreGenericArguments, expandParams: sem.ExpandParams); // Methods implementing methods with [InlineCode(..., GeneratedMethodName = "Something")] are treated as normal methods.
if (eaa != null)
sem = sem.WithEnumerateAsArray();
_methodSemantics[method] = sem;
return;
}
else {
if (includeGenericArguments == null) {
_errorReporter.Region = method.Region;
Message(Messages._7027, method);
includeGenericArguments = true;
}
if (epa != null) {
if (!method.Parameters.Any(p => p.IsParams)) {
Message(Messages._7137, method);
}
}
if (preferredName == "") {
// Special case - Script# supports setting the name of a method to an empty string, which means that it simply removes the name (eg. "x.M(a)" becomes "x(a)"). We model this with literal code.
if (method.DeclaringTypeDefinition.Kind == TypeKind.Interface) {
Message(Messages._7138, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else if (method.IsOverridable) {
Message(Messages._7139, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else if (method.IsStatic) {
Message(Messages._7140, method);
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name);
return;
}
else {
_methodSemantics[method] = MethodScriptSemantics.InlineCode("{this}(" + string.Join(", ", method.Parameters.Select(p => "{" + p.Name + "}")) + ")", enumerateAsArray: eaa != null);
return;
}
}
else {
string name = nameSpecified ? preferredName : GetUniqueName(preferredName, usedNames);
if (asa == null)
usedNames[name] = true;
if (GetTypeSemanticsInternal(method.DeclaringTypeDefinition).IsSerializable && !method.IsStatic) {
_methodSemantics[method] = MethodScriptSemantics.StaticMethodWithThisAsFirstArgument(name, generateCode: !AttributeReader.HasAttribute<AlternateSignatureAttribute>(method), ignoreGenericArguments: !includeGenericArguments.Value, expandParams: epa != null, enumerateAsArray: eaa != null);
}
else {
_methodSemantics[method] = MethodScriptSemantics.NormalMethod(name, generateCode: !AttributeReader.HasAttribute<AlternateSignatureAttribute>(method), ignoreGenericArguments: !includeGenericArguments.Value, expandParams: epa != null, enumerateAsArray: eaa != null);
}
}
}
}
}
}
private void ProcessEvent(IEvent evt, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) {
if (GetTypeSemanticsInternal(evt.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript || AttributeReader.HasAttribute<NonScriptableAttribute>(evt)) {
_eventSemantics[evt] = EventScriptSemantics.NotUsableFromScript();
return;
}
else if (preferredName == "") {
Message(Messages._7141, evt);
_eventSemantics[evt] = EventScriptSemantics.AddAndRemoveMethods(MethodScriptSemantics.NormalMethod("add"), MethodScriptSemantics.NormalMethod("remove"));
return;
}
MethodScriptSemantics adder, remover;
if (evt.CanAdd) {
var getterName = DeterminePreferredMemberName(evt.AddAccessor);
if (!getterName.Item2)
getterName = Tuple.Create(!nameSpecified && _minimizeNames && evt.DeclaringType.Kind != TypeKind.Interface && MetadataUtils.CanBeMinimized(evt) ? null : (nameSpecified ? "add_" + preferredName : GetUniqueName("add_" + preferredName, usedNames)), false); // If the name was not specified, generate one.
ProcessMethod(evt.AddAccessor, getterName.Item1, getterName.Item2, usedNames);
adder = GetMethodSemanticsInternal(evt.AddAccessor);
}
else {
adder = null;
}
if (evt.CanRemove) {
var setterName = DeterminePreferredMemberName(evt.RemoveAccessor);
if (!setterName.Item2)
setterName = Tuple.Create(!nameSpecified && _minimizeNames && evt.DeclaringType.Kind != TypeKind.Interface && MetadataUtils.CanBeMinimized(evt) ? null : (nameSpecified ? "remove_" + preferredName : GetUniqueName("remove_" + preferredName, usedNames)), false); // If the name was not specified, generate one.
ProcessMethod(evt.RemoveAccessor, setterName.Item1, setterName.Item2, usedNames);
remover = GetMethodSemanticsInternal(evt.RemoveAccessor);
}
else {
remover = null;
}
_eventSemantics[evt] = EventScriptSemantics.AddAndRemoveMethods(adder, remover);
}
private void ProcessField(IField field, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) {
if (GetTypeSemanticsInternal(field.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript || AttributeReader.HasAttribute<NonScriptableAttribute>(field)) {
_fieldSemantics[field] = FieldScriptSemantics.NotUsableFromScript();
}
else if (preferredName == "") {
Message(Messages._7142, field);
_fieldSemantics[field] = FieldScriptSemantics.Field("X");
}
else {
string name = (nameSpecified ? preferredName : GetUniqueName(preferredName, usedNames));
if (AttributeReader.HasAttribute<InlineConstantAttribute>(field)) {
if (field.IsConst) {
name = null;
}
else {
Message(Messages._7152, field);
}
}
else {
usedNames[name] = true;
}
if (AttributeReader.HasAttribute<NoInlineAttribute>(field) && !field.IsConst) {
Message(Messages._7160, field);
}
if (GetTypeSemanticsInternal(field.DeclaringTypeDefinition).IsNamedValues) {
string value = preferredName;
if (!nameSpecified) { // This code handles the feature that it is possible to specify an invalid ScriptName for a member of a NamedValues enum, in which case that value has to be use as the constant value.
var sna = AttributeReader.ReadAttribute<ScriptNameAttribute>(field);
if (sna != null)
value = sna.Name;
}
_fieldSemantics[field] = FieldScriptSemantics.StringConstant(value, name);
}
else if (field.DeclaringType.Kind == TypeKind.Enum && AttributeReader.HasAttribute<ImportedAttribute>(field.DeclaringTypeDefinition) && AttributeReader.HasAttribute<ScriptNameAttribute>(field.DeclaringTypeDefinition)) {
// Fields of enums that are imported and have an explicit [ScriptName] are treated as normal fields.
_fieldSemantics[field] = FieldScriptSemantics.Field(name);
}
else if (name == null || (field.IsConst && !AttributeReader.HasAttribute<NoInlineAttribute>(field) && (field.DeclaringType.Kind == TypeKind.Enum || _minimizeNames))) {
object value = Saltarelle.Compiler.JSModel.Utils.ConvertToDoubleOrStringOrBoolean(field.ConstantValue);
if (value is bool)
_fieldSemantics[field] = FieldScriptSemantics.BooleanConstant((bool)value, name);
else if (value is double)
_fieldSemantics[field] = FieldScriptSemantics.NumericConstant((double)value, name);
else if (value is string)
_fieldSemantics[field] = FieldScriptSemantics.StringConstant((string)value, name);
else
_fieldSemantics[field] = FieldScriptSemantics.NullConstant(name);
}
else {
_fieldSemantics[field] = FieldScriptSemantics.Field(name);
}
}
}
public void Prepare(ITypeDefinition type) {
try {
ProcessType(type);
ProcessTypeMembers(type);
}
catch (Exception ex) {
_errorReporter.Region = type.Region;
_errorReporter.InternalError(ex, "Error importing type " + type.FullName);
}
}
public void ReserveMemberName(ITypeDefinition type, string name, bool isStatic) {
HashSet<string> names;
if (!isStatic) {
if (!_instanceMemberNamesByType.TryGetValue(type, out names))
_instanceMemberNamesByType[type] = names = new HashSet<string>();
}
else {
if (!_staticMemberNamesByType.TryGetValue(type, out names))
_staticMemberNamesByType[type] = names = new HashSet<string>();
}
names.Add(name);
}
public bool IsMemberNameAvailable(ITypeDefinition type, string name, bool isStatic) {
if (isStatic) {
if (_unusableStaticFieldNames.Contains(name))
return false;
HashSet<string> names;
if (!_staticMemberNamesByType.TryGetValue(type, out names))
return true;
return !names.Contains(name);
}
else {
if (_unusableInstanceFieldNames.Contains(name))
return false;
if (type.DirectBaseTypes.Select(d => d.GetDefinition()).Any(t => !IsMemberNameAvailable(t, name, false)))
return false;
HashSet<string> names;
if (!_instanceMemberNamesByType.TryGetValue(type, out names))
return true;
return !names.Contains(name);
}
}
public void SetMethodSemantics(IMethod method, MethodScriptSemantics semantics) {
_methodSemantics[method] = semantics;
_ignoredMembers.Add(method);
}
public void SetConstructorSemantics(IMethod method, ConstructorScriptSemantics semantics) {
_constructorSemantics[method] = semantics;
_ignoredMembers.Add(method);
}
public void SetPropertySemantics(IProperty property, PropertyScriptSemantics semantics) {
_propertySemantics[property] = semantics;
_ignoredMembers.Add(property);
}
public void SetFieldSemantics(IField field, FieldScriptSemantics semantics) {
_fieldSemantics[field] = semantics;
_ignoredMembers.Add(field);
}
public void SetEventSemantics(IEvent evt,EventScriptSemantics semantics) {
_eventSemantics[evt] = semantics;
_ignoredMembers.Add(evt);
}
private TypeSemantics GetTypeSemanticsInternal(ITypeDefinition typeDefinition) {
TypeSemantics ts;
if (_typeSemantics.TryGetValue(typeDefinition, out ts))
return ts;
throw new ArgumentException(string.Format("Type semantics for type {0} were not correctly imported", typeDefinition.FullName));
}
public TypeScriptSemantics GetTypeSemantics(ITypeDefinition typeDefinition) {
if (typeDefinition.Kind == TypeKind.Delegate)
return TypeScriptSemantics.NormalType("Function");
else if (typeDefinition.Kind == TypeKind.Array)
return TypeScriptSemantics.NormalType("Array");
return GetTypeSemanticsInternal(typeDefinition).Semantics;
}
private MethodScriptSemantics GetMethodSemanticsInternal(IMethod method) {
switch (method.DeclaringType.Kind) {
case TypeKind.Delegate:
return MethodScriptSemantics.NotUsableFromScript();
default:
MethodScriptSemantics result;
if (!_methodSemantics.TryGetValue((IMethod)method.MemberDefinition, out result))
throw new ArgumentException(string.Format("Semantics for method " + method + " were not imported"));
return result;
}
}
public MethodScriptSemantics GetMethodSemantics(IMethod method) {
if (method.IsAccessor)
throw new ArgumentException("GetMethodSemantics should not be called for the accessor " + method);
return GetMethodSemanticsInternal(method);
}
public ConstructorScriptSemantics GetConstructorSemantics(IMethod method) {
switch (method.DeclaringType.Kind) {
case TypeKind.Anonymous:
return ConstructorScriptSemantics.Json(new IMember[0]);
case TypeKind.Delegate:
return ConstructorScriptSemantics.NotUsableFromScript();
default:
ConstructorScriptSemantics result;
if (!_constructorSemantics.TryGetValue((IMethod)method.MemberDefinition, out result))
throw new ArgumentException(string.Format("Semantics for constructor " + method + " were not imported"));
return result;
}
}
public PropertyScriptSemantics GetPropertySemantics(IProperty property) {
switch (property.DeclaringType.Kind) {
case TypeKind.Anonymous:
return PropertyScriptSemantics.Field(property.Name.Replace("<>", "$"));
case TypeKind.Delegate:
return PropertyScriptSemantics.NotUsableFromScript();
default:
PropertyScriptSemantics result;
if (!_propertySemantics.TryGetValue((IProperty)property.MemberDefinition, out result))
throw new ArgumentException(string.Format("Semantics for property " + property + " were not imported"));
return result;
}
}
public DelegateScriptSemantics GetDelegateSemantics(ITypeDefinition delegateType) {
DelegateScriptSemantics result;
if (!_delegateSemantics.TryGetValue(delegateType, out result))
throw new ArgumentException(string.Format("Semantics for delegate " + delegateType + " were not imported"));
return result;
}
private string GetBackingFieldName(ITypeDefinition declaringTypeDefinition, string memberName) {
int inheritanceDepth = declaringTypeDefinition.GetAllBaseTypes().Count(b => b.Kind != TypeKind.Interface) - 1;
if (_minimizeNames) {
int count;
_backingFieldCountPerType.TryGetValue(declaringTypeDefinition, out count);
count++;
_backingFieldCountPerType[declaringTypeDefinition] = count;
return string.Format(CultureInfo.InvariantCulture, "${0}${1}", inheritanceDepth, count);
}
else {
return string.Format(CultureInfo.InvariantCulture, "${0}${1}Field", inheritanceDepth, memberName);
}
}
public string GetAutoPropertyBackingFieldName(IProperty property) {
property = (IProperty)property.MemberDefinition;
string result;
if (_propertyBackingFieldNames.TryGetValue(property, out result))
return result;
result = GetBackingFieldName(property.DeclaringTypeDefinition, property.Name);
_propertyBackingFieldNames[property] = result;
return result;
}
public FieldScriptSemantics GetFieldSemantics(IField field) {
switch (field.DeclaringType.Kind) {
case TypeKind.Delegate:
return FieldScriptSemantics.NotUsableFromScript();
default:
FieldScriptSemantics result;
if (!_fieldSemantics.TryGetValue((IField)field.MemberDefinition, out result))
throw new ArgumentException(string.Format("Semantics for field " + field + " were not imported"));
return result;
}
}
public EventScriptSemantics GetEventSemantics(IEvent evt) {
switch (evt.DeclaringType.Kind) {
case TypeKind.Delegate:
return EventScriptSemantics.NotUsableFromScript();
default:
EventScriptSemantics result;
if (!_eventSemantics.TryGetValue((IEvent)evt.MemberDefinition, out result))
throw new ArgumentException(string.Format("Semantics for field " + evt + " were not imported"));
return result;
}
}
public string GetAutoEventBackingFieldName(IEvent evt) {
evt = (IEvent)evt.MemberDefinition;
string result;
if (_eventBackingFieldNames.TryGetValue(evt, out result))
return result;
result = GetBackingFieldName(evt.DeclaringTypeDefinition, evt.Name);
_eventBackingFieldNames[evt] = result;
return result;
}
}
}
| |
using EIDSS.Reports.BaseControls.Filters;
namespace EIDSS.Reports.Parameterized.Human.AJ.Keepers
{
partial class BaseComparativeReportKeeper
{
#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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BaseComparativeReportKeeper));
this.StartYearLabel = new System.Windows.Forms.Label();
this.Year1SpinEdit = new DevExpress.XtraEditors.SpinEdit();
this.StartMonthLookUp = new DevExpress.XtraEditors.LookUpEdit();
this.EndMonthLookUp = new DevExpress.XtraEditors.LookUpEdit();
this.EndMonthLabel = new System.Windows.Forms.Label();
this.StartMonthLabel = new System.Windows.Forms.Label();
this.Year2SpinEdit = new DevExpress.XtraEditors.SpinEdit();
this.EndYearLabel = new System.Windows.Forms.Label();
this.region1Filter = new EIDSS.Reports.BaseControls.Filters.RegionFilter();
this.rayon1Filter = new EIDSS.Reports.BaseControls.Filters.RayonFilter();
this.region2Filter = new EIDSS.Reports.BaseControls.Filters.RegionFilter();
this.rayon2Filter = new EIDSS.Reports.BaseControls.Filters.RayonFilter();
this.CounterLookUp = new DevExpress.XtraEditors.LookUpEdit();
this.CounterLabel = new System.Windows.Forms.Label();
this.pnlSettings.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.ceUseArchiveData.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.Year1SpinEdit.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.StartMonthLookUp.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.EndMonthLookUp.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.Year2SpinEdit.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CounterLookUp.Properties)).BeginInit();
this.SuspendLayout();
//
// pnlSettings
//
this.pnlSettings.Controls.Add(this.CounterLookUp);
this.pnlSettings.Controls.Add(this.CounterLabel);
this.pnlSettings.Controls.Add(this.region2Filter);
this.pnlSettings.Controls.Add(this.rayon2Filter);
this.pnlSettings.Controls.Add(this.region1Filter);
this.pnlSettings.Controls.Add(this.rayon1Filter);
this.pnlSettings.Controls.Add(this.EndMonthLookUp);
this.pnlSettings.Controls.Add(this.StartMonthLookUp);
this.pnlSettings.Controls.Add(this.Year2SpinEdit);
this.pnlSettings.Controls.Add(this.StartMonthLabel);
this.pnlSettings.Controls.Add(this.EndMonthLabel);
this.pnlSettings.Controls.Add(this.Year1SpinEdit);
this.pnlSettings.Controls.Add(this.EndYearLabel);
this.pnlSettings.Controls.Add(this.StartYearLabel);
resources.ApplyResources(this.pnlSettings, "pnlSettings");
this.pnlSettings.Controls.SetChildIndex(this.GenerateReportButton, 0);
this.pnlSettings.Controls.SetChildIndex(this.StartYearLabel, 0);
this.pnlSettings.Controls.SetChildIndex(this.EndYearLabel, 0);
this.pnlSettings.Controls.SetChildIndex(this.ceUseArchiveData, 0);
this.pnlSettings.Controls.SetChildIndex(this.Year1SpinEdit, 0);
this.pnlSettings.Controls.SetChildIndex(this.EndMonthLabel, 0);
this.pnlSettings.Controls.SetChildIndex(this.StartMonthLabel, 0);
this.pnlSettings.Controls.SetChildIndex(this.Year2SpinEdit, 0);
this.pnlSettings.Controls.SetChildIndex(this.StartMonthLookUp, 0);
this.pnlSettings.Controls.SetChildIndex(this.EndMonthLookUp, 0);
this.pnlSettings.Controls.SetChildIndex(this.rayon1Filter, 0);
this.pnlSettings.Controls.SetChildIndex(this.region1Filter, 0);
this.pnlSettings.Controls.SetChildIndex(this.rayon2Filter, 0);
this.pnlSettings.Controls.SetChildIndex(this.region2Filter, 0);
this.pnlSettings.Controls.SetChildIndex(this.CounterLabel, 0);
this.pnlSettings.Controls.SetChildIndex(this.CounterLookUp, 0);
//
// ceUseArchiveData
//
resources.ApplyResources(this.ceUseArchiveData, "ceUseArchiveData");
this.ceUseArchiveData.Properties.Appearance.Options.UseFont = true;
this.ceUseArchiveData.Properties.AppearanceDisabled.Options.UseFont = true;
this.ceUseArchiveData.Properties.AppearanceFocused.Options.UseFont = true;
this.ceUseArchiveData.Properties.AppearanceReadOnly.Options.UseFont = true;
//
// GenerateReportButton
//
resources.ApplyResources(this.GenerateReportButton, "GenerateReportButton");
bv.common.Resources.BvResourceManagerChanger.GetResourceManager(typeof(BaseComparativeReportKeeper), out resources);
// Form Is Localizable: True
//
// StartYearLabel
//
resources.ApplyResources(this.StartYearLabel, "StartYearLabel");
this.StartYearLabel.ForeColor = System.Drawing.Color.Black;
this.StartYearLabel.Name = "StartYearLabel";
//
// Year1SpinEdit
//
resources.ApplyResources(this.Year1SpinEdit, "Year1SpinEdit");
this.Year1SpinEdit.Name = "Year1SpinEdit";
this.Year1SpinEdit.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.Year1SpinEdit.Properties.Mask.EditMask = resources.GetString("Year1SpinEdit.Properties.Mask.EditMask");
this.Year1SpinEdit.Properties.Mask.MaskType = ((DevExpress.XtraEditors.Mask.MaskType)(resources.GetObject("Year1SpinEdit.Properties.Mask.MaskType")));
this.Year1SpinEdit.Properties.MaxValue = new decimal(new int[] {
2030,
0,
0,
0});
this.Year1SpinEdit.Properties.MinValue = new decimal(new int[] {
2000,
0,
0,
0});
this.Year1SpinEdit.EditValueChanged += new System.EventHandler(this.seYear1_EditValueChanged);
//
// StartMonthLookUp
//
resources.ApplyResources(this.StartMonthLookUp, "StartMonthLookUp");
this.StartMonthLookUp.Name = "StartMonthLookUp";
this.StartMonthLookUp.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("StartMonthLookUp.Properties.Buttons")))),
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("StartMonthLookUp.Properties.Buttons1"))))});
this.StartMonthLookUp.Properties.DropDownRows = 12;
this.StartMonthLookUp.Properties.NullText = resources.GetString("StartMonthLookUp.Properties.NullText");
this.StartMonthLookUp.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(this.cbMonth_ButtonClick);
this.StartMonthLookUp.EditValueChanged += new System.EventHandler(this.StartMonth_EditValueChanged);
//
// EndMonthLookUp
//
resources.ApplyResources(this.EndMonthLookUp, "EndMonthLookUp");
this.EndMonthLookUp.Name = "EndMonthLookUp";
this.EndMonthLookUp.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("EndMonthLookUp.Properties.Buttons")))),
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("EndMonthLookUp.Properties.Buttons1"))))});
this.EndMonthLookUp.Properties.DropDownRows = 12;
this.EndMonthLookUp.Properties.NullText = resources.GetString("EndMonthLookUp.Properties.NullText");
this.EndMonthLookUp.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(this.cbMonth_ButtonClick);
this.EndMonthLookUp.EditValueChanged += new System.EventHandler(this.EndMonth_EditValueChanged);
//
// EndMonthLabel
//
resources.ApplyResources(this.EndMonthLabel, "EndMonthLabel");
this.EndMonthLabel.ForeColor = System.Drawing.Color.Black;
this.EndMonthLabel.Name = "EndMonthLabel";
//
// StartMonthLabel
//
resources.ApplyResources(this.StartMonthLabel, "StartMonthLabel");
this.StartMonthLabel.ForeColor = System.Drawing.Color.Black;
this.StartMonthLabel.Name = "StartMonthLabel";
//
// Year2SpinEdit
//
resources.ApplyResources(this.Year2SpinEdit, "Year2SpinEdit");
this.Year2SpinEdit.Name = "Year2SpinEdit";
this.Year2SpinEdit.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.Year2SpinEdit.Properties.Mask.EditMask = resources.GetString("Year2SpinEdit.Properties.Mask.EditMask");
this.Year2SpinEdit.Properties.Mask.MaskType = ((DevExpress.XtraEditors.Mask.MaskType)(resources.GetObject("Year2SpinEdit.Properties.Mask.MaskType")));
this.Year2SpinEdit.Properties.MaxValue = new decimal(new int[] {
2030,
0,
0,
0});
this.Year2SpinEdit.Properties.MinValue = new decimal(new int[] {
2000,
0,
0,
0});
this.Year2SpinEdit.EditValueChanged += new System.EventHandler(this.seYear2_EditValueChanged);
//
// EndYearLabel
//
resources.ApplyResources(this.EndYearLabel, "EndYearLabel");
this.EndYearLabel.ForeColor = System.Drawing.Color.Black;
this.EndYearLabel.Name = "EndYearLabel";
//
// region1Filter
//
this.region1Filter.Appearance.Options.UseFont = true;
resources.ApplyResources(this.region1Filter, "region1Filter");
this.region1Filter.Name = "region1Filter";
this.region1Filter.ValueChanged += new System.EventHandler<EIDSS.Reports.BaseControls.Filters.SingleFilterEventArgs>(this.Region1_ValueChanged);
//
// rayon1Filter
//
this.rayon1Filter.Appearance.Options.UseFont = true;
resources.ApplyResources(this.rayon1Filter, "rayon1Filter");
this.rayon1Filter.Name = "rayon1Filter";
this.rayon1Filter.ValueChanged += new System.EventHandler<EIDSS.Reports.BaseControls.Filters.SingleFilterEventArgs>(this.Rayon1_ValueChanged);
//
// region2Filter
//
this.region2Filter.Appearance.Options.UseFont = true;
resources.ApplyResources(this.region2Filter, "region2Filter");
this.region2Filter.Name = "region2Filter";
this.region2Filter.ValueChanged += new System.EventHandler<EIDSS.Reports.BaseControls.Filters.SingleFilterEventArgs>(this.Region2_ValueChanged);
//
// rayon2Filter
//
this.rayon2Filter.Appearance.Options.UseFont = true;
resources.ApplyResources(this.rayon2Filter, "rayon2Filter");
this.rayon2Filter.Name = "rayon2Filter";
this.rayon2Filter.ValueChanged += new System.EventHandler<EIDSS.Reports.BaseControls.Filters.SingleFilterEventArgs>(this.Rayon2_ValueChanged);
//
// CounterLookUp
//
resources.ApplyResources(this.CounterLookUp, "CounterLookUp");
this.CounterLookUp.Name = "CounterLookUp";
this.CounterLookUp.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("CounterLookUp.Properties.Buttons")))),
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("CounterLookUp.Properties.Buttons1"))))});
this.CounterLookUp.Properties.DropDownRows = 12;
this.CounterLookUp.Properties.NullText = resources.GetString("CounterLookUp.Properties.NullText");
//
// CounterLabel
//
resources.ApplyResources(this.CounterLabel, "CounterLabel");
this.CounterLabel.ForeColor = System.Drawing.Color.Black;
this.CounterLabel.Name = "CounterLabel";
//
// BaseComparativeReportKeeper
//
resources.ApplyResources(this, "$this");
this.HeaderHeight = 170;
this.Name = "BaseComparativeReportKeeper";
this.pnlSettings.ResumeLayout(false);
this.pnlSettings.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.ceUseArchiveData.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.Year1SpinEdit.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.StartMonthLookUp.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.EndMonthLookUp.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.Year2SpinEdit.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CounterLookUp.Properties)).EndInit();
this.ResumeLayout(false);
}
#endregion
protected System.Windows.Forms.Label StartYearLabel;
protected DevExpress.XtraEditors.SpinEdit Year1SpinEdit;
protected DevExpress.XtraEditors.LookUpEdit StartMonthLookUp;
protected DevExpress.XtraEditors.LookUpEdit EndMonthLookUp;
protected System.Windows.Forms.Label EndMonthLabel;
protected System.Windows.Forms.Label StartMonthLabel;
protected DevExpress.XtraEditors.SpinEdit Year2SpinEdit;
protected System.Windows.Forms.Label EndYearLabel;
protected RegionFilter region1Filter;
protected RayonFilter rayon1Filter;
protected RegionFilter region2Filter;
protected RayonFilter rayon2Filter;
protected DevExpress.XtraEditors.LookUpEdit CounterLookUp;
protected System.Windows.Forms.Label CounterLabel;
}
}
| |
#region Apache License
//
// 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.
//
#endregion
using System;
using System.Xml;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Threading;
using log4net.Appender;
using log4net.Util;
using log4net.Repository;
namespace log4net.Config
{
/// <summary>
/// Use this class to initialize the log4net environment using an Xml tree.
/// </summary>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// <para>
/// Configures a <see cref="ILoggerRepository"/> using an Xml tree.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
[Obsolete("Use XmlConfigurator instead of DOMConfigurator")]
public sealed class DOMConfigurator
{
#region Private Instance Constructors
/// <summary>
/// Private constructor
/// </summary>
private DOMConfigurator()
{
}
#endregion Protected Instance Constructors
#region Configure static methods
/// <summary>
/// Automatically configures the log4net system based on the
/// application's configuration settings.
/// </summary>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// Each application has a configuration file. This has the
/// same name as the application with '.config' appended.
/// This file is XML and calling this function prompts the
/// configurator to look in that file for a section called
/// <c>log4net</c> that contains the configuration data.
/// </remarks>
[Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")]
static public void Configure()
{
XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()));
}
/// <summary>
/// Automatically configures the <see cref="ILoggerRepository"/> using settings
/// stored in the application's configuration file.
/// </summary>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// Each application has a configuration file. This has the
/// same name as the application with '.config' appended.
/// This file is XML and calling this function prompts the
/// configurator to look in that file for a section called
/// <c>log4net</c> that contains the configuration data.
/// </remarks>
/// <param name="repository">The repository to configure.</param>
[Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")]
static public void Configure(ILoggerRepository repository)
{
XmlConfigurator.Configure(repository);
}
/// <summary>
/// Configures log4net using a <c>log4net</c> element
/// </summary>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// Loads the log4net configuration from the XML element
/// supplied as <paramref name="element"/>.
/// </remarks>
/// <param name="element">The element to parse.</param>
[Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")]
static public void Configure(XmlElement element)
{
XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), element);
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified XML
/// element.
/// </summary>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// Loads the log4net configuration from the XML element
/// supplied as <paramref name="element"/>.
/// </remarks>
/// <param name="repository">The repository to configure.</param>
/// <param name="element">The element to parse.</param>
[Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")]
static public void Configure(ILoggerRepository repository, XmlElement element)
{
XmlConfigurator.Configure(repository, element);
}
/// <summary>
/// Configures log4net using the specified configuration file.
/// </summary>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the log4net configuration data.
/// </para>
/// <para>
/// The log4net configuration file can possible be specified in the application's
/// configuration file (either <c>MyAppName.exe.config</c> for a
/// normal application on <c>Web.config</c> for an ASP.NET application).
/// </para>
/// <example>
/// The following example configures log4net using a configuration file, of which the
/// location is stored in the application's configuration file :
/// </example>
/// <code lang="C#">
/// using log4net.Config;
/// using System.IO;
/// using System.Configuration;
///
/// ...
///
/// DOMConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
/// </code>
/// <para>
/// In the <c>.config</c> file, the path to the log4net can be specified like this :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net-config-file" value="log.config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </remarks>
[Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")]
static public void Configure(FileInfo configFile)
{
XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile);
}
/// <summary>
/// Configures log4net using the specified configuration file.
/// </summary>
/// <param name="configStream">A stream to load the XML configuration from.</param>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// <para>
/// The configuration data must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the log4net configuration data.
/// </para>
/// <para>
/// Note that this method will NOT close the stream parameter.
/// </para>
/// </remarks>
[Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")]
static public void Configure(Stream configStream)
{
XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configStream);
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified configuration
/// file.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The log4net configuration file can possible be specified in the application's
/// configuration file (either <c>MyAppName.exe.config</c> for a
/// normal application on <c>Web.config</c> for an ASP.NET application).
/// </para>
/// <example>
/// The following example configures log4net using a configuration file, of which the
/// location is stored in the application's configuration file :
/// </example>
/// <code lang="C#">
/// using log4net.Config;
/// using System.IO;
/// using System.Configuration;
///
/// ...
///
/// DOMConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"]));
/// </code>
/// <para>
/// In the <c>.config</c> file, the path to the log4net can be specified like this :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="log4net-config-file" value="log.config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </remarks>
[Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")]
static public void Configure(ILoggerRepository repository, FileInfo configFile)
{
XmlConfigurator.Configure(repository, configFile);
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified configuration
/// file.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configStream">The stream to load the XML configuration from.</param>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// <para>
/// The configuration data must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// Note that this method will NOT close the stream parameter.
/// </para>
/// </remarks>
[Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")]
static public void Configure(ILoggerRepository repository, Stream configStream)
{
XmlConfigurator.Configure(repository, configStream);
}
#endregion Configure static methods
#region ConfigureAndWatch static methods
#if (!NETCF && !SSCLI)
/// <summary>
/// Configures log4net using the file specified, monitors the file for changes
/// and reloads the configuration if a change is detected.
/// </summary>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The configuration file will be monitored using a <see cref="FileSystemWatcher"/>
/// and depends on the behavior of that class.
/// </para>
/// <para>
/// For more information on how to configure log4net using
/// a separate configuration file, see <see cref="M:Configure(FileInfo)"/>.
/// </para>
/// </remarks>
/// <seealso cref="M:Configure(FileInfo)"/>
[Obsolete("Use XmlConfigurator.ConfigureAndWatch instead of DOMConfigurator.ConfigureAndWatch")]
static public void ConfigureAndWatch(FileInfo configFile)
{
XmlConfigurator.ConfigureAndWatch(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile);
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the file specified,
/// monitors the file for changes and reloads the configuration if a change
/// is detected.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>log4net</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The configuration file will be monitored using a <see cref="FileSystemWatcher"/>
/// and depends on the behavior of that class.
/// </para>
/// <para>
/// For more information on how to configure log4net using
/// a separate configuration file, see <see cref="M:Configure(FileInfo)"/>.
/// </para>
/// </remarks>
/// <seealso cref="M:Configure(FileInfo)"/>
[Obsolete("Use XmlConfigurator.ConfigureAndWatch instead of DOMConfigurator.ConfigureAndWatch")]
static public void ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile)
{
XmlConfigurator.ConfigureAndWatch(repository, configFile);
}
#endif
#endregion ConfigureAndWatch static methods
}
}
| |
// Copyright 2022 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 gax = Google.Api.Gax;
using gciv = Google.Cloud.Iot.V1;
using sys = System;
namespace Google.Cloud.Iot.V1
{
/// <summary>Resource name for the <c>Device</c> resource.</summary>
public sealed partial class DeviceName : gax::IResourceName, sys::IEquatable<DeviceName>
{
/// <summary>The possible contents of <see cref="DeviceName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/registries/{registry}/devices/{device}</c>.
/// </summary>
ProjectLocationRegistryDevice = 1,
}
private static gax::PathTemplate s_projectLocationRegistryDevice = new gax::PathTemplate("projects/{project}/locations/{location}/registries/{registry}/devices/{device}");
/// <summary>Creates a <see cref="DeviceName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="DeviceName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static DeviceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new DeviceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="DeviceName"/> with the pattern
/// <c>projects/{project}/locations/{location}/registries/{registry}/devices/{device}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="registryId">The <c>Registry</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deviceId">The <c>Device</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="DeviceName"/> constructed from the provided ids.</returns>
public static DeviceName FromProjectLocationRegistryDevice(string projectId, string locationId, string registryId, string deviceId) =>
new DeviceName(ResourceNameType.ProjectLocationRegistryDevice, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), registryId: gax::GaxPreconditions.CheckNotNullOrEmpty(registryId, nameof(registryId)), deviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(deviceId, nameof(deviceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="DeviceName"/> with pattern
/// <c>projects/{project}/locations/{location}/registries/{registry}/devices/{device}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="registryId">The <c>Registry</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deviceId">The <c>Device</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="DeviceName"/> with pattern
/// <c>projects/{project}/locations/{location}/registries/{registry}/devices/{device}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string registryId, string deviceId) =>
FormatProjectLocationRegistryDevice(projectId, locationId, registryId, deviceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="DeviceName"/> with pattern
/// <c>projects/{project}/locations/{location}/registries/{registry}/devices/{device}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="registryId">The <c>Registry</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deviceId">The <c>Device</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="DeviceName"/> with pattern
/// <c>projects/{project}/locations/{location}/registries/{registry}/devices/{device}</c>.
/// </returns>
public static string FormatProjectLocationRegistryDevice(string projectId, string locationId, string registryId, string deviceId) =>
s_projectLocationRegistryDevice.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(registryId, nameof(registryId)), gax::GaxPreconditions.CheckNotNullOrEmpty(deviceId, nameof(deviceId)));
/// <summary>Parses the given resource name string into a new <see cref="DeviceName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/registries/{registry}/devices/{device}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="deviceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="DeviceName"/> if successful.</returns>
public static DeviceName Parse(string deviceName) => Parse(deviceName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="DeviceName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/registries/{registry}/devices/{device}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="deviceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="DeviceName"/> if successful.</returns>
public static DeviceName Parse(string deviceName, bool allowUnparsed) =>
TryParse(deviceName, allowUnparsed, out DeviceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="DeviceName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/registries/{registry}/devices/{device}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="deviceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="DeviceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string deviceName, out DeviceName result) => TryParse(deviceName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="DeviceName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/registries/{registry}/devices/{device}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="deviceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="DeviceName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string deviceName, bool allowUnparsed, out DeviceName result)
{
gax::GaxPreconditions.CheckNotNull(deviceName, nameof(deviceName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationRegistryDevice.TryParseName(deviceName, out resourceName))
{
result = FromProjectLocationRegistryDevice(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(deviceName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private DeviceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string deviceId = null, string locationId = null, string projectId = null, string registryId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
DeviceId = deviceId;
LocationId = locationId;
ProjectId = projectId;
RegistryId = registryId;
}
/// <summary>
/// Constructs a new instance of a <see cref="DeviceName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/registries/{registry}/devices/{device}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="registryId">The <c>Registry</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deviceId">The <c>Device</c> ID. Must not be <c>null</c> or empty.</param>
public DeviceName(string projectId, string locationId, string registryId, string deviceId) : this(ResourceNameType.ProjectLocationRegistryDevice, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), registryId: gax::GaxPreconditions.CheckNotNullOrEmpty(registryId, nameof(registryId)), deviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(deviceId, nameof(deviceId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Device</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string DeviceId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Registry</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string RegistryId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationRegistryDevice: return s_projectLocationRegistryDevice.Expand(ProjectId, LocationId, RegistryId, DeviceId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as DeviceName);
/// <inheritdoc/>
public bool Equals(DeviceName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(DeviceName a, DeviceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(DeviceName a, DeviceName b) => !(a == b);
}
/// <summary>Resource name for the <c>Registry</c> resource.</summary>
public sealed partial class RegistryName : gax::IResourceName, sys::IEquatable<RegistryName>
{
/// <summary>The possible contents of <see cref="RegistryName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/registries/{registry}</c>.
/// </summary>
ProjectLocationRegistry = 1,
}
private static gax::PathTemplate s_projectLocationRegistry = new gax::PathTemplate("projects/{project}/locations/{location}/registries/{registry}");
/// <summary>Creates a <see cref="RegistryName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="RegistryName"/> containing the provided <paramref name="unparsedResourceName"/>
/// .
/// </returns>
public static RegistryName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new RegistryName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="RegistryName"/> with the pattern
/// <c>projects/{project}/locations/{location}/registries/{registry}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="registryId">The <c>Registry</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="RegistryName"/> constructed from the provided ids.</returns>
public static RegistryName FromProjectLocationRegistry(string projectId, string locationId, string registryId) =>
new RegistryName(ResourceNameType.ProjectLocationRegistry, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), registryId: gax::GaxPreconditions.CheckNotNullOrEmpty(registryId, nameof(registryId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RegistryName"/> with pattern
/// <c>projects/{project}/locations/{location}/registries/{registry}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="registryId">The <c>Registry</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RegistryName"/> with pattern
/// <c>projects/{project}/locations/{location}/registries/{registry}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string registryId) =>
FormatProjectLocationRegistry(projectId, locationId, registryId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="RegistryName"/> with pattern
/// <c>projects/{project}/locations/{location}/registries/{registry}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="registryId">The <c>Registry</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="RegistryName"/> with pattern
/// <c>projects/{project}/locations/{location}/registries/{registry}</c>.
/// </returns>
public static string FormatProjectLocationRegistry(string projectId, string locationId, string registryId) =>
s_projectLocationRegistry.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(registryId, nameof(registryId)));
/// <summary>Parses the given resource name string into a new <see cref="RegistryName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/registries/{registry}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="registryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="RegistryName"/> if successful.</returns>
public static RegistryName Parse(string registryName) => Parse(registryName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="RegistryName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/registries/{registry}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="registryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="RegistryName"/> if successful.</returns>
public static RegistryName Parse(string registryName, bool allowUnparsed) =>
TryParse(registryName, allowUnparsed, out RegistryName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="RegistryName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/registries/{registry}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="registryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="RegistryName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string registryName, out RegistryName result) => TryParse(registryName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="RegistryName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/registries/{registry}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="registryName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="RegistryName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string registryName, bool allowUnparsed, out RegistryName result)
{
gax::GaxPreconditions.CheckNotNull(registryName, nameof(registryName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationRegistry.TryParseName(registryName, out resourceName))
{
result = FromProjectLocationRegistry(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(registryName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private RegistryName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string registryId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProjectId = projectId;
RegistryId = registryId;
}
/// <summary>
/// Constructs a new instance of a <see cref="RegistryName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/registries/{registry}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="registryId">The <c>Registry</c> ID. Must not be <c>null</c> or empty.</param>
public RegistryName(string projectId, string locationId, string registryId) : this(ResourceNameType.ProjectLocationRegistry, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), registryId: gax::GaxPreconditions.CheckNotNullOrEmpty(registryId, nameof(registryId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Registry</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string RegistryId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationRegistry: return s_projectLocationRegistry.Expand(ProjectId, LocationId, RegistryId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as RegistryName);
/// <inheritdoc/>
public bool Equals(RegistryName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(RegistryName a, RegistryName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(RegistryName a, RegistryName b) => !(a == b);
}
public partial class Device
{
/// <summary>
/// <see cref="gciv::DeviceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gciv::DeviceName DeviceName
{
get => string.IsNullOrEmpty(Name) ? null : gciv::DeviceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class DeviceRegistry
{
/// <summary>
/// <see cref="gciv::RegistryName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gciv::RegistryName RegistryName
{
get => string.IsNullOrEmpty(Name) ? null : gciv::RegistryName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Util.Fst
{
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
using NUnit.Framework;
using System.IO;
/*
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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 Directory = Lucene.Net.Store.Directory;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using IOContext = Lucene.Net.Store.IOContext;
using PackedInts = Lucene.Net.Util.Packed.PackedInts;
/// <summary>
/// Helper class to test FSTs. </summary>
public class FSTTester<T>
{
internal readonly Random Random;
internal readonly List<InputOutput<T>> Pairs;
internal readonly int InputMode;
internal readonly Outputs<T> Outputs;
internal readonly Directory Dir;
internal readonly bool DoReverseLookup;
public FSTTester(Random random, Directory dir, int inputMode, List<InputOutput<T>> pairs, Outputs<T> outputs, bool doReverseLookup)
{
this.Random = random;
this.Dir = dir;
this.InputMode = inputMode;
this.Pairs = pairs;
this.Outputs = outputs;
this.DoReverseLookup = doReverseLookup;
}
internal static string InputToString(int inputMode, IntsRef term)
{
return InputToString(inputMode, term, true);
}
internal static string InputToString(int inputMode, IntsRef term, bool isValidUnicode)
{
if (!isValidUnicode)
{
return term.ToString();
}
else if (inputMode == 0)
{
// utf8
return ToBytesRef(term).Utf8ToString() + " " + term;
}
else
{
// utf32
return UnicodeUtil.NewString(term.Ints, term.Offset, term.Length) + " " + term;
}
}
private static BytesRef ToBytesRef(IntsRef ir)
{
BytesRef br = new BytesRef(ir.Length);
for (int i = 0; i < ir.Length; i++)
{
int x = ir.Ints[ir.Offset + i];
Debug.Assert(x >= 0 && x <= 255);
br.Bytes[i] = (byte)x;
}
br.Length = ir.Length;
return br;
}
internal static string GetRandomString(Random random)
{
string term;
if (random.NextBoolean())
{
term = TestUtil.RandomRealisticUnicodeString(random);
}
else
{
// we want to mix in limited-alphabet symbols so
// we get more sharing of the nodes given how few
// terms we are testing...
term = SimpleRandomString(random);
}
return term;
}
internal static string SimpleRandomString(Random r)
{
int end = r.Next(10);
if (end == 0)
{
// allow 0 length
return "";
}
char[] buffer = new char[end];
for (int i = 0; i < end; i++)
{
buffer[i] = (char)TestUtil.NextInt(r, 97, 102);
}
return new string(buffer, 0, end);
}
internal static IntsRef ToIntsRef(string s, int inputMode)
{
return ToIntsRef(s, inputMode, new IntsRef(10));
}
internal static IntsRef ToIntsRef(string s, int inputMode, IntsRef ir)
{
if (inputMode == 0)
{
// utf8
return ToIntsRef(new BytesRef(s), ir);
}
else
{
// utf32
return ToIntsRefUTF32(s, ir);
}
}
internal static IntsRef ToIntsRefUTF32(string s, IntsRef ir)
{
int charLength = s.Length;
int charIdx = 0;
int intIdx = 0;
while (charIdx < charLength)
{
if (intIdx == ir.Ints.Length)
{
ir.Grow(intIdx + 1);
}
int utf32 = Character.CodePointAt(s, charIdx);
ir.Ints[intIdx] = utf32;
charIdx += Character.CharCount(utf32);
intIdx++;
}
ir.Length = intIdx;
return ir;
}
internal static IntsRef ToIntsRef(BytesRef br, IntsRef ir)
{
if (br.Length > ir.Ints.Length)
{
ir.Grow(br.Length);
}
for (int i = 0; i < br.Length; i++)
{
ir.Ints[i] = br.Bytes[br.Offset + i] & 0xFF;
}
ir.Length = br.Length;
return ir;
}
/// <summary>
/// Holds one input/output pair. </summary>
public class InputOutput<T1> : IComparable<InputOutput<T1>>
{
public readonly IntsRef Input;
public readonly T1 Output;
public InputOutput(IntsRef input, T1 output)
{
this.Input = input;
this.Output = output;
}
public virtual int CompareTo(InputOutput<T1> other)
{
return this.Input.CompareTo(other.Input);
}
}
public virtual void DoTest(bool testPruning)
{
// no pruning
DoTest(0, 0, true);
if (testPruning)
{
// simple pruning
DoTest(TestUtil.NextInt(Random, 1, 1 + Pairs.Count), 0, true);
// leafy pruning
DoTest(0, TestUtil.NextInt(Random, 1, 1 + Pairs.Count), true);
}
}
// runs the term, returning the output, or null if term
// isn't accepted. if prefixLength is non-null it must be
// length 1 int array; prefixLength[0] is set to the length
// of the term prefix that matches
private T Run(FST<T> fst, IntsRef term, int[] prefixLength)
{
Debug.Assert(prefixLength == null || prefixLength.Length == 1);
FST<T>.Arc<T> arc = fst.GetFirstArc(new FST.Arc<T>());
T NO_OUTPUT = fst.Outputs.NoOutput;
T output = NO_OUTPUT;
FST.BytesReader fstReader = fst.BytesReader;
for (int i = 0; i <= term.Length; i++)
{
int label;
if (i == term.Length)
{
label = FST<T>.END_LABEL;
}
else
{
label = term.Ints[term.Offset + i];
}
// System.out.println(" loop i=" + i + " label=" + label + " output=" + fst.Outputs.outputToString(output) + " curArc: target=" + arc.target + " isFinal?=" + arc.isFinal());
if (fst.FindTargetArc(label, arc, arc, fstReader) == null)
{
// System.out.println(" not found");
if (prefixLength != null)
{
prefixLength[0] = i;
return output;
}
else
{
return default(T);
}
}
output = fst.Outputs.Add(output, arc.Output);
}
if (prefixLength != null)
{
prefixLength[0] = term.Length;
}
return output;
}
private T RandomAcceptedWord(FST<T> fst, IntsRef @in)
{
FST.Arc<T> arc = fst.GetFirstArc(new FST.Arc<T>());
IList<FST.Arc<T>> arcs = new List<FST.Arc<T>>();
@in.Length = 0;
@in.Offset = 0;
T NO_OUTPUT = fst.Outputs.NoOutput;
T output = NO_OUTPUT;
FST.BytesReader fstReader = fst.BytesReader;
while (true)
{
// read all arcs:
fst.ReadFirstTargetArc(arc, arc, fstReader);
arcs.Add((new FST.Arc<T>()).CopyFrom(arc));
while (!arc.Last)
{
fst.ReadNextArc(arc, fstReader);
arcs.Add((new FST.Arc<T>()).CopyFrom(arc));
}
// pick one
arc = arcs[Random.Next(arcs.Count)];
arcs.Clear();
// accumulate output
output = fst.Outputs.Add(output, arc.Output);
// append label
if (arc.Label == FST<T>.END_LABEL)
{
break;
}
if (@in.Ints.Length == @in.Length)
{
@in.Grow(1 + @in.Length);
}
@in.Ints[@in.Length++] = arc.Label;
}
return output;
}
internal virtual FST<T> DoTest(int prune1, int prune2, bool allowRandomSuffixSharing)
{
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("\nTEST: prune1=" + prune1 + " prune2=" + prune2);
}
bool willRewrite = Random.NextBoolean();
Builder<T> builder = new Builder<T>(InputMode == 0 ? FST.INPUT_TYPE.BYTE1 : FST.INPUT_TYPE.BYTE4, prune1, prune2, prune1 == 0 && prune2 == 0, allowRandomSuffixSharing ? Random.NextBoolean() : true, allowRandomSuffixSharing ? TestUtil.NextInt(Random, 1, 10) : int.MaxValue, Outputs, null, willRewrite, PackedInts.DEFAULT, true, 15);
if (LuceneTestCase.VERBOSE)
{
if (willRewrite)
{
Console.WriteLine("TEST: packed FST");
}
else
{
Console.WriteLine("TEST: non-packed FST");
}
}
foreach (InputOutput<T> pair in Pairs)
{
if (pair.Output is IList)
{
IList<long> longValues = (IList<long>)pair.Output;
Builder<object> builderObject = builder as Builder<object>;
foreach (long value in longValues)
{
builderObject.Add(pair.Input, value);
}
}
else
{
builder.Add(pair.Input, pair.Output);
}
}
FST<T> fst = builder.Finish();
if (Random.NextBoolean() && fst != null && !willRewrite)
{
IOContext context = LuceneTestCase.NewIOContext(Random);
IndexOutput @out = Dir.CreateOutput("fst.bin", context);
fst.Save(@out);
@out.Dispose();
IndexInput @in = Dir.OpenInput("fst.bin", context);
try
{
fst = new FST<T>(@in, Outputs);
}
finally
{
@in.Dispose();
Dir.DeleteFile("fst.bin");
}
}
if (LuceneTestCase.VERBOSE && Pairs.Count <= 20 && fst != null)
{
TextWriter w = new StreamWriter(new FileStream("out.dot", FileMode.Open), IOUtils.CHARSET_UTF_8);
Util.toDot(fst, w, false, false);
w.Close();
Console.WriteLine("SAVED out.dot");
}
if (LuceneTestCase.VERBOSE)
{
if (fst == null)
{
Console.WriteLine(" fst has 0 nodes (fully pruned)");
}
else
{
Console.WriteLine(" fst has " + fst.NodeCount + " nodes and " + fst.ArcCount + " arcs");
}
}
if (prune1 == 0 && prune2 == 0)
{
VerifyUnPruned(InputMode, fst);
}
else
{
VerifyPruned(InputMode, fst, prune1, prune2);
}
return fst;
}
protected internal virtual bool OutputsEqual(T a, T b)
{
return a.Equals(b);
}
// FST is complete
private void VerifyUnPruned(int inputMode, FST<T> fst)
{
FST<long?> fstLong;
ISet<long?> validOutputs;
long minLong = long.MaxValue;
long maxLong = long.MinValue;
if (DoReverseLookup)
{
FST<long?> fstLong0 = fst as FST<long?>;
fstLong = fstLong0;
validOutputs = new HashSet<long?>();
foreach (InputOutput<T> pair in Pairs)
{
long? output = pair.Output as long?;
maxLong = Math.Max(maxLong, output.Value);
minLong = Math.Min(minLong, output.Value);
validOutputs.Add(output.Value);
}
}
else
{
fstLong = null;
validOutputs = null;
}
if (Pairs.Count == 0)
{
Assert.IsNull(fst);
return;
}
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("TEST: now verify " + Pairs.Count + " terms");
foreach (InputOutput<T> pair in Pairs)
{
Assert.IsNotNull(pair);
Assert.IsNotNull(pair.Input);
Assert.IsNotNull(pair.Output);
Console.WriteLine(" " + InputToString(inputMode, pair.Input) + ": " + Outputs.OutputToString(pair.Output));
}
}
Assert.IsNotNull(fst);
// visit valid pairs in order -- make sure all words
// are accepted, and FSTEnum's next() steps through
// them correctly
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("TEST: check valid terms/next()");
}
{
IntsRefFSTEnum<T> fstEnum = new IntsRefFSTEnum<T>(fst);
foreach (InputOutput<T> pair in Pairs)
{
IntsRef term = pair.Input;
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("TEST: check term=" + InputToString(inputMode, term) + " output=" + fst.Outputs.OutputToString(pair.Output));
}
T output = Run(fst, term, null);
Assert.IsNotNull(output, "term " + InputToString(inputMode, term) + " is not accepted");
Assert.IsTrue(OutputsEqual(pair.Output, output));
// verify enum's next
IntsRefFSTEnum<T>.InputOutput<T> t = fstEnum.Next();
Assert.IsNotNull(t);
Assert.AreEqual(term, t.Input, "expected input=" + InputToString(inputMode, term) + " but fstEnum returned " + InputToString(inputMode, t.Input));
Assert.IsTrue(OutputsEqual(pair.Output, t.Output));
}
Assert.IsNull(fstEnum.Next());
}
IDictionary<IntsRef, T> termsMap = new Dictionary<IntsRef, T>();
foreach (InputOutput<T> pair in Pairs)
{
termsMap[pair.Input] = pair.Output;
}
if (DoReverseLookup && maxLong > minLong)
{
// Do random lookups so we test null (output doesn't
// exist) case:
Assert.IsNull(Util.GetByOutput(fstLong, minLong - 7));
Assert.IsNull(Util.GetByOutput(fstLong, maxLong + 7));
int num = LuceneTestCase.AtLeast(Random, 100);
for (int iter = 0; iter < num; iter++)
{
long v = TestUtil.NextLong(Random, minLong, maxLong);
IntsRef input = Util.GetByOutput(fstLong, v);
Assert.IsTrue(validOutputs.Contains(v) || input == null);
}
}
// find random matching word and make sure it's valid
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("TEST: verify random accepted terms");
}
IntsRef scratch = new IntsRef(10);
int num_ = LuceneTestCase.AtLeast(Random, 500);
for (int iter = 0; iter < num_; iter++)
{
T output = RandomAcceptedWord(fst, scratch);
Assert.IsTrue(termsMap.ContainsKey(scratch), "accepted word " + InputToString(inputMode, scratch) + " is not valid");
Assert.IsTrue(OutputsEqual(termsMap[scratch], output));
if (DoReverseLookup)
{
//System.out.println("lookup output=" + output + " outs=" + fst.Outputs);
IntsRef input = Util.GetByOutput(fstLong, (output as long?).Value);
Assert.IsNotNull(input);
//System.out.println(" got " + Util.toBytesRef(input, new BytesRef()).utf8ToString());
Assert.AreEqual(scratch, input);
}
}
// test IntsRefFSTEnum.Seek:
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("TEST: verify seek");
}
IntsRefFSTEnum<T> fstEnum_ = new IntsRefFSTEnum<T>(fst);
num_ = LuceneTestCase.AtLeast(Random, 100);
for (int iter = 0; iter < num_; iter++)
{
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(" iter=" + iter);
}
if (Random.NextBoolean())
{
// seek to term that doesn't exist:
while (true)
{
IntsRef term = ToIntsRef(GetRandomString(Random), inputMode);
int pos = Pairs.BinarySearch(new InputOutput<T>(term, default(T)));
if (pos < 0)
{
pos = -(pos + 1);
// ok doesn't exist
//System.out.println(" seek " + inputToString(inputMode, term));
IntsRefFSTEnum<T>.InputOutput<T> seekResult;
if (Random.Next(3) == 0)
{
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(" do non-exist seekExact term=" + InputToString(inputMode, term));
}
seekResult = fstEnum_.SeekExact(term);
pos = -1;
}
else if (Random.NextBoolean())
{
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(" do non-exist seekFloor term=" + InputToString(inputMode, term));
}
seekResult = fstEnum_.SeekFloor(term);
pos--;
}
else
{
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(" do non-exist seekCeil term=" + InputToString(inputMode, term));
}
seekResult = fstEnum_.SeekCeil(term);
}
if (pos != -1 && pos < Pairs.Count)
{
//System.out.println(" got " + inputToString(inputMode,seekResult.input) + " output=" + fst.Outputs.outputToString(seekResult.Output));
Assert.IsNotNull(seekResult, "got null but expected term=" + InputToString(inputMode, Pairs[pos].Input));
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(" got " + InputToString(inputMode, seekResult.Input));
}
Assert.AreEqual(Pairs[pos].Input, seekResult.Input, "expected " + InputToString(inputMode, Pairs[pos].Input) + " but got " + InputToString(inputMode, seekResult.Input));
Assert.IsTrue(OutputsEqual(Pairs[pos].Output, seekResult.Output));
}
else
{
// seeked before start or beyond end
//System.out.println("seek=" + seekTerm);
Assert.IsNull(seekResult, "expected null but got " + (seekResult == null ? "null" : InputToString(inputMode, seekResult.Input)));
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(" got null");
}
}
break;
}
}
}
else
{
// seek to term that does exist:
InputOutput<T> pair = Pairs[Random.Next(Pairs.Count)];
IntsRefFSTEnum<T>.InputOutput<T> seekResult;
if (Random.Next(3) == 2)
{
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(" do exists seekExact term=" + InputToString(inputMode, pair.Input));
}
seekResult = fstEnum_.SeekExact(pair.Input);
}
else if (Random.NextBoolean())
{
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(" do exists seekFloor " + InputToString(inputMode, pair.Input));
}
seekResult = fstEnum_.SeekFloor(pair.Input);
}
else
{
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(" do exists seekCeil " + InputToString(inputMode, pair.Input));
}
seekResult = fstEnum_.SeekCeil(pair.Input);
}
Assert.IsNotNull(seekResult);
Assert.AreEqual(pair.Input, seekResult.Input, "got " + InputToString(inputMode, seekResult.Input) + " but expected " + InputToString(inputMode, pair.Input));
Assert.IsTrue(OutputsEqual(pair.Output, seekResult.Output));
}
}
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("TEST: mixed next/seek");
}
// test mixed next/seek
num_ = LuceneTestCase.AtLeast(Random, 100);
for (int iter = 0; iter < num_; iter++)
{
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("TEST: iter " + iter);
}
// reset:
fstEnum_ = new IntsRefFSTEnum<T>(fst);
int upto = -1;
while (true)
{
bool isDone = false;
if (upto == Pairs.Count - 1 || Random.NextBoolean())
{
// next
upto++;
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(" do next");
}
isDone = fstEnum_.Next() == null;
}
else if (upto != -1 && upto < 0.75 * Pairs.Count && Random.NextBoolean())
{
int attempt = 0;
for (; attempt < 10; attempt++)
{
IntsRef term = ToIntsRef(GetRandomString(Random), inputMode);
if (!termsMap.ContainsKey(term) && term.CompareTo(Pairs[upto].Input) > 0)
{
int pos = Pairs.BinarySearch(new InputOutput<T>(term, default(T)));
Debug.Assert(pos < 0);
upto = -(pos + 1);
if (Random.NextBoolean())
{
upto--;
Assert.IsTrue(upto != -1);
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(" do non-exist seekFloor(" + InputToString(inputMode, term) + ")");
}
isDone = fstEnum_.SeekFloor(term) == null;
}
else
{
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(" do non-exist seekCeil(" + InputToString(inputMode, term) + ")");
}
isDone = fstEnum_.SeekCeil(term) == null;
}
break;
}
}
if (attempt == 10)
{
continue;
}
}
else
{
int inc = Random.Next(Pairs.Count - upto - 1);
upto += inc;
if (upto == -1)
{
upto = 0;
}
if (Random.NextBoolean())
{
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(" do seekCeil(" + InputToString(inputMode, Pairs[upto].Input) + ")");
}
isDone = fstEnum_.SeekCeil(Pairs[upto].Input) == null;
}
else
{
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(" do seekFloor(" + InputToString(inputMode, Pairs[upto].Input) + ")");
}
isDone = fstEnum_.SeekFloor(Pairs[upto].Input) == null;
}
}
if (LuceneTestCase.VERBOSE)
{
if (!isDone)
{
Console.WriteLine(" got " + InputToString(inputMode, fstEnum_.Current().Input));
}
else
{
Console.WriteLine(" got null");
}
}
if (upto == Pairs.Count)
{
Assert.IsTrue(isDone);
break;
}
else
{
Assert.IsFalse(isDone);
Assert.AreEqual(Pairs[upto].Input, fstEnum_.Current().Input);
Assert.IsTrue(OutputsEqual(Pairs[upto].Output, fstEnum_.Current().Output));
/*
if (upto < pairs.size()-1) {
int tryCount = 0;
while(tryCount < 10) {
final IntsRef t = toIntsRef(getRandomString(), inputMode);
if (pairs.get(upto).input.compareTo(t) < 0) {
final boolean expected = t.compareTo(pairs.get(upto+1).input) < 0;
if (LuceneTestCase.VERBOSE) {
System.out.println("TEST: call beforeNext(" + inputToString(inputMode, t) + "); current=" + inputToString(inputMode, pairs.get(upto).input) + " next=" + inputToString(inputMode, pairs.get(upto+1).input) + " expected=" + expected);
}
Assert.AreEqual(expected, fstEnum.beforeNext(t));
break;
}
tryCount++;
}
}
*/
}
}
}
}
private class CountMinOutput<S>
{
internal int Count;
internal S Output;
internal S FinalOutput;
internal bool IsLeaf = true;
internal bool IsFinal;
}
// FST is pruned
private void VerifyPruned(int inputMode, FST<T> fst, int prune1, int prune2)
{
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("TEST: now verify pruned " + Pairs.Count + " terms; outputs=" + Outputs);
foreach (InputOutput<T> pair in Pairs)
{
Console.WriteLine(" " + InputToString(inputMode, pair.Input) + ": " + Outputs.OutputToString(pair.Output));
}
}
// To validate the FST, we brute-force compute all prefixes
// in the terms, matched to their "common" outputs, prune that
// set according to the prune thresholds, then assert the FST
// matches that same set.
// NOTE: Crazy RAM intensive!!
//System.out.println("TEST: tally prefixes");
// build all prefixes
IDictionary<IntsRef, CountMinOutput<T>> prefixes = new Dictionary<IntsRef, CountMinOutput<T>>();
IntsRef scratch = new IntsRef(10);
foreach (InputOutput<T> pair in Pairs)
{
scratch.CopyInts(pair.Input);
for (int idx = 0; idx <= pair.Input.Length; idx++)
{
scratch.Length = idx;
CountMinOutput<T> cmo = prefixes[scratch];
if (cmo == null)
{
cmo = new CountMinOutput<T>();
cmo.Count = 1;
cmo.Output = pair.Output;
prefixes[IntsRef.DeepCopyOf(scratch)] = cmo;
}
else
{
cmo.Count++;
T output1 = cmo.Output;
if (output1.Equals(Outputs.NoOutput))
{
output1 = Outputs.NoOutput;
}
T output2 = pair.Output;
if (output2.Equals(Outputs.NoOutput))
{
output2 = Outputs.NoOutput;
}
cmo.Output = Outputs.Common(output1, output2);
}
if (idx == pair.Input.Length)
{
cmo.IsFinal = true;
cmo.FinalOutput = cmo.Output;
}
}
}
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("TEST: now prune");
}
// prune 'em
IEnumerator<KeyValuePair<IntsRef, CountMinOutput<T>>> it = prefixes.GetEnumerator();
while (it.MoveNext())
{
KeyValuePair<IntsRef, CountMinOutput<T>> ent = it.Current;
IntsRef prefix = ent.Key;
CountMinOutput<T> cmo = ent.Value;
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(" term prefix=" + InputToString(inputMode, prefix, false) + " count=" + cmo.Count + " isLeaf=" + cmo.IsLeaf + " output=" + Outputs.OutputToString(cmo.Output) + " isFinal=" + cmo.IsFinal);
}
bool keep;
if (prune1 > 0)
{
keep = cmo.Count >= prune1;
}
else
{
Debug.Assert(prune2 > 0);
if (prune2 > 1 && cmo.Count >= prune2)
{
keep = true;
}
else if (prefix.Length > 0)
{
// consult our parent
scratch.Length = prefix.Length - 1;
Array.Copy(prefix.Ints, prefix.Offset, scratch.Ints, 0, scratch.Length);
CountMinOutput<T> cmo2 = prefixes[scratch];
//System.out.println(" parent count = " + (cmo2 == null ? -1 : cmo2.count));
keep = cmo2 != null && ((prune2 > 1 && cmo2.Count >= prune2) || (prune2 == 1 && (cmo2.Count >= 2 || prefix.Length <= 1)));
}
else if (cmo.Count >= prune2)
{
keep = true;
}
else
{
keep = false;
}
}
if (!keep)
{
it.Reset();
//System.out.println(" remove");
}
else
{
// clear isLeaf for all ancestors
//System.out.println(" keep");
scratch.CopyInts(prefix);
scratch.Length--;
while (scratch.Length >= 0)
{
CountMinOutput<T> cmo2 = prefixes[scratch];
if (cmo2 != null)
{
//System.out.println(" clear isLeaf " + inputToString(inputMode, scratch));
cmo2.IsLeaf = false;
}
scratch.Length--;
}
}
}
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("TEST: after prune");
foreach (KeyValuePair<IntsRef, CountMinOutput<T>> ent in prefixes)
{
Console.WriteLine(" " + InputToString(inputMode, ent.Key, false) + ": isLeaf=" + ent.Value.IsLeaf + " isFinal=" + ent.Value.IsFinal);
if (ent.Value.IsFinal)
{
Console.WriteLine(" finalOutput=" + Outputs.OutputToString(ent.Value.FinalOutput));
}
}
}
if (prefixes.Count <= 1)
{
Assert.IsNull(fst);
return;
}
Assert.IsNotNull(fst);
// make sure FST only enums valid prefixes
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("TEST: check pruned enum");
}
IntsRefFSTEnum<T> fstEnum = new IntsRefFSTEnum<T>(fst);
IntsRefFSTEnum<T>.InputOutput<T> current;
while ((current = fstEnum.Next()) != null)
{
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(" fstEnum.next prefix=" + InputToString(inputMode, current.Input, false) + " output=" + Outputs.OutputToString(current.Output));
}
CountMinOutput<T> cmo = prefixes[current.Input];
Assert.IsNotNull(cmo);
Assert.IsTrue(cmo.IsLeaf || cmo.IsFinal);
//if (cmo.isFinal && !cmo.isLeaf) {
if (cmo.IsFinal)
{
Assert.AreEqual(cmo.FinalOutput, current.Output);
}
else
{
Assert.AreEqual(cmo.Output, current.Output);
}
}
// make sure all non-pruned prefixes are present in the FST
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("TEST: verify all prefixes");
}
int[] stopNode = new int[1];
foreach (KeyValuePair<IntsRef, CountMinOutput<T>> ent in prefixes)
{
if (ent.Key.Length > 0)
{
CountMinOutput<T> cmo = ent.Value;
T output = Run(fst, ent.Key, stopNode);
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("TEST: verify prefix=" + InputToString(inputMode, ent.Key, false) + " output=" + Outputs.OutputToString(cmo.Output));
}
// if (cmo.isFinal && !cmo.isLeaf) {
if (cmo.IsFinal)
{
Assert.AreEqual(cmo.FinalOutput, output);
}
else
{
Assert.AreEqual(cmo.Output, output);
}
Assert.AreEqual(ent.Key.Length, stopNode[0]);
}
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: Variant
**
**
** Purpose: The CLR implementation of Variant.
**
**
===========================================================*/
namespace System {
using System;
using System.Reflection;
using System.Threading;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
[Serializable]
[StructLayout(LayoutKind.Sequential)]
internal struct Variant {
//Do Not change the order of these fields.
//They are mapped to the native VariantData * data structure.
private Object m_objref;
private int m_data1;
private int m_data2;
private int m_flags;
// The following bits have been taken up as follows
// bits 0-15 - Type code
// bit 16 - Array
// bits 19-23 - Enums
// bits 24-31 - Optional VT code (for roundtrip VT preservation)
//What are the consequences of making this an enum?
///////////////////////////////////////////////////////////////////////
// If you update this, update the corresponding stuff in OAVariantLib.cs,
// COMOAVariant.cpp (2 tables, forwards and reverse), and perhaps OleVariant.h
///////////////////////////////////////////////////////////////////////
internal const int CV_EMPTY=0x0;
internal const int CV_VOID=0x1;
internal const int CV_BOOLEAN=0x2;
internal const int CV_CHAR=0x3;
internal const int CV_I1=0x4;
internal const int CV_U1=0x5;
internal const int CV_I2=0x6;
internal const int CV_U2=0x7;
internal const int CV_I4=0x8;
internal const int CV_U4=0x9;
internal const int CV_I8=0xa;
internal const int CV_U8=0xb;
internal const int CV_R4=0xc;
internal const int CV_R8=0xd;
internal const int CV_STRING=0xe;
internal const int CV_PTR=0xf;
internal const int CV_DATETIME = 0x10;
internal const int CV_TIMESPAN = 0x11;
internal const int CV_OBJECT=0x12;
internal const int CV_DECIMAL = 0x13;
internal const int CV_ENUM=0x15;
internal const int CV_MISSING=0x16;
internal const int CV_NULL=0x17;
internal const int CV_LAST=0x18;
internal const int TypeCodeBitMask=0xffff;
internal const int VTBitMask=unchecked((int)0xff000000);
internal const int VTBitShift=24;
internal const int ArrayBitMask =0x10000;
// Enum enum and Mask
internal const int EnumI1 =0x100000;
internal const int EnumU1 =0x200000;
internal const int EnumI2 =0x300000;
internal const int EnumU2 =0x400000;
internal const int EnumI4 =0x500000;
internal const int EnumU4 =0x600000;
internal const int EnumI8 =0x700000;
internal const int EnumU8 =0x800000;
internal const int EnumMask =0xF00000;
internal static readonly Type [] ClassTypes = {
typeof(System.Empty),
typeof(void),
typeof(Boolean),
typeof(Char),
typeof(SByte),
typeof(Byte),
typeof(Int16),
typeof(UInt16),
typeof(Int32),
typeof(UInt32),
typeof(Int64),
typeof(UInt64),
typeof(Single),
typeof(Double),
typeof(String),
typeof(void), // ptr for the moment
typeof(DateTime),
typeof(TimeSpan),
typeof(Object),
typeof(Decimal),
typeof(Object), // Treat enum as Object
typeof(System.Reflection.Missing),
typeof(System.DBNull),
};
internal static readonly Variant Empty = new Variant();
internal static readonly Variant Missing = new Variant(Variant.CV_MISSING, Type.Missing, 0, 0);
internal static readonly Variant DBNull = new Variant(Variant.CV_NULL, System.DBNull.Value, 0, 0);
//
// Native Methods
//
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern double GetR8FromVar();
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern float GetR4FromVar();
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void SetFieldsR4(float val);
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void SetFieldsR8(double val);
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void SetFieldsObject(Object val);
// Use this function instead of an ECALL - saves about 150 clock cycles
// by avoiding the ecall transition and because the JIT inlines this.
// Ends up only taking about 1/8 the time of the ECALL version.
internal long GetI8FromVar()
{
return ((long)m_data2<<32 | ((long)m_data1 & 0xFFFFFFFFL));
}
//
// Constructors
//
internal Variant(int flags, Object or, int data1, int data2) {
m_flags = flags;
m_objref=or;
m_data1=data1;
m_data2=data2;
}
public Variant(bool val) {
m_objref= null;
m_flags = CV_BOOLEAN;
m_data1 = (val)?Boolean.True:Boolean.False;
m_data2 = 0;
}
public Variant(sbyte val) {
m_objref=null;
m_flags=CV_I1;
m_data1=(int)val;
m_data2=(int)(((long)val)>>32);
}
public Variant(byte val) {
m_objref=null;
m_flags=CV_U1;
m_data1=(int)val;
m_data2=0;
}
public Variant(short val) {
m_objref=null;
m_flags=CV_I2;
m_data1=(int)val;
m_data2=(int)(((long)val)>>32);
}
public Variant(ushort val) {
m_objref=null;
m_flags=CV_U2;
m_data1=(int)val;
m_data2=0;
}
public Variant(char val) {
m_objref=null;
m_flags=CV_CHAR;
m_data1=(int)val;
m_data2=0;
}
public Variant(int val) {
m_objref=null;
m_flags=CV_I4;
m_data1=val;
m_data2=val >> 31;
}
public Variant(uint val) {
m_objref=null;
m_flags=CV_U4;
m_data1=(int)val;
m_data2=0;
}
public Variant(long val) {
m_objref=null;
m_flags=CV_I8;
m_data1 = (int)val;
m_data2 = (int)(val >> 32);
}
public Variant(ulong val) {
m_objref=null;
m_flags=CV_U8;
m_data1 = (int)val;
m_data2 = (int)(val >> 32);
}
[System.Security.SecuritySafeCritical] // auto-generated
public Variant(float val) {
m_objref=null;
m_flags=CV_R4;
m_data1=0;
m_data2=0;
SetFieldsR4(val);
}
[System.Security.SecurityCritical] // auto-generated
public Variant(double val) {
m_objref=null;
m_flags=CV_R8;
m_data1=0;
m_data2=0;
SetFieldsR8(val);
}
public Variant(DateTime val) {
m_objref=null;
m_flags=CV_DATETIME;
ulong ticks = (ulong)val.Ticks;
m_data1 = (int)ticks;
m_data2 = (int)(ticks>>32);
}
public Variant(Decimal val) {
m_objref = (Object)val;
m_flags = CV_DECIMAL;
m_data1=0;
m_data2=0;
}
[System.Security.SecuritySafeCritical] // auto-generated
public Variant(Object obj) {
m_data1=0;
m_data2=0;
VarEnum vt = VarEnum.VT_EMPTY;
if (obj is DateTime) {
m_objref=null;
m_flags=CV_DATETIME;
ulong ticks = (ulong)((DateTime)obj).Ticks;
m_data1 = (int)ticks;
m_data2 = (int)(ticks>>32);
return;
}
if (obj is String) {
m_flags=CV_STRING;
m_objref=obj;
return;
}
if (obj == null) {
this = Empty;
return;
}
if (obj == System.DBNull.Value) {
this = DBNull;
return;
}
if (obj == Type.Missing) {
this = Missing;
return;
}
if (obj is Array) {
m_flags=CV_OBJECT | ArrayBitMask;
m_objref=obj;
return;
}
// Compiler appeasement
m_flags = CV_EMPTY;
m_objref = null;
// Check to see if the object passed in is a wrapper object.
if (obj is UnknownWrapper)
{
vt = VarEnum.VT_UNKNOWN;
obj = ((UnknownWrapper)obj).WrappedObject;
}
else if (obj is DispatchWrapper)
{
vt = VarEnum.VT_DISPATCH;
obj = ((DispatchWrapper)obj).WrappedObject;
}
else if (obj is ErrorWrapper)
{
vt = VarEnum.VT_ERROR;
obj = (Object)(((ErrorWrapper)obj).ErrorCode);
Contract.Assert(obj != null, "obj != null");
}
else if (obj is CurrencyWrapper)
{
vt = VarEnum.VT_CY;
obj = (Object)(((CurrencyWrapper)obj).WrappedObject);
Contract.Assert(obj != null, "obj != null");
}
else if (obj is BStrWrapper)
{
vt = VarEnum.VT_BSTR;
obj = (Object)(((BStrWrapper)obj).WrappedObject);
}
if (obj != null)
{
SetFieldsObject(obj);
}
// If the object passed in is one of the wrappers then set the VARIANT type.
if (vt != VarEnum.VT_EMPTY)
m_flags |= ((int)vt << VTBitShift);
}
[System.Security.SecurityCritical] // auto-generated
unsafe public Variant(void* voidPointer,Type pointerType) {
if (pointerType == null)
throw new ArgumentNullException("pointerType");
if (!pointerType.IsPointer)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),"pointerType");
Contract.EndContractBlock();
m_objref = pointerType;
m_flags=CV_PTR;
m_data1=(int)voidPointer;
m_data2=0;
}
//This is a family-only accessor for the CVType.
//This is never to be exposed externally.
internal int CVType {
get {
return (m_flags&TypeCodeBitMask);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public Object ToObject() {
switch (CVType) {
case CV_EMPTY:
return null;
case CV_BOOLEAN:
return (Object)(m_data1!=0);
case CV_I1:
return (Object)((sbyte)m_data1);
case CV_U1:
return (Object)((byte)m_data1);
case CV_CHAR:
return (Object)((char)m_data1);
case CV_I2:
return (Object)((short)m_data1);
case CV_U2:
return (Object)((ushort)m_data1);
case CV_I4:
return (Object)(m_data1);
case CV_U4:
return (Object)((uint)m_data1);
case CV_I8:
return (Object)(GetI8FromVar());
case CV_U8:
return (Object)((ulong)GetI8FromVar());
case CV_R4:
return (Object)(GetR4FromVar());
case CV_R8:
return (Object)(GetR8FromVar());
case CV_DATETIME:
return new DateTime(GetI8FromVar());
case CV_TIMESPAN:
return new TimeSpan(GetI8FromVar());
case CV_ENUM:
return BoxEnum();
case CV_MISSING:
return Type.Missing;
case CV_NULL:
return System.DBNull.Value;
case CV_DECIMAL:
case CV_STRING:
case CV_OBJECT:
default:
return m_objref;
}
}
// This routine will return an boxed enum.
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern Object BoxEnum();
// Helper code for marshaling managed objects to VARIANT's (we use
// managed variants as an intermediate type.
[System.Security.SecuritySafeCritical] // auto-generated
internal static void MarshalHelperConvertObjectToVariant(Object o, ref Variant v)
{
#if FEATURE_REMOTING
IConvertible ic = System.Runtime.Remoting.RemotingServices.IsTransparentProxy(o) ? null : o as IConvertible;
#else
IConvertible ic = o as IConvertible;
#endif
if (o == null)
{
v = Empty;
}
else if (ic == null)
{
// This path should eventually go away. But until
// the work is done to have all of our wrapper types implement
// IConvertible, this is a cheapo way to get the work done.
v = new Variant(o);
}
else
{
IFormatProvider provider = CultureInfo.InvariantCulture;
switch (ic.GetTypeCode())
{
case TypeCode.Empty:
v = Empty;
break;
case TypeCode.Object:
v = new Variant((Object)o);
break;
case TypeCode.DBNull:
v = DBNull;
break;
case TypeCode.Boolean:
v = new Variant(ic.ToBoolean(provider));
break;
case TypeCode.Char:
v = new Variant(ic.ToChar(provider));
break;
case TypeCode.SByte:
v = new Variant(ic.ToSByte(provider));
break;
case TypeCode.Byte:
v = new Variant(ic.ToByte(provider));
break;
case TypeCode.Int16:
v = new Variant(ic.ToInt16(provider));
break;
case TypeCode.UInt16:
v = new Variant(ic.ToUInt16(provider));
break;
case TypeCode.Int32:
v = new Variant(ic.ToInt32(provider));
break;
case TypeCode.UInt32:
v = new Variant(ic.ToUInt32(provider));
break;
case TypeCode.Int64:
v = new Variant(ic.ToInt64(provider));
break;
case TypeCode.UInt64:
v = new Variant(ic.ToUInt64(provider));
break;
case TypeCode.Single:
v = new Variant(ic.ToSingle(provider));
break;
case TypeCode.Double:
v = new Variant(ic.ToDouble(provider));
break;
case TypeCode.Decimal:
v = new Variant(ic.ToDecimal(provider));
break;
case TypeCode.DateTime:
v = new Variant(ic.ToDateTime(provider));
break;
case TypeCode.String:
v = new Variant(ic.ToString(provider));
break;
default:
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnknownTypeCode", ic.GetTypeCode()));
}
}
}
// Helper code for marshaling VARIANTS to managed objects (we use
// managed variants as an intermediate type.
internal static Object MarshalHelperConvertVariantToObject(ref Variant v)
{
return v.ToObject();
}
// Helper code: on the back propagation path where a VT_BYREF VARIANT*
// is marshaled to a "ref Object", we use this helper to force the
// updated object back to the original type.
[System.Security.SecurityCritical] // auto-generated
internal static void MarshalHelperCastVariant(Object pValue, int vt, ref Variant v)
{
IConvertible iv = pValue as IConvertible;
if (iv == null)
{
switch (vt)
{
case 9: /*VT_DISPATCH*/
v = new Variant(new DispatchWrapper(pValue));
break;
case 12: /*VT_VARIANT*/
v = new Variant(pValue);
break;
case 13: /*VT_UNKNOWN*/
v = new Variant(new UnknownWrapper(pValue));
break;
case 36: /*VT_RECORD*/
v = new Variant(pValue);
break;
case 8: /*VT_BSTR*/
if (pValue == null)
{
v = new Variant(null);
v.m_flags = CV_STRING;
}
else
{
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCoerceByRefVariant"));
}
break;
default:
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCoerceByRefVariant"));
}
}
else
{
IFormatProvider provider = CultureInfo.InvariantCulture;
switch (vt)
{
case 0: /*VT_EMPTY*/
v = Empty;
break;
case 1: /*VT_NULL*/
v = DBNull;
break;
case 2: /*VT_I2*/
v = new Variant(iv.ToInt16(provider));
break;
case 3: /*VT_I4*/
v = new Variant(iv.ToInt32(provider));
break;
case 4: /*VT_R4*/
v = new Variant(iv.ToSingle(provider));
break;
case 5: /*VT_R8*/
v = new Variant(iv.ToDouble(provider));
break;
case 6: /*VT_CY*/
v = new Variant(new CurrencyWrapper(iv.ToDecimal(provider)));
break;
case 7: /*VT_DATE*/
v = new Variant(iv.ToDateTime(provider));
break;
case 8: /*VT_BSTR*/
v = new Variant(iv.ToString(provider));
break;
case 9: /*VT_DISPATCH*/
v = new Variant(new DispatchWrapper((Object)iv));
break;
case 10: /*VT_ERROR*/
v = new Variant(new ErrorWrapper(iv.ToInt32(provider)));
break;
case 11: /*VT_BOOL*/
v = new Variant(iv.ToBoolean(provider));
break;
case 12: /*VT_VARIANT*/
v = new Variant((Object)iv);
break;
case 13: /*VT_UNKNOWN*/
v = new Variant(new UnknownWrapper((Object)iv));
break;
case 14: /*VT_DECIMAL*/
v = new Variant(iv.ToDecimal(provider));
break;
// case 15: /*unused*/
// NOT SUPPORTED
case 16: /*VT_I1*/
v = new Variant(iv.ToSByte(provider));
break;
case 17: /*VT_UI1*/
v = new Variant(iv.ToByte(provider));
break;
case 18: /*VT_UI2*/
v = new Variant(iv.ToUInt16(provider));
break;
case 19: /*VT_UI4*/
v = new Variant(iv.ToUInt32(provider));
break;
case 20: /*VT_I8*/
v = new Variant(iv.ToInt64(provider));
break;
case 21: /*VT_UI8*/
v = new Variant(iv.ToUInt64(provider));
break;
case 22: /*VT_INT*/
v = new Variant(iv.ToInt32(provider));
break;
case 23: /*VT_UINT*/
v = new Variant(iv.ToUInt32(provider));
break;
default:
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCoerceByRefVariant"));
}
}
}
}
}
| |
// Copyright 2019 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
//
// 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 Google.Api.Ads.AdManager.Lib;
using Google.Api.Ads.AdManager.Util.v202108;
using Google.Api.Ads.AdManager.v202108;
using System;
namespace Google.Api.Ads.AdManager.Examples.CSharp.v202108
{
/// <summary>
/// This code example creates new line items. To determine which line items
/// exist, run GetAllLineItems.cs. To determine which orders exist, run
/// GetAllOrders.cs. To determine which placements exist, run
/// GetAllPlacements.cs. To determine the IDs for locations, run
/// GetGeoTargets.cs
/// </summary>
public class CreateLineItems : SampleBase
{
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description
{
get
{
return "This code example creates new line items. To determine which line items " +
"exist, run GetAllLineItems.cs. To determine which orders exist, " +
"run GetAllOrders.cs. To determine which placements exist, " +
"run GetAllPlacements.cs. To determine the IDs for locations, " +
"run GetGeoTargets.cs.";
}
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
public static void Main()
{
CreateLineItems codeExample = new CreateLineItems();
Console.WriteLine(codeExample.Description);
codeExample.Run(new AdManagerUser());
}
/// <summary>
/// Run the code examples.
/// </summary>
public void Run(AdManagerUser user)
{
using (LineItemService lineItemService = user.GetService<LineItemService>())
{
// Set the order that all created line items will belong to and the
// placement ID to target.
long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));
long[] targetPlacementIds = new long[]
{
long.Parse(_T("INSERT_PLACEMENT_ID_HERE"))
};
// Create inventory targeting.
InventoryTargeting inventoryTargeting = new InventoryTargeting();
inventoryTargeting.targetedPlacementIds = targetPlacementIds;
// Create geographical targeting.
GeoTargeting geoTargeting = new GeoTargeting();
// Include the US and Quebec, Canada.
Location countryLocation = new Location();
countryLocation.id = 2840L;
Location regionLocation = new Location();
regionLocation.id = 20123L;
geoTargeting.targetedLocations = new Location[]
{
countryLocation,
regionLocation
};
Location postalCodeLocation = new Location();
postalCodeLocation.id = 9000093;
// Exclude Chicago and the New York metro area.
Location cityLocation = new Location();
cityLocation.id = 1016367L;
Location metroLocation = new Location();
metroLocation.id = 200501L;
geoTargeting.excludedLocations = new Location[]
{
cityLocation,
metroLocation
};
// Exclude domains that are not under the network's control.
UserDomainTargeting userDomainTargeting = new UserDomainTargeting();
userDomainTargeting.domains = new String[]
{
"usa.gov"
};
userDomainTargeting.targeted = false;
// Create day-part targeting.
DayPartTargeting dayPartTargeting = new DayPartTargeting();
dayPartTargeting.timeZone = DeliveryTimeZone.BROWSER;
// Target only the weekend in the browser's timezone.
DayPart saturdayDayPart = new DayPart();
saturdayDayPart.dayOfWeek = Google.Api.Ads.AdManager.v202108.DayOfWeek.SATURDAY;
saturdayDayPart.startTime = new TimeOfDay();
saturdayDayPart.startTime.hour = 0;
saturdayDayPart.startTime.minute = MinuteOfHour.ZERO;
saturdayDayPart.endTime = new TimeOfDay();
saturdayDayPart.endTime.hour = 24;
saturdayDayPart.endTime.minute = MinuteOfHour.ZERO;
DayPart sundayDayPart = new DayPart();
sundayDayPart.dayOfWeek = Google.Api.Ads.AdManager.v202108.DayOfWeek.SUNDAY;
sundayDayPart.startTime = new TimeOfDay();
sundayDayPart.startTime.hour = 0;
sundayDayPart.startTime.minute = MinuteOfHour.ZERO;
sundayDayPart.endTime = new TimeOfDay();
sundayDayPart.endTime.hour = 24;
sundayDayPart.endTime.minute = MinuteOfHour.ZERO;
dayPartTargeting.dayParts = new DayPart[]
{
saturdayDayPart,
sundayDayPart
};
// Create technology targeting.
TechnologyTargeting technologyTargeting = new TechnologyTargeting();
// Create browser targeting.
BrowserTargeting browserTargeting = new BrowserTargeting();
browserTargeting.isTargeted = true;
// Target just the Chrome browser.
Technology browserTechnology = new Technology();
browserTechnology.id = 500072L;
browserTargeting.browsers = new Technology[]
{
browserTechnology
};
technologyTargeting.browserTargeting = browserTargeting;
// Create an array to store local line item objects.
LineItem[] lineItems = new LineItem[5];
for (int i = 0; i < 5; i++)
{
LineItem lineItem = new LineItem();
lineItem.name = "Line item #" + i;
lineItem.orderId = orderId;
lineItem.targeting = new Targeting();
lineItem.targeting.inventoryTargeting = inventoryTargeting;
lineItem.targeting.geoTargeting = geoTargeting;
lineItem.targeting.userDomainTargeting = userDomainTargeting;
lineItem.targeting.dayPartTargeting = dayPartTargeting;
lineItem.targeting.technologyTargeting = technologyTargeting;
lineItem.lineItemType = LineItemType.STANDARD;
lineItem.allowOverbook = true;
// Set the creative rotation type to even.
lineItem.creativeRotationType = CreativeRotationType.EVEN;
// Set the size of creatives that can be associated with this line item.
Size size = new Size();
size.width = 300;
size.height = 250;
size.isAspectRatio = false;
// Create the creative placeholder.
CreativePlaceholder creativePlaceholder = new CreativePlaceholder();
creativePlaceholder.size = size;
lineItem.creativePlaceholders = new CreativePlaceholder[]
{
creativePlaceholder
};
// Set the line item to run for one month.
lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
lineItem.endDateTime =
DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1),
"America/New_York");
// Set the cost per unit to $2.
lineItem.costType = CostType.CPM;
lineItem.costPerUnit = new Money();
lineItem.costPerUnit.currencyCode = "USD";
lineItem.costPerUnit.microAmount = 2000000L;
// Set the number of units bought to 500,000 so that the budget is
// $1,000.
Goal goal = new Goal();
goal.goalType = GoalType.LIFETIME;
goal.unitType = UnitType.IMPRESSIONS;
goal.units = 500000L;
lineItem.primaryGoal = goal;
lineItems[i] = lineItem;
}
try
{
// Create the line items on the server.
lineItems = lineItemService.createLineItems(lineItems);
if (lineItems != null)
{
foreach (LineItem lineItem in lineItems)
{
Console.WriteLine(
"A line item with ID \"{0}\", belonging to order ID \"{1}\", and" +
" named \"{2}\" was created.", lineItem.id, lineItem.orderId,
lineItem.name);
}
}
else
{
Console.WriteLine("No line items created.");
}
}
catch (Exception e)
{
Console.WriteLine("Failed to create line items. Exception says \"{0}\"",
e.Message);
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Text;
namespace System
{
public class RandomDataGenerator
{
private Random _rand = new Random();
private int? _seed = null;
public int? Seed
{
get { return _seed; }
set
{
if (!_seed.HasValue && value.HasValue)
{
_seed = value;
_rand = new Random(value.Value);
}
}
}
// returns a byte array of random data
public void GetBytes(int newSeed, byte[] buffer)
{
Seed = newSeed;
GetBytes(buffer);
}
public void GetBytes(byte[] buffer)
{
_rand.NextBytes(buffer);
}
// returns a non-negative Int64 between 0 and Int64.MaxValue
public long GetInt64(int newSeed)
{
Seed = newSeed;
return GetInt64();
}
public long GetInt64()
{
byte[] buffer = new byte[8];
GetBytes(buffer);
long result = BitConverter.ToInt64(buffer, 0);
return result != long.MinValue ? Math.Abs(result) : long.MaxValue;
}
// returns a non-negative Int32 between 0 and Int32.MaxValue
public int GetInt32(int new_seed)
{
Seed = new_seed;
return GetInt32();
}
public int GetInt32()
{
return _rand.Next();
}
// returns a non-negative Int16 between 0 and Int16.MaxValue
public short GetInt16(int new_seed)
{
Seed = new_seed;
return GetInt16();
}
public short GetInt16()
{
return (short)_rand.Next(1 + short.MaxValue);
}
// returns a non-negative Byte between 0 and Byte.MaxValue
public byte GetByte(int new_seed)
{
Seed = new_seed;
return GetByte();
}
public byte GetByte()
{
return (byte)_rand.Next(1 + byte.MaxValue);
}
// returns a non-negative Double between 0.0 and 1.0
public double GetDouble(int new_seed)
{
Seed = new_seed;
return GetDouble();
}
public double GetDouble()
{
return _rand.NextDouble();
}
// returns a non-negative Single between 0.0 and 1.0
public float GetSingle(int newSeed)
{
Seed = newSeed;
return GetSingle();
}
public float GetSingle()
{
return (float)_rand.NextDouble();
}
// returns a valid char that is a letter
public char GetCharLetter(int newSeed)
{
Seed = newSeed;
return GetCharLetter();
}
public char GetCharLetter()
{
return GetCharLetter(allowSurrogate: true);
}
// returns a valid char that is a letter
// if allowsurrogate is true then surrogates are valid return values
public char GetCharLetter(int newSeed, bool allowSurrogate)
{
Seed = newSeed;
return GetCharLetter(allowSurrogate);
}
public char GetCharLetter(bool allowSurrogate)
{
return GetCharLetter(allowSurrogate, allowNoWeight: true);
}
// returns a valid char that is a letter
// if allowsurrogate is true then surrogates are valid return values
// if allownoweight is true, then no-weight characters are valid return values
public char GetCharLetter(int newSeed, bool allowSurrogate, bool allowNoWeight)
{
Seed = newSeed;
return GetCharLetter(allowSurrogate, allowNoWeight);
}
public char GetCharLetter(bool allowSurrogate, bool allowNoWeight)
{
short iVal;
char c = 'a';
int counter;
bool loopCondition = true;
// attempt to randomly find a letter
counter = 100;
do
{
counter--;
iVal = GetInt16();
if (false == allowNoWeight)
{
throw new NotSupportedException("allownoweight = false is not supported in TestLibrary with FEATURE_NOPINVOKES");
}
c = Convert.ToChar(iVal);
loopCondition = allowSurrogate ? (!char.IsLetter(c)) : (!char.IsLetter(c) || char.IsSurrogate(c));
}
while (loopCondition && 0 < counter);
if (!char.IsLetter(c))
{
// we tried and failed to get a letter
// Grab an ASCII letter
c = Convert.ToChar(GetInt16() % 26 + 'A');
}
return c;
}
// returns a valid char that is a number
public char GetCharNumber(int newSeed)
{
Seed = newSeed;
return GetCharNumber();
}
public char GetCharNumber()
{
return GetCharNumber(true);
}
// returns a valid char that is a number
// if allownoweight is true, then no-weight characters are valid return values
public char GetCharNumber(int newSeed, bool allowNoWeight)
{
Seed = newSeed;
return GetCharNumber(allowNoWeight);
}
public char GetCharNumber(bool allowNoWeight)
{
char c = '0';
int counter;
short iVal;
bool loopCondition = true;
// attempt to randomly find a number
counter = 100;
do
{
counter--;
iVal = GetInt16();
if (false == allowNoWeight)
{
throw new InvalidOperationException("allownoweight = false is not supported in TestLibrary with FEATURE_NOPINVOKES");
}
c = Convert.ToChar(iVal);
loopCondition = !char.IsNumber(c);
}
while (loopCondition && 0 < counter);
if (!char.IsNumber(c))
{
// we tried and failed to get a letter
// Grab an ASCII number
c = Convert.ToChar(GetInt16() % 10 + '0');
}
return c;
}
// returns a valid char
public char GetChar(int newSeed)
{
Seed = newSeed;
return GetChar();
}
public char GetChar()
{
return GetChar(allowSurrogate: true);
}
// returns a valid char
// if allowsurrogate is true then surrogates are valid return values
public char GetChar(int newSeed, bool allowSurrogate)
{
Seed = newSeed;
return GetChar(allowSurrogate);
}
public char GetChar(bool allowSurrogate)
{
return GetChar(allowSurrogate, allowNoWeight: true);
}
// returns a valid char
// if allowsurrogate is true then surrogates are valid return values
// if allownoweight characters then noweight characters are valid return values
public char GetChar(int newSeed, bool allowSurrogate, bool allowNoWeight)
{
Seed = newSeed;
return GetChar(allowSurrogate, allowNoWeight);
}
public char GetChar(bool allowSurrogate, bool allowNoWeight)
{
short iVal = GetInt16();
char c = (char)(iVal);
if (!char.IsLetter(c))
{
// we tried and failed to get a letter
// Just grab an ASCII letter
c = (char)(GetInt16() % 26 + 'A');
}
return c;
}
// returns a string. If "validPath" is set, only valid path characters
// will be included
public string GetString(int newSeed, bool validPath, int minLength, int maxLength)
{
Seed = newSeed;
return GetString(validPath, minLength, maxLength);
}
public string GetString(bool validPath, int minLength, int maxLength)
{
return GetString(validPath, true, true, minLength, maxLength);
}
public string GetString(int newSeed, bool validPath, bool allowNulls, int minLength, int maxLength)
{
Seed = newSeed;
return GetString(validPath, allowNulls, minLength, maxLength);
}
public string GetString(bool validPath, bool allowNulls, int minLength, int maxLength)
{
return GetString(validPath, allowNulls, true, minLength, maxLength);
}
public string GetString(int newSeed, bool validPath, bool allowNulls, bool allowNoWeight, int minLength, int maxLength)
{
Seed = newSeed;
return GetString(validPath, allowNulls, allowNoWeight, minLength, maxLength);
}
public string GetString(bool validPath, bool allowNulls, bool allowNoWeight, int minLength, int maxLength)
{
StringBuilder sVal = new StringBuilder();
char c;
int length;
if (0 == minLength && 0 == maxLength) return string.Empty;
if (minLength > maxLength) return null;
length = minLength;
if (minLength != maxLength)
{
length = (GetInt32() % (maxLength - minLength)) + minLength;
}
for (int i = 0; length > i; i++)
{
if (validPath)
{
if (0 == (GetByte() % 2))
{
c = GetCharLetter(true, allowNoWeight);
}
else
{
c = GetCharNumber(allowNoWeight);
}
}
else if (!allowNulls)
{
do
{
c = GetChar(true, allowNoWeight);
} while (c == '\u0000');
}
else
{
c = GetChar(true, allowNoWeight);
}
sVal.Append(c);
}
string s = sVal.ToString();
return s;
}
public string[] GetStrings(int newSeed, bool validPath, int minLength, int maxLength)
{
Seed = newSeed;
return GetStrings(validPath, minLength, maxLength);
}
public string[] GetStrings(bool validPath, int minLength, int maxLength)
{
string validString;
const char c_LATIN_A = '\u0100';
const char c_LOWER_A = 'a';
const char c_UPPER_A = 'A';
const char c_ZERO_WEIGHT = '\uFEFF';
const char c_DOUBLE_WIDE_A = '\uFF21';
const string c_SURROGATE_UPPER = "\uD801\uDC00";
const string c_SURROGATE_LOWER = "\uD801\uDC28";
const char c_LOWER_SIGMA1 = (char)0x03C2;
const char c_LOWER_SIGMA2 = (char)0x03C3;
const char c_UPPER_SIGMA = (char)0x03A3;
const char c_SPACE = ' ';
if (2 >= minLength && 2 >= maxLength || minLength > maxLength)
return null;
validString = GetString(validPath, minLength - 1, maxLength - 1);
string[] retStrings = new string[12];
retStrings[0] = GetString(validPath, minLength, maxLength);
retStrings[1] = validString + c_LATIN_A;
retStrings[2] = validString + c_LOWER_A;
retStrings[3] = validString + c_UPPER_A;
retStrings[4] = validString + c_ZERO_WEIGHT;
retStrings[5] = validString + c_DOUBLE_WIDE_A;
retStrings[6] = GetString(validPath, minLength - 2, maxLength - 2) + c_SURROGATE_UPPER;
retStrings[7] = GetString(validPath, minLength - 2, maxLength - 2) + c_SURROGATE_LOWER;
retStrings[8] = validString + c_LOWER_SIGMA1;
retStrings[9] = validString + c_LOWER_SIGMA2;
retStrings[10] = validString + c_UPPER_SIGMA;
retStrings[11] = validString + c_SPACE;
return retStrings;
}
public static void VerifyRandomDistribution(byte[] random)
{
// Better tests for randomness are available. For now just use a simple
// check that compares the number of 0s and 1s in the bits.
VerifyNeutralParity(random);
}
private static void VerifyNeutralParity(byte[] random)
{
int zeroCount = 0, oneCount = 0;
for (int i = 0; i < random.Length; i++)
{
for (int j = 0; j < 8; j++)
{
if (((random[i] >> j) & 1) == 1)
{
oneCount++;
}
else
{
zeroCount++;
}
}
}
// Over the long run there should be about as many 1s as 0s.
// This isn't a guarantee, just a statistical observation.
// Allow a 7% tolerance band before considering it to have gotten out of hand.
double bitDifference = Math.Abs(zeroCount - oneCount) / (double)(zeroCount + oneCount);
const double AllowedTolerance = 0.07;
if (bitDifference > AllowedTolerance)
{
throw new InvalidOperationException("Expected bitDifference < " + AllowedTolerance + ", got " + bitDifference + ".");
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// URLString
//
//
// Implementation of membership condition for zones
//
namespace System.Security.Util {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Runtime.Serialization;
using System.Globalization;
using System.Text;
using System.IO;
using System.Diagnostics.Contracts;
[Serializable]
internal sealed class URLString : SiteString
{
private String m_protocol;
[OptionalField(VersionAdded = 2)]
private String m_userpass;
private SiteString m_siteString;
private int m_port;
#if !PLATFORM_UNIX
private LocalSiteString m_localSite;
#endif // !PLATFORM_UNIX
private DirectoryString m_directory;
private const String m_defaultProtocol = "file";
[OptionalField(VersionAdded = 2)]
private bool m_parseDeferred;
[OptionalField(VersionAdded = 2)]
private String m_urlOriginal;
[OptionalField(VersionAdded = 2)]
private bool m_parsedOriginal;
[OptionalField(VersionAdded = 3)]
private bool m_isUncShare;
// legacy field from v1.x, not used in v2 and beyond. Retained purely for serialization compatibility.
private String m_fullurl;
[OnDeserialized]
public void OnDeserialized(StreamingContext ctx)
{
if (m_urlOriginal == null)
{
// pre-v2 deserialization. Need to fix-up fields here
m_parseDeferred = false;
m_parsedOriginal = false; // Dont care what this value is - never used
m_userpass = "";
m_urlOriginal = m_fullurl;
m_fullurl = null;
}
}
[OnSerializing]
private void OnSerializing(StreamingContext ctx)
{
if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
{
DoDeferredParse();
m_fullurl = m_urlOriginal;
}
}
[OnSerialized]
private void OnSerialized(StreamingContext ctx)
{
if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
{
m_fullurl = null;
}
}
public URLString()
{
m_protocol = "";
m_userpass = "";
m_siteString = new SiteString();
m_port = -1;
#if !PLATFORM_UNIX
m_localSite = null;
#endif // !PLATFORM_UNIX
m_directory = new DirectoryString();
m_parseDeferred = false;
}
private void DoDeferredParse()
{
if (m_parseDeferred)
{
ParseString(m_urlOriginal, m_parsedOriginal);
m_parseDeferred = false;
}
}
public URLString(string url) : this(url, false, false) {}
public URLString(string url, bool parsed) : this(url, parsed, false) {}
internal URLString(string url, bool parsed, bool doDeferredParsing)
{
m_port = -1;
m_userpass = "";
DoFastChecks(url);
m_urlOriginal = url;
m_parsedOriginal = parsed;
m_parseDeferred = true;
if (doDeferredParsing)
DoDeferredParse();
}
// Converts %XX and %uYYYY to the actual characters (I.e. Unesacpes any escape characters present in the URL)
private String UnescapeURL(String url)
{
StringBuilder intermediate = StringBuilderCache.Acquire(url.Length);
int Rindex = 0; // index into temp that gives the rest of the string to be processed
int index;
int braIndex = -1;
int ketIndex = -1;
braIndex = url.IndexOf('[',Rindex);
if (braIndex != -1)
ketIndex = url.IndexOf(']', braIndex);
do
{
index = url.IndexOf( '%', Rindex);
if (index == -1)
{
intermediate = intermediate.Append(url, Rindex, (url.Length - Rindex));
break;
}
// if we hit a '%' in the middle of an IPv6 address, dont process that
if (index > braIndex && index < ketIndex)
{
intermediate = intermediate.Append(url, Rindex, (ketIndex - Rindex+1));
Rindex = ketIndex+1;
continue;
}
if (url.Length - index < 2) // Check that there is at least 1 char after the '%'
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
if (url[index+1] == 'u' || url[index+1] == 'U')
{
if (url.Length - index < 6) // example: "%u004d" is 6 chars long
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
// We have a unicode character specified in hex
try
{
char c = (char)(Hex.ConvertHexDigit( url[index+2] ) << 12 |
Hex.ConvertHexDigit( url[index+3] ) << 8 |
Hex.ConvertHexDigit( url[index+4] ) << 4 |
Hex.ConvertHexDigit( url[index+5] ));
intermediate = intermediate.Append(url, Rindex, index - Rindex);
intermediate = intermediate.Append(c);
}
catch(ArgumentException) // Hex.ConvertHexDigit can throw an "out of range" ArgumentException
{
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
}
Rindex = index + 6 ; //update the 'seen' length
}
else
{
// we have a hex character.
if (url.Length - index < 3) // example: "%4d" is 3 chars long
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
try
{
char c = (char)(Hex.ConvertHexDigit( url[index+1] ) << 4 | Hex.ConvertHexDigit( url[index+2] ));
intermediate = intermediate.Append(url, Rindex, index - Rindex);
intermediate = intermediate.Append(c);
}
catch(ArgumentException) // Hex.ConvertHexDigit can throw an "out of range" ArgumentException
{
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
}
Rindex = index + 3; // update the 'seen' length
}
}
while (true);
return StringBuilderCache.GetStringAndRelease(intermediate);
}
// Helper Function for ParseString:
// Search for the end of the protocol info and grab the actual protocol string
// ex. http://www.microsoft.com/complus would have a protocol string of http
private String ParseProtocol(String url)
{
String temp;
int index = url.IndexOf( ':' );
if (index == 0)
{
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
}
else if (index == -1)
{
m_protocol = m_defaultProtocol;
temp = url;
}
else if (url.Length > index + 1)
{
if (index == m_defaultProtocol.Length &&
String.Compare(url, 0, m_defaultProtocol, 0, index, StringComparison.OrdinalIgnoreCase) == 0)
{
m_protocol = m_defaultProtocol;
temp = url.Substring( index + 1 );
// Since an explicit file:// URL could be immediately followed by a host name, we will be
// conservative and assume that it is on a share rather than a potentally relative local
// URL.
m_isUncShare = true;
}
else if (url[index+1] != '\\')
{
#if !PLATFORM_UNIX
if (url.Length > index + 2 &&
url[index+1] == '/' &&
url[index+2] == '/')
#else
if (url.Length > index + 1 &&
url[index+1] == '/' ) // UNIX style "file:/home/me" is allowed, so account for that
#endif // !PLATFORM_UNIX
{
m_protocol = url.Substring( 0, index );
for (int i = 0; i < m_protocol.Length; ++i)
{
char c = m_protocol[i];
if ((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
(c == '+') ||
(c == '.') ||
(c == '-'))
{
continue;
}
else
{
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
}
}
#if !PLATFORM_UNIX
temp = url.Substring( index + 3 );
#else
// In UNIX, we don't know how many characters we'll have to skip past.
// Skip past \, /, and :
//
for ( int j=index ; j<url.Length ; j++ )
{
if ( url[j] != '\\' && url[j] != '/' && url[j] != ':' )
{
index = j;
break;
}
}
temp = url.Substring( index );
#endif // !PLATFORM_UNIX
}
else
{
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
}
}
else
{
m_protocol = m_defaultProtocol;
temp = url;
}
}
else
{
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
}
return temp;
}
private String ParsePort(String url)
{
String temp = url;
char[] separators = new char[] { ':', '/' };
int Rindex = 0;
int userpassIndex = temp.IndexOf('@');
if (userpassIndex != -1) {
if (temp.IndexOf('/',0,userpassIndex) == -1) {
// this is a user:pass type of string
m_userpass = temp.Substring(0,userpassIndex);
Rindex = userpassIndex + 1;
}
}
int braIndex = -1;
int ketIndex = -1;
int portIndex = -1;
braIndex = url.IndexOf('[',Rindex);
if (braIndex != -1)
ketIndex = url.IndexOf(']', braIndex);
if (ketIndex != -1)
{
// IPv6 address...ignore the IPv6 block when searching for the port
portIndex = temp.IndexOfAny(separators,ketIndex);
}
else
{
portIndex = temp.IndexOfAny(separators,Rindex);
}
if (portIndex != -1 && temp[portIndex] == ':')
{
// make sure it really is a port, and has a number after the :
if ( temp[portIndex+1] >= '0' && temp[portIndex+1] <= '9' )
{
int tempIndex = temp.IndexOf( '/', Rindex);
if (tempIndex == -1)
{
m_port = Int32.Parse( temp.Substring(portIndex + 1), CultureInfo.InvariantCulture );
if (m_port < 0)
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
temp = temp.Substring( Rindex, portIndex - Rindex );
}
else if (tempIndex > portIndex)
{
m_port = Int32.Parse( temp.Substring(portIndex + 1, tempIndex - portIndex - 1), CultureInfo.InvariantCulture );
temp = temp.Substring( Rindex, portIndex - Rindex ) + temp.Substring( tempIndex );
}
else
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
}
else
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
}
else {
// Chop of the user/pass portion if any
temp = temp.Substring(Rindex);
}
return temp;
}
// This does three things:
// 1. It makes the following modifications to the start of the string:
// a. \\?\ and \\?/ => <empty>
// b. \\.\ and \\./ => <empty>
// 2. If isFileUrl is true, converts all slashes to front slashes and strips leading
// front slashes. See comment by code.
// 3. Throws a PathTooLongException if the length of the resulting URL is >= MAX_PATH.
// This is done to prevent security issues due to canonicalization truncations.
// Remove this method when the Path class supports "\\?\"
internal static String PreProcessForExtendedPathRemoval(String url, bool isFileUrl)
{
bool uncShare = false;
return PreProcessForExtendedPathRemoval(url, isFileUrl, ref uncShare);
}
private static String PreProcessForExtendedPathRemoval(String url, bool isFileUrl, ref bool isUncShare)
{
// This is the modified URL that we will return
StringBuilder modifiedUrl = new StringBuilder(url);
// ITEM 1 - remove extended path characters.
{
// Keep track of where we are in both the comparison and altered strings.
int curCmpIdx = 0;
int curModIdx = 0;
// If all the '\' have already been converted to '/', just check for //?/ or //./
if ((url.Length - curCmpIdx) >= 4 &&
(String.Compare(url, curCmpIdx, "//?/", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(url, curCmpIdx, "//./", 0, 4, StringComparison.OrdinalIgnoreCase) == 0))
{
modifiedUrl.Remove(curModIdx, 4);
curCmpIdx += 4;
}
else
{
if (isFileUrl) {
// We need to handle an indefinite number of leading front slashes for file URLs since we could
// get something like:
// file://\\?\
// file:/\\?\
// file:\\?\
// etc...
while (url[curCmpIdx] == '/')
{
curCmpIdx++;
curModIdx++;
}
}
// Remove the extended path characters
if ((url.Length - curCmpIdx) >= 4 &&
(String.Compare(url, curCmpIdx, "\\\\?\\", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(url, curCmpIdx, "\\\\?/", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(url, curCmpIdx, "\\\\.\\", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(url, curCmpIdx, "\\\\./", 0, 4, StringComparison.OrdinalIgnoreCase) == 0))
{
modifiedUrl.Remove(curModIdx, 4);
curCmpIdx += 4;
}
}
}
// ITEM 2 - convert all slashes to forward slashes, and strip leading slashes.
if (isFileUrl)
{
int slashCount = 0;
bool seenFirstBackslash = false;
while (slashCount < modifiedUrl.Length && (modifiedUrl[slashCount] == '/' || modifiedUrl[slashCount] == '\\'))
{
// Look for sets of consecutive backslashes. We can't just look for these at the start
// of the string, since file:// might come first. Instead, once we see the first \, look
// for a second one following it.
if (!seenFirstBackslash && modifiedUrl[slashCount] == '\\')
{
seenFirstBackslash = true;
if (slashCount + 1 < modifiedUrl.Length && modifiedUrl[slashCount + 1] == '\\')
isUncShare = true;
}
slashCount++;
}
modifiedUrl.Remove(0, slashCount);
modifiedUrl.Replace('\\', '/');
}
// ITEM 3 - If the path is greater than or equal (due to terminating NULL in windows) MAX_PATH, we throw.
if (modifiedUrl.Length >= Path.MAX_PATH)
{
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
}
// Create the result string from the StringBuilder
return modifiedUrl.ToString();
}
// Do any misc massaging of data in the URL
private String PreProcessURL(String url, bool isFileURL)
{
#if !PLATFORM_UNIX
if (isFileURL) {
// Remove when the Path class supports "\\?\"
url = PreProcessForExtendedPathRemoval(url, true, ref m_isUncShare);
}
else {
url = url.Replace('\\', '/');
}
return url;
#else
// Remove superfluous '/'
// For UNIX, the file path would look something like:
// file:///home/johndoe/here
// file:/home/johndoe/here
// file:../johndoe/here
// file:~/johndoe/here
String temp = url;
int nbSlashes = 0;
while(nbSlashes<temp.Length && '/'==temp[nbSlashes])
nbSlashes++;
// if we get a path like file:///directory/name we need to convert
// this to /directory/name.
if(nbSlashes > 2)
temp = temp.Substring(nbSlashes-1, temp.Length - (nbSlashes-1));
else if (2 == nbSlashes) /* it's a relative path */
temp = temp.Substring(nbSlashes, temp.Length - nbSlashes);
return temp;
#endif // !PLATFORM_UNIX
}
private void ParseFileURL(String url)
{
String temp = url;
#if !PLATFORM_UNIX
int index = temp.IndexOf( '/');
if (index != -1 &&
((index == 2 &&
temp[index-1] != ':' &&
temp[index-1] != '|') ||
index != 2) &&
index != temp.Length - 1)
{
// Also, if it is a UNC share, we want m_localSite to
// be of the form "computername/share", so if the first
// fileEnd character found is a slash, do some more parsing
// to find the proper end character.
int tempIndex = temp.IndexOf( '/', index+1);
if (tempIndex != -1)
index = tempIndex;
else
index = -1;
}
String localSite;
if (index == -1)
localSite = temp;
else
localSite = temp.Substring(0,index);
if (localSite.Length == 0)
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
int i;
bool spacesAllowed;
if (localSite[0] == '\\' && localSite[1] == '\\')
{
spacesAllowed = true;
i = 2;
}
else
{
i = 0;
spacesAllowed = false;
}
bool useSmallCharToUpper = true;
for (; i < localSite.Length; ++i)
{
char c = localSite[i];
if ((c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') ||
(c == '-') || (c == '/') ||
(c == ':') || (c == '|') ||
(c == '.') || (c == '*') ||
(c == '$') || (spacesAllowed && c == ' '))
{
continue;
}
else
{
useSmallCharToUpper = false;
break;
}
}
if (useSmallCharToUpper)
localSite = String.SmallCharToUpper( localSite );
else
localSite = localSite.ToUpper(CultureInfo.InvariantCulture);
m_localSite = new LocalSiteString( localSite );
if (index == -1)
{
if (localSite[localSite.Length-1] == '*')
m_directory = new DirectoryString( "*", false );
else
m_directory = new DirectoryString();
}
else
{
String directoryString = temp.Substring( index + 1 );
if (directoryString.Length == 0)
{
m_directory = new DirectoryString();
}
else
{
m_directory = new DirectoryString( directoryString, true);
}
}
#else // !PLATFORM_UNIX
m_directory = new DirectoryString( temp, true);
#endif // !PLATFORM_UNIX
m_siteString = null;
return;
}
private void ParseNonFileURL(String url)
{
String temp = url;
int index = temp.IndexOf('/');
if (index == -1)
{
#if !PLATFORM_UNIX
m_localSite = null; // for drive letter
#endif // !PLATFORM_UNIX
m_siteString = new SiteString( temp );
m_directory = new DirectoryString();
}
else
{
#if !PLATFORM_UNIX
String site = temp.Substring( 0, index );
m_localSite = null;
m_siteString = new SiteString( site );
String directoryString = temp.Substring( index + 1 );
if (directoryString.Length == 0)
{
m_directory = new DirectoryString();
}
else
{
m_directory = new DirectoryString( directoryString, false );
}
#else
String directoryString = temp.Substring( index + 1 );
String site = temp.Substring( 0, index );
m_directory = new DirectoryString( directoryString, false );
m_siteString = new SiteString( site );
#endif //!PLATFORM_UNIX
}
return;
}
void DoFastChecks( String url )
{
if (url == null)
{
throw new ArgumentNullException( "url" );
}
Contract.EndContractBlock();
if (url.Length == 0)
{
throw new FormatException(Environment.GetResourceString("Format_StringZeroLength"));
}
}
// NOTE:
// 1. We support URLs that follow the common Internet scheme syntax
// (<scheme>://user:pass@<host>:<port>/<url-path>) and all windows file URLs.
// 2. In the general case we parse of the site and create a SiteString out of it
// (which supports our wildcarding scheme). In the case of files we don't support
// wildcarding and furthermore SiteString doesn't like ':' and '|' which can appear
// in file urls so we just keep that info in a separate string and set the
// SiteString to null.
//
// ex. http://www.microsoft.com/complus -> m_siteString = "www.microsoft.com" m_localSite = null
// ex. file:///c:/complus/mscorlib.dll -> m_siteString = null m_localSite = "c:"
// ex. file:///c|/complus/mscorlib.dll -> m_siteString = null m_localSite = "c:"
void ParseString( String url, bool parsed )
{
// If there are any escaped hex or unicode characters in the url, translate those
// into the proper character.
if (!parsed)
{
url = UnescapeURL(url);
}
// Identify the protocol and strip the protocol info from the string, if present.
String temp = ParseProtocol(url);
bool fileProtocol = (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0);
// handle any special preocessing...removing extra characters, etc.
temp = PreProcessURL(temp, fileProtocol);
if (fileProtocol)
{
ParseFileURL(temp);
}
else
{
// Check if there is a port number and parse that out.
temp = ParsePort(temp);
ParseNonFileURL(temp);
// Note: that we allow DNS and Netbios names for non-file protocols (since sitestring will check
// that the hostname satisfies these two protocols. DNS-only checking can theoretically be added
// here but that would break all the programs that use '_' (which is fairly common, yet illegal).
// If this needs to be done at any point, add a call to m_siteString.IsLegalDNSName().
}
}
public String Scheme
{
get
{
DoDeferredParse();
return m_protocol;
}
}
public String Host
{
get
{
DoDeferredParse();
if (m_siteString != null)
{
return m_siteString.ToString();
}
else
{
#if !PLATFORM_UNIX
return m_localSite.ToString();
#else
return "";
#endif // !PLATFORM_UNIX
}
}
}
public String Port
{
get
{
DoDeferredParse();
if (m_port == -1)
return null;
else
return m_port.ToString(CultureInfo.InvariantCulture);
}
}
public String Directory
{
get
{
DoDeferredParse();
return m_directory.ToString();
}
}
/// <summary>
/// Make a best guess at determining if this is URL refers to a file with a relative path. Since
/// this is a guess to help out users of UrlMembershipCondition who may accidentally supply a
/// relative URL, we'd rather err on the side of absolute than relative. (We'd rather accept some
/// meaningless membership conditions rather than reject meaningful ones).
///
/// In order to be a relative file URL, the URL needs to have a protocol of file, and not be on a
/// UNC share.
///
/// If both of the above are true, then the heuristics we'll use to detect an absolute URL are:
/// 1. A host name which is:
/// a. greater than one character and ends in a colon (representing the drive letter) OR
/// b. ends with a * (so we match any file with the given prefix if any)
/// 2. Has a directory name (cannot be simply file://c:)
/// </summary>
public bool IsRelativeFileUrl
{
get
{
DoDeferredParse();
if (String.Equals(m_protocol, "file", StringComparison.OrdinalIgnoreCase) && !m_isUncShare)
{
#if !PLATFORM_UNIX
string host = m_localSite != null ? m_localSite.ToString() : null;
// If the host name ends with the * character, treat this as an absolute URL since the *
// could represent the rest of the full path.
if (host.EndsWith('*'))
return false;
#endif // !PLATFORM_UNIX
string directory = m_directory != null ? m_directory.ToString() : null;
#if !PLATFORM_UNIX
return host == null || host.Length < 2 || !host.EndsWith(':') ||
String.IsNullOrEmpty(directory);
#else
return String.IsNullOrEmpty(directory);
#endif // !PLATFORM_UNIX
}
// Since this is not a local URL, it cannot be relative
return false;
}
}
public String GetFileName()
{
DoDeferredParse();
#if !PLATFORM_UNIX
if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0)
return null;
String intermediateDirectory = this.Directory.Replace( '/', '\\' );
String directory = this.Host.Replace( '/', '\\' );
int directorySlashIndex = directory.IndexOf( '\\' );
if (directorySlashIndex == -1)
{
if (directory.Length != 2 ||
!(directory[1] == ':' || directory[1] == '|'))
{
directory = "\\\\" + directory;
}
}
else if (directorySlashIndex != 2 ||
(directorySlashIndex == 2 && directory[1] != ':' && directory[1] != '|'))
{
directory = "\\\\" + directory;
}
directory += "\\" + intermediateDirectory;
return directory;
#else
// In Unix, directory contains the full pathname
// (this is what we get in Win32)
if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase ) != 0)
return null;
return this.Directory;
#endif // !PLATFORM_UNIX
}
public String GetDirectoryName()
{
DoDeferredParse();
#if !PLATFORM_UNIX
if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase ) != 0)
return null;
String intermediateDirectory = this.Directory.Replace( '/', '\\' );
int slashIndex = 0;
for (int i = intermediateDirectory.Length; i > 0; i--)
{
if (intermediateDirectory[i-1] == '\\')
{
slashIndex = i;
break;
}
}
String directory = this.Host.Replace( '/', '\\' );
int directorySlashIndex = directory.IndexOf( '\\' );
if (directorySlashIndex == -1)
{
if (directory.Length != 2 ||
!(directory[1] == ':' || directory[1] == '|'))
{
directory = "\\\\" + directory;
}
}
else if (directorySlashIndex > 2 ||
(directorySlashIndex == 2 && directory[1] != ':' && directory[1] != '|'))
{
directory = "\\\\" + directory;
}
directory += "\\";
if (slashIndex > 0)
{
directory += intermediateDirectory.Substring( 0, slashIndex );
}
return directory;
#else
if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0)
return null;
String directory = this.Directory.ToString();
int slashIndex = 0;
for (int i = directory.Length; i > 0; i--)
{
if (directory[i-1] == '/')
{
slashIndex = i;
break;
}
}
if (slashIndex > 0)
{
directory = directory.Substring( 0, slashIndex );
}
return directory;
#endif // !PLATFORM_UNIX
}
public override SiteString Copy()
{
return new URLString( m_urlOriginal, m_parsedOriginal );
}
public override bool IsSubsetOf( SiteString site )
{
if (site == null)
{
return false;
}
URLString url = site as URLString;
if (url == null)
{
return false;
}
DoDeferredParse();
url.DoDeferredParse();
URLString normalUrl1 = this.SpecialNormalizeUrl();
URLString normalUrl2 = url.SpecialNormalizeUrl();
if (String.Compare( normalUrl1.m_protocol, normalUrl2.m_protocol, StringComparison.OrdinalIgnoreCase) == 0 &&
normalUrl1.m_directory.IsSubsetOf( normalUrl2.m_directory ))
{
#if !PLATFORM_UNIX
if (normalUrl1.m_localSite != null)
{
// We do a little extra processing in here for local files since we allow
// both <drive_letter>: and <drive_letter>| forms of urls.
return normalUrl1.m_localSite.IsSubsetOf( normalUrl2.m_localSite );
}
else
#endif // !PLATFORM_UNIX
{
if (normalUrl1.m_port != normalUrl2.m_port)
return false;
return normalUrl2.m_siteString != null && normalUrl1.m_siteString.IsSubsetOf( normalUrl2.m_siteString );
}
}
else
{
return false;
}
}
public override String ToString()
{
return m_urlOriginal;
}
public override bool Equals(Object o)
{
DoDeferredParse();
if (o == null || !(o is URLString))
return false;
else
return this.Equals( (URLString)o );
}
public override int GetHashCode()
{
DoDeferredParse();
TextInfo info = CultureInfo.InvariantCulture.TextInfo;
int accumulator = 0;
if (this.m_protocol != null)
accumulator = info.GetCaseInsensitiveHashCode( this.m_protocol );
#if !PLATFORM_UNIX
if (this.m_localSite != null)
{
accumulator = accumulator ^ this.m_localSite.GetHashCode();
}
else
{
accumulator = accumulator ^ this.m_siteString.GetHashCode();
}
accumulator = accumulator ^ this.m_directory.GetHashCode();
#else
accumulator = accumulator ^ info.GetCaseInsensitiveHashCode(this.m_urlOriginal);
#endif // !PLATFORM_UNIX
return accumulator;
}
public bool Equals( URLString url )
{
return CompareUrls( this, url );
}
public static bool CompareUrls( URLString url1, URLString url2 )
{
if (url1 == null && url2 == null)
return true;
if (url1 == null || url2 == null)
return false;
url1.DoDeferredParse();
url2.DoDeferredParse();
URLString normalUrl1 = url1.SpecialNormalizeUrl();
URLString normalUrl2 = url2.SpecialNormalizeUrl();
// Compare protocol (case insensitive)
if (String.Compare( normalUrl1.m_protocol, normalUrl2.m_protocol, StringComparison.OrdinalIgnoreCase) != 0)
return false;
// Do special processing for file urls
if (String.Compare( normalUrl1.m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0)
{
#if !PLATFORM_UNIX
if (!normalUrl1.m_localSite.IsSubsetOf( normalUrl2.m_localSite ) ||
!normalUrl2.m_localSite.IsSubsetOf( normalUrl1.m_localSite ))
return false;
#else
return url1.IsSubsetOf( url2 ) &&
url2.IsSubsetOf( url1 );
#endif // !PLATFORM_UNIX
}
else
{
if (String.Compare( normalUrl1.m_userpass, normalUrl2.m_userpass, StringComparison.Ordinal) != 0)
return false;
if (!normalUrl1.m_siteString.IsSubsetOf( normalUrl2.m_siteString ) ||
!normalUrl2.m_siteString.IsSubsetOf( normalUrl1.m_siteString ))
return false;
if (url1.m_port != url2.m_port)
return false;
}
if (!normalUrl1.m_directory.IsSubsetOf( normalUrl2.m_directory ) ||
!normalUrl2.m_directory.IsSubsetOf( normalUrl1.m_directory ))
return false;
return true;
}
internal String NormalizeUrl()
{
DoDeferredParse();
StringBuilder builtUrl = StringBuilderCache.Acquire();
if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0)
{
#if !PLATFORM_UNIX
builtUrl = builtUrl.AppendFormat("FILE:///{0}/{1}", m_localSite.ToString(), m_directory.ToString());
#else
builtUrl = builtUrl.AppendFormat("FILE:///{0}", m_directory.ToString());
#endif // !PLATFORM_UNIX
}
else
{
builtUrl = builtUrl.AppendFormat("{0}://{1}{2}", m_protocol, m_userpass, m_siteString.ToString());
if (m_port != -1)
builtUrl = builtUrl.AppendFormat("{0}",m_port);
builtUrl = builtUrl.AppendFormat("/{0}", m_directory.ToString());
}
return StringBuilderCache.GetStringAndRelease(builtUrl).ToUpper(CultureInfo.InvariantCulture);
}
#if !PLATFORM_UNIX
[System.Security.SecuritySafeCritical] // auto-generated
internal URLString SpecialNormalizeUrl()
{
// Under WinXP, file protocol urls can be mapped to
// drives that aren't actually file protocol underneath
// due to drive mounting. This code attempts to figure
// out what a drive is mounted to and create the
// url is maps to.
DoDeferredParse();
if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0)
{
return this;
}
else
{
String localSite = m_localSite.ToString();
if (localSite.Length == 2 &&
(localSite[1] == '|' ||
localSite[1] == ':'))
{
String deviceName = null;
GetDeviceName(localSite, JitHelpers.GetStringHandleOnStack(ref deviceName));
if (deviceName != null)
{
if (deviceName.IndexOf( "://", StringComparison.Ordinal ) != -1)
{
URLString u = new URLString( deviceName + "/" + this.m_directory.ToString() );
u.DoDeferredParse(); // Presumably the caller of SpecialNormalizeUrl wants a fully parsed URL
return u;
}
else
{
URLString u = new URLString( "file://" + deviceName + "/" + this.m_directory.ToString() );
u.DoDeferredParse();// Presumably the caller of SpecialNormalizeUrl wants a fully parsed URL
return u;
}
}
else
return this;
}
else
{
return this;
}
}
}
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetDeviceName( String driveLetter, StringHandleOnStack retDeviceName );
#else
internal URLString SpecialNormalizeUrl()
{
return this;
}
#endif // !PLATFORM_UNIX
}
[Serializable]
internal class DirectoryString : SiteString
{
private bool m_checkForIllegalChars;
private new static char[] m_separators = { '/' };
// From KB #Q177506, file/folder illegal characters are \ / : * ? " < > |
protected static char[] m_illegalDirectoryCharacters = { '\\', ':', '*', '?', '"', '<', '>', '|' };
public DirectoryString()
{
m_site = "";
m_separatedSite = new ArrayList();
}
public DirectoryString( String directory, bool checkForIllegalChars )
{
m_site = directory;
m_checkForIllegalChars = checkForIllegalChars;
m_separatedSite = CreateSeparatedString(directory);
}
private ArrayList CreateSeparatedString(String directory)
{
if (directory == null || directory.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
}
Contract.EndContractBlock();
ArrayList list = new ArrayList();
String[] separatedArray = directory.Split(m_separators);
for (int index = 0; index < separatedArray.Length; ++index)
{
if (separatedArray[index] == null || separatedArray[index].Equals( "" ))
{
// this case is fine, we just ignore it the extra separators.
}
else if (separatedArray[index].Equals( "*" ))
{
if (index != separatedArray.Length-1)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
}
list.Add( separatedArray[index] );
}
else if (m_checkForIllegalChars && separatedArray[index].IndexOfAny( m_illegalDirectoryCharacters ) != -1)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
}
else
{
list.Add( separatedArray[index] );
}
}
return list;
}
public virtual bool IsSubsetOf( DirectoryString operand )
{
return this.IsSubsetOf( operand, true );
}
public virtual bool IsSubsetOf( DirectoryString operand, bool ignoreCase )
{
if (operand == null)
{
return false;
}
else if (operand.m_separatedSite.Count == 0)
{
return this.m_separatedSite.Count == 0 || this.m_separatedSite.Count > 0 && String.Compare((String)this.m_separatedSite[0], "*", StringComparison.Ordinal) == 0;
}
else if (this.m_separatedSite.Count == 0)
{
return String.Compare((String)operand.m_separatedSite[0], "*", StringComparison.Ordinal) == 0;
}
else
{
return base.IsSubsetOf( operand, ignoreCase );
}
}
}
#if !PLATFORM_UNIX
[Serializable]
internal class LocalSiteString : SiteString
{
private new static char[] m_separators = { '/' };
public LocalSiteString( String site )
{
m_site = site.Replace( '|', ':');
if (m_site.Length > 2 && m_site.IndexOf( ':' ) != -1)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
m_separatedSite = CreateSeparatedString(m_site);
}
private ArrayList CreateSeparatedString(String directory)
{
if (directory == null || directory.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
}
Contract.EndContractBlock();
ArrayList list = new ArrayList();
String[] separatedArray = directory.Split(m_separators);
for (int index = 0; index < separatedArray.Length; ++index)
{
if (separatedArray[index] == null || separatedArray[index].Equals( "" ))
{
if (index < 2 &&
directory[index] == '/')
{
list.Add( "//" );
}
else if (index != separatedArray.Length-1)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
}
}
else if (separatedArray[index].Equals( "*" ))
{
if (index != separatedArray.Length-1)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
}
list.Add( separatedArray[index] );
}
else
{
list.Add( separatedArray[index] );
}
}
return list;
}
public virtual bool IsSubsetOf( LocalSiteString operand )
{
return this.IsSubsetOf( operand, true );
}
public virtual bool IsSubsetOf( LocalSiteString operand, bool ignoreCase )
{
if (operand == null)
{
return false;
}
else if (operand.m_separatedSite.Count == 0)
{
return this.m_separatedSite.Count == 0 || this.m_separatedSite.Count > 0 && String.Compare((String)this.m_separatedSite[0], "*", StringComparison.Ordinal) == 0;
}
else if (this.m_separatedSite.Count == 0)
{
return String.Compare((String)operand.m_separatedSite[0], "*", StringComparison.Ordinal) == 0;
}
else
{
return base.IsSubsetOf( operand, ignoreCase );
}
}
}
#endif // !PLATFORM_UNIX
}
| |
// 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.Reflection;
using System.Xml;
using System.Collections;
using System.Diagnostics;
namespace System.Runtime.Serialization
{
internal static class XmlFormatGeneratorStatics
{
private static MethodInfo s_writeStartElementMethod2;
internal static MethodInfo WriteStartElementMethod2
{
get
{
if (s_writeStartElementMethod2 == null)
{
s_writeStartElementMethod2 = typeof(XmlWriterDelegator).GetMethod("WriteStartElement", Globals.ScanAllMembers, new Type[] { typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
Debug.Assert(s_writeStartElementMethod2 != null);
}
return s_writeStartElementMethod2;
}
}
private static MethodInfo s_writeStartElementMethod3;
internal static MethodInfo WriteStartElementMethod3
{
get
{
if (s_writeStartElementMethod3 == null)
{
s_writeStartElementMethod3 = typeof(XmlWriterDelegator).GetMethod("WriteStartElement", Globals.ScanAllMembers, new Type[] { typeof(string), typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
Debug.Assert(s_writeStartElementMethod3 != null);
}
return s_writeStartElementMethod3;
}
}
private static MethodInfo s_writeEndElementMethod;
internal static MethodInfo WriteEndElementMethod
{
get
{
if (s_writeEndElementMethod == null)
{
s_writeEndElementMethod = typeof(XmlWriterDelegator).GetMethod("WriteEndElement", Globals.ScanAllMembers, Array.Empty<Type>());
Debug.Assert(s_writeEndElementMethod != null);
}
return s_writeEndElementMethod;
}
}
private static MethodInfo s_writeNamespaceDeclMethod;
internal static MethodInfo WriteNamespaceDeclMethod
{
get
{
if (s_writeNamespaceDeclMethod == null)
{
s_writeNamespaceDeclMethod = typeof(XmlWriterDelegator).GetMethod("WriteNamespaceDecl", Globals.ScanAllMembers, new Type[] { typeof(XmlDictionaryString) });
Debug.Assert(s_writeNamespaceDeclMethod != null);
}
return s_writeNamespaceDeclMethod;
}
}
private static PropertyInfo s_extensionDataProperty;
internal static PropertyInfo ExtensionDataProperty => s_extensionDataProperty ??
(s_extensionDataProperty = typeof(IExtensibleDataObject).GetProperty("ExtensionData"));
private static ConstructorInfo s_dictionaryEnumeratorCtor;
internal static ConstructorInfo DictionaryEnumeratorCtor
{
get
{
if (s_dictionaryEnumeratorCtor == null)
s_dictionaryEnumeratorCtor = Globals.TypeOfDictionaryEnumerator.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfIDictionaryEnumerator });
return s_dictionaryEnumeratorCtor;
}
}
private static MethodInfo s_ienumeratorMoveNextMethod;
internal static MethodInfo MoveNextMethod
{
get
{
if (s_ienumeratorMoveNextMethod == null)
{
s_ienumeratorMoveNextMethod = typeof(IEnumerator).GetMethod("MoveNext");
Debug.Assert(s_ienumeratorMoveNextMethod != null);
}
return s_ienumeratorMoveNextMethod;
}
}
private static MethodInfo s_ienumeratorGetCurrentMethod;
internal static MethodInfo GetCurrentMethod
{
get
{
if (s_ienumeratorGetCurrentMethod == null)
{
s_ienumeratorGetCurrentMethod = typeof(IEnumerator).GetProperty("Current").GetMethod;
Debug.Assert(s_ienumeratorGetCurrentMethod != null);
}
return s_ienumeratorGetCurrentMethod;
}
}
private static MethodInfo s_getItemContractMethod;
internal static MethodInfo GetItemContractMethod
{
get
{
if (s_getItemContractMethod == null)
{
s_getItemContractMethod = typeof(CollectionDataContract).GetProperty("ItemContract", Globals.ScanAllMembers).GetMethod;
Debug.Assert(s_getItemContractMethod != null);
}
return s_getItemContractMethod;
}
}
private static MethodInfo s_isStartElementMethod2;
internal static MethodInfo IsStartElementMethod2
{
get
{
if (s_isStartElementMethod2 == null)
{
s_isStartElementMethod2 = typeof(XmlReaderDelegator).GetMethod("IsStartElement", Globals.ScanAllMembers, new Type[] { typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
Debug.Assert(s_isStartElementMethod2 != null);
}
return s_isStartElementMethod2;
}
}
private static MethodInfo s_isStartElementMethod0;
internal static MethodInfo IsStartElementMethod0
{
get
{
if (s_isStartElementMethod0 == null)
{
s_isStartElementMethod0 = typeof(XmlReaderDelegator).GetMethod("IsStartElement", Globals.ScanAllMembers, Array.Empty<Type>());
Debug.Assert(s_isStartElementMethod0 != null);
}
return s_isStartElementMethod0;
}
}
private static MethodInfo s_getUninitializedObjectMethod;
internal static MethodInfo GetUninitializedObjectMethod
{
get
{
if (s_getUninitializedObjectMethod == null)
{
s_getUninitializedObjectMethod = typeof(XmlFormatReaderGenerator).GetMethod("UnsafeGetUninitializedObject", Globals.ScanAllMembers, new Type[] { typeof(int) });
Debug.Assert(s_getUninitializedObjectMethod != null);
}
return s_getUninitializedObjectMethod;
}
}
private static MethodInfo s_onDeserializationMethod;
internal static MethodInfo OnDeserializationMethod
{
get
{
if (s_onDeserializationMethod == null)
s_onDeserializationMethod = typeof(IDeserializationCallback).GetMethod("OnDeserialization");
return s_onDeserializationMethod;
}
}
private static PropertyInfo s_nodeTypeProperty;
internal static PropertyInfo NodeTypeProperty
{
get
{
if (s_nodeTypeProperty == null)
{
s_nodeTypeProperty = typeof(XmlReaderDelegator).GetProperty("NodeType", Globals.ScanAllMembers);
Debug.Assert(s_nodeTypeProperty != null);
}
return s_nodeTypeProperty;
}
}
private static ConstructorInfo s_extensionDataObjectCtor;
internal static ConstructorInfo ExtensionDataObjectCtor => s_extensionDataObjectCtor ??
(s_extensionDataObjectCtor =
typeof (ExtensionDataObject).GetConstructor(Globals.ScanAllMembers, null, new Type[] {}, null));
private static ConstructorInfo s_hashtableCtor;
internal static ConstructorInfo HashtableCtor
{
get
{
if (s_hashtableCtor == null)
s_hashtableCtor = Globals.TypeOfHashtable.GetConstructor(Globals.ScanAllMembers, Array.Empty<Type>());
return s_hashtableCtor;
}
}
private static MethodInfo s_getStreamingContextMethod;
internal static MethodInfo GetStreamingContextMethod
{
get
{
if (s_getStreamingContextMethod == null)
{
s_getStreamingContextMethod = typeof(XmlObjectSerializerContext).GetMethod("GetStreamingContext", Globals.ScanAllMembers);
Debug.Assert(s_getStreamingContextMethod != null);
}
return s_getStreamingContextMethod;
}
}
private static MethodInfo s_getCollectionMemberMethod;
internal static MethodInfo GetCollectionMemberMethod
{
get
{
if (s_getCollectionMemberMethod == null)
{
s_getCollectionMemberMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetCollectionMember", Globals.ScanAllMembers);
Debug.Assert(s_getCollectionMemberMethod != null);
}
return s_getCollectionMemberMethod;
}
}
private static MethodInfo s_storeCollectionMemberInfoMethod;
internal static MethodInfo StoreCollectionMemberInfoMethod
{
get
{
if (s_storeCollectionMemberInfoMethod == null)
{
s_storeCollectionMemberInfoMethod = typeof(XmlObjectSerializerReadContext).GetMethod("StoreCollectionMemberInfo", Globals.ScanAllMembers, new Type[] { typeof(object) });
Debug.Assert(s_storeCollectionMemberInfoMethod != null);
}
return s_storeCollectionMemberInfoMethod;
}
}
private static MethodInfo s_storeIsGetOnlyCollectionMethod;
internal static MethodInfo StoreIsGetOnlyCollectionMethod
{
get
{
if (s_storeIsGetOnlyCollectionMethod == null)
{
s_storeIsGetOnlyCollectionMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("StoreIsGetOnlyCollection", Globals.ScanAllMembers);
Debug.Assert(s_storeIsGetOnlyCollectionMethod != null);
}
return s_storeIsGetOnlyCollectionMethod;
}
}
private static MethodInfo s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod;
internal static MethodInfo ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod
{
get
{
if (s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod == null)
{
s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowNullValueReturnedForGetOnlyCollectionException", Globals.ScanAllMembers);
Debug.Assert(s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod != null);
}
return s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod;
}
}
private static MethodInfo s_throwArrayExceededSizeExceptionMethod;
internal static MethodInfo ThrowArrayExceededSizeExceptionMethod
{
get
{
if (s_throwArrayExceededSizeExceptionMethod == null)
{
s_throwArrayExceededSizeExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowArrayExceededSizeException", Globals.ScanAllMembers);
Debug.Assert(s_throwArrayExceededSizeExceptionMethod != null);
}
return s_throwArrayExceededSizeExceptionMethod;
}
}
private static MethodInfo s_incrementItemCountMethod;
internal static MethodInfo IncrementItemCountMethod
{
get
{
if (s_incrementItemCountMethod == null)
{
s_incrementItemCountMethod = typeof(XmlObjectSerializerContext).GetMethod("IncrementItemCount", Globals.ScanAllMembers);
Debug.Assert(s_incrementItemCountMethod != null);
}
return s_incrementItemCountMethod;
}
}
private static MethodInfo s_internalDeserializeMethod;
internal static MethodInfo InternalDeserializeMethod
{
get
{
if (s_internalDeserializeMethod == null)
{
s_internalDeserializeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("InternalDeserialize", Globals.ScanAllMembers, new Type[] { typeof(XmlReaderDelegator), typeof(int), typeof(RuntimeTypeHandle), typeof(string), typeof(string) });
Debug.Assert(s_internalDeserializeMethod != null);
}
return s_internalDeserializeMethod;
}
}
private static MethodInfo s_moveToNextElementMethod;
internal static MethodInfo MoveToNextElementMethod
{
get
{
if (s_moveToNextElementMethod == null)
{
s_moveToNextElementMethod = typeof(XmlObjectSerializerReadContext).GetMethod("MoveToNextElement", Globals.ScanAllMembers);
Debug.Assert(s_moveToNextElementMethod != null);
}
return s_moveToNextElementMethod;
}
}
private static MethodInfo s_getMemberIndexMethod;
internal static MethodInfo GetMemberIndexMethod
{
get
{
if (s_getMemberIndexMethod == null)
{
s_getMemberIndexMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetMemberIndex", Globals.ScanAllMembers);
Debug.Assert(s_getMemberIndexMethod != null);
}
return s_getMemberIndexMethod;
}
}
private static MethodInfo s_getMemberIndexWithRequiredMembersMethod;
internal static MethodInfo GetMemberIndexWithRequiredMembersMethod
{
get
{
if (s_getMemberIndexWithRequiredMembersMethod == null)
{
s_getMemberIndexWithRequiredMembersMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetMemberIndexWithRequiredMembers", Globals.ScanAllMembers);
Debug.Assert(s_getMemberIndexWithRequiredMembersMethod != null);
}
return s_getMemberIndexWithRequiredMembersMethod;
}
}
private static MethodInfo s_throwRequiredMemberMissingExceptionMethod;
internal static MethodInfo ThrowRequiredMemberMissingExceptionMethod
{
get
{
if (s_throwRequiredMemberMissingExceptionMethod == null)
{
s_throwRequiredMemberMissingExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowRequiredMemberMissingException", Globals.ScanAllMembers);
Debug.Assert(s_throwRequiredMemberMissingExceptionMethod != null);
}
return s_throwRequiredMemberMissingExceptionMethod;
}
}
private static MethodInfo s_skipUnknownElementMethod;
internal static MethodInfo SkipUnknownElementMethod
{
get
{
if (s_skipUnknownElementMethod == null)
{
s_skipUnknownElementMethod = typeof(XmlObjectSerializerReadContext).GetMethod("SkipUnknownElement", Globals.ScanAllMembers);
Debug.Assert(s_skipUnknownElementMethod != null);
}
return s_skipUnknownElementMethod;
}
}
private static MethodInfo s_readIfNullOrRefMethod;
internal static MethodInfo ReadIfNullOrRefMethod
{
get
{
if (s_readIfNullOrRefMethod == null)
{
s_readIfNullOrRefMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadIfNullOrRef", Globals.ScanAllMembers, new Type[] { typeof(XmlReaderDelegator), typeof(Type), typeof(bool) });
Debug.Assert(s_readIfNullOrRefMethod != null);
}
return s_readIfNullOrRefMethod;
}
}
private static MethodInfo s_readAttributesMethod;
internal static MethodInfo ReadAttributesMethod
{
get
{
if (s_readAttributesMethod == null)
{
s_readAttributesMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadAttributes", Globals.ScanAllMembers);
Debug.Assert(s_readAttributesMethod != null);
}
return s_readAttributesMethod;
}
}
private static MethodInfo s_resetAttributesMethod;
internal static MethodInfo ResetAttributesMethod
{
get
{
if (s_resetAttributesMethod == null)
{
s_resetAttributesMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ResetAttributes", Globals.ScanAllMembers);
Debug.Assert(s_resetAttributesMethod != null);
}
return s_resetAttributesMethod;
}
}
private static MethodInfo s_getObjectIdMethod;
internal static MethodInfo GetObjectIdMethod
{
get
{
if (s_getObjectIdMethod == null)
{
s_getObjectIdMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetObjectId", Globals.ScanAllMembers);
Debug.Assert(s_getObjectIdMethod != null);
}
return s_getObjectIdMethod;
}
}
private static MethodInfo s_getArraySizeMethod;
internal static MethodInfo GetArraySizeMethod
{
get
{
if (s_getArraySizeMethod == null)
{
s_getArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetArraySize", Globals.ScanAllMembers);
Debug.Assert(s_getArraySizeMethod != null);
}
return s_getArraySizeMethod;
}
}
private static MethodInfo s_addNewObjectMethod;
internal static MethodInfo AddNewObjectMethod
{
get
{
if (s_addNewObjectMethod == null)
{
s_addNewObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("AddNewObject", Globals.ScanAllMembers);
Debug.Assert(s_addNewObjectMethod != null);
}
return s_addNewObjectMethod;
}
}
private static MethodInfo s_addNewObjectWithIdMethod;
internal static MethodInfo AddNewObjectWithIdMethod
{
get
{
if (s_addNewObjectWithIdMethod == null)
{
s_addNewObjectWithIdMethod = typeof(XmlObjectSerializerReadContext).GetMethod("AddNewObjectWithId", Globals.ScanAllMembers);
Debug.Assert(s_addNewObjectWithIdMethod != null);
}
return s_addNewObjectWithIdMethod;
}
}
private static MethodInfo s_getExistingObjectMethod;
internal static MethodInfo GetExistingObjectMethod
{
get
{
if (s_getExistingObjectMethod == null)
{
s_getExistingObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetExistingObject", Globals.ScanAllMembers);
Debug.Assert(s_getExistingObjectMethod != null);
}
return s_getExistingObjectMethod;
}
}
private static MethodInfo s_ensureArraySizeMethod;
internal static MethodInfo EnsureArraySizeMethod
{
get
{
if (s_ensureArraySizeMethod == null)
{
s_ensureArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("EnsureArraySize", Globals.ScanAllMembers);
Debug.Assert(s_ensureArraySizeMethod != null);
}
return s_ensureArraySizeMethod;
}
}
private static MethodInfo s_trimArraySizeMethod;
internal static MethodInfo TrimArraySizeMethod
{
get
{
if (s_trimArraySizeMethod == null)
{
s_trimArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("TrimArraySize", Globals.ScanAllMembers);
Debug.Assert(s_trimArraySizeMethod != null);
}
return s_trimArraySizeMethod;
}
}
private static MethodInfo s_checkEndOfArrayMethod;
internal static MethodInfo CheckEndOfArrayMethod
{
get
{
if (s_checkEndOfArrayMethod == null)
{
s_checkEndOfArrayMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CheckEndOfArray", Globals.ScanAllMembers);
Debug.Assert(s_checkEndOfArrayMethod != null);
}
return s_checkEndOfArrayMethod;
}
}
private static MethodInfo s_getArrayLengthMethod;
internal static MethodInfo GetArrayLengthMethod
{
get
{
if (s_getArrayLengthMethod == null)
{
s_getArrayLengthMethod = Globals.TypeOfArray.GetProperty("Length").GetMethod;
Debug.Assert(s_getArrayLengthMethod != null);
}
return s_getArrayLengthMethod;
}
}
private static MethodInfo s_createSerializationExceptionMethod;
internal static MethodInfo CreateSerializationExceptionMethod
{
get
{
if (s_createSerializationExceptionMethod == null)
{
s_createSerializationExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CreateSerializationException", Globals.ScanAllMembers, new Type[] { typeof(string) });
Debug.Assert(s_createSerializationExceptionMethod != null);
}
return s_createSerializationExceptionMethod;
}
}
private static MethodInfo s_readSerializationInfoMethod;
internal static MethodInfo ReadSerializationInfoMethod
{
get
{
if (s_readSerializationInfoMethod == null)
s_readSerializationInfoMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadSerializationInfo", Globals.ScanAllMembers);
return s_readSerializationInfoMethod;
}
}
private static MethodInfo s_createUnexpectedStateExceptionMethod;
internal static MethodInfo CreateUnexpectedStateExceptionMethod
{
get
{
if (s_createUnexpectedStateExceptionMethod == null)
{
s_createUnexpectedStateExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CreateUnexpectedStateException", Globals.ScanAllMembers, new Type[] { typeof(XmlNodeType), typeof(XmlReaderDelegator) });
Debug.Assert(s_createUnexpectedStateExceptionMethod != null);
}
return s_createUnexpectedStateExceptionMethod;
}
}
private static MethodInfo s_internalSerializeReferenceMethod;
internal static MethodInfo InternalSerializeReferenceMethod
{
get
{
if (s_internalSerializeReferenceMethod == null)
{
s_internalSerializeReferenceMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("InternalSerializeReference", Globals.ScanAllMembers);
Debug.Assert(s_internalSerializeReferenceMethod != null);
}
return s_internalSerializeReferenceMethod;
}
}
private static MethodInfo s_internalSerializeMethod;
internal static MethodInfo InternalSerializeMethod
{
get
{
if (s_internalSerializeMethod == null)
{
s_internalSerializeMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("InternalSerialize", Globals.ScanAllMembers);
Debug.Assert(s_internalSerializeMethod != null);
}
return s_internalSerializeMethod;
}
}
private static MethodInfo s_writeNullMethod;
internal static MethodInfo WriteNullMethod
{
get
{
if (s_writeNullMethod == null)
{
s_writeNullMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteNull", Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), typeof(Type), typeof(bool) });
Debug.Assert(s_writeNullMethod != null);
}
return s_writeNullMethod;
}
}
private static MethodInfo s_incrementArrayCountMethod;
internal static MethodInfo IncrementArrayCountMethod
{
get
{
if (s_incrementArrayCountMethod == null)
{
s_incrementArrayCountMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementArrayCount", Globals.ScanAllMembers);
Debug.Assert(s_incrementArrayCountMethod != null);
}
return s_incrementArrayCountMethod;
}
}
private static MethodInfo s_incrementCollectionCountMethod;
internal static MethodInfo IncrementCollectionCountMethod
{
get
{
if (s_incrementCollectionCountMethod == null)
{
s_incrementCollectionCountMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementCollectionCount", Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), typeof(ICollection) });
Debug.Assert(s_incrementCollectionCountMethod != null);
}
return s_incrementCollectionCountMethod;
}
}
private static MethodInfo s_incrementCollectionCountGenericMethod;
internal static MethodInfo IncrementCollectionCountGenericMethod
{
get
{
if (s_incrementCollectionCountGenericMethod == null)
{
s_incrementCollectionCountGenericMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementCollectionCountGeneric", Globals.ScanAllMembers);
Debug.Assert(s_incrementCollectionCountGenericMethod != null);
}
return s_incrementCollectionCountGenericMethod;
}
}
private static MethodInfo s_getDefaultValueMethod;
internal static MethodInfo GetDefaultValueMethod
{
get
{
if (s_getDefaultValueMethod == null)
{
s_getDefaultValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(nameof(XmlObjectSerializerWriteContext.GetDefaultValue), Globals.ScanAllMembers);
Debug.Assert(s_getDefaultValueMethod != null);
}
return s_getDefaultValueMethod;
}
}
internal static object GetDefaultValue(Type type)
{
return GetDefaultValueMethod.MakeGenericMethod(type).Invoke(null, Array.Empty<object>());
}
private static MethodInfo s_getNullableValueMethod;
internal static MethodInfo GetNullableValueMethod
{
get
{
if (s_getNullableValueMethod == null)
{
s_getNullableValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("GetNullableValue", Globals.ScanAllMembers);
Debug.Assert(s_getNullableValueMethod != null);
}
return s_getNullableValueMethod;
}
}
private static MethodInfo s_throwRequiredMemberMustBeEmittedMethod;
internal static MethodInfo ThrowRequiredMemberMustBeEmittedMethod
{
get
{
if (s_throwRequiredMemberMustBeEmittedMethod == null)
{
s_throwRequiredMemberMustBeEmittedMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("ThrowRequiredMemberMustBeEmitted", Globals.ScanAllMembers);
Debug.Assert(s_throwRequiredMemberMustBeEmittedMethod != null);
}
return s_throwRequiredMemberMustBeEmittedMethod;
}
}
private static MethodInfo s_getHasValueMethod;
internal static MethodInfo GetHasValueMethod
{
get
{
if (s_getHasValueMethod == null)
{
s_getHasValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("GetHasValue", Globals.ScanAllMembers);
Debug.Assert(s_getHasValueMethod != null);
}
return s_getHasValueMethod;
}
}
private static MethodInfo s_writeISerializableMethod;
internal static MethodInfo WriteISerializableMethod
{
get
{
if (s_writeISerializableMethod == null)
s_writeISerializableMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteISerializable", Globals.ScanAllMembers);
return s_writeISerializableMethod;
}
}
private static MethodInfo s_isMemberTypeSameAsMemberValue;
internal static MethodInfo IsMemberTypeSameAsMemberValue
{
get
{
if (s_isMemberTypeSameAsMemberValue == null)
{
s_isMemberTypeSameAsMemberValue = typeof(XmlObjectSerializerWriteContext).GetMethod("IsMemberTypeSameAsMemberValue", Globals.ScanAllMembers, new Type[] { typeof(object), typeof(Type) });
Debug.Assert(s_isMemberTypeSameAsMemberValue != null);
}
return s_isMemberTypeSameAsMemberValue;
}
}
private static MethodInfo s_writeExtensionDataMethod;
internal static MethodInfo WriteExtensionDataMethod => s_writeExtensionDataMethod ??
(s_writeExtensionDataMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteExtensionData", Globals.ScanAllMembers));
private static MethodInfo s_writeXmlValueMethod;
internal static MethodInfo WriteXmlValueMethod
{
get
{
if (s_writeXmlValueMethod == null)
{
s_writeXmlValueMethod = typeof(DataContract).GetMethod("WriteXmlValue", Globals.ScanAllMembers);
Debug.Assert(s_writeXmlValueMethod != null);
}
return s_writeXmlValueMethod;
}
}
private static MethodInfo s_readXmlValueMethod;
internal static MethodInfo ReadXmlValueMethod
{
get
{
if (s_readXmlValueMethod == null)
{
s_readXmlValueMethod = typeof(DataContract).GetMethod("ReadXmlValue", Globals.ScanAllMembers);
Debug.Assert(s_readXmlValueMethod != null);
}
return s_readXmlValueMethod;
}
}
private static PropertyInfo s_namespaceProperty;
internal static PropertyInfo NamespaceProperty
{
get
{
if (s_namespaceProperty == null)
{
s_namespaceProperty = typeof(DataContract).GetProperty("Namespace", Globals.ScanAllMembers);
Debug.Assert(s_namespaceProperty != null);
}
return s_namespaceProperty;
}
}
private static FieldInfo s_contractNamespacesField;
internal static FieldInfo ContractNamespacesField
{
get
{
if (s_contractNamespacesField == null)
{
s_contractNamespacesField = typeof(ClassDataContract).GetField("ContractNamespaces", Globals.ScanAllMembers);
Debug.Assert(s_contractNamespacesField != null);
}
return s_contractNamespacesField;
}
}
private static FieldInfo s_memberNamesField;
internal static FieldInfo MemberNamesField
{
get
{
if (s_memberNamesField == null)
{
s_memberNamesField = typeof(ClassDataContract).GetField("MemberNames", Globals.ScanAllMembers);
Debug.Assert(s_memberNamesField != null);
}
return s_memberNamesField;
}
}
private static MethodInfo s_extensionDataSetExplicitMethodInfo;
internal static MethodInfo ExtensionDataSetExplicitMethodInfo => s_extensionDataSetExplicitMethodInfo ??
(s_extensionDataSetExplicitMethodInfo = typeof(IExtensibleDataObject).GetMethod(Globals.ExtensionDataSetMethod));
private static PropertyInfo s_childElementNamespacesProperty;
internal static PropertyInfo ChildElementNamespacesProperty
{
get
{
if (s_childElementNamespacesProperty == null)
{
s_childElementNamespacesProperty = typeof(ClassDataContract).GetProperty("ChildElementNamespaces", Globals.ScanAllMembers);
Debug.Assert(s_childElementNamespacesProperty != null);
}
return s_childElementNamespacesProperty;
}
}
private static PropertyInfo s_collectionItemNameProperty;
internal static PropertyInfo CollectionItemNameProperty
{
get
{
if (s_collectionItemNameProperty == null)
{
s_collectionItemNameProperty = typeof(CollectionDataContract).GetProperty("CollectionItemName", Globals.ScanAllMembers);
Debug.Assert(s_collectionItemNameProperty != null);
}
return s_collectionItemNameProperty;
}
}
private static PropertyInfo s_childElementNamespaceProperty;
internal static PropertyInfo ChildElementNamespaceProperty
{
get
{
if (s_childElementNamespaceProperty == null)
{
s_childElementNamespaceProperty = typeof(CollectionDataContract).GetProperty("ChildElementNamespace", Globals.ScanAllMembers);
Debug.Assert(s_childElementNamespaceProperty != null);
}
return s_childElementNamespaceProperty;
}
}
private static MethodInfo s_getDateTimeOffsetMethod;
internal static MethodInfo GetDateTimeOffsetMethod
{
get
{
if (s_getDateTimeOffsetMethod == null)
{
s_getDateTimeOffsetMethod = typeof(DateTimeOffsetAdapter).GetMethod("GetDateTimeOffset", Globals.ScanAllMembers);
Debug.Assert(s_getDateTimeOffsetMethod != null);
}
return s_getDateTimeOffsetMethod;
}
}
private static MethodInfo s_getDateTimeOffsetAdapterMethod;
internal static MethodInfo GetDateTimeOffsetAdapterMethod
{
get
{
if (s_getDateTimeOffsetAdapterMethod == null)
{
s_getDateTimeOffsetAdapterMethod = typeof(DateTimeOffsetAdapter).GetMethod("GetDateTimeOffsetAdapter", Globals.ScanAllMembers);
Debug.Assert(s_getDateTimeOffsetAdapterMethod != null);
}
return s_getDateTimeOffsetAdapterMethod;
}
}
#if !NET_NATIVE
private static MethodInfo s_getTypeHandleMethod;
internal static MethodInfo GetTypeHandleMethod
{
get
{
if (s_getTypeHandleMethod == null)
{
s_getTypeHandleMethod = typeof(Type).GetMethod("get_TypeHandle");
Debug.Assert(s_getTypeHandleMethod != null);
}
return s_getTypeHandleMethod;
}
}
private static MethodInfo s_getTypeMethod;
internal static MethodInfo GetTypeMethod
{
get
{
if (s_getTypeMethod == null)
{
s_getTypeMethod = typeof(object).GetMethod("GetType");
Debug.Assert(s_getTypeMethod != null);
}
return s_getTypeMethod;
}
}
private static MethodInfo s_throwInvalidDataContractExceptionMethod;
internal static MethodInfo ThrowInvalidDataContractExceptionMethod
{
get
{
if (s_throwInvalidDataContractExceptionMethod == null)
{
s_throwInvalidDataContractExceptionMethod = typeof(DataContract).GetMethod("ThrowInvalidDataContractException", Globals.ScanAllMembers, new Type[] { typeof(string), typeof(Type) });
Debug.Assert(s_throwInvalidDataContractExceptionMethod != null);
}
return s_throwInvalidDataContractExceptionMethod;
}
}
private static PropertyInfo s_serializeReadOnlyTypesProperty;
internal static PropertyInfo SerializeReadOnlyTypesProperty
{
get
{
if (s_serializeReadOnlyTypesProperty == null)
{
s_serializeReadOnlyTypesProperty = typeof(XmlObjectSerializerWriteContext).GetProperty("SerializeReadOnlyTypes", Globals.ScanAllMembers);
Debug.Assert(s_serializeReadOnlyTypesProperty != null);
}
return s_serializeReadOnlyTypesProperty;
}
}
private static PropertyInfo s_classSerializationExceptionMessageProperty;
internal static PropertyInfo ClassSerializationExceptionMessageProperty
{
get
{
if (s_classSerializationExceptionMessageProperty == null)
{
s_classSerializationExceptionMessageProperty = typeof(ClassDataContract).GetProperty("SerializationExceptionMessage", Globals.ScanAllMembers);
Debug.Assert(s_classSerializationExceptionMessageProperty != null);
}
return s_classSerializationExceptionMessageProperty;
}
}
private static PropertyInfo s_collectionSerializationExceptionMessageProperty;
internal static PropertyInfo CollectionSerializationExceptionMessageProperty
{
get
{
if (s_collectionSerializationExceptionMessageProperty == null)
{
s_collectionSerializationExceptionMessageProperty = typeof(CollectionDataContract).GetProperty("SerializationExceptionMessage", Globals.ScanAllMembers);
Debug.Assert(s_collectionSerializationExceptionMessageProperty != null);
}
return s_collectionSerializationExceptionMessageProperty;
}
}
#endif
}
}
| |
namespace JoanZapata.XamarinIconify.Fonts
{
public enum MaterialCommunityIcons
{
mdi_account = '\uf101',
mdi_account_alert = '\uf102',
mdi_account_box = '\uf103',
mdi_account_box_outline = '\uf104',
mdi_account_check = '\uf105',
mdi_account_circle = '\uf106',
mdi_account_key = '\uf107',
mdi_account_location = '\uf108',
mdi_account_minus = '\uf109',
mdi_account_multiple = '\uf10a',
mdi_account_multiple_outline = '\uf10b',
mdi_account_multiple_plus = '\uf10c',
mdi_account_network = '\uf10d',
mdi_account_outline = '\uf10e',
mdi_account_plus = '\uf10f',
mdi_account_remove = '\uf110',
mdi_account_search = '\uf111',
mdi_account_star = '\uf112',
mdi_account_star_variant = '\uf113',
mdi_account_switch = '\uf114',
mdi_airballoon = '\uf115',
mdi_airplane = '\uf116',
mdi_airplane_off = '\uf117',
mdi_alarm = '\uf118',
mdi_alarm_check = '\uf119',
mdi_alarm_multiple = '\uf11a',
mdi_alarm_off = '\uf11b',
mdi_alarm_plus = '\uf11c',
mdi_album = '\uf11d',
mdi_alert = '\uf11e',
mdi_alert_box = '\uf11f',
mdi_alert_circle = '\uf120',
mdi_alert_octagon = '\uf121',
mdi_alpha = '\uf122',
mdi_alphabetical = '\uf123',
mdi_amazon = '\uf124',
mdi_amazon_clouddrive = '\uf125',
mdi_ambulance = '\uf126',
mdi_android = '\uf127',
mdi_android_debug_bridge = '\uf128',
mdi_android_studio = '\uf129',
mdi_apple = '\uf12a',
mdi_apple_finder = '\uf12b',
mdi_apple_ios = '\uf12c',
mdi_apple_mobileme = '\uf12d',
mdi_apple_safari = '\uf12e',
mdi_appnet = '\uf12f',
mdi_apps = '\uf130',
mdi_archive = '\uf131',
mdi_arrange_bring_forward = '\uf132',
mdi_arrange_bring_to_front = '\uf133',
mdi_arrange_send_backward = '\uf134',
mdi_arrange_send_to_back = '\uf135',
mdi_arrow_all = '\uf136',
mdi_arrow_bottom_left = '\uf137',
mdi_arrow_bottom_right = '\uf138',
mdi_arrow_collapse = '\uf139',
mdi_arrow_down = '\uf13a',
mdi_arrow_down_bold = '\uf13b',
mdi_arrow_down_bold_circle = '\uf13c',
mdi_arrow_down_bold_circle_outline = '\uf13d',
mdi_arrow_down_bold_hexagon_outline = '\uf13e',
mdi_arrow_expand = '\uf13f',
mdi_arrow_left = '\uf140',
mdi_arrow_left_bold = '\uf141',
mdi_arrow_left_bold_circle = '\uf142',
mdi_arrow_left_bold_circle_outline = '\uf143',
mdi_arrow_left_bold_hexagon_outline = '\uf144',
mdi_arrow_right = '\uf145',
mdi_arrow_right_bold = '\uf146',
mdi_arrow_right_bold_circle = '\uf147',
mdi_arrow_right_bold_circle_outline = '\uf148',
mdi_arrow_right_bold_hexagon_outline = '\uf149',
mdi_arrow_top_left = '\uf14a',
mdi_arrow_top_right = '\uf14b',
mdi_arrow_up = '\uf14c',
mdi_arrow_up_bold = '\uf14d',
mdi_arrow_up_bold_circle = '\uf14e',
mdi_arrow_up_bold_circle_outline = '\uf14f',
mdi_arrow_up_bold_hexagon_outline = '\uf150',
mdi_at = '\uf151',
mdi_attachment = '\uf152',
mdi_audiobook = '\uf153',
mdi_auto_fix = '\uf154',
mdi_auto_upload = '\uf155',
mdi_baby = '\uf156',
mdi_backburger = '\uf157',
mdi_backup_restore = '\uf158',
mdi_bank = '\uf159',
mdi_barcode = '\uf15a',
mdi_barley = '\uf15b',
mdi_barrel = '\uf15c',
mdi_basecamp = '\uf15d',
mdi_basket = '\uf15e',
mdi_basket_fill = '\uf15f',
mdi_basket_unfill = '\uf160',
mdi_battery = '\uf161',
mdi_battery_10 = '\uf162',
mdi_battery_20 = '\uf163',
mdi_battery_30 = '\uf164',
mdi_battery_40 = '\uf165',
mdi_battery_50 = '\uf166',
mdi_battery_60 = '\uf167',
mdi_battery_70 = '\uf168',
mdi_battery_80 = '\uf169',
mdi_battery_90 = '\uf16a',
mdi_battery_alert = '\uf16b',
mdi_battery_charging_100 = '\uf16c',
mdi_battery_charging_20 = '\uf16d',
mdi_battery_charging_30 = '\uf16e',
mdi_battery_charging_40 = '\uf16f',
mdi_battery_charging_60 = '\uf170',
mdi_battery_charging_80 = '\uf171',
mdi_battery_charging_90 = '\uf172',
mdi_battery_minus = '\uf173',
mdi_battery_negative = '\uf174',
mdi_battery_outline = '\uf175',
mdi_battery_plus = '\uf176',
mdi_battery_positive = '\uf177',
mdi_battery_unknown = '\uf178',
mdi_beach = '\uf179',
mdi_beaker = '\uf17a',
mdi_beaker_empty = '\uf17b',
mdi_beaker_empty_outline = '\uf17c',
mdi_beaker_outline = '\uf17d',
mdi_beats = '\uf17e',
mdi_beer = '\uf17f',
mdi_behance = '\uf180',
mdi_bell = '\uf181',
mdi_bell_off = '\uf182',
mdi_bell_outline = '\uf183',
mdi_bell_ring = '\uf184',
mdi_bell_ring_outline = '\uf185',
mdi_bell_sleep = '\uf186',
mdi_beta = '\uf187',
mdi_bike = '\uf188',
mdi_bing = '\uf189',
mdi_binoculars = '\uf18a',
mdi_bio = '\uf18b',
mdi_biohazard = '\uf18c',
mdi_bitbucket = '\uf18d',
mdi_black_mesa = '\uf18e',
mdi_blackberry = '\uf18f',
mdi_blinds = '\uf190',
mdi_block_helper = '\uf191',
mdi_blogger = '\uf192',
mdi_bluetooth = '\uf193',
mdi_bluetooth_audio = '\uf194',
mdi_bluetooth_connect = '\uf195',
mdi_bluetooth_settings = '\uf196',
mdi_bluetooth_transfer = '\uf197',
mdi_blur = '\uf198',
mdi_blur_linear = '\uf199',
mdi_blur_off = '\uf19a',
mdi_blur_radial = '\uf19b',
mdi_bone = '\uf19c',
mdi_book = '\uf19d',
mdi_book_multiple = '\uf19e',
mdi_book_multiple_variant = '\uf19f',
mdi_book_open = '\uf1a0',
mdi_book_variant = '\uf1a1',
mdi_bookmark = '\uf1a2',
mdi_bookmark_check = '\uf1a3',
mdi_bookmark_music = '\uf1a4',
mdi_bookmark_outline = '\uf1a5',
mdi_bookmark_outline_plus = '\uf1a6',
mdi_bookmark_plus = '\uf1a7',
mdi_bookmark_remove = '\uf1a8',
mdi_border_all = '\uf1a9',
mdi_border_bottom = '\uf1aa',
mdi_border_color = '\uf1ab',
mdi_border_horizontal = '\uf1ac',
mdi_border_inside = '\uf1ad',
mdi_border_left = '\uf1ae',
mdi_border_none = '\uf1af',
mdi_border_outside = '\uf1b0',
mdi_border_right = '\uf1b1',
mdi_border_top = '\uf1b2',
mdi_border_vertical = '\uf1b3',
mdi_bowling = '\uf1b4',
mdi_box = '\uf1b5',
mdi_briefcase = '\uf1b6',
mdi_briefcase_check = '\uf1b7',
mdi_briefcase_download = '\uf1b8',
mdi_briefcase_upload = '\uf1b9',
mdi_brightness_1 = '\uf1ba',
mdi_brightness_2 = '\uf1bb',
mdi_brightness_3 = '\uf1bc',
mdi_brightness_4 = '\uf1bd',
mdi_brightness_5 = '\uf1be',
mdi_brightness_6 = '\uf1bf',
mdi_brightness_7 = '\uf1c0',
mdi_brightness_auto = '\uf1c1',
mdi_broom = '\uf1c2',
mdi_brush = '\uf1c3',
mdi_bug = '\uf1c4',
mdi_bulletin_board = '\uf1c5',
mdi_bullhorn = '\uf1c6',
mdi_bus = '\uf1c7',
mdi_cake = '\uf1c8',
mdi_cake_variant = '\uf1c9',
mdi_calculator = '\uf1ca',
mdi_calendar = '\uf1cb',
mdi_calendar_blank = '\uf1cc',
mdi_calendar_check = '\uf1cd',
mdi_calendar_clock = '\uf1ce',
mdi_calendar_multiple = '\uf1cf',
mdi_calendar_multiple_check = '\uf1d0',
mdi_calendar_plus = '\uf1d1',
mdi_calendar_remove = '\uf1d2',
mdi_calendar_text = '\uf1d3',
mdi_calendar_today = '\uf1d4',
mdi_camcorder = '\uf1d5',
mdi_camcorder_box = '\uf1d6',
mdi_camcorder_box_off = '\uf1d7',
mdi_camcorder_off = '\uf1d8',
mdi_camera = '\uf1d9',
mdi_camera_front = '\uf1da',
mdi_camera_front_variant = '\uf1db',
mdi_camera_iris = '\uf1dc',
mdi_camera_party_mode = '\uf1dd',
mdi_camera_rear = '\uf1de',
mdi_camera_rear_variant = '\uf1df',
mdi_camera_switch = '\uf1e0',
mdi_camera_timer = '\uf1e1',
mdi_candycane = '\uf1e2',
mdi_car = '\uf1e3',
mdi_car_wash = '\uf1e4',
mdi_carrot = '\uf1e5',
mdi_cart = '\uf1e6',
mdi_cart_outline = '\uf1e7',
mdi_cash = '\uf1e8',
mdi_cash_100 = '\uf1e9',
mdi_cash_multiple = '\uf1ea',
mdi_cash_usd = '\uf1eb',
mdi_cast = '\uf1ec',
mdi_cast_connected = '\uf1ed',
mdi_castle = '\uf1ee',
mdi_cat = '\uf1ef',
mdi_cellphone = '\uf1f0',
mdi_cellphone_android = '\uf1f1',
mdi_cellphone_dock = '\uf1f2',
mdi_cellphone_iphone = '\uf1f3',
mdi_cellphone_link = '\uf1f4',
mdi_cellphone_link_off = '\uf1f5',
mdi_cellphone_settings = '\uf1f6',
mdi_chair_school = '\uf1f7',
mdi_chart_arc = '\uf1f8',
mdi_chart_areaspline = '\uf1f9',
mdi_chart_bar = '\uf1fa',
mdi_chart_histogram = '\uf1fb',
mdi_chart_line = '\uf1fc',
mdi_chart_pie = '\uf1fd',
mdi_check = '\uf1fe',
mdi_check_all = '\uf1ff',
mdi_checkbox_blank = '\uf200',
mdi_checkbox_blank_circle = '\uf201',
mdi_checkbox_blank_circle_outline = '\uf202',
mdi_checkbox_blank_outline = '\uf203',
mdi_checkbox_marked = '\uf204',
mdi_checkbox_marked_circle = '\uf205',
mdi_checkbox_marked_circle_outline = '\uf206',
mdi_checkbox_marked_outline = '\uf207',
mdi_checkbox_multiple_blank = '\uf208',
mdi_checkbox_multiple_blank_outline = '\uf209',
mdi_checkbox_multiple_marked = '\uf20a',
mdi_checkbox_multiple_marked_outline = '\uf20b',
mdi_checkerboard = '\uf20c',
mdi_chevron_double_down = '\uf20d',
mdi_chevron_double_left = '\uf20e',
mdi_chevron_double_right = '\uf20f',
mdi_chevron_double_up = '\uf210',
mdi_chevron_down = '\uf211',
mdi_chevron_left = '\uf212',
mdi_chevron_right = '\uf213',
mdi_chevron_up = '\uf214',
mdi_church = '\uf215',
mdi_cisco_webex = '\uf216',
mdi_city = '\uf217',
mdi_clipboard = '\uf218',
mdi_clipboard_account = '\uf219',
mdi_clipboard_alert = '\uf21a',
mdi_clipboard_arrow_down = '\uf21b',
mdi_clipboard_arrow_left = '\uf21c',
mdi_clipboard_check = '\uf21d',
mdi_clipboard_outline = '\uf21e',
mdi_clipboard_text = '\uf21f',
mdi_clippy = '\uf220',
mdi_clock = '\uf221',
mdi_clock_fast = '\uf222',
mdi_close = '\uf223',
mdi_close_box = '\uf224',
mdi_close_box_outline = '\uf225',
mdi_close_circle = '\uf226',
mdi_close_circle_outline = '\uf227',
mdi_close_network = '\uf228',
mdi_closed_caption = '\uf229',
mdi_cloud = '\uf22a',
mdi_cloud_check = '\uf22b',
mdi_cloud_circle = '\uf22c',
mdi_cloud_download = '\uf22d',
mdi_cloud_outline = '\uf22e',
mdi_cloud_outline_off = '\uf22f',
mdi_cloud_upload = '\uf230',
mdi_code_array = '\uf231',
mdi_code_braces = '\uf232',
mdi_code_equal = '\uf233',
mdi_code_greater_than = '\uf234',
mdi_code_less_than = '\uf235',
mdi_code_less_than_or_equal = '\uf236',
mdi_code_not_equal = '\uf237',
mdi_code_not_equal_variant = '\uf238',
mdi_code_string = '\uf239',
mdi_code_tags = '\uf23a',
mdi_codepen = '\uf23b',
mdi_coffee = '\uf23c',
mdi_coffee_to_go = '\uf23d',
mdi_coin = '\uf23e',
mdi_color_helper = '\uf23f',
mdi_comment = '\uf240',
mdi_comment_account = '\uf241',
mdi_comment_account_outline = '\uf242',
mdi_comment_alert = '\uf243',
mdi_comment_alert_outline = '\uf244',
mdi_comment_check = '\uf245',
mdi_comment_check_outline = '\uf246',
mdi_comment_multiple_outline = '\uf247',
mdi_comment_outline = '\uf248',
mdi_comment_plus_outline = '\uf249',
mdi_comment_processing = '\uf24a',
mdi_comment_processing_outline = '\uf24b',
mdi_comment_remove_outline = '\uf24c',
mdi_comment_text = '\uf24d',
mdi_comment_text_outline = '\uf24e',
mdi_compare = '\uf24f',
mdi_compass = '\uf250',
mdi_compass_outline = '\uf251',
mdi_console = '\uf252',
mdi_content_copy = '\uf253',
mdi_content_cut = '\uf254',
mdi_content_duplicate = '\uf255',
mdi_content_paste = '\uf256',
mdi_content_save = '\uf257',
mdi_content_save_all = '\uf258',
mdi_contrast = '\uf259',
mdi_contrast_box = '\uf25a',
mdi_contrast_circle = '\uf25b',
mdi_cow = '\uf25c',
mdi_credit_card = '\uf25d',
mdi_credit_card_multiple = '\uf25e',
mdi_crop = '\uf25f',
mdi_crop_free = '\uf260',
mdi_crop_landscape = '\uf261',
mdi_crop_portrait = '\uf262',
mdi_crop_square = '\uf263',
mdi_crosshairs = '\uf264',
mdi_crosshairs_gps = '\uf265',
mdi_crown = '\uf266',
mdi_cube = '\uf267',
mdi_cube_outline = '\uf268',
mdi_cube_unfolded = '\uf269',
mdi_cup = '\uf26a',
mdi_cup_water = '\uf26b',
mdi_currency_btc = '\uf26c',
mdi_currency_eur = '\uf26d',
mdi_currency_gbp = '\uf26e',
mdi_currency_inr = '\uf26f',
mdi_currency_rub = '\uf270',
mdi_currency_try = '\uf271',
mdi_currency_usd = '\uf272',
mdi_cursor_default = '\uf273',
mdi_cursor_default_outline = '\uf274',
mdi_cursor_move = '\uf275',
mdi_cursor_pointer = '\uf276',
mdi_database = '\uf277',
mdi_database_minus = '\uf278',
mdi_database_outline = '\uf279',
mdi_database_plus = '\uf27a',
mdi_debug_step_into = '\uf27b',
mdi_debug_step_out = '\uf27c',
mdi_debug_step_over = '\uf27d',
mdi_decimal_decrease = '\uf27e',
mdi_decimal_increase = '\uf27f',
mdi_delete = '\uf280',
mdi_delete_variant = '\uf281',
mdi_deskphone = '\uf282',
mdi_desktop_mac = '\uf283',
mdi_desktop_tower = '\uf284',
mdi_details = '\uf285',
mdi_deviantart = '\uf286',
mdi_diamond = '\uf287',
mdi_dice = '\uf288',
mdi_dice_1 = '\uf289',
mdi_dice_2 = '\uf28a',
mdi_dice_3 = '\uf28b',
mdi_dice_4 = '\uf28c',
mdi_dice_5 = '\uf28d',
mdi_dice_6 = '\uf28e',
mdi_directions = '\uf28f',
mdi_disk_alert = '\uf290',
mdi_disqus = '\uf291',
mdi_disqus_outline = '\uf292',
mdi_division = '\uf293',
mdi_division_box = '\uf294',
mdi_dns = '\uf295',
mdi_domain = '\uf296',
mdi_dots_horizontal = '\uf297',
mdi_dots_vertical = '\uf298',
mdi_download = '\uf299',
mdi_drag = '\uf29a',
mdi_drag_horizontal = '\uf29b',
mdi_drag_vertical = '\uf29c',
mdi_drawing = '\uf29d',
mdi_drawing_box = '\uf29e',
mdi_dribbble = '\uf29f',
mdi_dribbble_box = '\uf2a0',
mdi_drone = '\uf2a1',
mdi_dropbox = '\uf2a2',
mdi_drupal = '\uf2a3',
mdi_duck = '\uf2a4',
mdi_dumbbell = '\uf2a5',
mdi_earth = '\uf2a6',
mdi_earth_off = '\uf2a7',
mdi_edge = '\uf2a8',
mdi_eject = '\uf2a9',
mdi_elevation_decline = '\uf2aa',
mdi_elevation_rise = '\uf2ab',
mdi_elevator = '\uf2ac',
mdi_email = '\uf2ad',
mdi_email_open = '\uf2ae',
mdi_email_outline = '\uf2af',
mdi_email_secure = '\uf2b0',
mdi_emoticon = '\uf2b1',
mdi_emoticon_cool = '\uf2b2',
mdi_emoticon_devil = '\uf2b3',
mdi_emoticon_happy = '\uf2b4',
mdi_emoticon_neutral = '\uf2b5',
mdi_emoticon_poop = '\uf2b6',
mdi_emoticon_sad = '\uf2b7',
mdi_emoticon_tongue = '\uf2b8',
mdi_engine = '\uf2b9',
mdi_engine_outline = '\uf2ba',
mdi_equal = '\uf2bb',
mdi_equal_box = '\uf2bc',
mdi_eraser = '\uf2bd',
mdi_escalator = '\uf2be',
mdi_etsy = '\uf2bf',
mdi_evernote = '\uf2c0',
mdi_exclamation = '\uf2c1',
mdi_exit_to_app = '\uf2c2',
mdi_export = '\uf2c3',
mdi_eye = '\uf2c4',
mdi_eye_off = '\uf2c5',
mdi_eyedropper = '\uf2c6',
mdi_eyedropper_variant = '\uf2c7',
mdi_facebook = '\uf2c8',
mdi_facebook_box = '\uf2c9',
mdi_facebook_messenger = '\uf2ca',
mdi_factory = '\uf2cb',
mdi_fan = '\uf2cc',
mdi_fast_forward = '\uf2cd',
mdi_ferry = '\uf2ce',
mdi_file = '\uf2cf',
mdi_file_cloud = '\uf2d0',
mdi_file_delimited = '\uf2d1',
mdi_file_document = '\uf2d2',
mdi_file_document_box = '\uf2d3',
mdi_file_excel = '\uf2d4',
mdi_file_excel_box = '\uf2d5',
mdi_file_find = '\uf2d6',
mdi_file_image = '\uf2d7',
mdi_file_image_box = '\uf2d8',
mdi_file_multiple = '\uf2d9',
mdi_file_music = '\uf2da',
mdi_file_outline = '\uf2db',
mdi_file_pdf = '\uf2dc',
mdi_file_pdf_box = '\uf2dd',
mdi_file_powerpoint = '\uf2de',
mdi_file_powerpoint_box = '\uf2df',
mdi_file_presentation_box = '\uf2e0',
mdi_file_video = '\uf2e1',
mdi_file_word = '\uf2e2',
mdi_file_word_box = '\uf2e3',
mdi_file_xml = '\uf2e4',
mdi_film = '\uf2e5',
mdi_filmstrip = '\uf2e6',
mdi_filmstrip_off = '\uf2e7',
mdi_filter = '\uf2e8',
mdi_filter_outline = '\uf2e9',
mdi_filter_remove = '\uf2ea',
mdi_filter_remove_outline = '\uf2eb',
mdi_filter_variant = '\uf2ec',
mdi_fire = '\uf2ed',
mdi_firefox = '\uf2ee',
mdi_fish = '\uf2ef',
mdi_flag = '\uf2f0',
mdi_flag_checkered = '\uf2f1',
mdi_flag_outline = '\uf2f2',
mdi_flag_outline_variant = '\uf2f3',
mdi_flag_triangle = '\uf2f4',
mdi_flag_variant = '\uf2f5',
mdi_flash = '\uf2f6',
mdi_flash_auto = '\uf2f7',
mdi_flash_off = '\uf2f8',
mdi_flashlight = '\uf2f9',
mdi_flashlight_off = '\uf2fa',
mdi_flattr = '\uf2fb',
mdi_flip_to_back = '\uf2fc',
mdi_flip_to_front = '\uf2fd',
mdi_floppy = '\uf2fe',
mdi_flower = '\uf2ff',
mdi_folder = '\uf300',
mdi_folder_account = '\uf301',
mdi_folder_download = '\uf302',
mdi_folder_google_drive = '\uf303',
mdi_folder_image = '\uf304',
mdi_folder_lock = '\uf305',
mdi_folder_lock_open = '\uf306',
mdi_folder_move = '\uf307',
mdi_folder_multiple = '\uf308',
mdi_folder_multiple_image = '\uf309',
mdi_folder_multiple_outline = '\uf30a',
mdi_folder_outline = '\uf30b',
mdi_folder_plus = '\uf30c',
mdi_folder_remove = '\uf30d',
mdi_folder_upload = '\uf30e',
mdi_food = '\uf30f',
mdi_food_apple = '\uf310',
mdi_food_variant = '\uf311',
mdi_football = '\uf312',
mdi_football_helmet = '\uf313',
mdi_format_align_center = '\uf314',
mdi_format_align_justify = '\uf315',
mdi_format_align_left = '\uf316',
mdi_format_align_right = '\uf317',
mdi_format_bold = '\uf318',
mdi_format_clear = '\uf319',
mdi_format_color_fill = '\uf31a',
mdi_format_float_center = '\uf31b',
mdi_format_float_left = '\uf31c',
mdi_format_float_none = '\uf31d',
mdi_format_float_right = '\uf31e',
mdi_format_header_1 = '\uf31f',
mdi_format_header_2 = '\uf320',
mdi_format_header_3 = '\uf321',
mdi_format_header_4 = '\uf322',
mdi_format_header_5 = '\uf323',
mdi_format_header_6 = '\uf324',
mdi_format_header_decrease = '\uf325',
mdi_format_header_equal = '\uf326',
mdi_format_header_increase = '\uf327',
mdi_format_header_pound = '\uf328',
mdi_format_indent_decrease = '\uf329',
mdi_format_indent_increase = '\uf32a',
mdi_format_italic = '\uf32b',
mdi_format_line_spacing = '\uf32c',
mdi_format_list_bulleted = '\uf32d',
mdi_format_list_numbers = '\uf32e',
mdi_format_paint = '\uf32f',
mdi_format_paragraph = '\uf330',
mdi_format_quote = '\uf331',
mdi_format_size = '\uf332',
mdi_format_strikethrough = '\uf333',
mdi_format_subscript = '\uf334',
mdi_format_superscript = '\uf335',
mdi_format_text = '\uf336',
mdi_format_textdirection_l_to_r = '\uf337',
mdi_format_textdirection_r_to_l = '\uf338',
mdi_format_underline = '\uf339',
mdi_format_wrap_inline = '\uf33a',
mdi_format_wrap_square = '\uf33b',
mdi_format_wrap_tight = '\uf33c',
mdi_format_wrap_top_bottom = '\uf33d',
mdi_forum = '\uf33e',
mdi_forward = '\uf33f',
mdi_foursquare = '\uf340',
mdi_fridge = '\uf341',
mdi_fullscreen = '\uf342',
mdi_fullscreen_exit = '\uf343',
mdi_function = '\uf344',
mdi_gamepad = '\uf345',
mdi_gamepad_variant = '\uf346',
mdi_gas_station = '\uf347',
mdi_gavel = '\uf348',
mdi_gender_female = '\uf349',
mdi_gender_male = '\uf34a',
mdi_gender_male_female = '\uf34b',
mdi_gender_transgender = '\uf34c',
mdi_gift = '\uf34d',
mdi_git = '\uf34e',
mdi_github_box = '\uf34f',
mdi_github_circle = '\uf350',
mdi_glass_flute = '\uf351',
mdi_glass_mug = '\uf352',
mdi_glass_stange = '\uf353',
mdi_glass_tulip = '\uf354',
mdi_glasses = '\uf355',
mdi_gmail = '\uf356',
mdi_google = '\uf357',
mdi_google_chrome = '\uf358',
mdi_google_circles = '\uf359',
mdi_google_circles_communities = '\uf35a',
mdi_google_circles_extended = '\uf35b',
mdi_google_circles_group = '\uf35c',
mdi_google_controller = '\uf35d',
mdi_google_controller_off = '\uf35e',
mdi_google_drive = '\uf35f',
mdi_google_earth = '\uf360',
mdi_google_glass = '\uf361',
mdi_google_maps = '\uf362',
mdi_google_pages = '\uf363',
mdi_google_play = '\uf364',
mdi_google_plus = '\uf365',
mdi_google_plus_box = '\uf366',
mdi_grid = '\uf367',
mdi_grid_off = '\uf368',
mdi_group = '\uf369',
mdi_guitar = '\uf36a',
mdi_guitar_pick = '\uf36b',
mdi_guitar_pick_outline = '\uf36c',
mdi_hand_pointing_right = '\uf36d',
mdi_hanger = '\uf36e',
mdi_hangouts = '\uf36f',
mdi_harddisk = '\uf370',
mdi_headphones = '\uf371',
mdi_headphones_box = '\uf372',
mdi_headphones_settings = '\uf373',
mdi_headset = '\uf374',
mdi_headset_dock = '\uf375',
mdi_headset_off = '\uf376',
mdi_heart = '\uf377',
mdi_heart_box = '\uf378',
mdi_heart_box_outline = '\uf379',
mdi_heart_broken = '\uf37a',
mdi_heart_outline = '\uf37b',
mdi_help = '\uf37c',
mdi_help_circle = '\uf37d',
mdi_hexagon = '\uf37e',
mdi_hexagon_outline = '\uf37f',
mdi_history = '\uf380',
mdi_hololens = '\uf381',
mdi_home = '\uf382',
mdi_home_modern = '\uf383',
mdi_home_variant = '\uf384',
mdi_hops = '\uf385',
mdi_hospital = '\uf386',
mdi_hospital_building = '\uf387',
mdi_hospital_marker = '\uf388',
mdi_hotel = '\uf389',
mdi_houzz = '\uf38a',
mdi_houzz_box = '\uf38b',
mdi_human = '\uf38c',
mdi_human_child = '\uf38d',
mdi_human_male_female = '\uf38e',
mdi_image_album = '\uf38f',
mdi_image_area = '\uf390',
mdi_image_area_close = '\uf391',
mdi_image_broken = '\uf392',
mdi_image_filter = '\uf393',
mdi_image_filter_black_white = '\uf394',
mdi_image_filter_center_focus = '\uf395',
mdi_image_filter_drama = '\uf396',
mdi_image_filter_frames = '\uf397',
mdi_image_filter_hdr = '\uf398',
mdi_image_filter_none = '\uf399',
mdi_image_filter_tilt_shift = '\uf39a',
mdi_image_filter_vintage = '\uf39b',
mdi_import = '\uf39c',
mdi_inbox = '\uf39d',
mdi_information = '\uf39e',
mdi_information_outline = '\uf39f',
mdi_instagram = '\uf3a0',
mdi_instapaper = '\uf3a1',
mdi_internet_explorer = '\uf3a2',
mdi_invert_colors = '\uf3a3',
mdi_jira = '\uf3a4',
mdi_jsfiddle = '\uf3a5',
mdi_keg = '\uf3a6',
mdi_key = '\uf3a7',
mdi_key_change = '\uf3a8',
mdi_key_minus = '\uf3a9',
mdi_key_plus = '\uf3aa',
mdi_key_remove = '\uf3ab',
mdi_key_variant = '\uf3ac',
mdi_keyboard = '\uf3ad',
mdi_keyboard_backspace = '\uf3ae',
mdi_keyboard_caps = '\uf3af',
mdi_keyboard_close = '\uf3b0',
mdi_keyboard_off = '\uf3b1',
mdi_keyboard_return = '\uf3b2',
mdi_keyboard_tab = '\uf3b3',
mdi_keyboard_variant = '\uf3b4',
mdi_label = '\uf3b5',
mdi_label_outline = '\uf3b6',
mdi_language_csharp = '\uf3b7',
mdi_language_css3 = '\uf3b8',
mdi_language_html5 = '\uf3b9',
mdi_language_javascript = '\uf3ba',
mdi_language_python = '\uf3bb',
mdi_language_python_text = '\uf3bc',
mdi_laptop = '\uf3bd',
mdi_laptop_chromebook = '\uf3be',
mdi_laptop_mac = '\uf3bf',
mdi_laptop_windows = '\uf3c0',
mdi_lastfm = '\uf3c1',
mdi_launch = '\uf3c2',
mdi_layers = '\uf3c3',
mdi_layers_off = '\uf3c4',
mdi_leaf = '\uf3c5',
mdi_library = '\uf3c6',
mdi_library_books = '\uf3c7',
mdi_library_music = '\uf3c8',
mdi_library_plus = '\uf3c9',
mdi_lightbulb = '\uf3ca',
mdi_lightbulb_outline = '\uf3cb',
mdi_link = '\uf3cc',
mdi_link_off = '\uf3cd',
mdi_link_variant = '\uf3ce',
mdi_link_variant_off = '\uf3cf',
mdi_linkedin = '\uf3d0',
mdi_linkedin_box = '\uf3d1',
mdi_linux = '\uf3d2',
mdi_lock = '\uf3d3',
mdi_lock_open = '\uf3d4',
mdi_lock_open_outline = '\uf3d5',
mdi_lock_outline = '\uf3d6',
mdi_login = '\uf3d7',
mdi_logout = '\uf3d8',
mdi_looks = '\uf3d9',
mdi_loupe = '\uf3da',
mdi_lumx = '\uf3db',
mdi_magnet = '\uf3dc',
mdi_magnet_on = '\uf3dd',
mdi_magnify = '\uf3de',
mdi_magnify_minus = '\uf3df',
mdi_magnify_plus = '\uf3e0',
mdi_mail_ru = '\uf3e1',
mdi_map = '\uf3e2',
mdi_map_marker = '\uf3e3',
mdi_map_marker_circle = '\uf3e4',
mdi_map_marker_multiple = '\uf3e5',
mdi_map_marker_off = '\uf3e6',
mdi_map_marker_radius = '\uf3e7',
mdi_margin = '\uf3e8',
mdi_markdown = '\uf3e9',
mdi_marker_check = '\uf3ea',
mdi_martini = '\uf3eb',
mdi_material_ui = '\uf3ec',
mdi_math_compass = '\uf3ed',
mdi_maxcdn = '\uf3ee',
mdi_medium = '\uf3ef',
mdi_memory = '\uf3f0',
mdi_menu = '\uf3f1',
mdi_menu_down = '\uf3f2',
mdi_menu_left = '\uf3f3',
mdi_menu_right = '\uf3f4',
mdi_menu_up = '\uf3f5',
mdi_message = '\uf3f6',
mdi_message_alert = '\uf3f7',
mdi_message_draw = '\uf3f8',
mdi_message_image = '\uf3f9',
mdi_message_processing = '\uf3fa',
mdi_message_reply = '\uf3fb',
mdi_message_text = '\uf3fc',
mdi_message_text_outline = '\uf3fd',
mdi_message_video = '\uf3fe',
mdi_microphone = '\uf3ff',
mdi_microphone_off = '\uf400',
mdi_microphone_outline = '\uf401',
mdi_microphone_settings = '\uf402',
mdi_microphone_variant = '\uf403',
mdi_microphone_variant_off = '\uf404',
mdi_minus = '\uf405',
mdi_minus_box = '\uf406',
mdi_minus_circle = '\uf407',
mdi_minus_circle_outline = '\uf408',
mdi_minus_network = '\uf409',
mdi_monitor = '\uf40a',
mdi_monitor_multiple = '\uf40b',
mdi_more = '\uf40c',
mdi_motorbike = '\uf40d',
mdi_mouse = '\uf40e',
mdi_mouse_off = '\uf40f',
mdi_mouse_variant = '\uf410',
mdi_mouse_variant_off = '\uf411',
mdi_movie = '\uf412',
mdi_multiplication = '\uf413',
mdi_multiplication_box = '\uf414',
mdi_music_box = '\uf415',
mdi_music_box_outline = '\uf416',
mdi_music_circle = '\uf417',
mdi_music_note = '\uf418',
mdi_music_note_eighth = '\uf419',
mdi_music_note_half = '\uf41a',
mdi_music_note_off = '\uf41b',
mdi_music_note_quarter = '\uf41c',
mdi_music_note_sixteenth = '\uf41d',
mdi_music_note_whole = '\uf41e',
mdi_nature = '\uf41f',
mdi_nature_people = '\uf420',
mdi_navigation = '\uf421',
mdi_needle = '\uf422',
mdi_nest_protect = '\uf423',
mdi_nest_thermostat = '\uf424',
mdi_newspaper = '\uf425',
mdi_nfc = '\uf426',
mdi_nfc_tap = '\uf427',
mdi_nfc_variant = '\uf428',
mdi_note = '\uf429',
mdi_note_outline = '\uf42a',
mdi_note_text = '\uf42b',
mdi_numeric = '\uf42c',
mdi_numeric_0_box = '\uf42d',
mdi_numeric_0_box_multiple_outline = '\uf42e',
mdi_numeric_0_box_outline = '\uf42f',
mdi_numeric_1_box = '\uf430',
mdi_numeric_1_box_multiple_outline = '\uf431',
mdi_numeric_1_box_outline = '\uf432',
mdi_numeric_2_box = '\uf433',
mdi_numeric_2_box_multiple_outline = '\uf434',
mdi_numeric_2_box_outline = '\uf435',
mdi_numeric_3_box = '\uf436',
mdi_numeric_3_box_multiple_outline = '\uf437',
mdi_numeric_3_box_outline = '\uf438',
mdi_numeric_4_box = '\uf439',
mdi_numeric_4_box_multiple_outline = '\uf43a',
mdi_numeric_4_box_outline = '\uf43b',
mdi_numeric_5_box = '\uf43c',
mdi_numeric_5_box_multiple_outline = '\uf43d',
mdi_numeric_5_box_outline = '\uf43e',
mdi_numeric_6_box = '\uf43f',
mdi_numeric_6_box_multiple_outline = '\uf440',
mdi_numeric_6_box_outline = '\uf441',
mdi_numeric_7_box = '\uf442',
mdi_numeric_7_box_multiple_outline = '\uf443',
mdi_numeric_7_box_outline = '\uf444',
mdi_numeric_8_box = '\uf445',
mdi_numeric_8_box_multiple_outline = '\uf446',
mdi_numeric_8_box_outline = '\uf447',
mdi_numeric_9_box = '\uf448',
mdi_numeric_9_box_multiple_outline = '\uf449',
mdi_numeric_9_box_outline = '\uf44a',
mdi_numeric_9_plus_box = '\uf44b',
mdi_numeric_9_plus_box_multiple_outline = '\uf44c',
mdi_numeric_9_plus_box_outline = '\uf44d',
mdi_nutriton = '\uf44e',
mdi_odnoklassniki = '\uf44f',
mdi_office = '\uf450',
mdi_oil = '\uf451',
mdi_omega = '\uf452',
mdi_onedrive = '\uf453',
mdi_open_in_app = '\uf454',
mdi_open_in_new = '\uf455',
mdi_ornament = '\uf456',
mdi_ornament_variant = '\uf457',
mdi_outbox = '\uf458',
mdi_owl = '\uf459',
mdi_package = '\uf45a',
mdi_package_down = '\uf45b',
mdi_package_up = '\uf45c',
mdi_package_variant = '\uf45d',
mdi_package_variant_closed = '\uf45e',
mdi_palette = '\uf45f',
mdi_palette_advanced = '\uf460',
mdi_panda = '\uf461',
mdi_pandora = '\uf462',
mdi_panorama = '\uf463',
mdi_panorama_fisheye = '\uf464',
mdi_panorama_horizontal = '\uf465',
mdi_panorama_vertical = '\uf466',
mdi_panorama_wide_angle = '\uf467',
mdi_paper_cut_vertical = '\uf468',
mdi_paperclip = '\uf469',
mdi_parking = '\uf46a',
mdi_pause = '\uf46b',
mdi_pause_circle = '\uf46c',
mdi_pause_circle_outline = '\uf46d',
mdi_pause_octagon = '\uf46e',
mdi_pause_octagon_outline = '\uf46f',
mdi_paw = '\uf470',
mdi_pen = '\uf471',
mdi_pencil = '\uf472',
mdi_pencil_box = '\uf473',
mdi_pencil_box_outline = '\uf474',
mdi_percent = '\uf475',
mdi_pharmacy = '\uf476',
mdi_phone = '\uf477',
mdi_phone_bluetooth = '\uf478',
mdi_phone_forward = '\uf479',
mdi_phone_hangup = '\uf47a',
mdi_phone_in_talk = '\uf47b',
mdi_phone_incoming = '\uf47c',
mdi_phone_locked = '\uf47d',
mdi_phone_log = '\uf47e',
mdi_phone_missed = '\uf47f',
mdi_phone_outgoing = '\uf480',
mdi_phone_paused = '\uf481',
mdi_phone_settings = '\uf482',
mdi_pig = '\uf483',
mdi_pill = '\uf484',
mdi_pin = '\uf485',
mdi_pin_off = '\uf486',
mdi_pine_tree = '\uf487',
mdi_pine_tree_box = '\uf488',
mdi_pinterest = '\uf489',
mdi_pinterest_box = '\uf48a',
mdi_pizza = '\uf48b',
mdi_play = '\uf48c',
mdi_play_box_outline = '\uf48d',
mdi_play_circle = '\uf48e',
mdi_play_circle_outline = '\uf48f',
mdi_playlist_minus = '\uf490',
mdi_playlist_plus = '\uf491',
mdi_playstation = '\uf492',
mdi_plus = '\uf493',
mdi_plus_box = '\uf494',
mdi_plus_circle = '\uf495',
mdi_plus_circle_outline = '\uf496',
mdi_plus_network = '\uf497',
mdi_plus_one = '\uf498',
mdi_pocket = '\uf499',
mdi_poll = '\uf49a',
mdi_poll_box = '\uf49b',
mdi_polymer = '\uf49c',
mdi_popcorn = '\uf49d',
mdi_pound = '\uf49e',
mdi_pound_box = '\uf49f',
mdi_power = '\uf4a0',
mdi_power_settings = '\uf4a1',
mdi_power_socket = '\uf4a2',
mdi_presentation = '\uf4a3',
mdi_presentation_play = '\uf4a4',
mdi_printer = '\uf4a5',
mdi_printer_3d = '\uf4a6',
mdi_pulse = '\uf4a7',
mdi_puzzle = '\uf4a8',
mdi_qrcode = '\uf4a9',
mdi_quadcopter = '\uf4aa',
mdi_quality_high = '\uf4ab',
mdi_quicktime = '\uf4ac',
mdi_radiator = '\uf4ad',
mdi_radio = '\uf4ae',
mdi_radio_tower = '\uf4af',
mdi_radioactive = '\uf4b0',
mdi_radiobox_blank = '\uf4b1',
mdi_radiobox_marked = '\uf4b2',
mdi_raspberrypi = '\uf4b3',
mdi_rdio = '\uf4b4',
mdi_read = '\uf4b5',
mdi_readability = '\uf4b6',
mdi_receipt = '\uf4b7',
mdi_recycle = '\uf4b8',
mdi_redo = '\uf4b9',
mdi_redo_variant = '\uf4ba',
mdi_refresh = '\uf4bb',
mdi_relative_scale = '\uf4bc',
mdi_reload = '\uf4bd',
mdi_remote = '\uf4be',
mdi_rename_box = '\uf4bf',
mdi_repeat = '\uf4c0',
mdi_repeat_off = '\uf4c1',
mdi_repeat_once = '\uf4c2',
mdi_replay = '\uf4c3',
mdi_reply = '\uf4c4',
mdi_reply_all = '\uf4c5',
mdi_reproduction = '\uf4c6',
mdi_resize_bottom_right = '\uf4c7',
mdi_responsive = '\uf4c8',
mdi_rewind = '\uf4c9',
mdi_ribbon = '\uf4ca',
mdi_road = '\uf4cb',
mdi_rocket = '\uf4cc',
mdi_rotate_3d = '\uf4cd',
mdi_rotate_left = '\uf4ce',
mdi_rotate_left_variant = '\uf4cf',
mdi_rotate_right = '\uf4d0',
mdi_rotate_right_variant = '\uf4d1',
mdi_routes = '\uf4d2',
mdi_rss = '\uf4d3',
mdi_rss_box = '\uf4d4',
mdi_ruler = '\uf4d5',
mdi_run = '\uf4d6',
mdi_sale = '\uf4d7',
mdi_satellite = '\uf4d8',
mdi_satellite_variant = '\uf4d9',
mdi_scale = '\uf4da',
mdi_scale_bathroom = '\uf4db',
mdi_school = '\uf4dc',
mdi_screen_rotation = '\uf4dd',
mdi_screen_rotation_lock = '\uf4de',
mdi_script = '\uf4df',
mdi_sd = '\uf4e0',
mdi_security = '\uf4e1',
mdi_security_network = '\uf4e2',
mdi_select = '\uf4e3',
mdi_select_all = '\uf4e4',
mdi_select_inverse = '\uf4e5',
mdi_select_off = '\uf4e6',
mdi_send = '\uf4e7',
mdi_server = '\uf4e8',
mdi_server_minus = '\uf4e9',
mdi_server_network = '\uf4ea',
mdi_server_network_off = '\uf4eb',
mdi_server_off = '\uf4ec',
mdi_server_plus = '\uf4ed',
mdi_server_remove = '\uf4ee',
mdi_server_security = '\uf4ef',
mdi_settings = '\uf4f0',
mdi_settings_box = '\uf4f1',
mdi_shape_plus = '\uf4f2',
mdi_share = '\uf4f3',
mdi_share_variant = '\uf4f4',
mdi_shield = '\uf4f5',
mdi_shield_outline = '\uf4f6',
mdi_shopping = '\uf4f7',
mdi_shopping_music = '\uf4f8',
mdi_shuffle = '\uf4f9',
mdi_sigma = '\uf4fa',
mdi_sign_caution = '\uf4fb',
mdi_signal = '\uf4fc',
mdi_silverware = '\uf4fd',
mdi_silverware_fork = '\uf4fe',
mdi_silverware_spoon = '\uf4ff',
mdi_silverware_variant = '\uf500',
mdi_sim_alert = '\uf501',
mdi_sitemap = '\uf502',
mdi_skip_next = '\uf503',
mdi_skip_previous = '\uf504',
mdi_skype = '\uf505',
mdi_skype_business = '\uf506',
mdi_sleep = '\uf507',
mdi_sleep_off = '\uf508',
mdi_smoking = '\uf509',
mdi_smoking_off = '\uf50a',
mdi_snapchat = '\uf50b',
mdi_snowman = '\uf50c',
mdi_sofa = '\uf50d',
mdi_sort = '\uf50e',
mdi_sort_alphabetical = '\uf50f',
mdi_sort_ascending = '\uf510',
mdi_sort_descending = '\uf511',
mdi_sort_numeric = '\uf512',
mdi_sort_variant = '\uf513',
mdi_soundcloud = '\uf514',
mdi_source_fork = '\uf515',
mdi_source_pull = '\uf516',
mdi_speaker = '\uf517',
mdi_speaker_off = '\uf518',
mdi_speedometer = '\uf519',
mdi_spellcheck = '\uf51a',
mdi_spotify = '\uf51b',
mdi_spotlight = '\uf51c',
mdi_spotlight_beam = '\uf51d',
mdi_square_inc = '\uf51e',
mdi_square_inc_cash = '\uf51f',
mdi_stackoverflow = '\uf520',
mdi_star = '\uf521',
mdi_star_circle = '\uf522',
mdi_star_half = '\uf523',
mdi_star_outline = '\uf524',
mdi_steam = '\uf525',
mdi_stethoscope = '\uf526',
mdi_stocking = '\uf527',
mdi_stop = '\uf528',
mdi_store = '\uf529',
mdi_store_24_hour = '\uf52a',
mdi_stove = '\uf52b',
mdi_subway = '\uf52c',
mdi_sunglasses = '\uf52d',
mdi_swap_horizontal = '\uf52e',
mdi_swap_vertical = '\uf52f',
mdi_swim = '\uf530',
mdi_sword = '\uf531',
mdi_sync = '\uf532',
mdi_sync_alert = '\uf533',
mdi_sync_off = '\uf534',
mdi_tab = '\uf535',
mdi_tab_unselected = '\uf536',
mdi_table = '\uf537',
mdi_table_column_plus_after = '\uf538',
mdi_table_column_plus_before = '\uf539',
mdi_table_column_remove = '\uf53a',
mdi_table_column_width = '\uf53b',
mdi_table_edit = '\uf53c',
mdi_table_large = '\uf53d',
mdi_table_row_height = '\uf53e',
mdi_table_row_plus_after = '\uf53f',
mdi_table_row_plus_before = '\uf540',
mdi_table_row_remove = '\uf541',
mdi_tablet = '\uf542',
mdi_tablet_android = '\uf543',
mdi_tablet_ipad = '\uf544',
mdi_tag = '\uf545',
mdi_tag_faces = '\uf546',
mdi_tag_multiple = '\uf547',
mdi_tag_outline = '\uf548',
mdi_tag_text_outline = '\uf549',
mdi_taxi = '\uf54a',
mdi_teamviewer = '\uf54b',
mdi_telegram = '\uf54c',
mdi_television = '\uf54d',
mdi_television_guide = '\uf54e',
mdi_temperature_celsius = '\uf54f',
mdi_temperature_fahrenheit = '\uf550',
mdi_temperature_kelvin = '\uf551',
mdi_tennis = '\uf552',
mdi_tent = '\uf553',
mdi_terrain = '\uf554',
mdi_text_to_speech = '\uf555',
mdi_text_to_speech_off = '\uf556',
mdi_texture = '\uf557',
mdi_theater = '\uf558',
mdi_theme_light_dark = '\uf559',
mdi_thermometer = '\uf55a',
mdi_thermometer_lines = '\uf55b',
mdi_thumb_down = '\uf55c',
mdi_thumb_down_outline = '\uf55d',
mdi_thumb_up = '\uf55e',
mdi_thumb_up_outline = '\uf55f',
mdi_thumbs_up_down = '\uf560',
mdi_ticket = '\uf561',
mdi_ticket_account = '\uf562',
mdi_tie = '\uf563',
mdi_timelapse = '\uf564',
mdi_timer = '\uf565',
mdi_timer_10 = '\uf566',
mdi_timer_3 = '\uf567',
mdi_timer_off = '\uf568',
mdi_timer_sand = '\uf569',
mdi_timetable = '\uf56a',
mdi_toggle_switch = '\uf56b',
mdi_toggle_switch_off = '\uf56c',
mdi_tooltip = '\uf56d',
mdi_tooltip_edit = '\uf56e',
mdi_tooltip_image = '\uf56f',
mdi_tooltip_outline = '\uf570',
mdi_tooltip_outline_plus = '\uf571',
mdi_tooltip_text = '\uf572',
mdi_tor = '\uf573',
mdi_traffic_light = '\uf574',
mdi_train = '\uf575',
mdi_tram = '\uf576',
mdi_transcribe = '\uf577',
mdi_transcribe_close = '\uf578',
mdi_transfer = '\uf579',
mdi_tree = '\uf57a',
mdi_trello = '\uf57b',
mdi_trending_down = '\uf57c',
mdi_trending_neutral = '\uf57d',
mdi_trending_up = '\uf57e',
mdi_trophy = '\uf57f',
mdi_trophy_award = '\uf580',
mdi_trophy_variant = '\uf581',
mdi_truck = '\uf582',
mdi_tshirt_crew = '\uf583',
mdi_tshirt_v = '\uf584',
mdi_tumblr = '\uf585',
mdi_tumblr_reblog = '\uf586',
mdi_twitch = '\uf587',
mdi_twitter = '\uf588',
mdi_twitter_box = '\uf589',
mdi_twitter_circle = '\uf58a',
mdi_twitter_retweet = '\uf58b',
mdi_ubuntu = '\uf58c',
mdi_umbrella = '\uf58d',
mdi_umbrella_outline = '\uf58e',
mdi_undo = '\uf58f',
mdi_undo_variant = '\uf590',
mdi_unfold_less = '\uf591',
mdi_unfold_more = '\uf592',
mdi_ungroup = '\uf593',
mdi_untappd = '\uf594',
mdi_upload = '\uf595',
mdi_usb = '\uf596',
mdi_vector_curve = '\uf597',
mdi_vector_point = '\uf598',
mdi_vector_square = '\uf599',
mdi_verified = '\uf59a',
mdi_vibrate = '\uf59b',
mdi_video = '\uf59c',
mdi_video_off = '\uf59d',
mdi_video_switch = '\uf59e',
mdi_view_agenda = '\uf59f',
mdi_view_array = '\uf5a0',
mdi_view_carousel = '\uf5a1',
mdi_view_column = '\uf5a2',
mdi_view_dashboard = '\uf5a3',
mdi_view_day = '\uf5a4',
mdi_view_grid = '\uf5a5',
mdi_view_headline = '\uf5a6',
mdi_view_list = '\uf5a7',
mdi_view_module = '\uf5a8',
mdi_view_quilt = '\uf5a9',
mdi_view_stream = '\uf5aa',
mdi_view_week = '\uf5ab',
mdi_vimeo = '\uf5ac',
mdi_vine = '\uf5ad',
mdi_vk = '\uf5ae',
mdi_vk_box = '\uf5af',
mdi_vk_circle = '\uf5b0',
mdi_voicemail = '\uf5b1',
mdi_volume_high = '\uf5b2',
mdi_volume_low = '\uf5b3',
mdi_volume_medium = '\uf5b4',
mdi_volume_off = '\uf5b5',
mdi_vpn = '\uf5b6',
mdi_walk = '\uf5b7',
mdi_wallet = '\uf5b8',
mdi_wallet_giftcard = '\uf5b9',
mdi_wallet_membership = '\uf5ba',
mdi_wallet_travel = '\uf5bb',
mdi_watch = '\uf5bc',
mdi_watch_export = '\uf5bd',
mdi_watch_import = '\uf5be',
mdi_water = '\uf5bf',
mdi_water_off = '\uf5c0',
mdi_water_pump = '\uf5c1',
mdi_weather_cloudy = '\uf5c2',
mdi_weather_fog = '\uf5c3',
mdi_weather_hail = '\uf5c4',
mdi_weather_lightning = '\uf5c5',
mdi_weather_night = '\uf5c6',
mdi_weather_partlycloudy = '\uf5c7',
mdi_weather_pouring = '\uf5c8',
mdi_weather_rainy = '\uf5c9',
mdi_weather_snowy = '\uf5ca',
mdi_weather_sunny = '\uf5cb',
mdi_weather_sunset = '\uf5cc',
mdi_weather_sunset_down = '\uf5cd',
mdi_weather_sunset_up = '\uf5ce',
mdi_weather_windy = '\uf5cf',
mdi_weather_windy_variant = '\uf5d0',
mdi_web = '\uf5d1',
mdi_webcam = '\uf5d2',
mdi_weight = '\uf5d3',
mdi_weight_kilogram = '\uf5d4',
mdi_whatsapp = '\uf5d5',
mdi_wheelchair_accessibility = '\uf5d6',
mdi_white_balance_auto = '\uf5d7',
mdi_white_balance_incandescent = '\uf5d8',
mdi_white_balance_irradescent = '\uf5d9',
mdi_white_balance_sunny = '\uf5da',
mdi_wifi = '\uf5db',
mdi_wii = '\uf5dc',
mdi_wikipedia = '\uf5dd',
mdi_window_close = '\uf5de',
mdi_window_closed = '\uf5df',
mdi_window_maximize = '\uf5e0',
mdi_window_minimize = '\uf5e1',
mdi_window_open = '\uf5e2',
mdi_window_restore = '\uf5e3',
mdi_windows = '\uf5e4',
mdi_wordpress = '\uf5e5',
mdi_worker = '\uf5e6',
mdi_wunderlist = '\uf5e7',
mdi_xbox = '\uf5e8',
mdi_xbox_controller = '\uf5e9',
mdi_xbox_controller_off = '\uf5ea',
mdi_xda = '\uf5eb',
mdi_xml = '\uf5ec',
mdi_yeast = '\uf5ed',
mdi_yelp = '\uf5ee',
mdi_youtube_play = '\uf5ef',
mdi_zip_box = '\uf5f0'
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnIncisoItemGasto class.
/// </summary>
[Serializable]
public partial class PnIncisoItemGastoCollection : ActiveList<PnIncisoItemGasto, PnIncisoItemGastoCollection>
{
public PnIncisoItemGastoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnIncisoItemGastoCollection</returns>
public PnIncisoItemGastoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnIncisoItemGasto o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_inciso_item_gasto table.
/// </summary>
[Serializable]
public partial class PnIncisoItemGasto : ActiveRecord<PnIncisoItemGasto>, IActiveRecord
{
#region .ctors and Default Settings
public PnIncisoItemGasto()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnIncisoItemGasto(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnIncisoItemGasto(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnIncisoItemGasto(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_inciso_item_gasto", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdIncisoItemGasto = new TableSchema.TableColumn(schema);
colvarIdIncisoItemGasto.ColumnName = "id_inciso_item_gasto";
colvarIdIncisoItemGasto.DataType = DbType.Int32;
colvarIdIncisoItemGasto.MaxLength = 0;
colvarIdIncisoItemGasto.AutoIncrement = true;
colvarIdIncisoItemGasto.IsNullable = false;
colvarIdIncisoItemGasto.IsPrimaryKey = true;
colvarIdIncisoItemGasto.IsForeignKey = false;
colvarIdIncisoItemGasto.IsReadOnly = false;
colvarIdIncisoItemGasto.DefaultSetting = @"";
colvarIdIncisoItemGasto.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdIncisoItemGasto);
TableSchema.TableColumn colvarIdInciso = new TableSchema.TableColumn(schema);
colvarIdInciso.ColumnName = "id_inciso";
colvarIdInciso.DataType = DbType.Int32;
colvarIdInciso.MaxLength = 0;
colvarIdInciso.AutoIncrement = false;
colvarIdInciso.IsNullable = false;
colvarIdInciso.IsPrimaryKey = false;
colvarIdInciso.IsForeignKey = true;
colvarIdInciso.IsReadOnly = false;
colvarIdInciso.DefaultSetting = @"";
colvarIdInciso.ForeignKeyTableName = "PN_inciso";
schema.Columns.Add(colvarIdInciso);
TableSchema.TableColumn colvarIdItemGasto = new TableSchema.TableColumn(schema);
colvarIdItemGasto.ColumnName = "id_item_gasto";
colvarIdItemGasto.DataType = DbType.Int32;
colvarIdItemGasto.MaxLength = 0;
colvarIdItemGasto.AutoIncrement = false;
colvarIdItemGasto.IsNullable = false;
colvarIdItemGasto.IsPrimaryKey = false;
colvarIdItemGasto.IsForeignKey = true;
colvarIdItemGasto.IsReadOnly = false;
colvarIdItemGasto.DefaultSetting = @"";
colvarIdItemGasto.ForeignKeyTableName = "PN_item_gasto";
schema.Columns.Add(colvarIdItemGasto);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_inciso_item_gasto",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdIncisoItemGasto")]
[Bindable(true)]
public int IdIncisoItemGasto
{
get { return GetColumnValue<int>(Columns.IdIncisoItemGasto); }
set { SetColumnValue(Columns.IdIncisoItemGasto, value); }
}
[XmlAttribute("IdInciso")]
[Bindable(true)]
public int IdInciso
{
get { return GetColumnValue<int>(Columns.IdInciso); }
set { SetColumnValue(Columns.IdInciso, value); }
}
[XmlAttribute("IdItemGasto")]
[Bindable(true)]
public int IdItemGasto
{
get { return GetColumnValue<int>(Columns.IdItemGasto); }
set { SetColumnValue(Columns.IdItemGasto, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a PnInciso ActiveRecord object related to this PnIncisoItemGasto
///
/// </summary>
public DalSic.PnInciso PnInciso
{
get { return DalSic.PnInciso.FetchByID(this.IdInciso); }
set { SetColumnValue("id_inciso", value.IdInciso); }
}
/// <summary>
/// Returns a PnItemGasto ActiveRecord object related to this PnIncisoItemGasto
///
/// </summary>
public DalSic.PnItemGasto PnItemGasto
{
get { return DalSic.PnItemGasto.FetchByID(this.IdItemGasto); }
set { SetColumnValue("id_item_gasto", value.IdItemGasto); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdInciso,int varIdItemGasto)
{
PnIncisoItemGasto item = new PnIncisoItemGasto();
item.IdInciso = varIdInciso;
item.IdItemGasto = varIdItemGasto;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdIncisoItemGasto,int varIdInciso,int varIdItemGasto)
{
PnIncisoItemGasto item = new PnIncisoItemGasto();
item.IdIncisoItemGasto = varIdIncisoItemGasto;
item.IdInciso = varIdInciso;
item.IdItemGasto = varIdItemGasto;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdIncisoItemGastoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdIncisoColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdItemGastoColumn
{
get { return Schema.Columns[2]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdIncisoItemGasto = @"id_inciso_item_gasto";
public static string IdInciso = @"id_inciso";
public static string IdItemGasto = @"id_item_gasto";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// //
// MIT X11 license, Copyright (c) 2005-2006 by: //
// //
// Authors: //
// Michael Dominic K. <michaldominik@gmail.com> //
// Travis Hansen <travisghansen@gmail.com> //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included //
// in all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS //
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF //
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN //
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, //
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR //
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE //
// USE OR OTHER DEALINGS IN THE SOFTWARE. //
// //
////////////////////////////////////////////////////////////////////////////////
namespace Diva.Util {
using System;
using Gdv;
using Mono.Unix;
public static class TimeFu {
// Translatable ///////////////////////////////////////////////
readonly static string minSS = Catalog.GetString
("min");
readonly static string secSS = Catalog.GetString
("sec");
readonly static string minuteSS = Catalog.GetString
("minute");
readonly static string minutesSS = Catalog.GetString
("minutes");
readonly static string secondSS = Catalog.GetString
("second");
readonly static string secondsSS = Catalog.GetString
("seconds");
// Public Methods /////////////////////////////////////////////
/* Convert given time to a SMPTE value. With or without hours */
public static string ToSMPTE (Time time, Fraction fps, bool withHours)
{
UInt64 secsTotal = (UInt64) time.Seconds;
UInt64 minsTotal = secsTotal / 60;
UInt64 secs = secsTotal % 60;
UInt64 mins = (secsTotal / 60) % 60;
UInt64 hours = (minsTotal / 60);
UInt64 frames = (UInt64) (time % Time.OneSecond) / fps.FpsFrameDuration ();
if (! withHours && hours == 0)
return String.Format ("{0:d2}:{1:d2}:{2:d2}", mins, secs, frames);
else
return String.Format ("{0:d2}:{1:d2}:{2:d2}:{3:d2}", hours, mins, secs, frames);
}
/* Return the frame value of an SMPTE string give a Time and Fraction */
public static string SMPTEFrames (Time time, Fraction fps)
{
UInt64 secsTotal = (UInt64) time.Seconds;
UInt64 minsTotal = secsTotal / 60;
UInt64 secs = secsTotal % 60;
UInt64 mins = (secsTotal / 60) % 60;
UInt64 hours = (minsTotal / 60);
UInt64 frames = (UInt64) (time % Time.OneSecond) / fps.FpsFrameDuration ();
return frames.ToString();
}
/* Return the hour value of an SMPTE string given a Time */
public static string SMPTEHours (Time time)
{
UInt64 secsTotal = (UInt64) time.Seconds;
UInt64 minsTotal = secsTotal / 60;
UInt64 secs = secsTotal % 60;
UInt64 mins = (secsTotal / 60) % 60;
UInt64 hours = (minsTotal / 60);
return hours.ToString();
}
/* Return the minute value of an SMPTE string given a Time */
public static string SMPTEMinutes (Time time)
{
UInt64 secsTotal = (UInt64) time.Seconds;
UInt64 minsTotal = secsTotal / 60;
UInt64 secs = secsTotal % 60;
UInt64 mins = (secsTotal / 60) % 60;
return mins.ToString();
}
/* Return the seconds value of an SMPTE string given a Time */
public static string SMPTESeconds (Time time)
{
UInt64 secsTotal = (UInt64) time.Seconds;
UInt64 minsTotal = secsTotal / 60;
UInt64 secs = secsTotal % 60;
return secs.ToString();
}
/* Convert to SMPTE dropping the hours */
public static string ToSMPTE (Time time, Fraction fps)
{
return ToSMPTE (time, fps, false);
}
/* Convert to a short, canonical representation of duration */
public static string ToShortString (Time t)
{
if (t > Time.OneSecond * 60) {
UInt64 mins = (UInt64) t.Seconds / 60;
UInt64 secs = (UInt64) t.Seconds - mins * 60;
return String.Format ("{0} {1} {2} {3}",
mins,
minSS,
secs,
secSS);
}
if (t > Time.OneSecond + (Time.OneSecond / 2))
return String.Format ("{0} {1}", (UInt64) (t.Seconds),
secSS);
if (t >= Time.OneSecond)
return String.Format ("1 {0}", secSS);
return String.Format ("~" + "0 {0}", secSS);
}
public static string ToLongString (Time t)
{
if (t > Time.OneSecond * 60) {
UInt64 mins = (UInt64) t.Seconds / 60;
UInt64 secs = (UInt64) t.Seconds - mins * 60;
return String.Format ("{0} {1} {2} {3}",
mins,
(mins == 1) ? minuteSS : minutesSS,
secs,
(secs == 1) ? secondSS : secondsSS);
}
if (t > Time.OneSecond + (Time.OneSecond / 2))
return String.Format ("{0} {1}", (UInt64) (t.Seconds),
(((int) t.Seconds) == 1) ? secondSS : secondsSS);
if (t >= Time.OneSecond)
return String.Format ("1 {0}", secondSS);
return String.Format ("~" + "0 {0}", secondSS);
}
/* Convert time to pixel amount according to pixels-per-sec */
public static int ToPixels (Time t, double pixelspersec)
{
return (int) (t.Seconds * pixelspersec);
}
/* Convert no of pixels to time according to pixels-per-sec */
public static Time FromPixels (int pixels, double pixelspersec)
{
return Time.FromSeconds ((double) pixels / pixelspersec);
}
/* Get time from SMPTE formatted string */
public static Time FromSMPTE (string smpte, Fraction fps)
{
Time p = FromSMPTEMinusFrames (smpte);
Time q = FromSMPTEFps (smpte, fps);
Time total = p + q;
return total;
}
/* Get fps time from SMPTE formatted string */
public static Time FromSMPTEFps (string smpte, Fraction fps)
{
string formatted = StringToFormattedSMPTE (smpte);
string[] formattedSplit = formatted.Split(new char[] {':'});
UInt16 frames = UInt16.Parse(formattedSplit[3]);
Time p = frames * fps.FpsFrameDuration();
return p;
}
/* Convert SMPTE string to time leaving the frames out */
public static Time FromSMPTEMinusFrames (string smpte)
{
string formatted = StringToFormattedSMPTE (smpte);
string[] formattedSplit = formatted.Split(new char[] {':'});
UInt64 hours = UInt64.Parse(formattedSplit[0]);
UInt64 minutes = UInt64.Parse(formattedSplit[1]);
UInt64 seconds = UInt64.Parse(formattedSplit[2]);
UInt64 secondsFromHours = hours * 3600;
UInt64 secondsFromMinutes = minutes * 60;
UInt64 totalTime = seconds + secondsFromHours + secondsFromMinutes;
Time total = Time.FromSeconds(Double.Parse(totalTime.ToString()));
return total;
}
/* Convert partial/complete SMPTE string to complete 00:00:00:00 format */
private static string StringToFormattedSMPTE (string unformatted)
{
char[] separator = {':'};
int maxFields = 4;
unformatted = unformatted.Trim();
string[] unformattedSplit = unformatted.Split(separator);
int numFields = unformattedSplit.Length;
string formatted = "";
if (numFields > maxFields)
{
//TODO: Handle this graciously
throw new FormatException ("This is a problem...please fix");
}
if (numFields == 0)
{
//TODO: Handle this graciously
throw new FormatException ("This is a problem...please fix");
}
foreach (string nums in unformattedSplit)
{
if ( nums.Length > 2 )
{
throw new FormatException ("This is an issue as well");
}
}
foreach (string nums in unformattedSplit)
{
if ( ! StringFu.IsDigit (nums) )
{
throw new FormatException ("This is a format issue...please fix it");
}
}
switch (numFields)
{
case 1:
formatted = String.Format ("00:00:{0:##}:00",
unformattedSplit[0]);
break;
case 2:
formatted = String.Format ("00:{0:##}:{1:##}:00",
unformattedSplit[0],
unformattedSplit[1]);
break;
case 3:
formatted = String.Format ("{0:##}:{1:##}:{2:##}:00",
unformattedSplit[0],
unformattedSplit[1],
unformattedSplit[2]);
break;
case 4:
formatted = String.Format ("{0:##}:{1:##}:{2:##}:{3:##}",
unformattedSplit[0],
unformattedSplit[1],
unformattedSplit[2],
unformattedSplit[3]);
break;
default:
break;
}
return formatted;
}
}
}
| |
namespace System.Data.Test.Astoria
{
#region Namespaces.
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.IO.Compression;
#endregion Namespaces.
/// <summary>This class provides utility methods for I/O tasks.</summary>
public static class IOUtil
{
#region Public methods.
/// <summary>Copies a file if the source file is newer than the target file.</summary>
/// <param name="sourceFilePath">Path to source file.</param>
/// <param name="targetFilePath">Path to target file.</param>
public static void CopyFileIfNewer(string sourceFilePath, string targetFilePath)
{
CheckArgumentNotNull(sourceFilePath, "sourceFilePath");
CheckArgumentNotNull(targetFilePath, "targetFilePath");
if (!File.Exists(sourceFilePath))
{
throw new InvalidOperationException("Unable to setup service files - file not found at " + sourceFilePath);
}
if (!File.Exists(targetFilePath) ||
File.GetLastWriteTime(sourceFilePath) > File.GetLastWriteTime(targetFilePath))
{
File.Copy(sourceFilePath, targetFilePath, true /* overwrite */);
}
}
/// <summary>
/// Copies all contents from the <paramref name="source"/> folder to the
/// <paramref name="destination"/> folder, with the option to recurse down
/// subfolders.
/// </summary>
/// <param name="source">Path to source folder.</param>
/// <param name="destination">Path to destination folder.</param>
/// <param name="recursive">Whether to copy folders recursively.</param>
public static void CopyFolder(string source, string destination, bool recursive)
{
CopyFolder(source, destination, recursive, false);
}
public static void CopyFolder(string source, string destination, bool recursive, bool overWrite)
{
CheckArgumentNotNull(source, "source");
CheckArgumentNotNull(destination, "destination");
if (!Directory.Exists(source))
{
throw new ArgumentException("Source directory '" + source + "' doesn't exist.", "source");
}
if (!Directory.Exists(destination))
{
Trace.WriteLine("Creating directory '" + destination + "'...");
Directory.CreateDirectory(destination);
}
foreach (string file in Directory.GetFiles(source))
{
File.Copy(file, Path.Combine(destination, Path.GetFileName(file)), overWrite);
}
if (recursive)
{
foreach (string subdir in Directory.GetDirectories(source))
{
CopyFolder(subdir, Path.Combine(destination, Path.GetFileName(subdir)), recursive);
}
}
}
public static void RenameFile(string directoryPath, string currentFilename, string newFilename)
{
CheckArgumentNotNull(directoryPath, "Directory Path");
CheckArgumentNotNull(currentFilename, "Current Filename");
CheckArgumentNotNull(newFilename, "New Filename");
if (!Directory.Exists(directoryPath))
{
throw new ArgumentException("Source directory '" + directoryPath + "' doesn't exist.", "Directory Path");
}
string current = directoryPath + "\\" + currentFilename;
string newName = directoryPath + "\\" + newFilename;
EnsureFileDeleted(newName);
File.Move(current, newName);
EnsureFileDeleted(current);
}
/// <summary>Copies a resource embedded in the given assembly into a file.</summary>
/// <param name="assembly">Assembyl to copy resource from.</param>
/// <param name="resourceName">Resource name.</param>
/// <param name="destinationPath">Path to file.</param>
public static void CopyResourceToFile(Assembly assembly, string resourceName, string destinationPath)
{
CheckArgumentNotNull(assembly, "assembly");
CheckArgumentNotNull(resourceName, "resourceName");
CheckArgumentNotNull(destinationPath, "destinationPath");
using (Stream sourceStream = assembly.GetManifestResourceStream(resourceName))
using (Stream destinationStream = new FileStream(destinationPath, FileMode.Create, FileAccess.Write))
{
if (sourceStream == null)
{
throw new InvalidOperationException("Unable to extract resource '" + resourceName + "' from " +
"assembly '" + assembly.Location + "' with these resource:\r\n" + ListResourceNames(assembly));
}
CopyStream(sourceStream, destinationStream);
}
}
/// <summary>Copies content from one stream into another.</summary>
/// <param name="source">Stream to read from.</param>
/// <param name="destination">Stream to write to.</param>
/// <returns>The number of bytes copied from the source.</returns>
public static int CopyStream(Stream source, Stream destination)
{
CheckArgumentNotNull(source, "source");
CheckArgumentNotNull(destination, "destination");
int bytesCopied = 0;
int bytesRead;
byte[] buffer = new byte[1024];
do
{
bytesRead = source.Read(buffer, 0, buffer.Length);
destination.Write(buffer, 0, bytesRead);
bytesCopied += bytesRead;
}
while (bytesRead != 0);
return bytesCopied;
}
/// <summary>Creates a stream that can read the specified text as UTF-8 bytes.</summary>
/// <param name='text'>Text to read.</param>
/// <returns>A new stream.</returns>
public static Stream CreateStream(string text)
{
return CreateStream(text, System.Text.Encoding.UTF8);
}
/// <summary>Creates a stream that can read the specified text as encoded bytes.</summary>
/// <param name='text'>Text to read.</param>
/// <param name='encoding'>Encoding to convert text into bytes.</param>
/// <returns>A new stream.</returns>
public static Stream CreateStream(string text, System.Text.Encoding encoding)
{
CheckArgumentNotNull(text, "text");
CheckArgumentNotNull(encoding, "encoding");
return new MemoryStream(encoding.GetBytes(text));
}
/// <summary>Compresses <paramref name="sourcePath"/> into <paramref name="targetPath"/> using Deflate.</summary>
/// <param name="sourcePath">Path to file to compress.</param>
/// <param name="targetPath">Path to file to create.</param>
public static void DeflateCompressFile(string sourcePath, string targetPath)
{
CheckArgumentNotNull(sourcePath, "sourcePath");
CheckArgumentNotNull(targetPath, "targetPath");
using (Stream source = File.Open(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream target = File.Create(targetPath))
using (Stream compressingStream = new DeflateStream(target, System.IO.Compression.CompressionMode.Compress))
{
CopyStream(source, compressingStream);
}
}
/// <summary>Decompresses <paramref name="sourcePath"/> into <paramref name="targetPath"/> using Deflate.</summary>
/// <param name="sourcePath">Path to file to decompress.</param>
/// <param name="targetPath">Path to file to create.</param>
public static void DeflateDecompressFile(string sourcePath, string targetPath)
{
CheckArgumentNotNull(sourcePath, "sourcePath");
CheckArgumentNotNull(targetPath, "targetPath");
using (Stream source = File.Open(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream target = File.Create(targetPath))
using (Stream decompressingStream = new DeflateStream(source, System.IO.Compression.CompressionMode.Decompress))
{
CopyStream(decompressingStream, target);
}
}
/// <summary>Empties the specified directory of all sub-directories and files.</summary>
/// <param name="path">Path of directory to empty.</param>
public static void EmptyDirectoryRecusively(string path)
{
CheckArgumentNotNull(path, "path");
foreach (string dir in Directory.GetDirectories(path))
{
EmptyDirectoryRecusively(dir);
}
foreach (string file in Directory.GetFiles(path))
{
FileAttributes attributes = File.GetAttributes(file);
if (0 != (attributes & FileAttributes.ReadOnly))
{
attributes &= ~FileAttributes.ReadOnly;
File.SetAttributes(file, attributes);
}
File.Delete(file);
}
}
/// <summary>Creates the specified directory if it doesn't exist.</summary>
/// <param name="path">Path to directory to create.</param>
public static void EnsureDirectoryExists(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
/// <summary>Creates the specified directory if it doesn't exist, empties its contents otherwise.</summary>
/// <param name="path">Path to directory to create or empty.</param>
public static void EnsureEmptyDirectoryExists(string path)
{
if (Directory.Exists(path))
{
EmptyDirectoryRecusively(path);
// On a VM occationally the deleted files are not immediately released. This causes some
// tests to fail if they try to create the same files we just deleted.
// Forcing a thread switch seem to fix the issue on the VMs we've tried...
System.Threading.Thread.Sleep(1);
}
else
{
Directory.CreateDirectory(path);
}
}
private static System.Collections.ArrayList lockObject = new System.Collections.ArrayList();
/// <summary>Deletes the specified file if it exists.</summary>
/// <param name="path">File to delete.</param>
public static void EnsureFileDeleted(string path)
{
lock (lockObject)
{
if (File.Exists(path))
File.Delete(path);
while (File.Exists(path))
Threading.Thread.Sleep(1000);
}
}
public static void CreateEmptyFile(string path)
{
lock (lockObject)
{
File.Open(path, FileMode.CreateNew).Close();
}
}
public static string ReadAllFileText(string path)
{
lock (lockObject)
{
return File.ReadAllText(path);
}
}
/// <summary>Writes a resource with a trailing matching file name to a file.</summary>
/// <param name="assembly">Assembly containing the resource to write.</param>
/// <param name="path">Path to file to write.</param>
public static void FindAndWriteResourceToFile(Assembly assembly, string path)
{
CheckArgumentNotNull(assembly, "assembly");
CheckArgumentNotNull(path, "path");
string resourceName = FindResourceNameForPath(assembly, path);
CopyResourceToFile(assembly, resourceName, path);
}
/// <summary>Writes a resource with a trailing matching file name to a file.</summary>
/// <param name="assembly">Assembly containing the resource to write.</param>
/// <param name="path">Path to file to write.</param>
public static void FindAndWriteResourceToFile(Assembly assembly, string partialResourceName, string path)
{
CheckArgumentNotNull(assembly, "assembly");
CheckArgumentNotNull(path, "path");
string actualResourceName = null;
foreach (string resourceName in assembly.GetManifestResourceNames())
{
if (resourceName.EndsWith(partialResourceName, StringComparison.OrdinalIgnoreCase))
{
actualResourceName= resourceName;
break;
}
}
if (actualResourceName == null)
{
throw new InvalidOperationException(
"Unable to find a resource name in assembly '" + assembly.Location +
"' for path '" + partialResourceName + "' in this list:\r\n" +
ListResourceNames(assembly));
}
CopyResourceToFile(assembly, actualResourceName, path);
}
/// <summary>Finds the resource with the trailing matching file name.</summary>
/// <param name="assembly">Assembly containing resource to look for.</param>
/// <param name="path">Path with file name to find.</param>
/// <returns>Resource name of resource.</returns>
/// <exception cref="InvalidOperationException">When a match cannot be found for <paramref name="path"/>.</exception>
public static string FindResourceNameForPath(Assembly assembly, string path)
{
CheckArgumentNotNull(assembly, "assembly");
CheckArgumentNotNull(path, "path");
string specificResourceName = Path.GetFileName(path);
foreach (string resourceName in assembly.GetManifestResourceNames())
{
if (resourceName.EndsWith(specificResourceName, StringComparison.OrdinalIgnoreCase))
{
return resourceName;
}
}
throw new InvalidOperationException(
"Unable to find a resource name in assembly '" + assembly.Location +
"' for path '" + path + "' in this list:\r\n" +
ListResourceNames(assembly));
}
/// <summary>Creates a newline-separated list of resource names in the specified assembly.</summary>
/// <param name="assembly">Assembly to list resource names from.</param>
/// <returns>A string with resource names separated by line breaks.</returns>
public static string ListResourceNames(Assembly assembly)
{
CheckArgumentNotNull(assembly, "assembly");
string[] resourceNames = assembly.GetManifestResourceNames();
Array.Sort(resourceNames, StringComparer.OrdinalIgnoreCase);
return string.Join(Environment.NewLine, resourceNames);
}
/// <summary>Reads all text from the specified resource.</summary>
/// <param name="assembly">Assembly with resource.</param>
/// <param name="resourceName">Name of resource in assembly.</param>
/// <returns>All text from the specified resource.</returns>
public static string ReadResourceText(Assembly assembly, string resourceName)
{
CheckArgumentNotNull(assembly, "assembly");
CheckArgumentNotNull(resourceName, "resourceName");
using (Stream sourceStream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(sourceStream))
{
if (sourceStream == null)
{
throw new InvalidOperationException("Unable to extract resource '" + resourceName + "' from " +
"assembly '" + assembly.Location + "' with these resources:\r\n" + ListResourceNames(assembly));
}
return reader.ReadToEnd();
}
}
/// <summary>
/// Creates a new file, writes the specified string to the file, and then closes the file. If the target
/// file already exists, it is overwritten.
/// </summary>
/// <param name="path">The file to write to.</param>
/// <param name="contents">The string to write to the file.</param>
public static void WriteAllTextWithRetry(string path, string contents)
{
CheckArgumentNotNull(path, "path");
CheckArgumentNotNull(contents, "contents");
for (int i = 0; i < 3; i++)
{
try
{
File.WriteAllText(path, contents);
return;
}
catch (IOException)
{
Trace.Write("Unable to write contents to " + path + " on iteration #" + (i + 1) + " - waiting 2 seconds...");
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2));
}
}
}
#endregion Public methods.
#region Private methods.
/// <summary>Checks that <paramref name="argumentValue"/> is not null, throws an exception otherwise.</summary>
/// <param name="argumentValue">Argument value to check.</param>
/// <param name="argumentName">Argument name.</param>
public static void CheckArgumentNotNull(object argumentValue, string argumentName)
{
if (argumentValue == null)
{
throw new ArgumentNullException(argumentName);
}
}
#endregion Private methods.
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
namespace Orleans.Runtime
{
public enum CounterStorage
{
DontStore,
LogOnly,
LogAndTable
}
/// <summary>
/// A detailed statistic counter. Usually a low level performance statistic used in troubleshooting scenarios.
/// </summary>
public interface ICounter
{
/// <summary>
/// the name of the statistic counter
/// </summary>
string Name { get; }
/// <summary>
/// if this the statistic counter value is delta since last value reported or an absolute value
/// </summary>
bool IsValueDelta { get; }
string GetValueString();
string GetDeltaString();
void ResetCurrent();
string GetDisplayString();
CounterStorage Storage { get; }
void TrackMetric(Logger logger);
}
public static class Metric
{
public static string CreateCurrentName(string statisticName)
{
return statisticName + "." + "Current";
}
public static string CreateDeltaName(string statisticName)
{
return statisticName + "." + "Delta";
}
}
internal interface ICounter<out T> : ICounter
{
T GetCurrentValue();
}
internal class CounterStatistic : ICounter<long>
{
private class ReferenceLong
{
internal long Value;
}
private const int BUFFER_SIZE = 100;
[ThreadStatic]
private static List<ReferenceLong> allStatisticsFromSpecificThread;
[ThreadStatic]
private static bool isOrleansManagedThread;
private static readonly Dictionary<string, CounterStatistic> registeredStatistics;
private static readonly object lockable;
private static int nextId;
private readonly ConcurrentStack<ReferenceLong> specificStatisticFromAllThreads;
private readonly int id;
private long last;
private bool firstStatDisplay;
private Func<long, long> valueConverter;
private long nonOrleansThreadsCounter; // one for all non-Orleans threads
private readonly bool isHidden;
private readonly string currentName;
public string Name { get; }
public bool UseDelta { get; }
public CounterStorage Storage { get; }
static CounterStatistic()
{
registeredStatistics = new Dictionary<string, CounterStatistic>();
nextId = 0;
lockable = new object();
}
// Must be called while Lockable is locked
private CounterStatistic(string name, bool useDelta, CounterStorage storage, bool isHidden)
{
Name = name;
currentName = Metric.CreateCurrentName(name);
UseDelta = useDelta;
Storage = storage;
id = Interlocked.Increment(ref nextId);
last = 0;
firstStatDisplay = true;
valueConverter = null;
nonOrleansThreadsCounter = 0;
this.isHidden = isHidden;
specificStatisticFromAllThreads = new ConcurrentStack<ReferenceLong>();
}
internal static void SetOrleansManagedThread()
{
if (!isOrleansManagedThread)
{
lock (lockable)
{
isOrleansManagedThread = true;
allStatisticsFromSpecificThread = new List<ReferenceLong>(new ReferenceLong[BUFFER_SIZE]);
}
}
}
public static CounterStatistic FindOrCreate(StatisticName name)
{
return FindOrCreate_Impl(name, true, CounterStorage.LogAndTable, false);
}
public static CounterStatistic FindOrCreate(StatisticName name, bool useDelta, bool isHidden = false)
{
return FindOrCreate_Impl(name, useDelta, CounterStorage.LogAndTable, isHidden);
}
public static CounterStatistic FindOrCreate(StatisticName name, CounterStorage storage, bool isHidden = false)
{
return FindOrCreate_Impl(name, true, storage, isHidden);
}
public static CounterStatistic FindOrCreate(StatisticName name, bool useDelta, CounterStorage storage, bool isHidden = false)
{
return FindOrCreate_Impl(name, useDelta, storage, isHidden);
}
private static CounterStatistic FindOrCreate_Impl(StatisticName name, bool useDelta, CounterStorage storage, bool isHidden)
{
lock (lockable)
{
CounterStatistic stat;
if (registeredStatistics.TryGetValue(name.Name, out stat))
{
return stat;
}
var ctr = new CounterStatistic(name.Name, useDelta, storage, isHidden);
registeredStatistics[name.Name] = ctr;
return ctr;
}
}
public static bool Delete(string name)
{
lock (lockable)
{
return registeredStatistics.Remove(name);
}
}
public CounterStatistic AddValueConverter(Func<long, long> converter)
{
this.valueConverter = converter;
return this;
}
public void Increment()
{
IncrementBy(1);
}
public void DecrementBy(long n)
{
IncrementBy(-n);
}
// Orleans-managed threads aggregate stats in per thread local storage list.
// For non Orleans-managed threads (.NET IO completion port threads, thread pool timer threads) we don't want to allocate a thread local storage,
// since we don't control how many of those threads are created (could lead to too much thread local storage allocated).
// Thus, for non Orleans-managed threads, we use a counter shared between all those threads and Interlocked.Add it (creating small contention).
public void IncrementBy(long n)
{
if (isOrleansManagedThread)
{
if (allStatisticsFromSpecificThread.Count <= id)
{
var bufferSize = Math.Max(id - allStatisticsFromSpecificThread.Count, BUFFER_SIZE);
allStatisticsFromSpecificThread.AddRange(new ReferenceLong[bufferSize+1]);
}
var orleansValue = allStatisticsFromSpecificThread[id];
if (orleansValue == null)
{
orleansValue = new ReferenceLong();
allStatisticsFromSpecificThread[id] = orleansValue;
specificStatisticFromAllThreads.Push(orleansValue);
}
orleansValue.Value += n;
}
else
{
if (n == 1)
{
Interlocked.Increment(ref nonOrleansThreadsCounter);
}
else
{
Interlocked.Add(ref nonOrleansThreadsCounter, n);
}
}
}
/// <summary>
/// Returns the current value
/// </summary>
/// <returns></returns>
public long GetCurrentValue()
{
long val = specificStatisticFromAllThreads.Sum(a => a.Value);
return val + Interlocked.Read(ref nonOrleansThreadsCounter);
}
// does not reset delta
public long GetCurrentValueAndDelta(out long delta)
{
long currentValue = GetCurrentValue();
delta = UseDelta ? (currentValue - last) : 0;
return currentValue;
}
public bool IsValueDelta => UseDelta;
public void ResetCurrent()
{
var currentValue = GetCurrentValue();
last = currentValue;
}
public string GetValueString()
{
long current = GetCurrentValue();
if (valueConverter != null)
{
try
{
current = valueConverter(current);
}
catch (Exception) { }
}
return current.ToString(CultureInfo.InvariantCulture);
}
public string GetDeltaString()
{
long current = GetCurrentValue();
long delta = UseDelta ? (current - last) : 0;
if (valueConverter != null)
{
try
{
delta = valueConverter(delta);
}
catch (Exception) { }
}
return delta.ToString(CultureInfo.InvariantCulture);
}
public string GetDisplayString()
{
long delta;
long current = GetCurrentValueAndDelta(out delta);
if (firstStatDisplay)
{
delta = 0; // Special case: don't output first delta
firstStatDisplay = false;
}
if (valueConverter != null)
{
try
{
current = valueConverter(current);
}
catch (Exception) { }
try
{
delta = valueConverter(delta);
}
catch (Exception) { }
}
if (delta == 0)
{
return $"{Name}.Current={current.ToString(CultureInfo.InvariantCulture)}";
}
else
{
return
$"{Name}.Current={current.ToString(CultureInfo.InvariantCulture)}, Delta={delta.ToString(CultureInfo.InvariantCulture)}";
}
}
public override string ToString()
{
return GetDisplayString();
}
public static void AddCounters(List<ICounter> list, Func<CounterStatistic, bool> predicate)
{
lock (lockable)
{
list.AddRange(registeredStatistics.Values.Where( c => !c.isHidden && predicate(c)));
}
}
public void TrackMetric(Logger logger)
{
logger.TrackMetric(currentName, GetCurrentValue());
// TODO: track delta, when we figure out how to calculate them accurately
}
}
}
| |
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;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmFilterOrderList
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmFilterOrderList() : base()
{
Load += frmFilterOrderList_Load;
FormClosed += frmFilterOrderList_FormClosed;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.CheckedListBox withEventsField_lstFilter;
public System.Windows.Forms.CheckedListBox lstFilter {
get { return withEventsField_lstFilter; }
set {
if (withEventsField_lstFilter != null) {
withEventsField_lstFilter.ItemCheck -= lstFilter_ItemCheck;
withEventsField_lstFilter.KeyDown -= lstFilter_KeyDown;
withEventsField_lstFilter.KeyPress -= lstFilter_KeyPress;
}
withEventsField_lstFilter = value;
if (withEventsField_lstFilter != null) {
withEventsField_lstFilter.ItemCheck += lstFilter_ItemCheck;
withEventsField_lstFilter.KeyDown += lstFilter_KeyDown;
withEventsField_lstFilter.KeyPress += lstFilter_KeyPress;
}
}
}
public System.Windows.Forms.Button _cmdClick_4;
public System.Windows.Forms.Button _cmdClick_1;
public System.Windows.Forms.Button _cmdClick_2;
public System.Windows.Forms.Button _cmdClick_3;
private System.Windows.Forms.TextBox withEventsField_txtSearch;
public System.Windows.Forms.TextBox txtSearch {
get { return withEventsField_txtSearch; }
set {
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter -= txtSearch_Enter;
withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress;
}
withEventsField_txtSearch = value;
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter += txtSearch_Enter;
withEventsField_txtSearch.KeyDown += txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress += txtSearch_KeyPress;
}
}
}
private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button1;
public System.Windows.Forms.ToolStripButton _tbStockItem_Button1 {
get { return withEventsField__tbStockItem_Button1; }
set {
if (withEventsField__tbStockItem_Button1 != null) {
withEventsField__tbStockItem_Button1.Click -= tbStockItem_ButtonClick;
}
withEventsField__tbStockItem_Button1 = value;
if (withEventsField__tbStockItem_Button1 != null) {
withEventsField__tbStockItem_Button1.Click += tbStockItem_ButtonClick;
}
}
}
private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button2;
public System.Windows.Forms.ToolStripButton _tbStockItem_Button2 {
get { return withEventsField__tbStockItem_Button2; }
set {
if (withEventsField__tbStockItem_Button2 != null) {
withEventsField__tbStockItem_Button2.Click -= tbStockItem_ButtonClick;
}
withEventsField__tbStockItem_Button2 = value;
if (withEventsField__tbStockItem_Button2 != null) {
withEventsField__tbStockItem_Button2.Click += tbStockItem_ButtonClick;
}
}
}
private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button3;
public System.Windows.Forms.ToolStripButton _tbStockItem_Button3 {
get { return withEventsField__tbStockItem_Button3; }
set {
if (withEventsField__tbStockItem_Button3 != null) {
withEventsField__tbStockItem_Button3.Click -= tbStockItem_ButtonClick;
}
withEventsField__tbStockItem_Button3 = value;
if (withEventsField__tbStockItem_Button3 != null) {
withEventsField__tbStockItem_Button3.Click += tbStockItem_ButtonClick;
}
}
}
private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button4;
public System.Windows.Forms.ToolStripButton _tbStockItem_Button4 {
get { return withEventsField__tbStockItem_Button4; }
set {
if (withEventsField__tbStockItem_Button4 != null) {
withEventsField__tbStockItem_Button4.Click -= tbStockItem_ButtonClick;
}
withEventsField__tbStockItem_Button4 = value;
if (withEventsField__tbStockItem_Button4 != null) {
withEventsField__tbStockItem_Button4.Click += tbStockItem_ButtonClick;
}
}
}
public System.Windows.Forms.ToolStrip tbStockItem;
public System.Windows.Forms.ImageList ilSelect;
public System.Windows.Forms.Label _lbl_2;
//Public WithEvents cmdClick As Microsoft.VisualBasic.Compatibility.VB6.ButtonArray
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmFilterOrderList));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.lstFilter = new System.Windows.Forms.CheckedListBox();
this._cmdClick_4 = new System.Windows.Forms.Button();
this._cmdClick_1 = new System.Windows.Forms.Button();
this._cmdClick_2 = new System.Windows.Forms.Button();
this._cmdClick_3 = new System.Windows.Forms.Button();
this.txtSearch = new System.Windows.Forms.TextBox();
this.tbStockItem = new System.Windows.Forms.ToolStrip();
this._tbStockItem_Button1 = new System.Windows.Forms.ToolStripButton();
this._tbStockItem_Button2 = new System.Windows.Forms.ToolStripButton();
this._tbStockItem_Button3 = new System.Windows.Forms.ToolStripButton();
this._tbStockItem_Button4 = new System.Windows.Forms.ToolStripButton();
this.ilSelect = new System.Windows.Forms.ImageList();
this._lbl_2 = new System.Windows.Forms.Label();
//Me.cmdClick = New Microsoft.VisualBasic.Compatibility.VB6.ButtonArray(components)
//Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
this.tbStockItem.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
((System.ComponentModel.ISupportInitialize)this.cmdClick).BeginInit();
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
this.ControlBox = false;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.ClientSize = new System.Drawing.Size(293, 452);
this.Location = new System.Drawing.Point(3, 3);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.KeyPreview = false;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmFilterOrderList";
this.lstFilter.Size = new System.Drawing.Size(271, 379);
this.lstFilter.Location = new System.Drawing.Point(9, 63);
this.lstFilter.TabIndex = 7;
this.lstFilter.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lstFilter.BackColor = System.Drawing.SystemColors.Window;
this.lstFilter.CausesValidation = true;
this.lstFilter.Enabled = true;
this.lstFilter.ForeColor = System.Drawing.SystemColors.WindowText;
this.lstFilter.IntegralHeight = true;
this.lstFilter.Cursor = System.Windows.Forms.Cursors.Default;
this.lstFilter.SelectionMode = System.Windows.Forms.SelectionMode.One;
this.lstFilter.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lstFilter.Sorted = false;
this.lstFilter.TabStop = true;
this.lstFilter.Visible = true;
this.lstFilter.MultiColumn = false;
this.lstFilter.Name = "lstFilter";
this._cmdClick_4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this._cmdClick_4.Text = "&C";
this._cmdClick_4.Size = new System.Drawing.Size(103, 34);
this._cmdClick_4.Location = new System.Drawing.Point(360, 138);
this._cmdClick_4.TabIndex = 6;
this._cmdClick_4.TabStop = false;
this._cmdClick_4.BackColor = System.Drawing.SystemColors.Control;
this._cmdClick_4.CausesValidation = true;
this._cmdClick_4.Enabled = true;
this._cmdClick_4.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdClick_4.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdClick_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdClick_4.Name = "_cmdClick_4";
this._cmdClick_1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this._cmdClick_1.Text = "&A";
this._cmdClick_1.Size = new System.Drawing.Size(103, 34);
this._cmdClick_1.Location = new System.Drawing.Point(357, 204);
this._cmdClick_1.TabIndex = 5;
this._cmdClick_1.TabStop = false;
this._cmdClick_1.BackColor = System.Drawing.SystemColors.Control;
this._cmdClick_1.CausesValidation = true;
this._cmdClick_1.Enabled = true;
this._cmdClick_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdClick_1.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdClick_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdClick_1.Name = "_cmdClick_1";
this._cmdClick_2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this._cmdClick_2.Text = "&S";
this._cmdClick_2.Size = new System.Drawing.Size(103, 34);
this._cmdClick_2.Location = new System.Drawing.Point(360, 252);
this._cmdClick_2.TabIndex = 4;
this._cmdClick_2.TabStop = false;
this._cmdClick_2.BackColor = System.Drawing.SystemColors.Control;
this._cmdClick_2.CausesValidation = true;
this._cmdClick_2.Enabled = true;
this._cmdClick_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdClick_2.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdClick_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdClick_2.Name = "_cmdClick_2";
this._cmdClick_3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this._cmdClick_3.Text = "&U";
this._cmdClick_3.Size = new System.Drawing.Size(103, 34);
this._cmdClick_3.Location = new System.Drawing.Point(351, 303);
this._cmdClick_3.TabIndex = 3;
this._cmdClick_3.TabStop = false;
this._cmdClick_3.BackColor = System.Drawing.SystemColors.Control;
this._cmdClick_3.CausesValidation = true;
this._cmdClick_3.Enabled = true;
this._cmdClick_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._cmdClick_3.Cursor = System.Windows.Forms.Cursors.Default;
this._cmdClick_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._cmdClick_3.Name = "_cmdClick_3";
this.txtSearch.AutoSize = false;
this.txtSearch.Size = new System.Drawing.Size(223, 19);
this.txtSearch.Location = new System.Drawing.Point(57, 42);
this.txtSearch.TabIndex = 1;
this.txtSearch.AcceptsReturn = true;
this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtSearch.BackColor = System.Drawing.SystemColors.Window;
this.txtSearch.CausesValidation = true;
this.txtSearch.Enabled = true;
this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtSearch.HideSelection = true;
this.txtSearch.ReadOnly = false;
this.txtSearch.MaxLength = 0;
this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtSearch.Multiline = false;
this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtSearch.TabStop = true;
this.txtSearch.Visible = true;
this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.txtSearch.Name = "txtSearch";
this.tbStockItem.ShowItemToolTips = true;
this.tbStockItem.Size = new System.Drawing.Size(272, 40);
this.tbStockItem.Location = new System.Drawing.Point(9, 0);
this.tbStockItem.TabIndex = 0;
this.tbStockItem.ImageList = ilSelect;
this.tbStockItem.Name = "tbStockItem";
this._tbStockItem_Button1.Size = new System.Drawing.Size(68, 41);
this._tbStockItem_Button1.AutoSize = false;
this._tbStockItem_Button1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText;
this._tbStockItem_Button1.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this._tbStockItem_Button1.Text = "&All";
this._tbStockItem_Button1.Name = "All";
this._tbStockItem_Button1.ImageIndex = 0;
this._tbStockItem_Button1.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this._tbStockItem_Button2.Size = new System.Drawing.Size(68, 41);
this._tbStockItem_Button2.AutoSize = false;
this._tbStockItem_Button2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText;
this._tbStockItem_Button2.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this._tbStockItem_Button2.Text = "&Selected";
this._tbStockItem_Button2.Name = "Selected";
this._tbStockItem_Button2.ImageIndex = 1;
this._tbStockItem_Button2.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this._tbStockItem_Button3.Size = new System.Drawing.Size(68, 41);
this._tbStockItem_Button3.AutoSize = false;
this._tbStockItem_Button3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText;
this._tbStockItem_Button3.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this._tbStockItem_Button3.Text = "&Unselected";
this._tbStockItem_Button3.Name = "Unselected";
this._tbStockItem_Button3.ImageIndex = 2;
this._tbStockItem_Button3.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this._tbStockItem_Button4.Size = new System.Drawing.Size(68, 41);
this._tbStockItem_Button4.AutoSize = false;
this._tbStockItem_Button4.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText;
this._tbStockItem_Button4.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this._tbStockItem_Button4.Text = "&Clear All";
this._tbStockItem_Button4.Name = "clear";
this._tbStockItem_Button4.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
this.ilSelect.ImageSize = new System.Drawing.Size(20, 20);
this.ilSelect.TransparentColor = System.Drawing.Color.FromArgb(255, 0, 255);
this.ilSelect.ImageStream = (System.Windows.Forms.ImageListStreamer)resources.GetObject("ilSelect.ImageStream");
this.ilSelect.Images.SetKeyName(0, "");
this.ilSelect.Images.SetKeyName(1, "");
this.ilSelect.Images.SetKeyName(2, "");
this._lbl_2.Text = "Search:";
this._lbl_2.Size = new System.Drawing.Size(40, 13);
this._lbl_2.Location = new System.Drawing.Point(9, 48);
this._lbl_2.TabIndex = 2;
this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_2.BackColor = System.Drawing.Color.Transparent;
this._lbl_2.Enabled = true;
this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_2.UseMnemonic = true;
this._lbl_2.Visible = true;
this._lbl_2.AutoSize = false;
this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_2.Name = "_lbl_2";
this.Controls.Add(lstFilter);
this.Controls.Add(_cmdClick_4);
this.Controls.Add(_cmdClick_1);
this.Controls.Add(_cmdClick_2);
this.Controls.Add(_cmdClick_3);
this.Controls.Add(txtSearch);
this.Controls.Add(tbStockItem);
this.Controls.Add(_lbl_2);
this.tbStockItem.Items.Add(_tbStockItem_Button1);
this.tbStockItem.Items.Add(_tbStockItem_Button2);
this.tbStockItem.Items.Add(_tbStockItem_Button3);
this.tbStockItem.Items.Add(_tbStockItem_Button4);
//Me.cmdClick.SetIndex(_cmdClick_4, CType(4, Short))
//Me.cmdClick.SetIndex(_cmdClick_1, CType(1, Short))
//Me.cmdClick.SetIndex(_cmdClick_2, CType(2, Short))
//Me.cmdClick.SetIndex(_cmdClick_3, CType(3, Short))
//Me.lbl.SetIndex(_lbl_2, CType(2, Short))
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.cmdClick, System.ComponentModel.ISupportInitialize).EndInit()
this.tbStockItem.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
using System;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace zprotobuf
{
public abstract class wire {
private static int oid = 0;
private static Dictionary<IntPtr, wire> uds = new Dictionary<IntPtr, wire>();
private static int encode_cb(ref zdll.args arg) {
wire obj = uds[arg.ud];
return obj._encode_field(ref arg);
}
private static int decode_cb(ref zdll.args arg) {
wire obj = uds[arg.ud];
return obj._decode_field(ref arg);
}
private IntPtr udbegin() {
IntPtr id = (IntPtr)(++oid);
uds[id] = this;
return id;
}
private void udend(IntPtr id) {
Debug.Assert((IntPtr)oid == id);
--oid;
uds[id] = null;
}
protected int write(ref zdll.args arg, byte[] src) {
if (src.Length > arg.buffsz)
return zdll.OOM;
Marshal.Copy(src, 0, arg.buff, src.Length);
return src.Length;
}
protected int write(ref zdll.args arg, string val) {
byte[] src = Encoding.ASCII.GetBytes(val);
return write(ref arg, src);
}
protected int write(ref zdll.args arg, bool val) {
byte[] src = BitConverter.GetBytes(val);
return write(ref arg, src);
}
protected int write(ref zdll.args arg, sbyte val) {
byte[] src = new byte[1];
src[0] = (byte)val;
return write(ref arg, src);
}
protected int write(ref zdll.args arg, short val) {
byte[] src = BitConverter.GetBytes(val);
return write(ref arg, src);
}
protected int write(ref zdll.args arg, int val) {
byte[] src = BitConverter.GetBytes(val);
return write(ref arg, src);
}
protected int write(ref zdll.args arg, long val) {
byte[] src = BitConverter.GetBytes(val);
return write(ref arg, src);
}
protected int write(ref zdll.args arg, byte val) {
byte[] src = new byte[1];
src[0] = (byte)val;
return write(ref arg, src);
}
protected int write(ref zdll.args arg, ushort val) {
byte[] src = BitConverter.GetBytes(val);
return write(ref arg, src);
}
protected int write(ref zdll.args arg, uint val) {
byte[] src = BitConverter.GetBytes(val);
return write(ref arg, src);
}
protected int write(ref zdll.args arg, ulong val) {
byte[] src = BitConverter.GetBytes(val);
return write(ref arg, src);
}
protected int write(ref zdll.args arg, float val) {
byte[] src = BitConverter.GetBytes(val);
return write(ref arg, src);
}
private byte[] read(ref zdll.args arg) {
byte[] ret = new byte[arg.buffsz];
Marshal.Copy(arg.buff, ret, 0, ret.Length);
return ret;
}
protected int read(ref zdll.args arg, out bool val) {
val = BitConverter.ToBoolean(read(ref arg), 0);
return arg.buffsz;
}
protected int read(ref zdll.args arg, out sbyte val) {
val = (sbyte)read(ref arg)[0];
return arg.buffsz;
}
protected int read(ref zdll.args arg, out short val) {
val = BitConverter.ToInt16(read(ref arg), 0);
return arg.buffsz;
}
protected int read(ref zdll.args arg, out int val) {
val = BitConverter.ToInt32(read(ref arg), 0);
return arg.buffsz;
}
protected int read(ref zdll.args arg, out long val) {
val = BitConverter.ToInt64(read(ref arg), 0);
return arg.buffsz;
}
protected int read(ref zdll.args arg, out byte val) {
val = (byte)read(ref arg)[0];
return arg.buffsz;
}
protected int read(ref zdll.args arg, out ushort val) {
val = BitConverter.ToUInt16(read(ref arg), 0);
return arg.buffsz;
}
protected int read(ref zdll.args arg, out uint val) {
val = BitConverter.ToUInt32(read(ref arg), 0);
return arg.buffsz;
}
protected int read(ref zdll.args arg, out ulong val) {
val = BitConverter.ToUInt64(read(ref arg), 0);
return arg.buffsz;
}
protected int read(ref zdll.args arg, out float val) {
val = BitConverter.ToSingle(read(ref arg), 0);
return arg.buffsz;
}
protected int read(ref zdll.args arg, out byte[] val) {
val = read(ref arg);
return arg.buffsz;
}
protected int read(ref zdll.args arg, out string val) {
val = Encoding.Default.GetString(read(ref arg));
return arg.buffsz;
}
public int _encode(IntPtr buff, int len, IntPtr st) {
IntPtr id = udbegin();
int err = zdll.encode(st, buff, len, encode_cb, id);
udend(id);
return err;
}
public int _decode(IntPtr buff, int len, IntPtr st) {
IntPtr id = udbegin();
int err = zdll.decode(st, buff, len, decode_cb, id);
udend(id);
return err;
}
public virtual int _serialize(out byte[] dat) {
dat = null;
Debug.Assert("NotImplement" == null);
return zdll.ERROR;
}
public virtual int _parse(byte[] dat, int size) {
Debug.Assert("NotImplement" == null);
return zdll.ERROR;
}
public virtual int _parse(IntPtr dat, int size) {
Debug.Assert("NotImplement" == null);
return zdll.ERROR;
}
public virtual int _pack(byte[] src, int size, out byte[] dst) {
dst = null;
Debug.Assert("NotImplement" == null);
return zdll.ERROR;
}
public virtual int _unpack(byte[] src, int size, out byte[] dst) {
dst = null;
Debug.Assert("NotImplement" == null);
return zdll.ERROR;
}
public virtual int _tag() {
Debug.Assert("NotImplement" == null);
return 0;
}
//abstract function
public abstract string _name();
protected abstract int _encode_field(ref zdll.args arg);
protected abstract int _decode_field(ref zdll.args arg);
}
public class wiretree {
private string protodef = "";
private IntPtr Z = IntPtr.Zero;
private int buffsize = 64;
private Dictionary<string, IntPtr> cache = new Dictionary<string,IntPtr>();
public wiretree(string def) {
protodef = def;
Z = zdll.parse(protodef);
}
~wiretree() {
}
private IntPtr query(string name) {
if (cache.ContainsKey(name))
return cache[name];
IntPtr st = zdll.query(Z, name);
cache[name] = st;
return st;
}
public int tag(string name) {
IntPtr st = query(name);
return zdll.tag(st);
}
private IntPtr expand(IntPtr buf) {
buffsize *= 2;
return Marshal.ReAllocHGlobal(buf, (IntPtr)buffsize);
}
public int encode(wire obj, out byte[] data) {
data = null;
IntPtr st = query(obj._name());
IntPtr buff = Marshal.AllocHGlobal(buffsize);
for (;;) {
int sz = obj._encode(buff, buffsize, st);
if (sz == zdll.ERROR) {
Marshal.FreeHGlobal(buff);
return sz;
}
if (sz == zdll.OOM) {
buff = expand(buff);
continue;
}
data = new byte[sz];
Marshal.Copy(buff, data, 0, sz);
Marshal.FreeHGlobal(buff);
return sz;
}
}
public int decode(wire obj, byte[] data, int size) {
int ret;
IntPtr st = query(obj._name());
while (buffsize < size)
buffsize *= 2;
IntPtr buff = Marshal.AllocHGlobal(buffsize);
Marshal.Copy(data, 0, buff, size);
ret = obj._decode(buff, size, st);
Marshal.FreeHGlobal(buff);
return ret;
}
public int decode(wire obj, IntPtr data, int size) {
IntPtr st = query(obj._name());
return obj._decode(data, size, st);
}
public int pack(byte[] src, int size, out byte[] dst) {
IntPtr srcptr, dstptr;
while (buffsize < size)
buffsize *= 2;
srcptr = Marshal.AllocHGlobal(buffsize);
dstptr = Marshal.AllocHGlobal(buffsize);
Marshal.Copy(src, 0, srcptr, size);
dst = null;
for (;;) {
int ret = zdll.pack(srcptr, size, dstptr, buffsize);
if (ret == zdll.ERROR) {
Marshal.FreeHGlobal(srcptr);
Marshal.FreeHGlobal(dstptr);
return ret;
}
if (ret == zdll.OOM) {
dstptr = expand(dstptr);
continue;
}
dst = new byte[ret];
Marshal.Copy(dstptr, dst, 0, ret);
Marshal.FreeHGlobal(srcptr);
Marshal.FreeHGlobal(dstptr);
return ret;
}
}
public int unpack(byte[] src, int size, out byte[] dst) {
IntPtr srcptr, dstptr;
while (buffsize < size * 2) //assume compress ratio is 0.5
buffsize *= 2;
srcptr = Marshal.AllocHGlobal(buffsize);
dstptr = Marshal.AllocHGlobal(buffsize);
Marshal.Copy(src, 0, srcptr, size);
dst = null;
for (;;) {
int ret = zdll.unpack(srcptr, size, dstptr, buffsize);
if (ret == zdll.ERROR) {
Marshal.FreeHGlobal(srcptr);
Marshal.FreeHGlobal(dstptr);
return ret;
}
if (ret == zdll.OOM) {
dstptr = expand(dstptr);
continue;
}
dst = new byte[ret];
Marshal.Copy(dstptr, dst, 0, ret);
Marshal.FreeHGlobal(srcptr);
Marshal.FreeHGlobal(dstptr);
return ret;
}
}
}
public abstract class iwirep:wire {
public override int _serialize(out byte[] dat) {
return _wiretree().encode(this, out dat);
}
public override int _parse(byte[] dat, int size) {
return _wiretree().decode(this, dat, size);
}
public override int _parse(IntPtr dat, int size) {
return _wiretree().decode(this, dat, size);
}
public override int _pack(byte[] src, int size, out byte[] dst) {
return _wiretree().pack(src, size, out dst);
}
public override int _unpack(byte[] src, int size, out byte[] dst) {
return _wiretree().unpack(src, size, out dst);
}
public override int _tag() {
return _wiretree().tag(_name());
}
protected abstract wiretree _wiretree();
}
}
| |
/// <summary>
/// UnuGames - UIMan - Fast and flexible solution for development and UI management with MVVM pattern
/// @Author: Dang Minh Du
/// @Email: cp.dev.minhdu@gmail.com
/// </summary>
using System;
using UnityEngine;
using System.Collections;
using UnuGames.MVVM;
using UnuGames;
namespace UnuGames
{
[RequireComponent (typeof(CanvasGroup))]
[Serializable]
public class UIManBase : ViewModelBehaviour
{
[HideInInspector]
public UIMotion motionShow;
[HideInInspector]
public UIMotion motionHide;
[HideInInspector]
public UIMotion motionIdle;
[HideInInspector]
public Animator animRoot;
[HideInInspector]
public Vector3 showPosition = Vector3.zero;
[HideInInspector]
public float animTime = 0.25f;
Type _uiType;
public Type UIType {
get {
if (_uiType == null)
_uiType = this.GetType ();
return _uiType;
}
}
public UIState State { get; private set; }
private CanvasGroup mCanvasGroup;
public CanvasGroup GroupCanvas {
get {
if (mCanvasGroup == null)
mCanvasGroup = GetComponent<CanvasGroup> ();
if (mCanvasGroup == null)
mCanvasGroup = gameObject.AddComponent<CanvasGroup> ();
return mCanvasGroup;
}
}
private RectTransform mRectTrans;
public RectTransform RectTrans {
get {
if (mRectTrans == null)
mRectTrans = GetComponent<RectTransform> ();
return mRectTrans;
}
}
private Transform mTrans;
public Transform Trans {
get {
if (mTrans == null)
mTrans = GetComponent<Transform> ();
return mTrans;
}
}
private bool _isReady = false;
public bool IsActive {
get { return _isReady; }
set { _isReady = value; }
}
/// <summary>
/// Gets the type of the user interface.
/// </summary>
/// <returns>The user interface type.</returns>
public virtual UIBaseType GetUIBaseType ()
{
return default(UIBaseType);
}
/// <summary>
/// Raises the show event.
/// </summary>
/// <param name="args">Arguments.</param>
public virtual void OnShow (params object[] args)
{
if (GroupCanvas.alpha != 0 && (motionShow != UIMotion.CUSTOM_MECANIM_ANIMATION && motionShow != UIMotion.CUSTOM_SCRIPT_ANIMATION))
GroupCanvas.alpha = 0;
State = UIState.BUSY;
IsActive = false;
}
/// <summary>
/// Raises the hide event.
/// </summary>
public virtual void OnHide ()
{
if (GroupCanvas.alpha != 1 && motionHide != UIMotion.CUSTOM_MECANIM_ANIMATION && motionHide != UIMotion.CUSTOM_SCRIPT_ANIMATION)
GroupCanvas.alpha = 1;
State = UIState.BUSY;
IsActive = false;
}
/// <summary>
/// Raises the show complete event.
/// </summary>
public virtual void OnShowComplete ()
{
State = UIState.SHOW;
IsActive = true;
}
/// <summary>
/// Raises the hide complete event.
/// </summary>
public virtual void OnHideComplete ()
{
State = UIState.HIDE;
}
/// <summary>
/// Updates the alpha.
/// </summary>
/// <param name="alpha">Alpha.</param>
public void UpdateAlpha (float alpha)
{
GroupCanvas.alpha = alpha;
}
/// <summary>
/// Internal function for hide current ui
/// </summary>
public void HideMe ()
{
if (GetUIBaseType () == UIBaseType.SCREEN) {
UIMan.Instance.HideScreen (UIType);
} else {
UIMan.Instance.HideDialog (UIType);
}
}
/// <summary>
/// Animations the show.
/// </summary>
public virtual IEnumerator AnimationShow ()
{
yield return null;
}
/// <summary>
/// Animations the hide.
/// </summary>
public virtual IEnumerator AnimationHide ()
{
yield return null;
}
/// <summary>
/// Animations the idle.
/// </summary>
public virtual IEnumerator AnimationIdle ()
{
yield return null;
}
/// <summary>
/// Locks the input.
/// </summary>
public void LockInput ()
{
GroupCanvas.interactable = false;
GroupCanvas.blocksRaycasts = false;
}
/// <summary>
/// Unlocks the input.
/// </summary>
public void UnlockInput ()
{
GroupCanvas.interactable = true;
GroupCanvas.blocksRaycasts = true;
}
/// <summary>
/// Forces the state.
/// </summary>
/// <param name="state">State.</param>
public void ForceState (UIState state) {
State = state;
}
}
}
| |
namespace System.Reflection
{
using System.Collections.Generic;
using System.Linq;
static class ObjectExtensions
{
private static Func<object, object> _memberwiseClone;
static ObjectExtensions()
{
var clone = typeof(object).GetTypeInfo().GetDeclaredMethod("MemberwiseClone");
_memberwiseClone = (Func<object, object>)clone.CreateDelegate(typeof(Func<object, object>));
}
public static T MemberwiseClone<T>(this T target)
{
if (target == null) return target;
return (T)_memberwiseClone(target);
}
public static object GetProperty<T>(this T target, string property)
{
foreach (var pi in Accessor<T>.Properties)
{
if (pi.Member.Name == property)
{
return pi.GetValue(target);
}
}
foreach (var fi in Accessor<T>.Fields)
{
if (fi.Name == property)
{
return fi.GetValue(target);
}
}
return null;
}
public static void SetProperty<T>(this T target, string property, object value)
{
foreach (var pi in Accessor<T>.Properties)
{
if (pi.Member.Name == property)
{
pi.SetValue(target, value);
return;
}
}
foreach (var fi in Accessor<T>.Fields)
{
if (fi.Name == property)
{
fi.SetValue(target, value);
return;
}
}
}
public static T With<T>(this T target, T change, string property)
{
var result = _memberwiseClone(target);
foreach (var pi in Accessor<T>.Properties)
{
if (pi.Member.Name == property)
{
pi.Copy(change, result);
return (T)result;
}
}
foreach (var fi in Accessor<T>.Fields)
{
if (fi.Name == property)
{
fi.SetValue(result, fi.GetValue(change));
return (T)result;
}
}
return (T)result;
}
public static T With<T>(this T target, T change, string property, params string[] properties)
{
var result = _memberwiseClone(target);
var found = false;
if (property != null)
{
foreach (var pi in Accessor<T>.Properties)
{
if (pi.Member.Name == property)
{
pi.Copy(change, result);
found = true;
break;
}
}
if (!found)
{
foreach (var fi in Accessor<T>.Fields)
{
if (fi.Name == property)
{
fi.SetValue(result, fi.GetValue(change));
break;
}
}
}
}
foreach (var p in properties)
{
found = false;
foreach (var pi in Accessor<T>.Properties)
{
if (pi.Member.Name == p)
{
pi.Copy(change, result);
found = true;
break;
}
}
if (!found)
{
foreach (var fi in Accessor<T>.Fields)
{
if (fi.Name == p)
{
fi.SetValue(result, fi.GetValue(change));
break;
}
}
}
}
return (T)result;
}
public static T With<T>(this T target, T change, IEnumerable<string> properties)
{
var result = _memberwiseClone(target);
foreach (var p in properties)
{
var found = false;
foreach (var pi in Accessor<T>.Properties)
{
if (pi.Member.Name == p)
{
pi.Copy(change, result);
found = true;
break;
}
}
if (!found)
{
foreach (var fi in Accessor<T>.Fields)
{
if (fi.Name == p)
{
fi.SetValue(result, fi.GetValue(change));
break;
}
}
}
}
return (T)result;
}
public static T With<T>(this T target, IReadOnlyDictionary<string, object> changes)
{
if (changes == null || changes.Count <= 0) return target;
var result = _memberwiseClone(target);
foreach (var p in changes)
{
var found = false;
foreach (var pi in Accessor<T>.Properties)
{
if (pi.Member.Name == p.Key)
{
pi.SetValue(result, p.Value);
found = true;
break;
}
}
if (!found)
{
foreach (var fi in Accessor<T>.Fields)
{
if (fi.Name == p.Key)
{
fi.SetValue(result, p.Value);
break;
}
}
}
}
return (T)result;
}
public static T Merge<T>(this T target, T change) where T : class, new()
{
if (ReferenceEquals(target, change)) return target;
foreach (var pi in Accessor<T>.Properties)
{
pi.Copy(change, target);
}
foreach (var fi in Accessor<T>.Fields)
{
fi.SetValue(target, fi.GetValue(change));
}
return target;
}
public static T Merge<T>(this T target, T change, Func<MemberInfo, bool> predicate) where T : class, new()
{
if (ReferenceEquals(target, change)) return target;
foreach (var pi in Accessor<T>.Properties)
{
if (predicate(pi.Member))
{
pi.Copy(change, target);
}
}
foreach (var pi in Accessor<T>.Fields)
{
if (predicate(pi))
{
pi.SetValue(target, pi.GetValue(change));
}
}
return target;
}
public static IEnumerable<string> Delta<T>(this T target, T comparand) where T : class, new()
{
if (ReferenceEquals(target, comparand)) yield break;
foreach (var pi in Accessor<T>.Properties)
{
if (pi.Compare(target, comparand))
{
yield return pi.Member.Name;
}
}
foreach (var fi in Accessor<T>.Fields)
{
if (!Equals(fi.GetValue(target),
fi.GetValue(target)))
{
yield return fi.Name;
}
}
}
internal interface IPropertyAccessor
{
PropertyInfo Member { get; }
object GetValue(object source);
void SetValue(object source, object value);
void Copy(object source, object target);
bool Compare(object source, object target);
}
class PropertyAccessor<T, TValue> : IPropertyAccessor
{
private readonly Func<T, TValue> _getter;
private readonly Action<T, TValue> _setter;
private readonly PropertyInfo _pi;
public PropertyInfo Member => _pi;
public PropertyAccessor(PropertyInfo pi)
{
_pi = pi;
_getter = (Func<T, TValue>)pi.GetMethod.CreateDelegate(typeof(Func<T, TValue>));
_setter = (Action<T, TValue>)pi.SetMethod.CreateDelegate(typeof(Action<T, TValue>));
}
public object GetValue(object source) => _getter((T)source);
public void SetValue(object source, object value) => _setter((T)source, (TValue)value);
public void Copy(object source, object target) => _setter((T)target, _getter((T)source));
public bool Compare(object source, object target) => Equals(_getter((T)source), _getter((T)target));
}
internal static class Accessor<T>
{
public static readonly IPropertyAccessor[] Properties = (
from pi in GetAllProperties(typeof(T))
where pi.GetMethod != null && pi.GetMethod.IsPublic && pi.SetMethod != null && pi.SetMethod.IsPublic
let accessorType = typeof(PropertyAccessor<,>).MakeGenericType(typeof(T), pi.PropertyType)
select (IPropertyAccessor)Activator.CreateInstance(accessorType, pi)).ToArray();
public static readonly FieldInfo[] Fields = (
from fi in GetAllFields(typeof(T)) where fi.IsPublic select fi).ToArray();
private static IEnumerable<PropertyInfo> GetAllProperties(Type type)
{
while (type != null)
{
var ti = type.GetTypeInfo();
foreach (var prop in ti.DeclaredProperties)
{
yield return prop;
}
type = ti.BaseType;
}
}
private static IEnumerable<FieldInfo> GetAllFields(Type type)
{
while (type != null)
{
var ti = type.GetTypeInfo();
foreach (var field in ti.DeclaredFields)
{
yield return field;
}
type = ti.BaseType;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IO;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
namespace System.ServiceModel.Dispatcher
{
internal class StreamFormatter
{
private string _wrapperName;
private string _wrapperNS;
private string _partName;
private string _partNS;
private int _streamIndex;
private bool _isRequest;
private string _operationName;
private const int returnValueIndex = -1;
internal static StreamFormatter Create(MessageDescription messageDescription, string operationName, bool isRequest)
{
MessagePartDescription streamPart = ValidateAndGetStreamPart(messageDescription, isRequest, operationName);
if (streamPart == null)
return null;
return new StreamFormatter(messageDescription, streamPart, operationName, isRequest);
}
private StreamFormatter(MessageDescription messageDescription, MessagePartDescription streamPart, string operationName, bool isRequest)
{
if ((object)streamPart == (object)messageDescription.Body.ReturnValue)
_streamIndex = returnValueIndex;
else
_streamIndex = streamPart.Index;
_wrapperName = messageDescription.Body.WrapperName;
_wrapperNS = messageDescription.Body.WrapperNamespace;
_partName = streamPart.Name;
_partNS = streamPart.Namespace;
_isRequest = isRequest;
_operationName = operationName;
}
internal void Serialize(XmlDictionaryWriter writer, object[] parameters, object returnValue)
{
Stream streamValue = GetStreamAndWriteStartWrapperIfNecessary(writer, parameters, returnValue);
writer.WriteValue(new OperationStreamProvider(streamValue));
WriteEndWrapperIfNecessary(writer);
}
private Stream GetStreamAndWriteStartWrapperIfNecessary(XmlDictionaryWriter writer, object[] parameters, object returnValue)
{
Stream streamValue = GetStreamValue(parameters, returnValue);
if (streamValue == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(_partName);
if (WrapperName != null)
writer.WriteStartElement(WrapperName, WrapperNamespace);
writer.WriteStartElement(PartName, PartNamespace);
return streamValue;
}
private void WriteEndWrapperIfNecessary(XmlDictionaryWriter writer)
{
writer.WriteEndElement();
if (_wrapperName != null)
writer.WriteEndElement();
}
internal IAsyncResult BeginSerialize(XmlDictionaryWriter writer, object[] parameters, object returnValue, AsyncCallback callback, object state)
{
return new SerializeAsyncResult(this, writer, parameters, returnValue, callback, state);
}
public void EndSerialize(IAsyncResult result)
{
SerializeAsyncResult.End(result);
}
internal class SerializeAsyncResult : AsyncResult
{
private static AsyncCompletion s_handleEndSerialize = new AsyncCompletion(HandleEndSerialize);
private StreamFormatter _streamFormatter;
private XmlDictionaryWriter _writer;
internal SerializeAsyncResult(StreamFormatter streamFormatter, XmlDictionaryWriter writer, object[] parameters, object returnValue,
AsyncCallback callback, object state)
: base(callback, state)
{
_streamFormatter = streamFormatter;
_writer = writer;
throw ExceptionHelper.PlatformNotSupported("StreamFormatter.SerializeAsyncResult is not supported.");
}
private static bool HandleEndSerialize(IAsyncResult result)
{
SerializeAsyncResult thisPtr = (SerializeAsyncResult)result.AsyncState;
thisPtr._streamFormatter.WriteEndWrapperIfNecessary(thisPtr._writer);
return true;
}
public static void End(IAsyncResult result)
{
AsyncResult.End<SerializeAsyncResult>(result);
}
}
internal void Deserialize(object[] parameters, ref object retVal, Message message)
{
SetStreamValue(parameters, ref retVal, new MessageBodyStream(message, WrapperName, WrapperNamespace, PartName, PartNamespace, _isRequest));
}
internal string WrapperName
{
get { return _wrapperName; }
set { _wrapperName = value; }
}
internal string WrapperNamespace
{
get { return _wrapperNS; }
set { _wrapperNS = value; }
}
internal string PartName
{
get { return _partName; }
}
internal string PartNamespace
{
get { return _partNS; }
}
private Stream GetStreamValue(object[] parameters, object returnValue)
{
if (_streamIndex == returnValueIndex)
return (Stream)returnValue;
return (Stream)parameters[_streamIndex];
}
private void SetStreamValue(object[] parameters, ref object returnValue, Stream streamValue)
{
if (_streamIndex == returnValueIndex)
returnValue = streamValue;
else
parameters[_streamIndex] = streamValue;
}
private static MessagePartDescription ValidateAndGetStreamPart(MessageDescription messageDescription, bool isRequest, string operationName)
{
MessagePartDescription part = GetStreamPart(messageDescription);
if (part != null)
return part;
if (HasStream(messageDescription))
{
if (messageDescription.IsTypedMessage)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStreamInTypedMessage, messageDescription.MessageName)));
else if (isRequest)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStreamInRequest, operationName)));
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStreamInResponse, operationName)));
}
return null;
}
private static bool HasStream(MessageDescription messageDescription)
{
if (messageDescription.Body.ReturnValue != null && messageDescription.Body.ReturnValue.Type == typeof(Stream))
return true;
foreach (MessagePartDescription part in messageDescription.Body.Parts)
{
if (part.Type == typeof(Stream))
return true;
}
return false;
}
private static MessagePartDescription GetStreamPart(MessageDescription messageDescription)
{
if (OperationFormatter.IsValidReturnValue(messageDescription.Body.ReturnValue))
{
if (messageDescription.Body.Parts.Count == 0)
if (messageDescription.Body.ReturnValue.Type == typeof(Stream))
return messageDescription.Body.ReturnValue;
}
else
{
if (messageDescription.Body.Parts.Count == 1)
if (messageDescription.Body.Parts[0].Type == typeof(Stream))
return messageDescription.Body.Parts[0];
}
return null;
}
internal static bool IsStream(MessageDescription messageDescription)
{
return GetStreamPart(messageDescription) != null;
}
internal class MessageBodyStream : Stream
{
private Message _message;
private XmlDictionaryReader _reader;
private long _position;
private string _wrapperName, _wrapperNs;
private string _elementName, _elementNs;
private bool _isRequest;
internal MessageBodyStream(Message message, string wrapperName, string wrapperNs, string elementName, string elementNs, bool isRequest)
{
_message = message;
_position = 0;
_wrapperName = wrapperName;
_wrapperNs = wrapperNs;
_elementName = elementName;
_elementNs = elementNs;
_isRequest = isRequest;
}
public override int Read(byte[] buffer, int offset, int count)
{
EnsureStreamIsOpen();
if (buffer == null)
throw TraceUtility.ThrowHelperError(new ArgumentNullException("buffer"), _message);
if (offset < 0)
throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", offset,
SR.Format(SR.ValueMustBeNonNegative)), _message);
if (count < 0)
throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", count,
SR.Format(SR.ValueMustBeNonNegative)), _message);
if (buffer.Length - offset < count)
throw TraceUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.SFxInvalidStreamOffsetLength, offset + count)), _message);
try
{
if (_reader == null)
{
_reader = _message.GetReaderAtBodyContents();
if (_wrapperName != null)
{
_reader.MoveToContent();
_reader.ReadStartElement(_wrapperName, _wrapperNs);
}
_reader.MoveToContent();
if (_reader.NodeType == XmlNodeType.EndElement)
{
return 0;
}
_reader.ReadStartElement(_elementName, _elementNs);
}
if (_reader.MoveToContent() != XmlNodeType.Text)
{
Exhaust(_reader);
return 0;
}
int bytesRead = _reader.ReadContentAsBase64(buffer, offset, count);
_position += bytesRead;
if (bytesRead == 0)
{
Exhaust(_reader);
}
return bytesRead;
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
throw;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new IOException(SR.Format(SR.SFxStreamIOException), ex));
}
}
private void EnsureStreamIsOpen()
{
if (_message.State == MessageState.Closed)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(SR.Format(
_isRequest ? SR.SFxStreamRequestMessageClosed : SR.SFxStreamResponseMessageClosed)));
}
private static void Exhaust(XmlDictionaryReader reader)
{
if (reader != null)
{
while (reader.Read())
{
// drain
}
}
}
public override long Position
{
get
{
EnsureStreamIsOpen();
return _position;
}
set { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); }
}
protected override void Dispose(bool isDisposing)
{
_message.Close();
if (_reader != null)
{
_reader.Dispose();
_reader = null;
}
base.Dispose(isDisposing);
}
public override bool CanRead { get { return _message.State != MessageState.Closed; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return false; } }
public override long Length
{
get
{
throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message);
}
}
public override void Flush() { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); }
public override long Seek(long offset, SeekOrigin origin) { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); }
public override void SetLength(long value) { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); }
public override void Write(byte[] buffer, int offset, int count) { throw TraceUtility.ThrowHelperError(new NotSupportedException(), _message); }
}
internal class OperationStreamProvider
{
private Stream _stream;
internal OperationStreamProvider(Stream stream)
{
_stream = stream;
}
public Stream GetStream()
{
return _stream;
}
public void ReleaseStream(Stream stream)
{
//Noop
}
}
}
}
| |
//! \file ArcKaguya.cs
//! \date Mon Jun 01 07:03:03 2015
//! \brief KaGuYa archive format.
//
// Copyright (C) 2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using GameRes.Utility;
namespace GameRes.Formats.Kaguya
{
internal class AriEntry : PackedEntry
{
public ushort Mode;
}
[Export(typeof(ArchiveFormat))]
public class ArcOpener : ArchiveFormat
{
public override string Tag { get { return "ARI"; } }
public override string Description { get { return "KaGuYa script engine resource archive"; } }
public override uint Signature { get { return 0x314c4657; } } // 'WFL1'
public override bool IsHierarchic { get { return true; } }
public override bool CanWrite { get { return false; } }
public ArcOpener ()
{
Extensions = new string[] { "arc" };
}
public override ArcFile TryOpen (ArcView file)
{
var reader = new IndexReader();
var dir = reader.ReadIndex (file);
if (null == dir || 0 == dir.Count)
return null;
return new ArcFile (file, this, dir);
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var packed_entry = entry as PackedEntry;
if (null == packed_entry || !packed_entry.IsPacked)
return arc.File.CreateStream (entry.Offset, entry.Size);
if (0 == packed_entry.UnpackedSize)
packed_entry.UnpackedSize = arc.File.View.ReadUInt32 (entry.Offset-4);
using (var input = arc.File.CreateStream (entry.Offset, entry.Size))
using (var reader = new LzReader (input, entry.Size, packed_entry.UnpackedSize))
{
reader.Unpack();
return new BinMemoryStream (reader.Data, entry.Name);
}
}
}
internal class IndexReader
{
byte[] m_name_buf = new byte[0x20];
List<Entry> m_dir = new List<Entry>();
public List<Entry> ReadIndex (ArcView file)
{
string ari_name = Path.ChangeExtension (file.Name, "ari");
List<Entry> dir = null;
if (file.Name != ari_name && VFS.FileExists (ari_name))
dir = ReadAriIndex (file, ari_name);
if (null == dir || 0 == dir.Count)
dir = BuildIndex (file);
return dir;
}
List<Entry> ReadAriIndex (ArcView file, string ari_name)
{
long arc_offset = 4;
using (var ari = VFS.OpenView (ari_name))
{
long index_offset = 0;
while (index_offset+4 < ari.MaxOffset)
{
int name_len = ari.View.ReadInt32 (index_offset);
var name = ReadName (ari, index_offset+4, name_len);
if (null == name)
return null;
var entry = new AriEntry { Name = name };
index_offset += name_len + 4;
entry.Mode = ari.View.ReadUInt16 (index_offset);
entry.Size = ari.View.ReadUInt32 (index_offset+2);
entry.UnpackedSize = 0;
SetType (entry);
index_offset += 6;
arc_offset += name_len + 10;
if (1 == entry.Mode)
{
entry.IsPacked = true;
arc_offset += 4;
}
entry.Offset = arc_offset;
if (!entry.CheckPlacement (file.MaxOffset))
return null;
arc_offset += entry.Size;
m_dir.Add (entry);
}
}
return m_dir;
}
List<Entry> BuildIndex (ArcView file)
{
long arc_offset = 4;
while (arc_offset+4 < file.MaxOffset)
{
int name_len = file.View.ReadInt32 (arc_offset);
var name = ReadName (file, arc_offset+4, name_len);
if (null == name)
return null;
var entry = new AriEntry { Name = name };
arc_offset += name_len + 4;
entry.Mode = file.View.ReadUInt16 (arc_offset);
entry.Size = file.View.ReadUInt32 (arc_offset+2);
SetType (entry);
arc_offset += 6;
if (1 == entry.Mode)
{
entry.IsPacked = true;
entry.UnpackedSize = file.View.ReadUInt32 (arc_offset);
arc_offset += 4;
}
entry.Offset = arc_offset;
if (!entry.CheckPlacement (file.MaxOffset))
return null;
arc_offset += entry.Size;
m_dir.Add (entry);
}
return m_dir;
}
void SetType (AriEntry entry)
{
if (2 == entry.Mode)
entry.Type = "audio";
else if (1 == entry.Mode)
entry.Type = "image";
else
entry.Type = FormatCatalog.Instance.GetTypeFromName (entry.Name);
}
string ReadName (ArcView file, long offset, int name_len)
{
if (name_len <= 0 || offset+name_len+6 > file.MaxOffset || name_len > 0x100)
return null;
if (name_len > m_name_buf.Length)
m_name_buf = new byte[name_len];
file.View.Read (offset, m_name_buf, 0, (uint)name_len);
return DecryptName (m_name_buf, name_len).TrimStart ('\\');
}
string DecryptName (byte[] name_buf, int name_len)
{
for (int i = 0; i < name_len; ++i)
name_buf[i] ^= 0xff;
return Encodings.cp932.GetString (name_buf, 0, name_len);
}
}
internal sealed class LzReader : IDisposable, IDataUnpacker
{
MsbBitStream m_input;
byte[] m_output;
public byte[] Data { get { return m_output; } }
public LzReader (Stream input, uint packed_size, uint unpacked_size)
{
m_input = new MsbBitStream (input, true);
m_output = new byte[unpacked_size];
}
public void Unpack ()
{
int dst = 0;
int frame_pos = 1;
byte[] frame = new byte[4096];
int frame_mask = frame.Length - 1;
while (dst < m_output.Length)
{
int bit = m_input.GetNextBit();
if (-1 == bit)
break;
if (0 != bit)
{
int data = m_input.GetBits (8);
m_output[dst++] = (byte)data;
frame[frame_pos++] = (byte)data;
frame_pos &= frame_mask;
}
else
{
int win_offset = m_input.GetBits (12);
if (-1 == win_offset || 0 == win_offset)
break;
int count = m_input.GetBits(4) + 2;
for (int i = 0; i < count; i++)
{
byte data = frame[(win_offset + i) & frame_mask];
m_output[dst++] = data;
frame[frame_pos++] = data;
frame_pos &= frame_mask;
}
}
}
}
#region IDisposable Members
bool _disposed = false;
public void Dispose ()
{
if (!_disposed)
{
m_input.Dispose();
_disposed = true;
}
}
#endregion
}
}
| |
/*
* 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 System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
using Mono.Data.Sqlite;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.SQLite
{
public class SQLiteEstateStore : IEstateDataStore
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private SqliteConnection m_connection;
private string m_connectionString;
private FieldInfo[] m_Fields;
private Dictionary<string, FieldInfo> m_FieldMap =
new Dictionary<string, FieldInfo>();
public void Initialise(string connectionString)
{
m_connectionString = connectionString;
m_log.Info("[ESTATE DB]: Sqlite - connecting: "+m_connectionString);
m_connection = new SqliteConnection(m_connectionString);
m_connection.Open();
Assembly assem = GetType().Assembly;
Migration m = new Migration(m_connection, assem, "EstateStore");
m.Update();
//m_connection.Close();
// m_connection.Open();
Type t = typeof(EstateSettings);
m_Fields = t.GetFields(BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
foreach (FieldInfo f in m_Fields)
if (f.Name.Substring(0, 2) == "m_")
m_FieldMap[f.Name.Substring(2)] = f;
}
private string[] FieldList
{
get { return new List<string>(m_FieldMap.Keys).ToArray(); }
}
public EstateSettings LoadEstateSettings(UUID regionID, bool create)
{
string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = :RegionID";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":RegionID", regionID.ToString());
return DoLoad(cmd, regionID, create);
}
private EstateSettings DoLoad(SqliteCommand cmd, UUID regionID, bool create)
{
EstateSettings es = new EstateSettings();
es.OnSave += StoreEstateSettings;
IDataReader r = cmd.ExecuteReader();
if (r.Read())
{
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
int v = Convert.ToInt32(r[name]);
if (v != 0)
m_FieldMap[name].SetValue(es, true);
else
m_FieldMap[name].SetValue(es, false);
}
else if (m_FieldMap[name].GetValue(es) is UUID)
{
UUID uuid = UUID.Zero;
UUID.TryParse(r[name].ToString(), out uuid);
m_FieldMap[name].SetValue(es, uuid);
}
else
{
m_FieldMap[name].SetValue(es, Convert.ChangeType(r[name], m_FieldMap[name].FieldType));
}
}
r.Close();
}
else if (create)
{
r.Close();
List<string> names = new List<string>(FieldList);
names.Remove("EstateID");
string sql = "insert into estate_settings ("+String.Join(",", names.ToArray())+") values ( :"+String.Join(", :", names.ToArray())+")";
cmd.CommandText = sql;
cmd.Parameters.Clear();
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
if ((bool)m_FieldMap[name].GetValue(es))
cmd.Parameters.AddWithValue(":"+name, "1");
else
cmd.Parameters.AddWithValue(":"+name, "0");
}
else
{
cmd.Parameters.AddWithValue(":"+name, m_FieldMap[name].GetValue(es).ToString());
}
}
cmd.ExecuteNonQuery();
cmd.CommandText = "select LAST_INSERT_ROWID() as id";
cmd.Parameters.Clear();
r = cmd.ExecuteReader();
r.Read();
es.EstateID = Convert.ToUInt32(r["id"]);
r.Close();
cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)";
cmd.Parameters.AddWithValue(":RegionID", regionID.ToString());
cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString());
// This will throw on dupe key
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
es.Save();
}
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
return es;
}
public void StoreEstateSettings(EstateSettings es)
{
List<string> fields = new List<string>(FieldList);
fields.Remove("EstateID");
List<string> terms = new List<string>();
foreach (string f in fields)
terms.Add(f+" = :"+f);
string sql = "update estate_settings set "+String.Join(", ", terms.ToArray())+" where EstateID = :EstateID";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
if ((bool)m_FieldMap[name].GetValue(es))
cmd.Parameters.AddWithValue(":"+name, "1");
else
cmd.Parameters.AddWithValue(":"+name, "0");
}
else
{
cmd.Parameters.AddWithValue(":"+name, m_FieldMap[name].GetValue(es).ToString());
}
}
cmd.ExecuteNonQuery();
SaveBanList(es);
SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers);
SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess);
SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups);
}
private void LoadBanList(EstateSettings es)
{
es.ClearBans();
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "select bannedUUID from estateban where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", es.EstateID);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
EstateBan eb = new EstateBan();
UUID uuid = new UUID();
UUID.TryParse(r["bannedUUID"].ToString(), out uuid);
eb.BannedUserID = uuid;
eb.BannedHostAddress = "0.0.0.0";
eb.BannedHostIPMask = "0.0.0.0";
es.AddBan(eb);
}
r.Close();
}
private void SaveBanList(EstateSettings es)
{
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "delete from estateban where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( :EstateID, :bannedUUID, '', '', '' )";
foreach (EstateBan b in es.EstateBans)
{
cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString());
cmd.Parameters.AddWithValue(":bannedUUID", b.BannedUserID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
void SaveUUIDList(uint EstateID, string table, UUID[] data)
{
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "delete from "+table+" where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", EstateID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into "+table+" (EstateID, uuid) values ( :EstateID, :uuid )";
foreach (UUID uuid in data)
{
cmd.Parameters.AddWithValue(":EstateID", EstateID.ToString());
cmd.Parameters.AddWithValue(":uuid", uuid.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
UUID[] LoadUUIDList(uint EstateID, string table)
{
List<UUID> uuids = new List<UUID>();
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "select uuid from "+table+" where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", EstateID);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
// EstateBan eb = new EstateBan();
UUID uuid = new UUID();
UUID.TryParse(r["uuid"].ToString(), out uuid);
uuids.Add(uuid);
}
r.Close();
return uuids.ToArray();
}
public EstateSettings LoadEstateSettings(int estateID)
{
string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_settings where estate_settings.EstateID = :EstateID";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":EstateID", estateID.ToString());
return DoLoad(cmd, UUID.Zero, false);
}
public List<int> GetEstates(string search)
{
List<int> result = new List<int>();
string sql = "select EstateID from estate_settings where estate_settings.EstateName = :EstateName";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":EstateName", search);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
result.Add(Convert.ToInt32(r["EstateID"]));
}
r.Close();
return result;
}
public bool LinkRegion(UUID regionID, int estateID)
{
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)";
cmd.Parameters.AddWithValue(":RegionID", regionID.ToString());
cmd.Parameters.AddWithValue(":EstateID", estateID.ToString());
if (cmd.ExecuteNonQuery() == 0)
return false;
return true;
}
public List<UUID> GetRegions(int estateID)
{
return new List<UUID>();
}
public bool DeleteEstate(int estateID)
{
return false;
}
}
}
| |
namespace EIDSS.Reports.Document.Lim.Case
{
partial class TestValidationReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TestValidationReport));
this.Detail = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable2 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellRule = new DevExpress.XtraReports.UI.XRTableCell();
this.lblRuleOut = new DevExpress.XtraReports.UI.XRLabel();
this.lblRuleIn = new DevExpress.XtraReports.UI.XRLabel();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.PageHeader = new DevExpress.XtraReports.UI.PageHeaderBand();
this.xrLabel3 = new DevExpress.XtraReports.UI.XRLabel();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.PageFooter = new DevExpress.XtraReports.UI.PageFooterBand();
this.testValidationDataSet1 = new EIDSS.Reports.Document.Lim.Case.TestValidationDataSet();
this.sp_rep_LIM_CaseTestsValidationTableAdapter1 = new EIDSS.Reports.Document.Lim.Case.TestValidationDataSetTableAdapters.sp_rep_LIM_CaseTestsValidationTableAdapter();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.testValidationDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// Detail
//
this.Detail.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable2});
resources.ApplyResources(this.Detail, "Detail");
this.Detail.Name = "Detail";
this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.Detail.StylePriority.UseBorders = false;
this.Detail.StylePriority.UseTextAlignment = false;
//
// xrTable2
//
resources.ApplyResources(this.xrTable2, "xrTable2");
this.xrTable2.Name = "xrTable2";
this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow2});
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell12,
this.xrTableCell13,
this.xrTableCell14,
this.cellRule,
this.xrTableCell16,
this.xrTableCell17,
this.xrTableCell18,
this.xrTableCell19,
this.xrTableCell20,
this.xrTableCell21,
this.xrTableCell22});
this.xrTableRow2.Name = "xrTableRow2";
this.xrTableRow2.Weight = 1;
//
// xrTableCell12
//
this.xrTableCell12.Angle = 90F;
this.xrTableCell12.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTestsValidation.Diagnosis")});
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.Weight = 0.29030710172744723;
//
// xrTableCell13
//
this.xrTableCell13.Angle = 90F;
this.xrTableCell13.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTestsValidation.TestName")});
this.xrTableCell13.Name = "xrTableCell13";
this.xrTableCell13.Weight = 0.29030710172744723;
//
// xrTableCell14
//
this.xrTableCell14.Angle = 90F;
this.xrTableCell14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTestsValidation.TestType")});
this.xrTableCell14.Name = "xrTableCell14";
this.xrTableCell14.Weight = 0.28982725527831088;
//
// cellRule
//
this.cellRule.Angle = 90F;
this.cellRule.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.lblRuleOut,
this.lblRuleIn});
this.cellRule.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTestsValidation.intRuleStatus")});
this.cellRule.Name = "cellRule";
resources.ApplyResources(this.cellRule, "cellRule");
this.cellRule.Weight = 0.29030710172744723;
this.cellRule.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.cellRule_BeforePrint);
//
// lblRuleOut
//
resources.ApplyResources(this.lblRuleOut, "lblRuleOut");
this.lblRuleOut.Name = "lblRuleOut";
this.lblRuleOut.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
//
// lblRuleIn
//
resources.ApplyResources(this.lblRuleIn, "lblRuleIn");
this.lblRuleIn.Name = "lblRuleIn";
this.lblRuleIn.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 96F);
//
// xrTableCell16
//
this.xrTableCell16.Angle = 90F;
this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTestsValidation.strRuleComment")});
this.xrTableCell16.Name = "xrTableCell16";
this.xrTableCell16.Weight = 0.29030710172744723;
//
// xrTableCell17
//
this.xrTableCell17.Angle = 90F;
this.xrTableCell17.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTestsValidation.interpretedDate", "{0:dd/MM/yyyy}")});
this.xrTableCell17.Name = "xrTableCell17";
this.xrTableCell17.Weight = 0.29030710172744723;
//
// xrTableCell18
//
this.xrTableCell18.Angle = 90F;
this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTestsValidation.InterpretedBy")});
this.xrTableCell18.Name = "xrTableCell18";
this.xrTableCell18.Weight = 0.29030710172744723;
//
// xrTableCell19
//
this.xrTableCell19.Angle = 90F;
this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTestsValidation.intValidateStatus")});
this.xrTableCell19.Name = "xrTableCell19";
this.xrTableCell19.Weight = 0.28958733205374282;
//
// xrTableCell20
//
this.xrTableCell20.Angle = 90F;
this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTestsValidation.strValidateComment")});
this.xrTableCell20.Name = "xrTableCell20";
this.xrTableCell20.Weight = 0.28958733205374287;
//
// xrTableCell21
//
this.xrTableCell21.Angle = 90F;
this.xrTableCell21.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTestsValidation.validatedDate", "{0:dd/MM/yyyy}")});
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.Weight = 0.28958733205374282;
//
// xrTableCell22
//
this.xrTableCell22.Angle = 90F;
this.xrTableCell22.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTestsValidation.ValidatedBy")});
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.Weight = 0.29822456813819581;
//
// PageHeader
//
this.PageHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel3,
this.xrTable1});
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.Name = "PageHeader";
this.PageHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.PageHeader.StylePriority.UseBorders = false;
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UseTextAlignment = false;
//
// xrLabel3
//
this.xrLabel3.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrLabel3, "xrLabel3");
this.xrLabel3.Name = "xrLabel3";
this.xrLabel3.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel3.StylePriority.UseBorders = false;
this.xrLabel3.StylePriority.UseFont = false;
this.xrLabel3.StylePriority.UseTextAlignment = false;
//
// xrTable1
//
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1});
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell11,
this.xrTableCell10,
this.xrTableCell1,
this.xrTableCell9,
this.xrTableCell7,
this.xrTableCell8,
this.xrTableCell2,
this.xrTableCell5,
this.xrTableCell4,
this.xrTableCell6,
this.xrTableCell3});
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.Weight = 1;
//
// xrTableCell11
//
this.xrTableCell11.Angle = 90F;
this.xrTableCell11.Name = "xrTableCell11";
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
this.xrTableCell11.Weight = 0.29030710172744723;
//
// xrTableCell10
//
this.xrTableCell10.Angle = 90F;
this.xrTableCell10.Name = "xrTableCell10";
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
this.xrTableCell10.Weight = 0.29030710172744723;
//
// xrTableCell1
//
this.xrTableCell1.Angle = 90F;
this.xrTableCell1.Name = "xrTableCell1";
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Weight = 0.28982725527831088;
//
// xrTableCell9
//
this.xrTableCell9.Angle = 90F;
this.xrTableCell9.Name = "xrTableCell9";
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
this.xrTableCell9.Weight = 0.29030710172744723;
//
// xrTableCell7
//
this.xrTableCell7.Angle = 90F;
this.xrTableCell7.Name = "xrTableCell7";
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Weight = 0.29030710172744723;
//
// xrTableCell8
//
this.xrTableCell8.Angle = 90F;
this.xrTableCell8.Name = "xrTableCell8";
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Weight = 0.29030710172744723;
//
// xrTableCell2
//
this.xrTableCell2.Angle = 90F;
this.xrTableCell2.Name = "xrTableCell2";
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Weight = 0.29030710172744723;
//
// xrTableCell5
//
this.xrTableCell5.Angle = 90F;
this.xrTableCell5.Name = "xrTableCell5";
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Weight = 0.28958733205374282;
//
// xrTableCell4
//
this.xrTableCell4.Angle = 90F;
this.xrTableCell4.Name = "xrTableCell4";
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Weight = 0.28958733205374287;
//
// xrTableCell6
//
this.xrTableCell6.Angle = 90F;
this.xrTableCell6.Name = "xrTableCell6";
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Weight = 0.28958733205374282;
//
// xrTableCell3
//
this.xrTableCell3.Angle = 90F;
this.xrTableCell3.Name = "xrTableCell3";
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Weight = 0.29822456813819581;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.Name = "PageFooter";
this.PageFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
//
// testValidationDataSet1
//
this.testValidationDataSet1.DataSetName = "TestValidationDataSet";
this.testValidationDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// sp_rep_LIM_CaseTestsValidationTableAdapter1
//
this.sp_rep_LIM_CaseTestsValidationTableAdapter1.ClearBeforeFill = true;
//
// TestValidationReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter});
this.DataAdapter = this.sp_rep_LIM_CaseTestsValidationTableAdapter1;
this.DataMember = "spRepLimCaseTestsValidation";
this.DataSource = this.testValidationDataSet1;
resources.ApplyResources(this, "$this");
this.Landscape = true;
this.PageHeight = 827;
this.PageWidth = 1169;
this.PaperKind = System.Drawing.Printing.PaperKind.A4;
this.Version = "10.1";
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.testValidationDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailBand Detail;
private DevExpress.XtraReports.UI.PageHeaderBand PageHeader;
private DevExpress.XtraReports.UI.PageFooterBand PageFooter;
private TestValidationDataSet testValidationDataSet1;
private EIDSS.Reports.Document.Lim.Case.TestValidationDataSetTableAdapters.sp_rep_LIM_CaseTestsValidationTableAdapter sp_rep_LIM_CaseTestsValidationTableAdapter1;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTable xrTable2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell cellRule;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.XRLabel xrLabel3;
private DevExpress.XtraReports.UI.XRLabel lblRuleIn;
private DevExpress.XtraReports.UI.XRLabel lblRuleOut;
}
}
| |
using System;
using System.Linq;
using System.Web;
using System.Web.Compilation;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.SessionState;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Web.Models;
using Umbraco.Web.Routing;
using System.Collections.Generic;
using Umbraco.Web.Features;
namespace Umbraco.Web.Mvc
{
public class RenderRouteHandler : IRouteHandler
{
// Define reserved dictionary keys for controller, action and area specified in route additional values data
private static class ReservedAdditionalKeys
{
internal const string Controller = "c";
internal const string Action = "a";
internal const string Area = "ar";
}
public RenderRouteHandler(IControllerFactory controllerFactory)
{
if (controllerFactory == null) throw new ArgumentNullException("controllerFactory");
_controllerFactory = controllerFactory;
}
/// <summary>
/// Contructor generally used for unit testing
/// </summary>
/// <param name="controllerFactory"></param>
/// <param name="umbracoContext"></param>
internal RenderRouteHandler(IControllerFactory controllerFactory, UmbracoContext umbracoContext)
{
if (controllerFactory == null) throw new ArgumentNullException("controllerFactory");
if (umbracoContext == null) throw new ArgumentNullException("umbracoContext");
_controllerFactory = controllerFactory;
_umbracoContext = umbracoContext;
}
private readonly IControllerFactory _controllerFactory;
private readonly UmbracoContext _umbracoContext;
/// <summary>
/// Returns the current UmbracoContext
/// </summary>
public UmbracoContext UmbracoContext
{
get { return _umbracoContext ?? UmbracoContext.Current; }
}
#region IRouteHandler Members
/// <summary>
/// Assigns the correct controller based on the Umbraco request and returns a standard MvcHandler to prcess the response,
/// this also stores the render model into the data tokens for the current RouteData.
/// </summary>
/// <param name="requestContext"></param>
/// <returns></returns>
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
if (UmbracoContext == null)
{
throw new NullReferenceException("There is no current UmbracoContext, it must be initialized before the RenderRouteHandler executes");
}
var docRequest = UmbracoContext.PublishedContentRequest;
if (docRequest == null)
{
throw new NullReferenceException("There is no current PublishedContentRequest, it must be initialized before the RenderRouteHandler executes");
}
SetupRouteDataForRequest(
new RenderModel(docRequest.PublishedContent, docRequest.Culture),
requestContext,
docRequest);
return GetHandlerForRoute(requestContext, docRequest);
}
#endregion
/// <summary>
/// Ensures that all of the correct DataTokens are added to the route values which are all required for rendering front-end umbraco views
/// </summary>
/// <param name="renderModel"></param>
/// <param name="requestContext"></param>
/// <param name="docRequest"></param>
internal void SetupRouteDataForRequest(RenderModel renderModel, RequestContext requestContext, PublishedContentRequest docRequest)
{
//put essential data into the data tokens, the 'umbraco' key is required to be there for the view engine
requestContext.RouteData.DataTokens.Add(Core.Constants.Web.UmbracoDataToken, renderModel); //required for the RenderModelBinder and view engine
requestContext.RouteData.DataTokens.Add(Core.Constants.Web.PublishedDocumentRequestDataToken, docRequest); //required for RenderMvcController
requestContext.RouteData.DataTokens.Add(Core.Constants.Web.UmbracoContextDataToken, UmbracoContext); //required for UmbracoTemplatePage
}
private void UpdateRouteDataForRequest(RenderModel renderModel, RequestContext requestContext)
{
if (renderModel == null) throw new ArgumentNullException("renderModel");
if (requestContext == null) throw new ArgumentNullException("requestContext");
requestContext.RouteData.DataTokens[Core.Constants.Web.UmbracoDataToken] = renderModel;
// the rest should not change -- it's only the published content that has changed
}
/// <summary>
/// Checks the request and query strings to see if it matches the definition of having a Surface controller
/// posted/get value, if so, then we return a PostedDataProxyInfo object with the correct information.
/// </summary>
/// <param name="requestContext"></param>
/// <returns></returns>
internal static PostedDataProxyInfo GetFormInfo(RequestContext requestContext)
{
if (requestContext == null) throw new ArgumentNullException("requestContext");
//if it is a POST/GET then a value must be in the request
if (requestContext.HttpContext.Request.QueryString["ufprt"].IsNullOrWhiteSpace()
&& requestContext.HttpContext.Request.Form["ufprt"].IsNullOrWhiteSpace())
{
return null;
}
string encodedVal;
switch (requestContext.HttpContext.Request.RequestType)
{
case "POST":
//get the value from the request.
//this field will contain an encrypted version of the surface route vals.
encodedVal = requestContext.HttpContext.Request.Form["ufprt"];
break;
case "GET":
//this field will contain an encrypted version of the surface route vals.
encodedVal = requestContext.HttpContext.Request.QueryString["ufprt"];
break;
default:
return null;
}
string decryptedString;
try
{
decryptedString = encodedVal.DecryptWithMachineKey();
}
catch (FormatException)
{
LogHelper.Warn<RenderRouteHandler>("A value was detected in the ufprt parameter but Umbraco could not decrypt the string");
return null;
}
var parsedQueryString = HttpUtility.ParseQueryString(decryptedString);
var decodedParts = new Dictionary<string, string>();
foreach (var key in parsedQueryString.AllKeys)
{
decodedParts[key] = parsedQueryString[key];
}
//validate all required keys exist
//the controller
if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Controller))
return null;
//the action
if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Action))
return null;
//the area
if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Area))
return null;
foreach (var item in decodedParts.Where(x => new[] {
ReservedAdditionalKeys.Controller,
ReservedAdditionalKeys.Action,
ReservedAdditionalKeys.Area }.Contains(x.Key) == false))
{
// Populate route with additional values which aren't reserved values so they eventually to action parameters
requestContext.RouteData.Values[item.Key] = item.Value;
}
//return the proxy info without the surface id... could be a local controller.
return new PostedDataProxyInfo
{
ControllerName = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Controller).Value),
ActionName = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Action).Value),
Area = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Area).Value),
};
}
/// <summary>
/// Handles a posted form to an Umbraco Url and ensures the correct controller is routed to and that
/// the right DataTokens are set.
/// </summary>
/// <param name="requestContext"></param>
/// <param name="postedInfo"></param>
internal static IHttpHandler HandlePostedValues(RequestContext requestContext, PostedDataProxyInfo postedInfo)
{
if (requestContext == null) throw new ArgumentNullException("requestContext");
if (postedInfo == null) throw new ArgumentNullException("postedInfo");
//set the standard route values/tokens
requestContext.RouteData.Values["controller"] = postedInfo.ControllerName;
requestContext.RouteData.Values["action"] = postedInfo.ActionName;
IHttpHandler handler;
//get the route from the defined routes
using (RouteTable.Routes.GetReadLock())
{
Route surfaceRoute;
if (postedInfo.Area.IsNullOrWhiteSpace())
{
//find the controller in the route table without an area
var surfaceRoutes = RouteTable.Routes.OfType<Route>()
.Where(x => x.Defaults != null &&
x.Defaults.ContainsKey("controller") &&
x.Defaults["controller"].ToString().InvariantEquals(postedInfo.ControllerName) &&
x.DataTokens.ContainsKey("area") == false).ToList();
// If more than one route is found, find one with a matching action
if (surfaceRoutes.Count() > 1)
{
surfaceRoute = surfaceRoutes.FirstOrDefault(x =>
x.Defaults["action"] != null &&
x.Defaults["action"].ToString().InvariantEquals(postedInfo.ActionName));
}
else
{
surfaceRoute = surfaceRoutes.SingleOrDefault();
}
}
else
{
//find the controller in the route table with the specified area
surfaceRoute = RouteTable.Routes.OfType<Route>()
.SingleOrDefault(x => x.Defaults != null &&
x.Defaults.ContainsKey("controller") &&
x.Defaults["controller"].ToString().InvariantEquals(postedInfo.ControllerName) &&
x.DataTokens.ContainsKey("area") &&
x.DataTokens["area"].ToString().InvariantEquals(postedInfo.Area));
}
if (surfaceRoute == null)
throw new InvalidOperationException("Could not find a Surface controller route in the RouteTable for controller name " + postedInfo.ControllerName);
//set the area if one is there.
if (surfaceRoute.DataTokens.ContainsKey("area"))
{
requestContext.RouteData.DataTokens["area"] = surfaceRoute.DataTokens["area"];
}
//set the 'Namespaces' token so the controller factory knows where to look to construct it
if (surfaceRoute.DataTokens.ContainsKey("Namespaces"))
{
requestContext.RouteData.DataTokens["Namespaces"] = surfaceRoute.DataTokens["Namespaces"];
}
handler = surfaceRoute.RouteHandler.GetHttpHandler(requestContext);
}
return handler;
}
/// <summary>
/// Returns a RouteDefinition object based on the current renderModel
/// </summary>
/// <param name="requestContext"></param>
/// <param name="publishedContentRequest"></param>
/// <returns></returns>
internal virtual RouteDefinition GetUmbracoRouteDefinition(RequestContext requestContext, PublishedContentRequest publishedContentRequest)
{
if (requestContext == null) throw new ArgumentNullException("requestContext");
if (publishedContentRequest == null) throw new ArgumentNullException("publishedContentRequest");
var defaultControllerType = DefaultRenderMvcControllerResolver.Current.GetDefaultControllerType();
var defaultControllerName = ControllerExtensions.GetControllerName(defaultControllerType);
//creates the default route definition which maps to the 'UmbracoController' controller
var def = new RouteDefinition
{
ControllerName = defaultControllerName,
ControllerType = defaultControllerType,
PublishedContentRequest = publishedContentRequest,
ActionName = ((Route)requestContext.RouteData.Route).Defaults["action"].ToString(),
HasHijackedRoute = false
};
//check that a template is defined), if it doesn't and there is a hijacked route it will just route
// to the index Action
if (publishedContentRequest.HasTemplate)
{
//the template Alias should always be already saved with a safe name.
//if there are hyphens in the name and there is a hijacked route, then the Action will need to be attributed
// with the action name attribute.
var templateName = publishedContentRequest.TemplateAlias.Split('.')[0].ToSafeAlias();
def.ActionName = templateName;
}
//check if there's a custom controller assigned, base on the document type alias.
var controllerType = _controllerFactory.GetControllerTypeInternal(requestContext, publishedContentRequest.PublishedContent.DocumentTypeAlias);
//check if that controller exists
if (controllerType != null)
{
//ensure the controller is of type IRenderMvcController and ControllerBase
if (TypeHelper.IsTypeAssignableFrom<IRenderController>(controllerType) &&
TypeHelper.IsTypeAssignableFrom<ControllerBase>(controllerType))
{
//set the controller and name to the custom one
def.ControllerType = controllerType;
def.ControllerName = ControllerExtensions.GetControllerName(controllerType);
if (def.ControllerName != defaultControllerName)
{
def.HasHijackedRoute = true;
}
}
else
{
LogHelper.Warn<RenderRouteHandler>(
"The current Document Type {0} matches a locally declared controller of type {1}. Custom Controllers for Umbraco routing must implement '{2}' and inherit from '{3}'.",
() => publishedContentRequest.PublishedContent.DocumentTypeAlias,
() => controllerType.FullName,
() => typeof(IRenderController).FullName,
() => typeof(ControllerBase).FullName);
//we cannot route to this custom controller since it is not of the correct type so we'll continue with the defaults
// that have already been set above.
}
}
//store the route definition
requestContext.RouteData.DataTokens[Core.Constants.Web.UmbracoRouteDefinitionDataToken] = def;
return def;
}
internal IHttpHandler GetHandlerOnMissingTemplate(PublishedContentRequest pcr)
{
if (pcr == null) throw new ArgumentNullException("pcr");
// missing template, so we're in a 404 here
// so the content, if any, is a custom 404 page of some sort
if (pcr.HasPublishedContent == false)
// means the builder could not find a proper document to handle 404
return new PublishedContentNotFoundHandler();
if (pcr.HasTemplate == false)
// means the engine could find a proper document, but the document has no template
// at that point there isn't much we can do and there is no point returning
// to Mvc since Mvc can't do much
return new PublishedContentNotFoundHandler("In addition, no template exists to render the custom 404.");
// so we have a template, so we should have a rendering engine
if (pcr.RenderingEngine == RenderingEngine.WebForms) // back to webforms ?
return GetWebFormsHandler();
if (pcr.RenderingEngine != RenderingEngine.Mvc) // else ?
return new PublishedContentNotFoundHandler("In addition, no rendering engine exists to render the custom 404.");
return null;
}
/// <summary>
/// this will determine the controller and set the values in the route data
/// </summary>
/// <param name="requestContext"></param>
/// <param name="publishedContentRequest"></param>
internal IHttpHandler GetHandlerForRoute(RequestContext requestContext, PublishedContentRequest publishedContentRequest)
{
if (requestContext == null) throw new ArgumentNullException("requestContext");
if (publishedContentRequest == null) throw new ArgumentNullException("publishedContentRequest");
var routeDef = GetUmbracoRouteDefinition(requestContext, publishedContentRequest);
//Need to check for a special case if there is form data being posted back to an Umbraco URL
var postedInfo = GetFormInfo(requestContext);
if (postedInfo != null)
{
return HandlePostedValues(requestContext, postedInfo);
}
//Now we can check if we are supposed to render WebForms when the route has not been hijacked
if (publishedContentRequest.RenderingEngine == RenderingEngine.WebForms
&& publishedContentRequest.HasTemplate
&& routeDef.HasHijackedRoute == false)
{
return GetWebFormsHandler();
}
//Here we need to check if there is no hijacked route and no template assigned,
//if this is the case we want to return a blank page, but we'll leave that up to the NoTemplateHandler.
//We also check if templates have been disabled since if they are then we're allowed to render even though there's no template,
//for example for json rendering in headless.
if ((publishedContentRequest.HasTemplate == false && FeaturesResolver.Current.Features.Disabled.DisableTemplates == false)
&& routeDef.HasHijackedRoute == false)
{
publishedContentRequest.UpdateOnMissingTemplate(); // will go 404
// HandleHttpResponseStatus returns a value indicating that the request should
// not be processed any further, eg because it has been redirect. then, exit.
if (UmbracoModule.HandleHttpResponseStatus(requestContext.HttpContext, publishedContentRequest))
return null;
var handler = GetHandlerOnMissingTemplate(publishedContentRequest);
// if it's not null it can be either the PublishedContentNotFoundHandler (no document was
// found to handle 404, or document with no template was found) or the WebForms handler
// (a document was found and its template is WebForms)
// if it's null it means that a document was found and its template is Mvc
// if we have a handler, return now
if (handler != null)
return handler;
// else we are running Mvc
// update the route data - because the PublishedContent has changed
UpdateRouteDataForRequest(
new RenderModel(publishedContentRequest.PublishedContent, publishedContentRequest.Culture),
requestContext);
// update the route definition
routeDef = GetUmbracoRouteDefinition(requestContext, publishedContentRequest);
}
//no post values, just route to the controller/action requried (local)
requestContext.RouteData.Values["controller"] = routeDef.ControllerName;
if (string.IsNullOrWhiteSpace(routeDef.ActionName) == false)
{
requestContext.RouteData.Values["action"] = routeDef.ActionName;
}
// Set the session state requirements
requestContext.HttpContext.SetSessionStateBehavior(GetSessionStateBehavior(requestContext, routeDef.ControllerName));
// reset the friendly path so in the controllers and anything occuring after this point in time,
//the URL is reset back to the original request.
requestContext.HttpContext.RewritePath(UmbracoContext.OriginalRequestUrl.PathAndQuery);
return new UmbracoMvcHandler(requestContext);
}
/// <summary>
/// Returns the handler for webforms requests
/// </summary>
/// <returns></returns>
internal static IHttpHandler GetWebFormsHandler()
{
return (global::umbraco.UmbracoDefault)BuildManager.CreateInstanceFromVirtualPath("~/default.aspx", typeof(global::umbraco.UmbracoDefault));
}
private SessionStateBehavior GetSessionStateBehavior(RequestContext requestContext, string controllerName)
{
return _controllerFactory.GetControllerSessionBehavior(requestContext, controllerName);
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
namespace System.Security.Principal
{
public class IdentityReferenceCollection : ICollection<IdentityReference>
{
#region Private members
//
// Container enumerated by this collection
//
private readonly List<IdentityReference> _Identities;
#endregion
#region Constructors
//
// Creates an empty collection of default size
//
public IdentityReferenceCollection()
: this(0)
{
}
//
// Creates an empty collection of given initial size
//
public IdentityReferenceCollection(int capacity)
{
_Identities = new List<IdentityReference>(capacity);
}
#endregion
#region ICollection<IdentityReference> implementation
public void CopyTo(IdentityReference[] array, int offset)
{
_Identities.CopyTo(0, array, offset, Count);
}
public int Count
{
get
{
return _Identities.Count;
}
}
bool ICollection<IdentityReference>.IsReadOnly
{
get
{
return false;
}
}
public void Add(IdentityReference identity)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
_Identities.Add(identity);
}
public bool Remove(IdentityReference identity)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
if (Contains(identity))
{
return _Identities.Remove(identity);
}
return false;
}
public void Clear()
{
_Identities.Clear();
}
public bool Contains(IdentityReference identity)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
return _Identities.Contains(identity);
}
#endregion
#region IEnumerable<IdentityReference> implementation
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<IdentityReference> GetEnumerator()
{
return new IdentityReferenceEnumerator(this);
}
#endregion
#region Public methods
public IdentityReference this[int index]
{
get
{
return _Identities[index];
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_Identities[index] = value;
}
}
internal List<IdentityReference> Identities
{
get
{
return _Identities;
}
}
public IdentityReferenceCollection Translate(Type targetType)
{
return Translate(targetType, false);
}
public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess)
{
if (targetType == null)
{
throw new ArgumentNullException(nameof(targetType));
}
//
// Target type must be a subclass of IdentityReference
//
if (!targetType.GetTypeInfo().IsSubclassOf(typeof(IdentityReference)))
{
throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, nameof(targetType));
}
//
// if the source collection is empty, just return an empty collection
//
if (Identities.Count == 0)
{
return new IdentityReferenceCollection();
}
int SourceSidsCount = 0;
int SourceNTAccountsCount = 0;
//
// First, see how many of each of the source types we have.
// The cases where source type == target type require no conversion.
//
for (int i = 0; i < Identities.Count; i++)
{
Type type = Identities[i].GetType();
if (type == targetType)
{
continue;
}
else if (type == typeof(SecurityIdentifier))
{
SourceSidsCount += 1;
}
else if (type == typeof(NTAccount))
{
SourceNTAccountsCount += 1;
}
else
{
//
// Rare case that we have defined a type of identity reference and not included it in the code logic above.
// To avoid this we do not allow IdentityReference to be subclassed outside of the BCL.
//
Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
throw new NotSupportedException();
}
}
bool Homogeneous = false;
IdentityReferenceCollection SourceSids = null;
IdentityReferenceCollection SourceNTAccounts = null;
if (SourceSidsCount == Count)
{
Homogeneous = true;
SourceSids = this;
}
else if (SourceSidsCount > 0)
{
SourceSids = new IdentityReferenceCollection(SourceSidsCount);
}
if (SourceNTAccountsCount == Count)
{
Homogeneous = true;
SourceNTAccounts = this;
}
else if (SourceNTAccountsCount > 0)
{
SourceNTAccounts = new IdentityReferenceCollection(SourceNTAccountsCount);
}
//
// Repackage only if the source is not homogeneous (contains different source types)
//
IdentityReferenceCollection Result = null;
if (!Homogeneous)
{
Result = new IdentityReferenceCollection(Identities.Count);
for (int i = 0; i < Identities.Count; i++)
{
IdentityReference id = this[i];
Type type = id.GetType();
if (type == targetType)
{
continue;
}
else if (type == typeof(SecurityIdentifier))
{
SourceSids.Add(id);
}
else if (type == typeof(NTAccount))
{
SourceNTAccounts.Add(id);
}
else
{
//
// Rare case that we have defined a type of identity reference and not included it in the code logic above.
// To avoid this we do not allow IdentityReference to be subclassed outside of the BCL.
//
Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
throw new NotSupportedException();
}
}
}
bool someFailed = false;
IdentityReferenceCollection TargetSids = null, TargetNTAccounts = null;
if (SourceSidsCount > 0)
{
TargetSids = SecurityIdentifier.Translate(SourceSids, targetType, out someFailed);
if (Homogeneous && !(forceSuccess && someFailed))
{
Result = TargetSids;
}
}
if (SourceNTAccountsCount > 0)
{
TargetNTAccounts = NTAccount.Translate(SourceNTAccounts, targetType, out someFailed);
if (Homogeneous && !(forceSuccess && someFailed))
{
Result = TargetNTAccounts;
}
}
if (forceSuccess && someFailed)
{
//
// Need to throw an exception here and provide information regarding
// which identity references could not be translated to the target type
//
Result = new IdentityReferenceCollection();
if (TargetSids != null)
{
foreach (IdentityReference id in TargetSids)
{
if (id.GetType() != targetType)
{
Result.Add(id);
}
}
}
if (TargetNTAccounts != null)
{
foreach (IdentityReference id in TargetNTAccounts)
{
if (id.GetType() != targetType)
{
Result.Add(id);
}
}
}
throw new IdentityNotMappedException(SR.IdentityReference_IdentityNotMapped, Result);
}
else if (!Homogeneous)
{
SourceSidsCount = 0;
SourceNTAccountsCount = 0;
Result = new IdentityReferenceCollection(Identities.Count);
for (int i = 0; i < Identities.Count; i++)
{
IdentityReference id = this[i];
Type type = id.GetType();
if (type == targetType)
{
Result.Add(id);
}
else if (type == typeof(SecurityIdentifier))
{
Result.Add(TargetSids[SourceSidsCount++]);
}
else if (type == typeof(NTAccount))
{
Result.Add(TargetNTAccounts[SourceNTAccountsCount++]);
}
else
{
//
// Rare case that we have defined a type of identity reference and not included it in the code logic above.
// To avoid this we do not allow IdentityReference to be subclassed outside of the BCL.
//
Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
throw new NotSupportedException();
}
}
}
return Result;
}
#endregion
}
internal class IdentityReferenceEnumerator : IEnumerator<IdentityReference>, IDisposable
{
#region Private members
//
// Current enumeration index
//
private int _current;
//
// Parent collection
//
private readonly IdentityReferenceCollection _collection;
#endregion
#region Constructors
internal IdentityReferenceEnumerator(IdentityReferenceCollection collection)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
_collection = collection;
_current = -1;
}
#endregion
#region IEnumerator implementation
/// <internalonly/>
object IEnumerator.Current
{
get
{
return Current;
}
}
public IdentityReference Current
{
get
{
return _collection.Identities[_current];
}
}
public bool MoveNext()
{
_current++;
return (_current < _collection.Count);
}
public void Reset()
{
_current = -1;
}
public void Dispose()
{
}
#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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryMultiplyTests
{
#region Test methods
[Fact]
public static void CheckByteMultiplyTest()
{
byte[] array = new byte[] { 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyByteMultiply(array[i], array[j]);
}
}
}
[Fact]
public static void CheckSByteMultiplyTest()
{
sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifySByteMultiply(array[i], array[j]);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUShortMultiplyTest(bool useInterpreter)
{
ushort[] array = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUShortMultiply(array[i], array[j], useInterpreter);
VerifyUShortMultiplyOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckShortMultiplyTest(bool useInterpreter)
{
short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyShortMultiply(array[i], array[j], useInterpreter);
VerifyShortMultiplyOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUIntMultiplyTest(bool useInterpreter)
{
uint[] array = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUIntMultiply(array[i], array[j], useInterpreter);
VerifyUIntMultiplyOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIntMultiplyTest(bool useInterpreter)
{
int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyIntMultiply(array[i], array[j], useInterpreter);
VerifyIntMultiplyOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckULongMultiplyTest(bool useInterpreter)
{
ulong[] array = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyULongMultiply(array[i], array[j], useInterpreter);
VerifyULongMultiplyOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLongMultiplyTest(bool useInterpreter)
{
long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyLongMultiply(array[i], array[j], useInterpreter);
// we are not calling VerifyLongMultiplyOvf here
// because it currently fails on Linux
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLongMultiplyTestOvf(bool useInterpreter)
{
long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyLongMultiplyOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckFloatMultiplyTest(bool useInterpreter)
{
float[] array = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyFloatMultiply(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDoubleMultiplyTest(bool useInterpreter)
{
double[] array = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDoubleMultiply(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDecimalMultiplyTest(bool useInterpreter)
{
decimal[] array = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDecimalMultiply(array[i], array[j], useInterpreter);
}
}
}
[Fact]
public static void CheckCharMultiplyTest()
{
char[] array = new char[] { '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyCharMultiply(array[i], array[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyByteMultiply(byte a, byte b)
{
Expression aExp = Expression.Constant(a, typeof(byte));
Expression bExp = Expression.Constant(b, typeof(byte));
Assert.Throws<InvalidOperationException>(() => Expression.Multiply(aExp, bExp));
}
private static void VerifySByteMultiply(sbyte a, sbyte b)
{
Expression aExp = Expression.Constant(a, typeof(sbyte));
Expression bExp = Expression.Constant(b, typeof(sbyte));
Assert.Throws<InvalidOperationException>(() => Expression.Multiply(aExp, bExp));
}
private static void VerifyUShortMultiply(ushort a, ushort b, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.Multiply(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((ushort)(a * b)), f());
}
private static void VerifyUShortMultiplyOvf(ushort a, ushort b, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
ushort expected = 0;
try
{
expected = checked((ushort)(a * b));
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyShortMultiply(short a, short b, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.Multiply(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((short)(a * b)), f());
}
private static void VerifyShortMultiplyOvf(short a, short b, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
short expected = 0;
try
{
expected = checked((short)(a * b));
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyUIntMultiply(uint a, uint b, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.Multiply(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a * b), f());
}
private static void VerifyUIntMultiplyOvf(uint a, uint b, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
uint expected = 0;
try
{
expected = checked(a * b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyIntMultiply(int a, int b, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Multiply(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a * b), f());
}
private static void VerifyIntMultiplyOvf(int a, int b, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
int expected = 0;
try
{
expected = checked(a * b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyULongMultiply(ulong a, ulong b, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.Multiply(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a * b), f());
}
private static void VerifyULongMultiplyOvf(ulong a, ulong b, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
ulong expected = 0;
try
{
expected = checked(a * b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyLongMultiply(long a, long b, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.Multiply(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a * b), f());
}
private static void VerifyLongMultiplyOvf(long a, long b, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.MultiplyChecked(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
long expected = 0;
try
{
expected = checked(a * b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyFloatMultiply(float a, float b, bool useInterpreter)
{
Expression<Func<float>> e =
Expression.Lambda<Func<float>>(
Expression.Multiply(
Expression.Constant(a, typeof(float)),
Expression.Constant(b, typeof(float))),
Enumerable.Empty<ParameterExpression>());
Func<float> f = e.Compile(useInterpreter);
Assert.Equal(a * b, f());
}
private static void VerifyDoubleMultiply(double a, double b, bool useInterpreter)
{
Expression<Func<double>> e =
Expression.Lambda<Func<double>>(
Expression.Multiply(
Expression.Constant(a, typeof(double)),
Expression.Constant(b, typeof(double))),
Enumerable.Empty<ParameterExpression>());
Func<double> f = e.Compile(useInterpreter);
Assert.Equal(a * b, f());
}
private static void VerifyDecimalMultiply(decimal a, decimal b, bool useInterpreter)
{
Expression<Func<decimal>> e =
Expression.Lambda<Func<decimal>>(
Expression.Multiply(
Expression.Constant(a, typeof(decimal)),
Expression.Constant(b, typeof(decimal))),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f = e.Compile(useInterpreter);
decimal expected = 0;
try
{
expected = a * b;
}
catch(OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyCharMultiply(char a, char b)
{
Expression aExp = Expression.Constant(a, typeof(char));
Expression bExp = Expression.Constant(b, typeof(char));
Assert.Throws<InvalidOperationException>(() => Expression.Multiply(aExp, bExp));
}
#endregion
[Fact]
public static void CannotReduce()
{
Expression exp = Expression.Multiply(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void CannotReduceChecked()
{
Expression exp = Expression.MultiplyChecked(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void ThrowsOnLeftNull()
{
Assert.Throws<ArgumentNullException>("left", () => Expression.Multiply(null, Expression.Constant("")));
}
[Fact]
public static void ThrowsOnRightNull()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.Multiply(Expression.Constant(""), null));
}
[Fact]
public static void CheckedThrowsOnLeftNull()
{
Assert.Throws<ArgumentNullException>("left", () => Expression.MultiplyChecked(null, Expression.Constant("")));
}
[Fact]
public static void CheckedThrowsOnRightNull()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.MultiplyChecked(Expression.Constant(""), null));
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
[Fact]
public static void ThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("left", () => Expression.Multiply(value, Expression.Constant(1)));
}
[Fact]
public static void ThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("right", () => Expression.Multiply(Expression.Constant(1), value));
}
[Fact]
public static void CheckedThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("left", () => Expression.MultiplyChecked(value, Expression.Constant(1)));
}
[Fact]
public static void CheckedThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("right", () => Expression.MultiplyChecked(Expression.Constant(1), value));
}
[Fact]
public static void ToStringTest()
{
BinaryExpression e1 = Expression.Multiply(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a * b)", e1.ToString());
BinaryExpression e2 = Expression.MultiplyChecked(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a * b)", e2.ToString());
}
}
}
| |
//#define Linux
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using ObisoftWebCore.Models;
using ObisoftWebCore.Models.ManageViewModels;
using ObisoftWebCore.Services;
using ObisoftWebCore.Data;
using Microsoft.EntityFrameworkCore;
using ObisoftWebCore.Attributes;
using System.IO;
namespace ObisoftWebCore.Controllers
{
[Authorize]
[ObiRequireHttps]
public class ManageController : Controller
{
private readonly UserManager<ObisoftCoreUser> _userManager;
private readonly SignInManager<ObisoftCoreUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
private readonly ObisoftCoreDbContext _dbContext;
public ManageController(
UserManager<ObisoftCoreUser> userManager,
SignInManager<ObisoftCoreUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory,
ObisoftCoreDbContext dbContext)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<ManageController>();
_dbContext = dbContext;
}
//
// GET: /Manage/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? id = null)
{
ViewData["StatusMessage"] =
id == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: id == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: id == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: id == ManageMessageId.Error ? "An error has occurred."
: id == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: id == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: id == ManageMessageId.ChangeInfoSuccess ? "Your basic info has been changed."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var model = new IndexViewModel
{
UserId = user.Id,
HasPassword = await _userManager.HasPasswordAsync(user),
PhoneNumber = await _userManager.GetPhoneNumberAsync(user),
TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user),
Logins = await _userManager.GetLoginsAsync(user),
BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user),
NickName = user.NickName,
IconAddress = user.IconAddress,
IP = HttpContext.Connection.RemoteIpAddress.ToString(),
EmailConfirmed = await _userManager.IsEmailConfirmedAsync(user),
Email = user.Email,
BlogPartId = (await _dbContext.CommunityParts.SingleOrDefaultAsync(t => t.CommunityName.Contains("Blog"))).CommunityPartId,
};
return PartialView(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction(nameof(ManageLogins), new { id = message });
}
//
// GET: /Manage/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return PartialView();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code);
return Redirect($"/#/Manage/{nameof(VerifyPhoneNumber)}/{model.PhoneNumber}");
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(1, "User enabled two-factor authentication.");
}
return PartialView("_TwoFactor", await _userManager.GetTwoFactorEnabledAsync(user));
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(2, "User disabled two-factor authentication.");
}
return PartialView("_TwoFactor", await _userManager.GetTwoFactorEnabledAsync(user));
}
//
// GET: /Manage/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string id)
{
string phoneNumber = id;
var user = await GetCurrentUserAsync();
if (user == null)
{
return PartialView("Error");
}
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null ? PartialView("Error") : PartialView(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return Redirect($"/#/Manage/{nameof(Index)}/{ManageMessageId.AddPhoneSuccess }");
}
}
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// POST: /Manage/RemovePhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return Redirect($"/#/Manage/{nameof(Index)}/{ManageMessageId.RemovePhoneSuccess }");
}
}
return RedirectToAction($"/#/Manage/{nameof(Index)}/{ManageMessageId.Error}");
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return PartialView();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
ViewData["ServerPage"] = "true";
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User changed their password successfully.");
return Redirect($"/#/Manage/{nameof(Index)}/{ManageMessageId.ChangePasswordSuccess}");
}
AddErrors(result);
ViewData["ServerPage"] = "true";
return View(model);
}
return Redirect($"/#/Manage/{nameof(Index)}/{ManageMessageId.Error}");
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return PartialView();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
ViewData["ServerPage"] = "true";
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return Redirect($"/#/Manage/Index/{ManageMessageId.SetPasswordSuccess}");
}
AddErrors(result);
ViewData["ServerPage"] = "true";
return View(model);
}
return Redirect($"/#/Manage/Index/{ManageMessageId.Error}");
}
//GET: /Manage/ManageLogins
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? id = null)
{
ViewData["StatusMessage"] =
id == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: id == ManageMessageId.AddLoginSuccess ? "The external login was added."
: id == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(user);
var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return PartialView(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return Challenge(properties, provider);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user));
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { id = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new { id = message });
}
public async Task<ActionResult> ChangeBasicInfo()
{
var user = await GetCurrentUserAsync();
return PartialView(new ChangeBasicInfoViewModel
{
NickName = user.NickName,
ShortDescription = user.Description
});
}
[HttpPost]
public async Task<ActionResult> ChangeBasicInfo(ChangeBasicInfoViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
user.NickName = model.NickName;
user.Description = model.ShortDescription;
await _userManager.UpdateAsync(user);
ViewData["ServerPage"] = "true";
return Redirect($"/#/Manage/Index/{nameof(ManageMessageId.ChangeInfoSuccess)}");
}
public async Task<IActionResult> ChangeIcon()
{
var user = await GetCurrentUserAsync();
return PartialView();
}
[HttpPost]
public async Task<IActionResult> ChangeIcon(string id)
{
var file = Request.Form.Files[0];
if (file != null && file.Length < 4096000 && file.FileName.IsImage())
{
var _filename = Path.GetFileName(file.FileName).Replace(" ", "_");
#if (Linux)
var _wwwroot = Directory.GetCurrentDirectory() + @"/wwwroot";
var _path = _wwwroot + @"/" + _filename;
#else
var _wwwroot = Directory.GetCurrentDirectory() + @"\wwwroot";
var _path = _wwwroot + @"\" + _filename;
#endif
var _fileStream = new FileStream(path: _path, mode: FileMode.Create);
await file.CopyToAsync(_fileStream);
_fileStream.Dispose();
var Token = HttpContext.Request.Cookies["Token"];
if (string.IsNullOrEmpty(Token))
{
throw new NotImplementedException();
}
var Icon = await OSSService.UploadFile(_path,Token);
var user = await GetCurrentUserAsync();
user.IconAddress = Icon;
await _userManager.UpdateAsync(user);
System.IO.File.Delete(_path);
return Redirect($"/#/Manage/Index/{nameof(ManageMessageId.ChangeInfoSuccess)}");
}
return View();
}
[AllowAnonymous]
public IActionResult _Header()
{
return PartialView();
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error,
ChangeInfoSuccess
}
private Task<ObisoftCoreUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
#endregion
}
}
| |
//
// EventClient.cs
//
// Author:
// Scott Thomas <lunchtimemama@gmail.com>
//
// Copyright (C) 2008 S&S Black Ltd.
//
// 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.Net;
using System.Net.Sockets;
using System.Xml;
using Mono.Upnp.Control;
namespace Mono.Upnp.Internal
{
class EventClient : IDisposable
{
static readonly Random random = new Random ();
static int id;
readonly IMap<string, StateVariable> state_variables;
readonly Uri url;
readonly TimeoutDispatcher dispatcher = new TimeoutDispatcher ();
readonly string prefix = GeneratePrefix ();
volatile bool started;
volatile bool confidently_subscribed;
HttpListener listener;
uint expire_timeout_id;
uint renew_timeout_id;
string subscription_uuid;
int ref_count;
public EventClient (IMap<string, StateVariable> stateVariable, Uri url)
{
this.state_variables = stateVariable;
this.url = url;
}
static string GeneratePrefix ()
{
// FIXME configure the network interface
foreach (var address in Dns.GetHostAddresses (Dns.GetHostName ())) {
if (address.AddressFamily == AddressFamily.InterNetwork) {
return string.Format (
"http://{0}:{1}/upnp/event-subscriber/{2}/", address, random.Next (1024, 5000), id++);
}
}
return null;
}
public void Ref ()
{
if (ref_count == 0) {
Start ();
}
ref_count++;
}
public void Unref ()
{
ref_count--;
if (ref_count == 0) {
Stop ();
}
}
public void Start ()
{
if (started) {
return;
}
StartListening ();
Subscribe ();
started = true;
}
void StartListening ()
{
if (listener == null) {
listener = new HttpListener { IgnoreWriteExceptions = true };
listener.Prefixes.Add (prefix);
}
lock (listener) {
listener.Start ();
listener.BeginGetContext (OnGotContext, null);
}
}
void OnGotContext (IAsyncResult asyncResult)
{
lock (listener) {
if (!listener.IsListening) {
return;
}
var context = listener.EndGetContext (asyncResult);
try {
using (var stream = context.Request.InputStream) {
using (var reader = XmlReader.Create (stream)) {
if (reader.MoveToContent () != XmlNodeType.Element) {
Log.Warning ("The event update has no root XML element.");
} else if (reader.LocalName != "propertyset"
&& reader.NamespaceURI != Protocol.EventSchema)
{
Log.Warning ("The event update has no propertyset.");
} else if (!reader.ReadToDescendant ("property", Protocol.EventSchema)) {
Log.Warning ("The event update has an empty propertyset.");
} else {
do {
reader.Read ();
StateVariable state_variable;
if (state_variables.TryGetValue (reader.Name, out state_variable)) {
state_variable.Value = reader.ReadElementContentAsString ();
} else {
Log.Warning (string.Format (
"{0} published an event update to {1} " +
"which includes unknown state variable {2}.",
context.Request.RemoteEndPoint, context.Request.Url, reader.Name));
}
} while (reader.ReadToNextSibling ("property", Protocol.EventSchema));
}
}
}
} catch (Exception e) {
Log.Exception (string.Format ("There was a problem processing an event update from {0} to {1}.",
context.Request.RemoteEndPoint, context.Request.Url), e);
}
context.Response.Close ();
listener.BeginGetContext (OnGotContext, null);
}
}
void StopListening ()
{
lock (listener) {
listener.Stop ();
}
}
void Subscribe ()
{
var request = WebRequest.Create (url);
request.Method = "SUBSCRIBE";
request.Headers.Add ("USERAGENT", Protocol.UserAgent);
request.Headers.Add ("CALLBACK", string.Format ("<{0}>", prefix));
request.Headers.Add ("NT", "upnp:event");
request.Headers.Add ("TIMEOUT", "Second-1800");
lock (this) {
request.BeginGetResponse (OnSubscribeResponse, request);
expire_timeout_id = dispatcher.Add (TimeSpan.FromSeconds (30), OnSubscribeTimeout, request);
confidently_subscribed = false;
}
}
bool OnSubscribeTimeout (object state, ref TimeSpan interval)
{
lock (this) {
expire_timeout_id = 0;
if (!confidently_subscribed) {
var request = (WebRequest)state;
request.Abort ();
Stop ();
// TODO retry
Log.Error ("Failed to subscribe or renew. The server did not respond in 30 seconds.");
//controller.Description.CheckDisposed ();
}
}
return false;
}
void OnSubscribeResponse (IAsyncResult asyncResult)
{
lock (this) {
if (expire_timeout_id != 0) {
dispatcher.Remove (expire_timeout_id);
}
var request = (WebRequest)asyncResult.AsyncState;
try {
using (var response = (HttpWebResponse)request.EndGetResponse (asyncResult)) {
if (response.StatusCode == HttpStatusCode.GatewayTimeout) {
throw new WebException ("", WebExceptionStatus.Timeout);
} else if (response.StatusCode != HttpStatusCode.OK) {
throw new WebException ();
} else if (!started) {
return;
}
confidently_subscribed = true;
subscription_uuid = response.Headers["SID"];
var timeout_header = response.Headers["TIMEOUT"];
if (timeout_header == "infinate") {
return;
}
var timeout = TimeSpan.FromSeconds (double.Parse (timeout_header.Substring (7)));
if (timeout > TimeSpan.FromMinutes (2)) {
timeout -= TimeSpan.FromMinutes (2);
}
renew_timeout_id = dispatcher.Add (timeout, OnRenewTimeout);
}
} catch (WebException e) {
Stop ();
// TODO more info
Log.Exception (new UpnpException ("Failed to subscribe or renew.", e));
if (e.Status == WebExceptionStatus.Timeout) {
//controller.Description.CheckDisposed ();
}
}
}
}
bool OnRenewTimeout (object state, ref TimeSpan interval)
{
lock (this) {
renew_timeout_id = 0;
if (started) {
Renew ();
}
return false;
}
}
void Renew ()
{
lock (this) {
var request = WebRequest.Create (url);
request.Method = "SUBSCRIBE";
request.Headers.Add ("SID", subscription_uuid);
request.Headers.Add ("TIMEOUT", "Second-1800");
request.BeginGetResponse (OnSubscribeResponse, request);
expire_timeout_id = dispatcher.Add (TimeSpan.FromSeconds (30), OnSubscribeTimeout, request);
confidently_subscribed = false;
}
}
void Unsubscribe ()
{
lock (this) {
var request = WebRequest.Create (url);
request.Method = "UNSUBSCRIBE";
request.Headers.Add ("SID", subscription_uuid);
request.BeginGetResponse (OnUnsubscribeResponse, request);
confidently_subscribed = false;
}
}
void OnUnsubscribeResponse (IAsyncResult asyncResult)
{
try {
((WebRequest)asyncResult).EndGetResponse (asyncResult).Close ();
} catch {
}
}
public void Stop ()
{
if (!started) {
return;
}
if (renew_timeout_id != 0) {
dispatcher.Remove (renew_timeout_id);
renew_timeout_id = 0;
}
if (expire_timeout_id != 0) {
dispatcher.Remove (expire_timeout_id);
expire_timeout_id = 0;
}
lock (this) {
if (confidently_subscribed) {
Unsubscribe ();
}
}
StopListening ();
started = false;
}
public void Dispose ()
{
Stop ();
lock (listener) {
listener.Close ();
}
}
}
}
| |
// 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 ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.conversion.overload001.overload001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.conversion.overload001.overload001;
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static implicit operator short (Base b)
{
return short.MinValue;
}
}
public class Derived : Base
{
public static implicit operator short (Derived x)
{
return short.MaxValue;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
short x = d;
if (x == short.MaxValue)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.conversion.overload002.overload002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.conversion.overload002.overload002;
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static implicit operator short (Base x)
{
return short.MinValue;
}
}
public class Derived : Base
{
public static implicit operator int (Derived x)
{
return int.MaxValue;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
int x = d;
if (x == int.MaxValue)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.conversion.overload004.overload004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.conversion.overload004.overload004;
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static explicit operator short (Base x)
{
return short.MinValue;
}
}
public class Derived : Base
{
public static explicit operator int (Derived x)
{
return int.MaxValue;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Base();
short x = (short)d;
if (x == short.MinValue)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.conversion.overload006.overload006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.conversion.overload006.overload006;
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public static implicit operator short (Base x)
{
return short.MinValue;
}
}
public class Derived : Base
{
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
short x = d;
if (x == short.MinValue)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.conversion.overload007.overload007
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Operators.Twoclass2operates.conversion.overload007.overload007;
// <Title> Tests overload resolution for 2 class and 2 methods</Title>
// <Description>
// Call methods with different accessibility level and selecting the right one.:)
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Base
{
public int Field;
public static implicit operator Base(short x)
{
return new Base()
{
Field = x
}
;
}
}
public class Derived
{
public static explicit operator short (Derived x)
{
return short.MinValue;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new Derived();
Base x = (short)d;
if (x.Field == short.MinValue)
return 0;
return 1;
}
}
// </Code>
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.