context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using UnityEngine;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace FMODUnity
{
public class EventNotFoundException : Exception
{
public Guid Guid;
public string Path;
public EventNotFoundException(string path)
: base("[FMOD] Event not found '" + path + "'")
{
Path = path;
}
public EventNotFoundException(Guid guid)
: base("[FMOD] Event not found " + guid.ToString("b") + "")
{
Guid = guid;
}
}
public class BusNotFoundException : Exception
{
public string Path;
public BusNotFoundException(string path)
: base("[FMOD] Bus not found '" + path + "'")
{
Path = path;
}
}
public class VCANotFoundException : Exception
{
public string Path;
public VCANotFoundException(string path)
: base("[FMOD] VCA not found '" + path + "'")
{
Path = path;
}
}
public class BankLoadException : Exception
{
public string Path;
public FMOD.RESULT Result;
public BankLoadException(string path, FMOD.RESULT result)
: base(string.Format("[FMOD] Could not load bank '{0}' : {1} : {2}", path, result.ToString(), FMOD.Error.String(result)))
{
Path = path;
Result = result;
}
public BankLoadException(string path, string error)
: base(string.Format("[FMOD] Could not load bank '{0}' : {1}", path, error))
{
Path = path;
Result = FMOD.RESULT.ERR_INTERNAL;
}
}
public class SystemNotInitializedException : Exception
{
public FMOD.RESULT Result;
public string Location;
public SystemNotInitializedException(FMOD.RESULT result, string location)
: base(string.Format("[FMOD] Initialization failed : {2} : {0} : {1}", result.ToString(), FMOD.Error.String(result), location))
{
Result = result;
Location = location;
}
public SystemNotInitializedException(Exception inner)
: base("[FMOD] Initialization failed", inner)
{
}
}
public enum EmitterGameEvent : int
{
None,
ObjectStart,
ObjectDestroy,
TriggerEnter,
TriggerExit,
TriggerEnter2D,
TriggerExit2D,
CollisionEnter,
CollisionExit,
CollisionEnter2D,
CollisionExit2D,
ObjectEnable,
ObjectDisable,
MouseEnter,
MouseExit,
MouseDown,
MouseUp,
}
public enum LoaderGameEvent : int
{
None,
ObjectStart,
ObjectDestroy,
TriggerEnter,
TriggerExit,
TriggerEnter2D,
TriggerExit2D,
}
public static class RuntimeUtils
{
public static string GetCommonPlatformPath(string path)
{
if (string.IsNullOrEmpty(path))
{
return path;
}
return path.Replace('\\', '/');
}
public static FMOD.VECTOR ToFMODVector(this Vector3 vec)
{
FMOD.VECTOR temp;
temp.x = vec.x;
temp.y = vec.y;
temp.z = vec.z;
return temp;
}
public static FMOD.ATTRIBUTES_3D To3DAttributes(this Vector3 pos)
{
FMOD.ATTRIBUTES_3D attributes = new FMOD.ATTRIBUTES_3D();
attributes.forward = ToFMODVector(Vector3.forward);
attributes.up = ToFMODVector(Vector3.up);
attributes.position = ToFMODVector(pos);
return attributes;
}
public static FMOD.ATTRIBUTES_3D To3DAttributes(this Transform transform)
{
FMOD.ATTRIBUTES_3D attributes = new FMOD.ATTRIBUTES_3D();
attributes.forward = transform.forward.ToFMODVector();
attributes.up = transform.up.ToFMODVector();
attributes.position = transform.position.ToFMODVector();
return attributes;
}
public static FMOD.ATTRIBUTES_3D To3DAttributes(Transform transform, Rigidbody rigidbody = null)
{
FMOD.ATTRIBUTES_3D attributes = transform.To3DAttributes();
if (rigidbody)
{
attributes.velocity = rigidbody.velocity.ToFMODVector();
}
return attributes;
}
public static FMOD.ATTRIBUTES_3D To3DAttributes(GameObject go, Rigidbody rigidbody = null)
{
FMOD.ATTRIBUTES_3D attributes = go.transform.To3DAttributes();
if (rigidbody)
{
attributes.velocity = rigidbody.velocity.ToFMODVector();
}
return attributes;
}
public static FMOD.ATTRIBUTES_3D To3DAttributes(Transform transform, Rigidbody2D rigidbody)
{
FMOD.ATTRIBUTES_3D attributes = transform.To3DAttributes();
if (rigidbody)
{
FMOD.VECTOR vel;
vel.x = rigidbody.velocity.x;
vel.y = rigidbody.velocity.y;
vel.z = 0;
attributes.velocity = vel;
}
return attributes;
}
public static FMOD.ATTRIBUTES_3D To3DAttributes(GameObject go, Rigidbody2D rigidbody)
{
FMOD.ATTRIBUTES_3D attributes = go.transform.To3DAttributes();
if (rigidbody)
{
FMOD.VECTOR vel;
vel.x = rigidbody.velocity.x;
vel.y = rigidbody.velocity.y;
vel.z = 0;
attributes.velocity = vel;
}
return attributes;
}
// Internal Helper Functions
internal static FMODPlatform GetCurrentPlatform()
{
#if UNITY_EDITOR
return FMODPlatform.PlayInEditor;
#elif UNITY_STANDALONE_WIN
return FMODPlatform.Windows;
#elif UNITY_STANDALONE_OSX
return FMODPlatform.Mac;
#elif UNITY_STANDALONE_LINUX
return FMODPlatform.Linux;
#elif UNITY_TVOS
return FMODPlatform.AppleTV;
#elif UNITY_IOS
FMODPlatform result;
switch (UnityEngine.iOS.Device.generation)
{
case UnityEngine.iOS.DeviceGeneration.iPad1Gen:
case UnityEngine.iOS.DeviceGeneration.iPad2Gen:
case UnityEngine.iOS.DeviceGeneration.iPad3Gen:
case UnityEngine.iOS.DeviceGeneration.iPadMini1Gen:
case UnityEngine.iOS.DeviceGeneration.iPhone:
case UnityEngine.iOS.DeviceGeneration.iPhone3G:
case UnityEngine.iOS.DeviceGeneration.iPhone3GS:
case UnityEngine.iOS.DeviceGeneration.iPhone4:
case UnityEngine.iOS.DeviceGeneration.iPhone4S:
result = FMODPlatform.MobileLow;
break;
default:
result = FMODPlatform.MobileHigh;
break;
}
UnityEngine.Debug.Log(String.Format("FMOD Studio: Device {0} classed as {1}", SystemInfo.deviceModel, result.ToString()));
return result;
#elif UNITY_ANDROID
FMODPlatform result;
if (SystemInfo.processorCount <= 2)
{
result = FMODPlatform.MobileLow;
}
else if (SystemInfo.processorCount >= 8)
{
result = FMODPlatform.MobileHigh;
}
else
{
// check the clock rate on quad core systems
string freqinfo = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq";
try
{
using (global::System.IO.TextReader reader = new global::System.IO.StreamReader(freqinfo))
{
string line = reader.ReadLine();
int khz = Int32.Parse(line) / 1000;
if (khz >= 1600)
{
result = FMODPlatform.MobileHigh;
}
else
{
result = FMODPlatform.MobileLow;
}
}
}
catch
{
result = FMODPlatform.MobileLow;
}
}
UnityEngine.Debug.Log(String.Format("[FMOD] Device {0} classed as {1}", SystemInfo.deviceModel, result.ToString()));
return result;
#elif UNITY_WINRT_8_1
FMODPlatform result;
if (SystemInfo.processorCount <= 2)
{
result = FMODPlatform.MobileLow;
}
else
{
result = FMODPlatform.MobileHigh;
}
UnityEngine.Debug.Log(String.Format("[FMOD] Device {0} classed as {1}", SystemInfo.deviceModel, result.ToString()));
return result;
#elif UNITY_PS4
return FMODPlatform.PS4;
#elif UNITY_XBOXONE
return FMODPlatform.XboxOne;
#elif UNITY_WSA_10_0
return FMODPlatform.UWP;
#elif UNITY_SWITCH
return FMODPlatform.Switch;
#elif UNITY_WEBGL
return FMODPlatform.WebGL;
#elif UNITY_STADIA
return FMODPlatform.Stadia;
#endif
}
const string BankExtension = ".bank";
internal static string GetBankPath(string bankName)
{
#if UNITY_EDITOR
// For play in editor use original asset location because streaming asset folder will contain platform specific banks
string bankFolder = Settings.Instance.SourceBankPath;
if (Settings.Instance.HasPlatforms)
{
bankFolder = global::System.IO.Path.Combine(bankFolder, Settings.Instance.GetBankPlatform(FMODPlatform.PlayInEditor));
}
#elif UNITY_ANDROID
string bankFolder = null;
if (System.IO.Path.GetExtension(Application.dataPath) == ".apk")
{
bankFolder = "file:///android_asset";
}
else
{
bankFolder = String.Format("jar:file://{0}!/assets", Application.dataPath);
}
#elif UNITY_WINRT_8_1 || UNITY_WSA_10_0
string bankFolder = "ms-appx:///Data/StreamingAssets";
#else
string bankFolder = Application.streamingAssetsPath;
#endif
// Special case for Switch, remove / at start if needed.
#if UNITY_SWITCH
if (bankFolder[0] == '/')
bankFolder = bankFolder.Substring(1);
#endif
if (System.IO.Path.GetExtension(bankName) != BankExtension)
{
return string.Format("{0}/{1}.bank", bankFolder, bankName);
}
else
{
return string.Format("{0}/{1}", bankFolder, bankName);
}
}
internal static string GetPluginPath(string pluginName)
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_XBOXONE || UNITY_WINRT_8_1 || UNITY_WSA_10_0
string pluginFileName = pluginName + ".dll";
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
string pluginFileName = pluginName + ".bundle";
#elif UNITY_PS4
string pluginFileName = pluginName + ".prx";
#elif UNITY_ANDROID || UNITY_STANDALONE_LINUX
string pluginFileName = "lib" + pluginName + ".so";
#elif UNITY_WEBGL
string pluginFileName = pluginName + ".bc";
#endif
string fmodLibPath = "/Plugins/FMOD/lib";
#if UNITY_EDITOR_WIN && UNITY_EDITOR_64
string pluginFolder = Application.dataPath + fmodLibPath + "/win/X86_64/";
#elif UNITY_EDITOR_WIN
string pluginFolder = Application.dataPath + fmodLibPath + "/win/X86/";
#elif UNITY_EDITOR_OSX
string pluginFolder = Application.dataPath + fmodLibPath + "/mac/";
#elif UNITY_STANDALONE_WIN || UNITY_PS4 || UNITY_XBOXONE || UNITY_STANDALONE_OSX || UNITY_WEBGL
string pluginFolder = Application.dataPath + "/Plugins/";
#elif UNITY_STANDALONE_LINUX
string pluginFolder = Application.dataPath + fmodLibPath + ((IntPtr.Size == 8) ? "/linux/x86_64/" : "/linux/x86/");
#elif UNITY_WSA || UNITY_ANDROID
string pluginFolder = "";
#else
string pluginFileName = "";
string pluginFolder = "";
#endif
return pluginFolder + pluginFileName;
}
public static void EnforceLibraryOrder()
{
#if UNITY_ANDROID && !UNITY_EDITOR
AndroidJavaClass jSystem = new AndroidJavaClass("java.lang.System");
jSystem.CallStatic("loadLibrary", FMOD.VERSION.dll);
jSystem.CallStatic("loadLibrary", FMOD.Studio.STUDIO_VERSION.dll);
#endif
// Call a function in fmod.dll to make sure it's loaded before fmodstudio.dll
int temp1, temp2;
FMOD.Memory.GetStats(out temp1, out temp2);
Guid temp3;
FMOD.Studio.Util.parseID("", out temp3);
}
#if UNITY_EDITOR
public static FMODPlatform GetEditorFMODPlatform()
{
switch (EditorUserBuildSettings.activeBuildTarget)
{
case BuildTarget.Android:
return FMODPlatform.Android;
case BuildTarget.iOS:
return FMODPlatform.iOS;
case BuildTarget.PS4:
return FMODPlatform.PS4;
#if !UNITY_2019_2_OR_NEWER
case BuildTarget.StandaloneLinux:
case BuildTarget.StandaloneLinuxUniversal:
#endif
case BuildTarget.StandaloneLinux64:
return FMODPlatform.Linux;
case BuildTarget.StandaloneOSX:
return FMODPlatform.Mac;
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
return FMODPlatform.Windows;
case BuildTarget.XboxOne:
return FMODPlatform.XboxOne;
case BuildTarget.WSAPlayer:
return FMODPlatform.UWP;
case BuildTarget.tvOS:
return FMODPlatform.AppleTV;
#if UNITY_SWITCH
case BuildTarget.Switch:
return FMODPlatform.Switch;
#endif
#if UNITY_WEBGL
case BuildTarget.WebGL:
return FMODPlatform.WebGL;
#endif
#if UNITY_STADIA
case BuildTarget.Stadia:
return FMODPlatform.Stadia;
#endif
default:
return FMODPlatform.None;
}
}
#endif
public static bool VerifyPlatformLibsExist()
{
string libPath = Application.dataPath + "/Plugins/FMOD/lib/";
#if UNITY_XBOXONE
libPath += "xboxone/fmodstudio.dll";
#elif UNITY_PS4
libPath += "ps4/libfmodstudio.prx";
#elif UNITY_STADIA
libPath += "stadia/libfmodstudio.so";
#elif UNITY_SWITCH && UNITY_EDITOR // Not called at runtime because the static lib is not included in the built game.
libPath += "switch/libfmodstudiounityplugin.a";
#endif
if (Path.HasExtension(libPath) && !File.Exists(libPath))
{
Debug.LogWarning("[FMOD] Unable to locate '" + libPath +"'.");
Debug.LogWarning("[FMOD] This platform requires verification 'https://fmod.com/profile#permissions' and an additional package from 'https://fmod.com/download'.");
return false;
}
return true;
}
}
}
| |
using System;
using Jint.Native.Object;
using Jint.Native.TypedArray;
using Jint.Runtime;
namespace Jint.Native.ArrayBuffer
{
/// <summary>
/// https://tc39.es/ecma262/#sec-arraybuffer-objects
/// </summary>
public sealed class ArrayBufferInstance : ObjectInstance
{
// so that we don't need to allocate while or reading setting values
private readonly byte[] _workBuffer = new byte[8];
private byte[] _arrayBufferData;
private readonly JsValue _arrayBufferDetachKey = Undefined;
internal ArrayBufferInstance(
Engine engine,
ulong byteLength) : base(engine)
{
var block = byteLength > 0 ? CreateByteDataBlock(byteLength) : System.Array.Empty<byte>();
_arrayBufferData = block;
}
private byte[] CreateByteDataBlock(ulong byteLength)
{
if (byteLength > int.MaxValue)
{
ExceptionHelper.ThrowRangeError(_engine.Realm, "Array buffer allocation failed");
}
return new byte[byteLength];
}
internal int ArrayBufferByteLength => _arrayBufferData.Length;
internal byte[] ArrayBufferData => _arrayBufferData;
internal bool IsDetachedBuffer => _arrayBufferData is null;
internal bool IsSharedArrayBuffer => false; // TODO SharedArrayBuffer
/// <summary>
/// https://tc39.es/ecma262/#sec-detacharraybuffer
/// </summary>
internal void DetachArrayBuffer(JsValue key = null)
{
key ??= Undefined;
if (!SameValue(_arrayBufferDetachKey, key))
{
ExceptionHelper.ThrowTypeError(_engine.Realm);
}
_arrayBufferData = null;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-clonearraybuffer
/// </summary>
internal ArrayBufferInstance CloneArrayBuffer(
ArrayBufferConstructor constructor,
int srcByteOffset,
uint srcLength,
JsValue cloneConstructor)
{
var targetBuffer = constructor.AllocateArrayBuffer(cloneConstructor, srcLength);
AssertNotDetached();
var srcBlock = _arrayBufferData;
var targetBlock = targetBuffer.ArrayBufferData;
// TODO SharedArrayBuffer would use this
//CopyDataBlockBytes(targetBlock, 0, srcBlock, srcByteOffset, srcLength).
System.Array.Copy(srcBlock, srcByteOffset, targetBlock, 0, srcLength);
return targetBuffer;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-getvaluefrombuffer
/// </summary>
internal TypedArrayValue GetValueFromBuffer(
int byteIndex,
TypedArrayElementType type,
bool isTypedArray,
ArrayBufferOrder order,
bool? isLittleEndian = null)
{
if (!IsSharedArrayBuffer)
{
// If isLittleEndian is not present, set isLittleEndian to the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
return RawBytesToNumeric(type, byteIndex, isLittleEndian ?? BitConverter.IsLittleEndian);
}
/*
Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent EsprimaExtensions.Record.
b. Let eventList be the [[EventList]] field of the element in execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
c. If isTypedArray is true and IsNoTearConfiguration(type, order) is true, let noTear be true; otherwise let noTear be false.
d. Let rawValue be a List of length elementSize whose elements are nondeterministically chosen byte values.
e. NOTE: In implementations, rawValue is the result of a non-atomic or atomic read instruction on the underlying hardware. The nondeterminism is a semantic prescription of the memory model to describe observable behaviour of hardware with weak consistency.
f. Let readEvent be ReadSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize }.
g. Append readEvent to eventList.
h. Append Chosen Value EsprimaExtensions.Record { [[Event]]: readEvent, [[ChosenValue]]: rawValue } to execution.[[ChosenValues]].
*/
ExceptionHelper.ThrowNotImplementedException("SharedArrayBuffer not implemented");
return default;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-rawbytestonumeric
/// </summary>
internal TypedArrayValue RawBytesToNumeric(TypedArrayElementType type, int byteIndex, bool isLittleEndian)
{
var elementSize = type.GetElementSize();
var rawBytes = _arrayBufferData;
// 8 byte values require a little more at the moment
var needsReverse = !isLittleEndian
&& elementSize > 1
&& type is TypedArrayElementType.Float32 or TypedArrayElementType.Float64 or TypedArrayElementType.BigInt64 or TypedArrayElementType.BigUint64;
if (needsReverse)
{
System.Array.Copy(rawBytes, byteIndex, _workBuffer, 0, elementSize);
byteIndex = 0;
System.Array.Reverse(_workBuffer, 0, elementSize);
rawBytes = _workBuffer;
}
if (type == TypedArrayElementType.Float32)
{
// rawBytes concatenated and interpreted as a little-endian bit string encoding of an IEEE 754-2019 binary32 value.
var value = BitConverter.ToSingle(rawBytes, byteIndex);
// If value is an IEEE 754-2019 binary32 NaN value, return the NaN Number value.
if (float.IsNaN(value))
{
return double.NaN;
}
return value;
}
if (type == TypedArrayElementType.Float64)
{
// rawBytes concatenated and interpreted as a little-endian bit string encoding of an IEEE 754-2019 binary64 value.
var value = BitConverter.ToDouble(rawBytes, byteIndex);
return value;
}
if (type == TypedArrayElementType.BigUint64)
{
var value = BitConverter.ToUInt64(rawBytes, byteIndex);
return value;
}
if (type == TypedArrayElementType.BigInt64)
{
var value = BitConverter.ToInt64(rawBytes, byteIndex);
return value;
}
TypedArrayValue? arrayValue = type switch
{
TypedArrayElementType.Int8 => ((sbyte) rawBytes[byteIndex]),
TypedArrayElementType.Uint8 => (rawBytes[byteIndex]),
TypedArrayElementType.Uint8C =>(rawBytes[byteIndex]),
TypedArrayElementType.Int16 => (isLittleEndian
? (short) (rawBytes[byteIndex] | (rawBytes[byteIndex + 1] << 8))
: (short) (rawBytes[byteIndex + 1] | (rawBytes[byteIndex] << 8))
),
TypedArrayElementType.Uint16 => (isLittleEndian
? (ushort) (rawBytes[byteIndex] | (rawBytes[byteIndex + 1] << 8))
: (ushort) (rawBytes[byteIndex + 1] | (rawBytes[byteIndex] << 8))
),
TypedArrayElementType.Int32 => (isLittleEndian
? rawBytes[byteIndex] | (rawBytes[byteIndex + 1] << 8) | (rawBytes[byteIndex + 2] << 16) | (rawBytes[byteIndex + 3] << 24)
: rawBytes[byteIndex + 3] | (rawBytes[byteIndex + 2] << 8) | (rawBytes[byteIndex + 1] << 16) | (rawBytes[byteIndex + 0] << 24)
),
TypedArrayElementType.Uint32 => (isLittleEndian
? (uint) (rawBytes[byteIndex] | (rawBytes[byteIndex + 1] << 8) | (rawBytes[byteIndex + 2] << 16) | (rawBytes[byteIndex + 3] << 24))
: (uint) (rawBytes[byteIndex + 3] | (rawBytes[byteIndex + 2] << 8) | (rawBytes[byteIndex + 1] << 16) | (rawBytes[byteIndex] << 24))
),
_ => null
};
if (arrayValue is null)
{
ExceptionHelper.ThrowArgumentOutOfRangeException(nameof(type), type.ToString());
}
return arrayValue.Value;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-setvalueinbuffer
/// </summary>
internal void SetValueInBuffer(
int byteIndex,
TypedArrayElementType type,
TypedArrayValue value,
bool isTypedArray,
ArrayBufferOrder order,
bool? isLittleEndian = null)
{
var block = _arrayBufferData;
if (!IsSharedArrayBuffer)
{
// If isLittleEndian is not present, set isLittleEndian to the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
var rawBytes = NumericToRawBytes(type, value, isLittleEndian ?? BitConverter.IsLittleEndian);
System.Array.Copy(rawBytes, 0, block, byteIndex, type.GetElementSize());
}
else
{
/*
a. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
b. Let eventList be the [[EventList]] field of the element in execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
c. If isTypedArray is true and IsNoTearConfiguration(type, order) is true, let noTear be true; otherwise let noTear be false.
d. Append WriteSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes } to eventList.
*/
ExceptionHelper.ThrowNotImplementedException("SharedArrayBuffer not implemented");
}
}
private byte[] NumericToRawBytes(TypedArrayElementType type, TypedArrayValue value, bool isLittleEndian)
{
byte[] rawBytes;
if (type == TypedArrayElementType.Float32)
{
// Let rawBytes be a List whose elements are the 4 bytes that are the result of converting value to IEEE 754-2019 binary32 format using roundTiesToEven mode. If isLittleEndian is false, the bytes are arranged in big endian order. Otherwise, the bytes are arranged in little endian order. If value is NaN, rawBytes may be set to any implementation chosen IEEE 754-2019 binary32 format Not-a-Number encoding. An implementation must always choose the same encoding for each implementation distinguishable NaN value.
rawBytes = BitConverter.GetBytes((float) value.DoubleValue);
}
else if (type == TypedArrayElementType.Float64)
{
// Let rawBytes be a List whose elements are the 8 bytes that are the IEEE 754-2019 binary64 format encoding of value. If isLittleEndian is false, the bytes are arranged in big endian order. Otherwise, the bytes are arranged in little endian order. If value is NaN, rawBytes may be set to any implementation chosen IEEE 754-2019 binary64 format Not-a-Number encoding. An implementation must always choose the same encoding for each implementation distinguishable NaN value.
rawBytes = BitConverter.GetBytes(value.DoubleValue);
}
else if (type == TypedArrayElementType.BigInt64)
{
rawBytes = BitConverter.GetBytes(TypeConverter.ToBigInt64(value.BigInteger));
}
else if (type == TypedArrayElementType.BigUint64)
{
rawBytes = BitConverter.GetBytes(TypeConverter.ToBigUint64(value.BigInteger));
}
else
{
// inlined conversion for faster speed instead of getting the method in spec
var doubleValue = value.DoubleValue;
var intValue = double.IsNaN(doubleValue) || doubleValue == 0 || double.IsInfinity(doubleValue)
? 0
: (long) doubleValue;
rawBytes = _workBuffer;
switch (type)
{
case TypedArrayElementType.Int8:
rawBytes[0] = (byte) (sbyte) intValue;
break;
case TypedArrayElementType.Uint8:
rawBytes[0] = (byte) intValue;
break;
case TypedArrayElementType.Uint8C:
rawBytes[0] = (byte) TypeConverter.ToUint8Clamp(value.DoubleValue);
break;
case TypedArrayElementType.Int16:
#if !NETSTANDARD2_1
rawBytes = BitConverter.GetBytes((short) intValue);
#else
BitConverter.TryWriteBytes(rawBytes, (short) intValue);
#endif
break;
case TypedArrayElementType.Uint16:
#if !NETSTANDARD2_1
rawBytes = BitConverter.GetBytes((ushort) intValue);
#else
BitConverter.TryWriteBytes(rawBytes, (ushort) intValue);
#endif
break;
case TypedArrayElementType.Int32:
#if !NETSTANDARD2_1
rawBytes = BitConverter.GetBytes((uint) intValue);
#else
BitConverter.TryWriteBytes(rawBytes, (uint) intValue);
#endif
break;
case TypedArrayElementType.Uint32:
#if !NETSTANDARD2_1
rawBytes = BitConverter.GetBytes((uint) intValue);
#else
BitConverter.TryWriteBytes(rawBytes, (uint) intValue);
#endif
break;
default:
ExceptionHelper.ThrowArgumentOutOfRangeException();
return null;
}
}
var elementSize = type.GetElementSize();
if (!isLittleEndian && elementSize > 1)
{
System.Array.Reverse(rawBytes, 0, elementSize);
}
return rawBytes;
}
internal void AssertNotDetached()
{
if (IsDetachedBuffer)
{
ExceptionHelper.ThrowTypeError(_engine.Realm, "ArrayBuffer has been detached");
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="AppendBlobWriter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Azure.Storage.DataMovement.TransferControllers
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.Storage.Blob.Protocol;
internal sealed class AppendBlobWriter : TransferReaderWriterBase
{
private volatile State state;
private AzureBlobLocation destLocation;
private CloudAppendBlob appendBlob;
private long expectedOffset = 0;
/// <summary>
/// Work token indicates whether this writer has work, could be 0(no work) or 1(has work).
/// </summary>
private volatile int workToken;
/// <summary>
/// To indicate whether the destination already exist before this writing.
/// If no, when try to set destination's attribute, should get its attributes first.
/// </summary>
private bool destExist = false;
public AppendBlobWriter(
TransferScheduler scheduler,
SyncTransferController controller,
CancellationToken cancellationToken)
: base(scheduler, controller, cancellationToken)
{
this.destLocation = this.SharedTransferData.TransferJob.Destination as AzureBlobLocation;
this.appendBlob = this.destLocation.Blob as CloudAppendBlob;
Debug.Assert(null != this.appendBlob, "The destination is not an append blob while initializing a AppendBlobWriter instance.");
this.state = State.FetchAttributes;
this.workToken = 1;
}
public override bool HasWork
{
get
{
return this.workToken == 1 &&
((State.FetchAttributes == this.state) ||
(State.Create == this.state) ||
(State.UploadBlob == this.state && this.SharedTransferData.AvailableData.ContainsKey(this.expectedOffset)) ||
(State.Commit == this.state && null != this.SharedTransferData.Attributes));
}
}
public override bool IsFinished
{
get
{
return State.Error == this.state || State.Finished == this.state;
}
}
private enum State
{
FetchAttributes,
Create,
UploadBlob,
Commit,
Error,
Finished
};
public override async Task DoWorkInternalAsync()
{
switch (this.state)
{
case State.FetchAttributes:
await this.FetchAttributesAsync();
break;
case State.Create:
await this.CreateAsync();
break;
case State.UploadBlob:
await this.UploadBlobAsync();
break;
case State.Commit:
await this.CommitAsync();
break;
case State.Error:
default:
break;
}
}
private async Task FetchAttributesAsync()
{
Debug.Assert(
this.state == State.FetchAttributes,
"FetchAttributesAsync called, but state isn't FetchAttributes",
"Current state is {0}",
this.state);
if (Interlocked.CompareExchange(ref workToken, 0, 1) == 0)
{
return;
}
if (this.SharedTransferData.TotalLength > Constants.MaxAppendBlobFileSize)
{
string exceptionMessage = string.Format(
CultureInfo.CurrentCulture,
Resources.BlobFileSizeTooLargeException,
Utils.BytesToHumanReadableSize(this.SharedTransferData.TotalLength),
Resources.AppendBlob,
Utils.BytesToHumanReadableSize(Constants.MaxAppendBlobFileSize));
throw new TransferException(
TransferErrorCode.UploadSourceFileSizeTooLarge,
exceptionMessage);
}
bool existingBlob = !this.Controller.IsForceOverwrite;
if (!this.Controller.IsForceOverwrite)
{
AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition(
this.destLocation.AccessCondition,
this.destLocation.CheckedAccessCondition);
try
{
await Utils.ExecuteXsclApiCallAsync(
async () => await this.appendBlob.FetchAttributesAsync(
accessCondition,
Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions),
Utils.GenerateOperationContext(this.Controller.TransferContext),
this.CancellationToken),
this.CancellationToken);
this.destExist = true;
}
#if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION
catch (Exception e) when (e is StorageException || (e is AggregateException && e.InnerException is StorageException))
{
var se = e as StorageException ?? e.InnerException as StorageException;
#else
catch (StorageException se)
{
#endif
// Getting a storage exception is expected if the blob doesn't
// exist. In this case we won't error out, but set the
// existingBlob flag to false to indicate we're uploading
// a new blob instead of overwriting an existing blob.
if (null != se.RequestInformation &&
se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound)
{
existingBlob = false;
}
else if (null != se &&
(0 == string.Compare(se.Message, Constants.BlobTypeMismatch, StringComparison.OrdinalIgnoreCase)))
{
throw new InvalidOperationException(Resources.DestinationBlobTypeNotMatch, se);
}
else
{
throw;
}
}
}
await this.HandleFetchAttributesResultAsync(existingBlob);
}
private async Task HandleFetchAttributesResultAsync(bool existingBlob)
{
this.destLocation.CheckedAccessCondition = true;
if (!this.Controller.IsForceOverwrite)
{
// If destination file exists, query user whether to overwrite it.
await this.Controller.CheckOverwriteAsync(
existingBlob,
this.SharedTransferData.TransferJob.Source.Instance,
this.appendBlob);
}
this.Controller.UpdateProgressAddBytesTransferred(0);
if (existingBlob)
{
if (this.appendBlob.Properties.BlobType == BlobType.Unspecified)
{
throw new InvalidOperationException(Resources.FailedToGetBlobTypeException);
}
if (this.appendBlob.Properties.BlobType != BlobType.AppendBlob)
{
throw new InvalidOperationException(Resources.DestinationBlobTypeNotMatch);
}
}
// We do check point consistency validation in reader, so directly use it here.
SingleObjectCheckpoint checkpoint = this.SharedTransferData.TransferJob.CheckPoint;
if ((null != checkpoint.TransferWindow)
&& (checkpoint.TransferWindow.Any()))
{
checkpoint.TransferWindow.Sort();
this.expectedOffset = checkpoint.TransferWindow[0];
}
else
{
this.expectedOffset = checkpoint.EntryTransferOffset;
}
if (0 == this.expectedOffset)
{
this.state = State.Create;
}
else
{
if (!this.Controller.IsForceOverwrite && !existingBlob)
{
throw new TransferException(Resources.DestinationChangedException);
}
this.PreProcessed = true;
if (this.expectedOffset == this.SharedTransferData.TotalLength)
{
this.state = State.Commit;
}
else
{
this.state = State.UploadBlob;
}
}
this.workToken = 1;
}
private async Task CreateAsync()
{
Debug.Assert(State.Create == this.state, "Calling CreateAsync, state should be Create");
if (Interlocked.CompareExchange(ref workToken, 0, 1) == 0)
{
return;
}
AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition(
this.destLocation.AccessCondition,
true);
if (this.destExist)
{
this.CleanupPropertyForCanonicalization();
}
await Utils.ExecuteXsclApiCallAsync(
async () => await this.appendBlob.CreateOrReplaceAsync(
accessCondition,
Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions, true),
Utils.GenerateOperationContext(this.Controller.TransferContext),
this.CancellationToken),
this.CancellationToken);
this.PreProcessed = true;
if (this.expectedOffset == this.SharedTransferData.TotalLength)
{
this.state = State.Commit;
}
else
{
this.state = State.UploadBlob;
}
this.workToken = 1;
}
private async Task UploadBlobAsync()
{
Debug.Assert(State.UploadBlob == this.state, "Calling UploadBlobAsync, state should be UploadBlob");
if (Interlocked.CompareExchange(ref workToken, 0, 1) == 0)
{
return;
}
TransferData transferData = null;
if (!this.SharedTransferData.AvailableData.TryRemove(this.expectedOffset, out transferData))
{
this.workToken = 1;
return;
}
if (null != transferData)
{
using (transferData)
{
long currentOffset = this.expectedOffset;
if (0 != transferData.Length)
{
this.expectedOffset += transferData.Length;
if (transferData.MemoryBuffer.Length == 1)
{
transferData.Stream = new MemoryStream(transferData.MemoryBuffer[0], 0, transferData.Length);
}
else
{
transferData.Stream = new ChunkedMemoryStream(transferData.MemoryBuffer, 0, transferData.Length);
}
AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition, true) ?? new AccessCondition();
accessCondition.IfAppendPositionEqual = currentOffset;
bool needToCheckContent = false;
StorageException catchedStorageException = null;
try
{
await Utils.ExecuteXsclApiCallAsync(
async () => await this.appendBlob.AppendBlockAsync(
transferData.Stream,
null,
accessCondition,
Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions),
Utils.GenerateOperationContext(this.Controller.TransferContext),
this.CancellationToken),
this.CancellationToken);
}
#if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION
catch (Exception e) when (e is StorageException || (e is AggregateException && e.InnerException is StorageException))
{
var se = e as StorageException ?? e.InnerException as StorageException;
#else
catch (StorageException se)
{
#endif
if ((null != se.RequestInformation) &&
((int)HttpStatusCode.PreconditionFailed == se.RequestInformation.HttpStatusCode) &&
(se.RequestInformation.ErrorCode == BlobErrorCodeStrings.InvalidAppendCondition))
{
needToCheckContent = true;
catchedStorageException = se;
}
else
{
throw;
}
}
if (needToCheckContent &&
(!await this.ValidateUploadedChunkAsync(transferData.MemoryBuffer, currentOffset, (long)transferData.Length)))
{
throw new InvalidOperationException(Resources.DestinationChangedException, catchedStorageException);
}
}
this.Controller.UpdateProgress(() =>
{
lock (this.SharedTransferData.TransferJob.CheckPoint.TransferWindowLock)
{
this.SharedTransferData.TransferJob.CheckPoint.TransferWindow.Remove(currentOffset);
}
this.SharedTransferData.TransferJob.Transfer.UpdateJournal();
// update progress
this.Controller.UpdateProgressAddBytesTransferred(transferData.Length);
});
if (this.expectedOffset == this.SharedTransferData.TotalLength)
{
this.state = State.Commit;
}
this.workToken = 1;
}
}
}
/// <summary>
/// Cleanup properties that might cause request canonicalization check failure.
/// </summary>
private void CleanupPropertyForCanonicalization()
{
this.appendBlob.Properties.ContentLanguage = null;
this.appendBlob.Properties.ContentEncoding = null;
}
private async Task CommitAsync()
{
Debug.Assert(State.Commit == this.state, "Calling CommitAsync, state should be Commit");
if (Interlocked.CompareExchange(ref workToken, 0, 1) == 0)
{
return;
}
BlobRequestOptions blobRequestOptions = Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions);
OperationContext operationContext = Utils.GenerateOperationContext(this.Controller.TransferContext);
if (!this.Controller.IsForceOverwrite && !this.destExist)
{
await Utils.ExecuteXsclApiCallAsync(
async () => await this.appendBlob.FetchAttributesAsync(
Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition),
blobRequestOptions,
operationContext,
this.CancellationToken),
this.CancellationToken);
}
var originalMetadata = new Dictionary<string, string>(this.appendBlob.Metadata);
Utils.SetAttributes(this.appendBlob, this.SharedTransferData.Attributes);
await this.Controller.SetCustomAttributesAsync(this.SharedTransferData.TransferJob.Source.Instance, this.appendBlob);
await this.appendBlob.SetPropertiesAsync(
Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition),
blobRequestOptions,
operationContext,
this.CancellationToken);
if (!originalMetadata.DictionaryEquals(this.appendBlob.Metadata))
{
await this.appendBlob.SetMetadataAsync(
Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition),
blobRequestOptions,
operationContext,
this.CancellationToken);
}
this.SetFinish();
}
private async Task<bool> ValidateUploadedChunkAsync(byte[][] currentData, long startOffset, long length)
{
AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition, true);
OperationContext operationContext = Utils.GenerateOperationContext(this.Controller.TransferContext);
await this.appendBlob.FetchAttributesAsync(
accessCondition,
Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions),
operationContext,
this.CancellationToken);
this.destExist = true;
if (this.appendBlob.Properties.Length != (startOffset + length))
{
return false;
}
if (length <= 0)
{
// Nothing to compare
return true;
}
byte[] buffer = new byte[length];
// Do not expect any exception here.
await this.appendBlob.DownloadRangeToByteArrayAsync(
buffer,
0,
startOffset,
length,
accessCondition,
Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions),
operationContext,
this.CancellationToken);
int index = 0;
for (int i = 0; i < currentData.Length; i++)
{
for (int j = 0; j < currentData[i].Length; j++)
{
if (currentData[i][j] != buffer[index++])
{
return false;
}
if (index == length)
{
// Reach to the end and nothing different
return true;
}
}
}
return true;
}
private void SetFinish()
{
this.state = State.Finished;
this.NotifyFinished(null);
this.workToken = 0;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Buffers
{
using System;
using System.Diagnostics.Contracts;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using DotNetty.Common;
using DotNetty.Common.Utilities;
/// <summary>
/// Abstract base class implementation of a <see cref="IByteBuffer"/>
/// </summary>
public abstract class AbstractByteBuffer : IByteBuffer
{
int markedReaderIndex;
int markedWriterIndex;
protected AbstractByteBuffer(int maxCapacity)
{
this.MaxCapacity = maxCapacity;
}
public abstract int Capacity { get; }
public abstract IByteBuffer AdjustCapacity(int newCapacity);
public int MaxCapacity { get; protected set; }
public abstract IByteBufferAllocator Allocator { get; }
public virtual int ReaderIndex { get; protected set; }
public virtual int WriterIndex { get; protected set; }
public virtual IByteBuffer SetWriterIndex(int writerIndex)
{
if (writerIndex < this.ReaderIndex || writerIndex > this.Capacity)
{
throw new IndexOutOfRangeException(string.Format("WriterIndex: {0} (expected: 0 <= readerIndex({1}) <= writerIndex <= capacity ({2})", writerIndex, this.ReaderIndex, this.Capacity));
}
this.WriterIndex = writerIndex;
return this;
}
public virtual IByteBuffer SetReaderIndex(int readerIndex)
{
if (readerIndex < 0 || readerIndex > this.WriterIndex)
{
throw new IndexOutOfRangeException(string.Format("ReaderIndex: {0} (expected: 0 <= readerIndex <= writerIndex({1})", readerIndex, this.WriterIndex));
}
this.ReaderIndex = readerIndex;
return this;
}
public virtual IByteBuffer SetIndex(int readerIndex, int writerIndex)
{
if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > this.Capacity)
{
throw new IndexOutOfRangeException(string.Format("ReaderIndex: {0}, WriterIndex: {1} (expected: 0 <= readerIndex <= writerIndex <= capacity ({2})", readerIndex, writerIndex, this.Capacity));
}
this.ReaderIndex = readerIndex;
this.WriterIndex = writerIndex;
return this;
}
public virtual int ReadableBytes
{
get { return this.WriterIndex - this.ReaderIndex; }
}
public virtual int WritableBytes
{
get { return this.Capacity - this.WriterIndex; }
}
public virtual int MaxWritableBytes
{
get { return this.MaxCapacity - this.WriterIndex; }
}
public bool IsReadable()
{
return this.IsReadable(1);
}
public bool IsReadable(int size)
{
return this.ReadableBytes >= size;
}
public bool IsWritable()
{
return this.IsWritable(1);
}
public bool IsWritable(int size)
{
return this.WritableBytes >= size;
}
public virtual IByteBuffer Clear()
{
this.ReaderIndex = this.WriterIndex = 0;
return this;
}
public virtual IByteBuffer MarkReaderIndex()
{
this.markedReaderIndex = this.ReaderIndex;
return this;
}
public virtual IByteBuffer ResetReaderIndex()
{
this.SetReaderIndex(this.markedReaderIndex);
return this;
}
public virtual IByteBuffer MarkWriterIndex()
{
this.markedWriterIndex = this.WriterIndex;
return this;
}
public virtual IByteBuffer ResetWriterIndex()
{
this.SetWriterIndex(this.markedWriterIndex);
return this;
}
public virtual IByteBuffer DiscardReadBytes()
{
this.EnsureAccessible();
if (this.ReaderIndex == 0)
{
return this;
}
if (this.ReaderIndex != this.WriterIndex)
{
this.SetBytes(0, this, this.ReaderIndex, this.WriterIndex - this.ReaderIndex);
this.WriterIndex -= this.ReaderIndex;
this.AdjustMarkers(this.ReaderIndex);
this.ReaderIndex = 0;
}
else
{
this.AdjustMarkers(this.ReaderIndex);
this.WriterIndex = this.ReaderIndex = 0;
}
return this;
}
public virtual IByteBuffer EnsureWritable(int minWritableBytes)
{
if (minWritableBytes < 0)
{
throw new ArgumentOutOfRangeException("minWritableBytes",
"expected minWritableBytes to be greater than zero");
}
if (minWritableBytes <= this.WritableBytes)
{
return this;
}
if (minWritableBytes > this.MaxCapacity - this.WriterIndex)
{
throw new IndexOutOfRangeException(string.Format(
"writerIndex({0}) + minWritableBytes({1}) exceeds maxCapacity({2}): {3}",
this.WriterIndex, minWritableBytes, this.MaxCapacity, this));
}
//Normalize the current capacity to the power of 2
int newCapacity = this.CalculateNewCapacity(this.WriterIndex + minWritableBytes);
//Adjust to the new capacity
this.AdjustCapacity(newCapacity);
return this;
}
int CalculateNewCapacity(int minNewCapacity)
{
int maxCapacity = this.MaxCapacity;
const int Threshold = 4 * 1024 * 1024; // 4 MiB page
int newCapacity;
if (minNewCapacity == Threshold)
{
return Threshold;
}
// If over threshold, do not double but just increase by threshold.
if (minNewCapacity > Threshold)
{
newCapacity = minNewCapacity - (minNewCapacity % Threshold);
return Math.Min(maxCapacity, newCapacity + Threshold);
}
// Not over threshold. Double up to 4 MiB, starting from 64.
newCapacity = 64;
while (newCapacity < minNewCapacity)
{
newCapacity <<= 1;
}
return Math.Min(newCapacity, maxCapacity);
}
public virtual bool GetBoolean(int index)
{
return this.GetByte(index) != 0;
}
public virtual byte GetByte(int index)
{
this.CheckIndex(index);
return this._GetByte(index);
}
protected abstract byte _GetByte(int index);
public virtual short GetShort(int index)
{
this.CheckIndex(index, 2);
return this._GetShort(index);
}
protected abstract short _GetShort(int index);
public virtual ushort GetUnsignedShort(int index)
{
unchecked
{
return (ushort)(this.GetShort(index));
}
}
public virtual int GetInt(int index)
{
this.CheckIndex(index, 4);
return this._GetInt(index);
}
protected abstract int _GetInt(int index);
public virtual uint GetUnsignedInt(int index)
{
unchecked
{
return (uint)(this.GetInt(index));
}
}
public virtual long GetLong(int index)
{
this.CheckIndex(index, 8);
return this._GetLong(index);
}
protected abstract long _GetLong(int index);
public virtual char GetChar(int index)
{
return Convert.ToChar(this.GetShort(index));
}
public virtual double GetDouble(int index)
{
return BitConverter.Int64BitsToDouble(this.GetLong(index));
}
public virtual IByteBuffer GetBytes(int index, IByteBuffer destination)
{
this.GetBytes(index, destination, destination.WritableBytes);
return this;
}
public virtual IByteBuffer GetBytes(int index, IByteBuffer destination, int length)
{
this.GetBytes(index, destination, destination.WriterIndex, length);
return this;
}
public abstract IByteBuffer GetBytes(int index, IByteBuffer destination, int dstIndex, int length);
public virtual IByteBuffer GetBytes(int index, byte[] destination)
{
this.GetBytes(index, destination, 0, destination.Length);
return this;
}
public abstract IByteBuffer GetBytes(int index, byte[] destination, int dstIndex, int length);
public virtual IByteBuffer SetBoolean(int index, bool value)
{
this.SetByte(index, value ? 1 : 0);
return this;
}
public virtual IByteBuffer SetByte(int index, int value)
{
this.CheckIndex(index);
this._SetByte(index, value);
return this;
}
protected abstract void _SetByte(int index, int value);
public virtual IByteBuffer SetShort(int index, int value)
{
this.CheckIndex(index, 2);
this._SetShort(index, value);
return this;
}
public IByteBuffer SetUnsignedShort(int index, int value)
{
this.SetShort(index, value);
return this;
}
protected abstract void _SetShort(int index, int value);
public virtual IByteBuffer SetInt(int index, int value)
{
this.CheckIndex(index, 4);
this._SetInt(index, value);
return this;
}
public IByteBuffer SetUnsignedInt(int index, uint value)
{
unchecked
{
this.SetInt(index, (int)value);
}
return this;
}
protected abstract void _SetInt(int index, int value);
public virtual IByteBuffer SetLong(int index, long value)
{
this.CheckIndex(index, 8);
this._SetLong(index, value);
return this;
}
protected abstract void _SetLong(int index, long value);
public virtual IByteBuffer SetChar(int index, char value)
{
this.SetShort(index, value);
return this;
}
public virtual IByteBuffer SetDouble(int index, double value)
{
this.SetLong(index, BitConverter.DoubleToInt64Bits(value));
return this;
}
public virtual IByteBuffer SetBytes(int index, IByteBuffer src)
{
this.SetBytes(index, src, src.ReadableBytes);
return this;
}
public virtual IByteBuffer SetBytes(int index, IByteBuffer src, int length)
{
this.CheckIndex(index, length);
if (src == null)
{
throw new NullReferenceException("src cannot be null");
}
if (length > src.ReadableBytes)
{
throw new IndexOutOfRangeException(string.Format(
"length({0}) exceeds src.readableBytes({1}) where src is: {2}", length, src.ReadableBytes, src));
}
this.SetBytes(index, src, src.ReaderIndex, length);
src.SetReaderIndex(src.ReaderIndex + length);
return this;
}
public abstract IByteBuffer SetBytes(int index, IByteBuffer src, int srcIndex, int length);
public virtual IByteBuffer SetBytes(int index, byte[] src)
{
this.SetBytes(index, src, 0, src.Length);
return this;
}
public abstract IByteBuffer SetBytes(int index, byte[] src, int srcIndex, int length);
public virtual bool ReadBoolean()
{
return this.ReadByte() != 0;
}
public virtual byte ReadByte()
{
this.CheckReadableBytes(1);
int i = this.ReaderIndex;
byte b = this.GetByte(i);
this.ReaderIndex = i + 1;
return b;
}
public virtual short ReadShort()
{
this.CheckReadableBytes(2);
short v = this._GetShort(this.ReaderIndex);
this.ReaderIndex += 2;
return v;
}
public virtual ushort ReadUnsignedShort()
{
unchecked
{
return (ushort)(this.ReadShort());
}
}
public virtual int ReadInt()
{
this.CheckReadableBytes(4);
int v = this._GetInt(this.ReaderIndex);
this.ReaderIndex += 4;
return v;
}
public virtual uint ReadUnsignedInt()
{
unchecked
{
return (uint)(this.ReadInt());
}
}
public virtual long ReadLong()
{
this.CheckReadableBytes(8);
long v = this._GetLong(this.ReaderIndex);
this.ReaderIndex += 8;
return v;
}
public virtual char ReadChar()
{
return (char)this.ReadShort();
}
public virtual double ReadDouble()
{
return BitConverter.Int64BitsToDouble(this.ReadLong());
}
public IByteBuffer ReadBytes(int length)
{
this.CheckReadableBytes(length);
if (length == 0)
{
return Unpooled.Empty;
}
IByteBuffer buf = Unpooled.Buffer(length, this.MaxCapacity);
buf.WriteBytes(this, this.ReaderIndex, length);
this.ReaderIndex += length;
return buf;
}
public virtual IByteBuffer ReadBytes(IByteBuffer destination)
{
this.ReadBytes(destination, destination.WritableBytes);
return this;
}
public virtual IByteBuffer ReadBytes(IByteBuffer destination, int length)
{
if (length > destination.WritableBytes)
{
throw new IndexOutOfRangeException(string.Format("length({0}) exceeds destination.WritableBytes({1}) where destination is: {2}",
length, destination.WritableBytes, destination));
}
this.ReadBytes(destination, destination.WriterIndex, length);
destination.SetWriterIndex(destination.WriterIndex + length);
return this;
}
public virtual IByteBuffer ReadBytes(IByteBuffer destination, int dstIndex, int length)
{
this.CheckReadableBytes(length);
this.GetBytes(this.ReaderIndex, destination, dstIndex, length);
this.ReaderIndex += length;
return this;
}
public virtual IByteBuffer ReadBytes(byte[] destination)
{
this.ReadBytes(destination, 0, destination.Length);
return this;
}
public virtual IByteBuffer ReadBytes(byte[] destination, int dstIndex, int length)
{
this.CheckReadableBytes(length);
this.GetBytes(this.ReaderIndex, destination, dstIndex, length);
this.ReaderIndex += length;
return this;
}
public virtual IByteBuffer SkipBytes(int length)
{
this.CheckReadableBytes(length);
int newReaderIndex = this.ReaderIndex + length;
if (newReaderIndex > this.WriterIndex)
{
throw new IndexOutOfRangeException(string.Format(
"length: {0} (expected: readerIndex({1}) + length <= writerIndex({2}))",
length, this.ReaderIndex, this.WriterIndex));
}
this.ReaderIndex = newReaderIndex;
return this;
}
public virtual IByteBuffer WriteBoolean(bool value)
{
this.WriteByte(value ? 1 : 0);
return this;
}
public virtual IByteBuffer WriteByte(int value)
{
this.EnsureWritable(1);
this.SetByte(this.WriterIndex, value);
this.WriterIndex += 1;
return this;
}
public virtual IByteBuffer WriteShort(int value)
{
this.EnsureWritable(2);
this._SetShort(this.WriterIndex, value);
this.WriterIndex += 2;
return this;
}
public IByteBuffer WriteUnsignedShort(int value)
{
unchecked
{
this.WriteShort((short)value);
}
return this;
}
public virtual IByteBuffer WriteInt(int value)
{
this.EnsureWritable(4);
this._SetInt(this.WriterIndex, value);
this.WriterIndex += 4;
return this;
}
public IByteBuffer WriteUnsignedInt(uint value)
{
unchecked
{
this.WriteInt((int)value);
}
return this;
}
public virtual IByteBuffer WriteLong(long value)
{
this.EnsureWritable(8);
this._SetLong(this.WriterIndex, value);
this.WriterIndex += 8;
return this;
}
public virtual IByteBuffer WriteChar(char value)
{
this.WriteShort(value);
return this;
}
public virtual IByteBuffer WriteDouble(double value)
{
this.WriteLong(BitConverter.DoubleToInt64Bits(value));
return this;
}
public virtual IByteBuffer WriteBytes(IByteBuffer src)
{
this.WriteBytes(src, src.ReadableBytes);
return this;
}
public virtual IByteBuffer WriteBytes(IByteBuffer src, int length)
{
if (length > src.ReadableBytes)
{
throw new IndexOutOfRangeException(string.Format("length({0}) exceeds src.readableBytes({1}) where src is: {2}", length, src.ReadableBytes, src));
}
this.WriteBytes(src, src.ReaderIndex, length);
src.SetReaderIndex(src.ReaderIndex + length);
return this;
}
public virtual IByteBuffer WriteBytes(IByteBuffer src, int srcIndex, int length)
{
this.EnsureAccessible();
this.EnsureWritable(length);
this.SetBytes(this.WriterIndex, src, srcIndex, length);
this.WriterIndex += length;
return this;
}
public virtual IByteBuffer WriteBytes(byte[] src)
{
this.WriteBytes(src, 0, src.Length);
return this;
}
public virtual IByteBuffer WriteBytes(byte[] src, int srcIndex, int length)
{
this.EnsureAccessible();
this.EnsureWritable(length);
this.SetBytes(this.WriterIndex, src, srcIndex, length);
this.WriterIndex += length;
return this;
}
public Task<int> WriteBytesAsync(Stream stream, int length, CancellationToken cancellationToken)
{
this.EnsureAccessible();
this.EnsureWritable(length);
if (this.WritableBytes < length)
{
throw new ArgumentOutOfRangeException("length");
}
return this.HasArray && this.Array.Length > 0
? this.WriteBytesToArrayAsync(stream, length, cancellationToken)
: this.WriteBytesThroughBufferAsync(stream, length, cancellationToken);
}
async Task<int> WriteBytesToArrayAsync(Stream stream, int length, CancellationToken cancellationToken)
{
int readTotal = 0;
int read;
int localWriterIndex = this.ArrayOffset + this.WriterIndex;
do
{
read = await stream.ReadAsync(this.Array, localWriterIndex + readTotal, length - readTotal, cancellationToken);
readTotal += read;
}
while (read > 0 && readTotal < length);
this.SetWriterIndex(localWriterIndex + readTotal);
return readTotal;
}
async Task<int> WriteBytesThroughBufferAsync(Stream stream, int length, CancellationToken cancellationToken)
{
int bufferCapacity = Math.Min(64 * 1024, length);
IByteBuffer buffer = Unpooled.Buffer(bufferCapacity);
Contract.Assert(buffer.HasArray);
int readTotal = 0;
int read;
do
{
read = await buffer.WriteBytesAsync(stream, bufferCapacity, cancellationToken);
buffer.ReadBytes(this, read)
.DiscardReadBytes();
}
while (read == bufferCapacity);
return readTotal;
}
public abstract bool HasArray { get; }
public abstract byte[] Array { get; }
public abstract int ArrayOffset { get; }
public virtual byte[] ToArray()
{
if (this.HasArray)
{
return this.Array.Slice(this.ArrayOffset + this.ReaderIndex, this.ReadableBytes);
}
var bytes = new byte[this.ReadableBytes];
this.GetBytes(this.ReaderIndex, bytes);
return bytes;
}
public virtual IByteBuffer Duplicate()
{
return new DuplicatedByteBuffer(this);
}
public abstract IByteBuffer Unwrap();
public virtual ByteOrder Order // todo: push to actual implementations for them to decide
{
get { return ByteOrder.BigEndian; }
}
public IByteBuffer WithOrder(ByteOrder order)
{
if (order == this.Order)
{
return this;
}
throw new NotImplementedException("TODO: bring over SwappedByteBuf");
}
protected void AdjustMarkers(int decrement)
{
int markedReaderIndex = this.markedReaderIndex;
if (markedReaderIndex <= decrement)
{
this.markedReaderIndex = 0;
int markedWriterIndex = this.markedWriterIndex;
if (markedWriterIndex <= decrement)
{
this.markedWriterIndex = 0;
}
else
{
this.markedWriterIndex = markedWriterIndex - decrement;
}
}
else
{
this.markedReaderIndex = markedReaderIndex - decrement;
this.markedWriterIndex -= decrement;
}
}
protected void CheckIndex(int index)
{
this.EnsureAccessible();
if (index < 0 || index >= this.Capacity)
{
throw new IndexOutOfRangeException(string.Format("index: {0} (expected: range(0, {1})", index, this.Capacity));
}
}
protected void CheckIndex(int index, int fieldLength)
{
this.EnsureAccessible();
if (fieldLength < 0)
{
throw new IndexOutOfRangeException(string.Format("length: {0} (expected: >= 0)", fieldLength));
}
if (index < 0 || index > this.Capacity - fieldLength)
{
throw new IndexOutOfRangeException(string.Format("index: {0}, length: {1} (expected: range(0, {2})", index, fieldLength, this.Capacity));
}
}
protected void CheckSrcIndex(int index, int length, int srcIndex, int srcCapacity)
{
this.CheckIndex(index, length);
if (srcIndex < 0 || srcIndex > srcCapacity - length)
{
throw new IndexOutOfRangeException(string.Format(
"srcIndex: {0}, length: {1} (expected: range(0, {2}))", srcIndex, length, srcCapacity));
}
}
protected void CheckDstIndex(int index, int length, int dstIndex, int dstCapacity)
{
this.CheckIndex(index, length);
if (dstIndex < 0 || dstIndex > dstCapacity - length)
{
throw new IndexOutOfRangeException(string.Format(
"dstIndex: {0}, length: {1} (expected: range(0, {2}))", dstIndex, length, dstCapacity));
}
}
/// <summary>
/// Throws a <see cref="IndexOutOfRangeException"/> if the current <see cref="ReadableBytes"/> of this buffer
/// is less than <see cref="minimumReadableBytes"/>.
/// </summary>
protected void CheckReadableBytes(int minimumReadableBytes)
{
this.EnsureAccessible();
if (minimumReadableBytes < 0)
{
throw new ArgumentOutOfRangeException("minimumReadableBytes", string.Format("minimumReadableBytes: {0} (expected: >= 0)", minimumReadableBytes));
}
if (this.ReaderIndex > this.WriterIndex - minimumReadableBytes)
{
throw new IndexOutOfRangeException(string.Format(
"readerIndex({0}) + length({1}) exceeds writerIndex({2}): {3}",
this.ReaderIndex, minimumReadableBytes, this.WriterIndex, this));
}
}
protected void EnsureAccessible()
{
if (this.ReferenceCount == 0)
{
throw new IllegalReferenceCountException(0);
}
}
public IByteBuffer Copy()
{
return this.Copy(this.ReaderIndex, this.ReadableBytes);
}
public abstract IByteBuffer Copy(int index, int length);
public IByteBuffer Slice()
{
return this.Slice(this.ReaderIndex, this.ReadableBytes);
}
public virtual IByteBuffer Slice(int index, int length)
{
return new SlicedByteBuffer(this, index, length);
}
public IByteBuffer ReadSlice(int length)
{
IByteBuffer slice = this.Slice(this.ReaderIndex, length);
this.ReaderIndex += length;
return slice;
}
public Task<int> WriteBytesAsync(Stream stream, int length)
{
return this.WriteBytesAsync(stream, length, CancellationToken.None);
}
public abstract int ReferenceCount { get; }
public abstract IReferenceCounted Retain();
public abstract IReferenceCounted Retain(int increment);
public abstract bool Release();
public abstract bool Release(int decrement);
protected void DiscardMarkers()
{
this.markedReaderIndex = this.markedWriterIndex = 0;
}
}
}
| |
//
// Mono.CSharp CSharpCodeCompiler Class implementation
//
// Authors:
// Sean Kasun (seank@users.sf.net)
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// Copyright (c) Novell, Inc. (http://www.novell.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.
//
//Modified by Richard Kopelow
namespace Modified.CSharp
{
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Linq;
#if NET_2_0
using System.Threading;
using System.Collections.Generic;
#endif
internal class UnityCSharpCodeCompiler : ICodeCompiler
{
static string windowsMcsPath;
static string windowsMonoPath;
#if NET_2_0
Mutex mcsOutMutex;
StringCollection mcsOutput;
#endif
static UnityCSharpCodeCompiler()
{
if (Path.DirectorySeparatorChar == '\\')
{
// default mono install directory
string monoFolderPath = "C:\\Program Files (x86)\\Mono";
if (UnityEngine.Application.isEditor)
{
PropertyInfo property = typeof(Environment).GetProperty("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
MethodInfo getMethod = property.GetGetMethod(true);
monoFolderPath = Path.GetDirectoryName((string)getMethod.Invoke(null, null));
monoFolderPath = monoFolderPath.Substring(0, monoFolderPath.Length - 9);
//windowsMonoPath = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(monoFolderPath)), "bin\\mono.bat");
}
else
{
UnityEngine.Debug.Log(UnityEngine.Application.dataPath);
monoFolderPath = UnityEngine.Application.dataPath+"/StreamingAssets/Mono";
}
windowsMonoPath = Path.Combine(monoFolderPath, "bin\\mono.bat");
if (!File.Exists(windowsMonoPath)) windowsMonoPath = Path.Combine(monoFolderPath, "bin\\mono.exe");
if (!File.Exists(windowsMonoPath))
throw new FileNotFoundException("Windows mono path not found: " + windowsMonoPath);
/*#if NET_4_0
windowsMcsPath =
Path.Combine (p, "4.0\\dmcs.exe");
#elif NET_2_0
*/
windowsMcsPath =
Path.Combine (monoFolderPath, "lib\\mono\\2.0\\gmcs.exe");
/*#else
windowsMcsPath =
Path.Combine(monoFolderPath, "lib\\mono\\4.5\\mcs.exe");
//#endif*/
if (!File.Exists(windowsMcsPath))
throw new FileNotFoundException("Windows mcs path not found: " + windowsMcsPath);
}
}
//
// Constructors
//
public UnityCSharpCodeCompiler()
{
}
#if NET_2_0
public CSharpCodeCompiler (IDictionary <string, string> providerOptions) :
base (providerOptions)
{
}
#endif
//
// Methods
//
public CompilerResults CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit e)
{
return CompileAssemblyFromDomBatch(options, new CodeCompileUnit[] { e });
}
public CompilerResults CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] ea)
{
if (options == null)
{
throw new ArgumentNullException("options");
}
try
{
return CompileFromDomBatch(options, ea);
}
finally
{
options.TempFiles.Delete();
}
}
public CompilerResults CompileAssemblyFromFile(CompilerParameters options, string fileName)
{
return CompileAssemblyFromFileBatch(options, new string[] { fileName });
}
public CompilerResults CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames)
{
if (options == null)
{
throw new ArgumentNullException("options");
}
try
{
return CompileFromFileBatch(options, fileNames);
}
finally
{
options.TempFiles.Delete();
}
}
public CompilerResults CompileAssemblyFromSource(CompilerParameters options, string source)
{
return CompileAssemblyFromSourceBatch(options, new string[] { source });
}
public CompilerResults CompileAssemblyFromSourceBatch(CompilerParameters options, string[] sources)
{
if (options == null)
{
throw new ArgumentNullException("options");
}
try
{
return CompileFromSourceBatch(options, sources);
}
finally
{
options.TempFiles.Delete();
}
}
private CompilerResults CompileFromFileBatch(CompilerParameters options, string[] fileNames)
{
if (null == options)
throw new ArgumentNullException("options");
if (null == fileNames)
throw new ArgumentNullException("fileNames");
CompilerResults results = new CompilerResults(options.TempFiles);
Process mcs = new Process();
#if !NET_2_0
string mcs_output;
string mcs_stdout;
string[] mcsOutput;
#endif
// FIXME: these lines had better be platform independent.
if (Path.DirectorySeparatorChar == '\\')
{
mcs.StartInfo.FileName = windowsMonoPath;
mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " +
#if NET_2_0
BuildArgs (options, fileNames, ProviderOptions);
#else
BuildArgs(options, fileNames);
#endif
}
else
{
#if NET_2_0
// FIXME: This is a temporary hack to make code genaration work in 2.0+
#if NET_4_0
mcs.StartInfo.FileName="dmcs";
#else
mcs.StartInfo.FileName="gmcs";
#endif
mcs.StartInfo.Arguments=BuildArgs(options, fileNames, ProviderOptions);
#else
mcs.StartInfo.FileName = "mcs";
mcs.StartInfo.Arguments = BuildArgs(options, fileNames);
#endif
}
#if NET_2_0
mcsOutput = new StringCollection ();
mcsOutMutex = new Mutex ();
#endif
string monoPath = Environment.GetEnvironmentVariable("MONO_PATH");
if (monoPath == null)
monoPath = String.Empty;
string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
if (privateBinPath != null && privateBinPath.Length > 0)
monoPath = String.Format("{0}:{1}", privateBinPath, monoPath);
if (monoPath.Length > 0)
{
StringDictionary dict = mcs.StartInfo.EnvironmentVariables;
if (dict.ContainsKey("MONO_PATH"))
dict["MONO_PATH"] = monoPath;
else
dict.Add("MONO_PATH", monoPath);
}
mcs.StartInfo.CreateNoWindow = true;
mcs.StartInfo.UseShellExecute = false;
mcs.StartInfo.RedirectStandardOutput = true;
mcs.StartInfo.RedirectStandardError = true;
#if NET_2_0
mcs.ErrorDataReceived += new DataReceivedEventHandler (McsStderrDataReceived);
#endif
try
{
mcs.Start();
}
catch (Exception e)
{
Win32Exception exc = e as Win32Exception;
if (exc != null)
{
/*throw new SystemException(String.Format("Error running {0}: {1}", mcs.StartInfo.FileName,
Win32Exception.W32ErrorMessage(exc.NativeErrorCode)));*/
}
throw;
}
try
{
#if NET_2_0
mcs.BeginOutputReadLine ();
mcs.BeginErrorReadLine ();
#else
// If there are a few kB in stdout, we might lock
mcs_output = mcs.StandardError.ReadToEnd();
mcs_stdout = mcs.StandardOutput.ReadToEnd();
#endif
mcs.WaitForExit();
results.NativeCompilerReturnValue = mcs.ExitCode;
}
finally
{
#if NET_2_0
mcs.CancelErrorRead ();
mcs.CancelOutputRead ();
#endif
mcs.Close();
}
#if NET_2_0
StringCollection sc = mcsOutput;
#else
mcsOutput = mcs_output.Split(System.Environment.NewLine.ToCharArray());
StringCollection sc = new StringCollection();
#endif
bool loadIt = true;
foreach (string error_line in mcsOutput)
{
#if !NET_2_0
sc.Add(error_line);
#endif
CompilerError error = CreateErrorFromString(error_line);
if (error != null)
{
results.Errors.Add(error);
if (!error.IsWarning)
loadIt = false;
}
}
if (sc.Count > 0)
{
sc.Insert(0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);
//results.Output = sc;
}
if (loadIt)
{
if (!File.Exists(options.OutputAssembly))
{
StringBuilder sb = new StringBuilder();
foreach (string s in sc)
sb.Append(s + Environment.NewLine);
throw new Exception("Compiler failed to produce the assembly. Output: '" + sb.ToString() + "'");
}
if (options.GenerateInMemory)
{
using (FileStream fs = File.OpenRead(options.OutputAssembly))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
results.CompiledAssembly = Assembly.Load(buffer, null, options.Evidence);
fs.Close();
}
}
else
{
// Avoid setting CompiledAssembly right now since the output might be a netmodule
results.PathToAssembly = options.OutputAssembly;
}
}
else
{
results.CompiledAssembly = null;
}
return results;
}
#if NET_2_0
void McsStderrDataReceived (object sender, DataReceivedEventArgs args)
{
if (args.Data != null) {
mcsOutMutex.WaitOne ();
mcsOutput.Add (args.Data);
mcsOutMutex.ReleaseMutex ();
}
}
private static string BuildArgs(CompilerParameters options,string[] fileNames, IDictionary <string, string> providerOptions)
#else
private static string BuildArgs(CompilerParameters options, string[] fileNames)
#endif
{
StringBuilder args = new StringBuilder();
if (options.GenerateExecutable)
args.Append("/target:exe ");
else
args.Append("/target:library ");
string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
if (privateBinPath != null && privateBinPath.Length > 0)
args.AppendFormat("/lib:\"{0}\" ", privateBinPath);
if (options.Win32Resource != null)
args.AppendFormat("/win32res:\"{0}\" ",
options.Win32Resource);
if (options.IncludeDebugInformation)
args.Append("/debug+ /optimize- ");
else
args.Append("/debug- /optimize+ ");
if (options.TreatWarningsAsErrors)
args.Append("/warnaserror ");
if (options.WarningLevel >= 0)
args.AppendFormat("/warn:{0} ", options.WarningLevel);
if (options.OutputAssembly == null || options.OutputAssembly.Length == 0)
{
string extension = (options.GenerateExecutable ? "exe" : "dll");
options.OutputAssembly = GetTempFileNameWithExtension(options.TempFiles, extension,
!options.GenerateInMemory);
}
args.AppendFormat("/out:\"{0}\" ", options.OutputAssembly);
string[] mcsDefaultReferencedAssemblies = { "mscorlib.dll", "System.dll", "System.Xml.dll", "System.Core.dll" };
foreach (string import in options.ReferencedAssemblies)
{
if (mcsDefaultReferencedAssemblies.Contains(Path.GetFileName(import)))
continue;
if (import == null || import.Length == 0)
continue;
args.AppendFormat("/r:\"{0}\" ", import);
}
if (options.CompilerOptions != null)
{
args.Append(options.CompilerOptions);
args.Append(" ");
}
#if NET_2_0
foreach (string embeddedResource in options.EmbeddedResources) {
args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
}
foreach (string linkedResource in options.LinkedResources) {
args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
}
if (providerOptions != null && providerOptions.Count > 0) {
string langver;
if (!providerOptions.TryGetValue ("CompilerVersion", out langver))
#if NET_4_0
langver = "3.5";
#else
langver = "2.0";
#endif
if (langver.Length >= 1 && langver [0] == 'v')
langver = langver.Substring (1);
switch (langver) {
case "2.0":
args.Append ("/langversion:ISO-2");
break;
case "3.5":
// current default, omit the switch
break;
}
}
#endif
args.Append(" -- ");
foreach (string source in fileNames)
args.AppendFormat("\"{0}\" ", source);
return args.ToString();
}
private static CompilerError CreateErrorFromString(string error_string)
{
#if NET_2_0
if (error_string.StartsWith ("BETA"))
return null;
#endif
if (error_string == null || error_string == "")
return null;
CompilerError error = new CompilerError();
Regex reg = new Regex(@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*))?\)(:)?\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)",
RegexOptions.Compiled | RegexOptions.ExplicitCapture);
Match match = reg.Match(error_string);
if (!match.Success)
{
// We had some sort of runtime crash
error.ErrorText = error_string;
error.IsWarning = false;
error.ErrorNumber = "";
return error;
}
if (String.Empty != match.Result("${file}"))
error.FileName = match.Result("${file}");
if (String.Empty != match.Result("${line}"))
error.Line = Int32.Parse(match.Result("${line}"));
if (String.Empty != match.Result("${column}"))
error.Column = Int32.Parse(match.Result("${column}"));
string level = match.Result("${level}");
if (level == "warning")
error.IsWarning = true;
else if (level != "error")
return null; // error CS8028 will confuse the regex.
error.ErrorNumber = match.Result("${number}");
error.ErrorText = match.Result("${message}");
return error;
}
private static string GetTempFileNameWithExtension(TempFileCollection temp_files, string extension, bool keepFile)
{
return temp_files.AddExtension(extension, keepFile);
}
private static string GetTempFileNameWithExtension(TempFileCollection temp_files, string extension)
{
return temp_files.AddExtension(extension);
}
private CompilerResults CompileFromDomBatch(CompilerParameters options, CodeCompileUnit[] ea)
{
if (options == null)
{
throw new ArgumentNullException("options");
}
if (ea == null)
{
throw new ArgumentNullException("ea");
}
string[] fileNames = new string[ea.Length];
StringCollection assemblies = options.ReferencedAssemblies;
for (int i = 0; i < ea.Length; i++)
{
CodeCompileUnit compileUnit = ea[i];
fileNames[i] = GetTempFileNameWithExtension(options.TempFiles, i + ".cs");
FileStream f = new FileStream(fileNames[i], FileMode.OpenOrCreate);
StreamWriter s = new StreamWriter(f, Encoding.UTF8);
if (compileUnit.ReferencedAssemblies != null)
{
foreach (string str in compileUnit.ReferencedAssemblies)
{
if (!assemblies.Contains(str))
assemblies.Add(str);
}
}
((ICodeGenerator)this).GenerateCodeFromCompileUnit(compileUnit, s, new CodeGeneratorOptions());
s.Close();
f.Close();
}
return CompileAssemblyFromFileBatch(options, fileNames);
}
private CompilerResults CompileFromSourceBatch(CompilerParameters options, string[] sources)
{
if (options == null)
{
throw new ArgumentNullException("options");
}
if (sources == null)
{
throw new ArgumentNullException("sources");
}
string[] fileNames = new string[sources.Length];
for (int i = 0; i < sources.Length; i++)
{
fileNames[i] = GetTempFileNameWithExtension(options.TempFiles, i + ".cs");
FileStream f = new FileStream(fileNames[i], FileMode.OpenOrCreate);
using (StreamWriter s = new StreamWriter(f, Encoding.UTF8))
{
s.Write(sources[i]);
s.Close();
}
f.Close();
}
return CompileFromFileBatch(options, fileNames);
}
}
}
| |
#region Copyright and License
// Copyright 2010..2014 Alexander Reinert
//
// This file is part of the ARSoft.Tools.Net - C# DNS client/server and SPF Library (http://arsofttoolsnet.codeplex.com/)
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using ARSoft.Tools.Net.Dns.DynamicUpdate;
namespace ARSoft.Tools.Net.Dns
{
/// <summary>
/// Base class for a dns answer
/// </summary>
public abstract class DnsMessageBase
{
protected ushort Flags;
protected internal List<DnsQuestion> Questions = new List<DnsQuestion>();
protected internal List<DnsRecordBase> AnswerRecords = new List<DnsRecordBase>();
protected internal List<DnsRecordBase> AuthorityRecords = new List<DnsRecordBase>();
private List<DnsRecordBase> _additionalRecords = new List<DnsRecordBase>();
/// <summary>
/// Gets or sets the entries in the additional records section
/// </summary>
public List<DnsRecordBase> AdditionalRecords
{
get { return _additionalRecords; }
set { _additionalRecords = (value ?? new List<DnsRecordBase>()); }
}
internal abstract bool IsTcpUsingRequested { get; }
internal abstract bool IsTcpResendingRequested { get; }
internal abstract bool IsTcpNextMessageWaiting(bool isSubsequentResponseMessage);
#region Header
/// <summary>
/// Gets or sets the transaction identifier (ID) of the message
/// </summary>
public ushort TransactionID { get; set; }
/// <summary>
/// Gets or sets the query (QR) flag
/// </summary>
public bool IsQuery
{
get { return (Flags & 0x8000) == 0; }
set
{
if (value)
{
Flags &= 0x7fff;
}
else
{
Flags |= 0x8000;
}
}
}
/// <summary>
/// Gets or sets the Operation Code (OPCODE)
/// </summary>
public OperationCode OperationCode
{
get { return (OperationCode)((Flags & 0x7800) >> 11); }
set
{
ushort clearedOp = (ushort)(Flags & 0x8700);
Flags = (ushort)(clearedOp | (ushort)value << 11);
}
}
/// <summary>
/// Gets or sets the return code (RCODE)
/// </summary>
public ReturnCode ReturnCode
{
get
{
ReturnCode rcode = (ReturnCode)(Flags & 0x000f);
OptRecord ednsOptions = EDnsOptions;
if (ednsOptions == null)
{
return rcode;
}
else
{
return (rcode | ednsOptions.ExtendedReturnCode);
}
}
set
{
OptRecord ednsOptions = EDnsOptions;
if ((ushort)value > 15)
{
if (ednsOptions == null)
{
throw new ArgumentOutOfRangeException("value", "ReturnCodes greater than 15 only allowed in edns messages");
}
else
{
ednsOptions.ExtendedReturnCode = value;
}
}
else
{
if (ednsOptions != null)
{
ednsOptions.ExtendedReturnCode = 0;
}
}
ushort clearedOp = (ushort)(Flags & 0xfff0);
Flags = (ushort)(clearedOp | ((ushort)value & 0x0f));
}
}
#endregion
#region EDNS
/// <summary>
/// Enables or disables EDNS
/// </summary>
public bool IsEDnsEnabled
{
get
{
if (_additionalRecords != null)
{
return _additionalRecords.Any(record => (record.RecordType == RecordType.Opt));
}
else
{
return false;
}
}
set
{
if (value && !IsEDnsEnabled)
{
if (_additionalRecords == null)
{
_additionalRecords = new List<DnsRecordBase>();
}
_additionalRecords.Add(new OptRecord());
}
else if (!value && IsEDnsEnabled)
{
_additionalRecords.RemoveAll(record => (record.RecordType == RecordType.Opt));
}
}
}
/// <summary>
/// Gets or set the OptRecord for the EDNS options
/// </summary>
public OptRecord EDnsOptions
{
get
{
if (_additionalRecords != null)
{
return (OptRecord)_additionalRecords.Find(record => (record.RecordType == RecordType.Opt));
}
else
{
return null;
}
}
set
{
if (value == null)
{
IsEDnsEnabled = false;
}
else if (IsEDnsEnabled)
{
int pos = _additionalRecords.FindIndex(record => (record.RecordType == RecordType.Opt));
_additionalRecords[pos] = value;
}
else
{
if (_additionalRecords == null)
{
_additionalRecords = new List<DnsRecordBase>();
}
_additionalRecords.Add(value);
}
}
}
/// <summary>
/// <para>Gets or sets the DNSSEC answer OK (DO) flag</para>
/// <para>
/// Defined in
/// <see cref="!:http://tools.ietf.org/html/rfc4035">RFC 4035</see>
/// and
/// <see cref="!:http://tools.ietf.org/html/rfc3225">RFC 3225</see>
/// </para>
/// </summary>
public bool IsDnsSecOk
{
get
{
OptRecord ednsOptions = EDnsOptions;
return (ednsOptions != null) && ednsOptions.IsDnsSecOk;
}
set
{
OptRecord ednsOptions = EDnsOptions;
if (ednsOptions == null)
{
if (value)
{
throw new ArgumentOutOfRangeException("value", "Setting DO flag is allowed in edns messages only");
}
}
else
{
ednsOptions.IsDnsSecOk = value;
}
}
}
#endregion
#region TSig
/// <summary>
/// Gets or set the TSigRecord for the tsig signed messages
/// </summary>
public TSigRecord TSigOptions { get; set; }
internal static DnsMessageBase CreateByFlag(byte[] data, DnsServer.SelectTsigKey tsigKeySelector, byte[] originalMac)
{
int flagPosition = 2;
ushort flags = ParseUShort(data, ref flagPosition);
DnsMessageBase res;
switch ((OperationCode)((flags & 0x7800) >> 11))
{
case OperationCode.Update:
res = new DnsUpdateMessage();
break;
default:
res = new DnsMessage();
break;
}
res.ParseInternal(data, tsigKeySelector, originalMac);
return res;
}
internal static TMessage Parse<TMessage>(byte[] data)
where TMessage : DnsMessageBase, new()
{
return Parse<TMessage>(data, null, null);
}
internal static TMessage Parse<TMessage>(byte[] data, DnsServer.SelectTsigKey tsigKeySelector, byte[] originalMac)
where TMessage : DnsMessageBase, new()
{
TMessage result = new TMessage();
result.ParseInternal(data, tsigKeySelector, originalMac);
return result;
}
private void ParseInternal(byte[] data, DnsServer.SelectTsigKey tsigKeySelector, byte[] originalMac)
{
int currentPosition = 0;
TransactionID = ParseUShort(data, ref currentPosition);
Flags = ParseUShort(data, ref currentPosition);
int questionCount = ParseUShort(data, ref currentPosition);
int answerRecordCount = ParseUShort(data, ref currentPosition);
int authorityRecordCount = ParseUShort(data, ref currentPosition);
int additionalRecordCount = ParseUShort(data, ref currentPosition);
ParseQuestions(data, ref currentPosition, questionCount);
ParseSection(data, ref currentPosition, AnswerRecords, answerRecordCount);
ParseSection(data, ref currentPosition, AuthorityRecords, authorityRecordCount);
ParseSection(data, ref currentPosition, _additionalRecords, additionalRecordCount);
if (_additionalRecords.Count > 0)
{
int tSigPos = _additionalRecords.FindIndex(record => (record.RecordType == RecordType.TSig));
if (tSigPos == (_additionalRecords.Count - 1))
{
TSigOptions = (TSigRecord)_additionalRecords[tSigPos];
_additionalRecords.RemoveAt(tSigPos);
TSigOptions.ValidationResult = ValidateTSig(data, tsigKeySelector, originalMac);
}
}
FinishParsing();
}
private ReturnCode ValidateTSig(byte[] resultData, DnsServer.SelectTsigKey tsigKeySelector, byte[] originalMac)
{
byte[] keyData;
if ((TSigOptions.Algorithm == TSigAlgorithm.Unknown) || (tsigKeySelector == null) || ((keyData = tsigKeySelector(TSigOptions.Algorithm, TSigOptions.Name)) == null))
{
return ReturnCode.BadKey;
}
else if (((TSigOptions.TimeSigned - TSigOptions.Fudge) > DateTime.Now) || ((TSigOptions.TimeSigned + TSigOptions.Fudge) < DateTime.Now))
{
return ReturnCode.BadTime;
}
else if ((TSigOptions.Mac == null) || (TSigOptions.Mac.Length == 0))
{
return ReturnCode.BadSig;
}
else
{
TSigOptions.KeyData = keyData;
// maxLength for the buffer to validate: Original (unsigned) dns message and encoded TSigOptions
// because of compression of keyname, the size of the signed message can not be used
int maxLength = TSigOptions.StartPosition + TSigOptions.MaximumLength;
if (originalMac != null)
{
// add length of mac on responses. MacSize not neccessary, this field is allready included in the size of the tsig options
maxLength += originalMac.Length;
}
byte[] validationBuffer = new byte[maxLength];
int currentPosition = 0;
// original mac if neccessary
if ((originalMac != null) && (originalMac.Length > 0))
{
EncodeUShort(validationBuffer, ref currentPosition, (ushort)originalMac.Length);
EncodeByteArray(validationBuffer, ref currentPosition, originalMac);
}
// original unsiged buffer
Buffer.BlockCopy(resultData, 0, validationBuffer, currentPosition, TSigOptions.StartPosition);
// update original transaction id and ar count in message
EncodeUShort(validationBuffer, currentPosition, TSigOptions.OriginalID);
EncodeUShort(validationBuffer, currentPosition + 10, (ushort)_additionalRecords.Count);
currentPosition += TSigOptions.StartPosition;
// TSig Variables
EncodeDomainName(validationBuffer, 0, ref currentPosition, TSigOptions.Name, false, null);
EncodeUShort(validationBuffer, ref currentPosition, (ushort)TSigOptions.RecordClass);
EncodeInt(validationBuffer, ref currentPosition, (ushort)TSigOptions.TimeToLive);
EncodeDomainName(validationBuffer, 0, ref currentPosition, TSigAlgorithmHelper.GetDomainName(TSigOptions.Algorithm), false, null);
TSigRecord.EncodeDateTime(validationBuffer, ref currentPosition, TSigOptions.TimeSigned);
EncodeUShort(validationBuffer, ref currentPosition, (ushort)TSigOptions.Fudge.TotalSeconds);
EncodeUShort(validationBuffer, ref currentPosition, (ushort)TSigOptions.Error);
EncodeUShort(validationBuffer, ref currentPosition, (ushort)TSigOptions.OtherData.Length);
EncodeByteArray(validationBuffer, ref currentPosition, TSigOptions.OtherData);
// Validate MAC
KeyedHashAlgorithm hashAlgorithm = TSigAlgorithmHelper.GetHashAlgorithm(TSigOptions.Algorithm);
hashAlgorithm.Key = keyData;
return (hashAlgorithm.ComputeHash(validationBuffer, 0, currentPosition).SequenceEqual(TSigOptions.Mac)) ? ReturnCode.NoError : ReturnCode.BadSig;
}
}
#endregion
#region Parsing
protected virtual void FinishParsing() { }
#region Methods for parsing answer
private static void ParseSection(byte[] resultData, ref int currentPosition, List<DnsRecordBase> sectionList, int recordCount)
{
for (int i = 0; i < recordCount; i++)
{
sectionList.Add(ParseRecord(resultData, ref currentPosition));
}
}
private static DnsRecordBase ParseRecord(byte[] resultData, ref int currentPosition)
{
int startPosition = currentPosition;
string name = ParseDomainName(resultData, ref currentPosition);
RecordType recordType = (RecordType)ParseUShort(resultData, ref currentPosition);
DnsRecordBase record = DnsRecordBase.Create(recordType, resultData, currentPosition + 6);
record.StartPosition = startPosition;
record.Name = name;
record.RecordType = recordType;
record.RecordClass = (RecordClass)ParseUShort(resultData, ref currentPosition);
record.TimeToLive = ParseInt(resultData, ref currentPosition);
record.RecordDataLength = ParseUShort(resultData, ref currentPosition);
if (record.RecordDataLength > 0)
{
record.ParseRecordData(resultData, currentPosition, record.RecordDataLength);
currentPosition += record.RecordDataLength;
}
return record;
}
private void ParseQuestions(byte[] resultData, ref int currentPosition, int recordCount)
{
for (int i = 0; i < recordCount; i++)
{
DnsQuestion question = new DnsQuestion
{
Name = ParseDomainName(resultData, ref currentPosition),
RecordType = (RecordType)ParseUShort(resultData, ref currentPosition),
RecordClass = (RecordClass)ParseUShort(resultData, ref currentPosition)
};
Questions.Add(question);
}
}
#endregion
#region Helper methods for parsing records
internal static string ParseText(byte[] resultData, ref int currentPosition)
{
int length = resultData[currentPosition++];
return ParseText(resultData, ref currentPosition, length);
}
internal static string ParseText(byte[] resultData, ref int currentPosition, int length)
{
string res = Encoding.ASCII.GetString(resultData, currentPosition, length);
currentPosition += length;
return res;
}
internal static string ParseDomainName(byte[] resultData, ref int currentPosition)
{
int firstLabelLength;
string res = ParseDomainName(resultData, currentPosition, out firstLabelLength);
currentPosition += firstLabelLength;
return res;
}
internal static ushort ParseUShort(byte[] resultData, ref int currentPosition)
{
ushort res;
if (BitConverter.IsLittleEndian)
{
res = (ushort)((resultData[currentPosition++] << 8) | resultData[currentPosition++]);
}
else
{
res = (ushort)(resultData[currentPosition++] | (resultData[currentPosition++] << 8));
}
return res;
}
internal static int ParseInt(byte[] resultData, ref int currentPosition)
{
int res;
if (BitConverter.IsLittleEndian)
{
res = ((resultData[currentPosition++] << 24) | (resultData[currentPosition++] << 16) | (resultData[currentPosition++] << 8) | resultData[currentPosition++]);
}
else
{
res = (resultData[currentPosition++] | (resultData[currentPosition++] << 8) | (resultData[currentPosition++] << 16) | (resultData[currentPosition++] << 24));
}
return res;
}
internal static uint ParseUInt(byte[] resultData, ref int currentPosition)
{
uint res;
if (BitConverter.IsLittleEndian)
{
res = (((uint)resultData[currentPosition++] << 24) | ((uint)resultData[currentPosition++] << 16) | ((uint)resultData[currentPosition++] << 8) | resultData[currentPosition++]);
}
else
{
res = (resultData[currentPosition++] | ((uint)resultData[currentPosition++] << 8) | ((uint)resultData[currentPosition++] << 16) | ((uint)resultData[currentPosition++] << 24));
}
return res;
}
internal static ulong ParseULong(byte[] resultData, ref int currentPosition)
{
ulong res;
if (BitConverter.IsLittleEndian)
{
res = ((ulong)ParseUInt(resultData, ref currentPosition) << 32) | ParseUInt(resultData, ref currentPosition);
}
else
{
res = ParseUInt(resultData, ref currentPosition) | ((ulong)ParseUInt(resultData, ref currentPosition) << 32);
}
return res;
}
private static string ParseDomainName(byte[] resultData, int currentPosition, out int firstLabelBytes)
{
StringBuilder sb = new StringBuilder(64, 255);
bool isInFirstLabel = true;
firstLabelBytes = 0;
while (true) // loop will be ended gracefully or when StringBuilder grows over 255 bytes
{
byte currentByte = resultData[currentPosition++];
if (currentByte == 0)
{
// end of domain, RFC1035
if (isInFirstLabel)
firstLabelBytes += 1;
break;
}
else if (currentByte >= 192)
{
// Pointer, RFC1035
if (isInFirstLabel)
{
firstLabelBytes += 2;
isInFirstLabel = false;
}
int pointer;
if (BitConverter.IsLittleEndian)
{
pointer = (ushort)(((currentByte - 192) << 8) | resultData[currentPosition++]);
}
else
{
pointer = (ushort)((currentByte - 192) | (resultData[currentPosition++] << 8));
}
currentPosition = pointer;
}
else if (currentByte == 65)
{
// binary EDNS label, RFC2673, RFC3363, RFC3364
int length = resultData[currentPosition++];
if (isInFirstLabel)
firstLabelBytes += 1;
if (length == 0)
length = 256;
sb.Append(@"\[x");
string suffix = "/" + length + "]";
do
{
currentByte = resultData[currentPosition++];
if (isInFirstLabel)
firstLabelBytes += 1;
if (length < 8)
{
currentByte &= (byte)(0xff >> (8 - length));
}
sb.Append(currentByte.ToString("x2"));
length = length - 8;
} while (length > 0);
sb.Append(suffix);
}
else if (currentByte >= 64)
{
// extended dns label RFC 2671
throw new NotSupportedException("Unsupported extended dns label");
}
else
{
// append additional text part
if (isInFirstLabel)
firstLabelBytes += 1 + currentByte;
sb.Append(Encoding.ASCII.GetString(resultData, currentPosition, currentByte));
sb.Append(".");
currentPosition += currentByte;
}
}
return (sb.Length == 0) ? String.Empty : sb.ToString(0, sb.Length - 1);
}
internal static byte[] ParseByteData(byte[] resultData, ref int currentPosition, int length)
{
if (length == 0)
{
return new byte[] { };
}
else
{
byte[] res = new byte[length];
Buffer.BlockCopy(resultData, currentPosition, res, 0, length);
currentPosition += length;
return res;
}
}
#endregion
#endregion
#region Serializing
protected virtual void PrepareEncoding() { }
public int Encode(bool addLengthPrefix, out byte[] messageData)
{
byte[] newTSigMac;
return Encode(addLengthPrefix, null, false, out messageData, out newTSigMac);
}
public int Encode(bool addLengthPrefix, out byte[] messageData, bool useCompressionMutation)
{
byte[] newTSigMac;
return Encode(addLengthPrefix, null, false, useCompressionMutation, out messageData, out newTSigMac);
}
public int Encode(bool addLengthPrefix, byte[] originalTsigMac, out byte[] messageData)
{
byte[] newTSigMac;
return Encode(addLengthPrefix, originalTsigMac, false, out messageData, out newTSigMac);
}
public int Encode(bool addLengthPrefix, byte[] originalTsigMac, bool isSubSequentResponse, out byte[] messageData,
out byte[] newTSigMac)
{
return Encode(addLengthPrefix, originalTsigMac, isSubSequentResponse, false, out messageData, out newTSigMac);
}
public int Encode(bool addLengthPrefix, byte[] originalTsigMac, bool isSubSequentResponse, bool useCompressionMutation, out byte[] messageData, out byte[] newTSigMac)
{
PrepareEncoding();
int offset = 0;
int messageOffset = offset;
int maxLength = addLengthPrefix ? 2 : 0;
if (useCompressionMutation)
maxLength++;
originalTsigMac = originalTsigMac ?? new byte[] { };
if (TSigOptions != null)
{
if (!IsQuery)
{
offset += 2 + originalTsigMac.Length;
maxLength += 2 + originalTsigMac.Length;
}
maxLength += TSigOptions.MaximumLength;
}
#region Get Message Length
maxLength += 12;
maxLength += Questions.Sum(question => question.MaximumLength);
maxLength += AnswerRecords.Sum(record => record.MaximumLength);
maxLength += AuthorityRecords.Sum(record => record.MaximumLength);
maxLength += _additionalRecords.Sum(record => record.MaximumLength);
#endregion
messageData = new byte[maxLength];
int currentPosition = offset;
Dictionary<string, ushort> domainNames = new Dictionary<string, ushort>();
EncodeUShort(messageData, ref currentPosition, TransactionID);
EncodeUShort(messageData, ref currentPosition, Flags);
EncodeUShort(messageData, ref currentPosition, (ushort)Questions.Count);
EncodeUShort(messageData, ref currentPosition, (ushort)AnswerRecords.Count);
EncodeUShort(messageData, ref currentPosition, (ushort)AuthorityRecords.Count);
EncodeUShort(messageData, ref currentPosition, (ushort)_additionalRecords.Count);
foreach (DnsQuestion question in Questions)
{
question.Encode(messageData, offset, ref currentPosition, domainNames, useCompressionMutation);
}
foreach (DnsRecordBase record in AnswerRecords)
{
record.Encode(messageData, offset, ref currentPosition, domainNames);
}
foreach (DnsRecordBase record in AuthorityRecords)
{
record.Encode(messageData, offset, ref currentPosition, domainNames);
}
foreach (DnsRecordBase record in _additionalRecords)
{
record.Encode(messageData, offset, ref currentPosition, domainNames);
}
if (TSigOptions == null)
{
newTSigMac = null;
}
else
{
if (!IsQuery)
{
EncodeUShort(messageData, messageOffset, (ushort)originalTsigMac.Length);
Buffer.BlockCopy(originalTsigMac, 0, messageData, messageOffset + 2, originalTsigMac.Length);
}
EncodeUShort(messageData, offset, TSigOptions.OriginalID);
int tsigVariablesPosition = currentPosition;
if (isSubSequentResponse)
{
TSigRecord.EncodeDateTime(messageData, ref tsigVariablesPosition, TSigOptions.TimeSigned);
EncodeUShort(messageData, ref tsigVariablesPosition, (ushort)TSigOptions.Fudge.TotalSeconds);
}
else
{
EncodeDomainName(messageData, offset, ref tsigVariablesPosition, TSigOptions.Name, false, null);
EncodeUShort(messageData, ref tsigVariablesPosition, (ushort)TSigOptions.RecordClass);
EncodeInt(messageData, ref tsigVariablesPosition, (ushort)TSigOptions.TimeToLive);
EncodeDomainName(messageData, offset, ref tsigVariablesPosition, TSigAlgorithmHelper.GetDomainName(TSigOptions.Algorithm), false, null);
TSigRecord.EncodeDateTime(messageData, ref tsigVariablesPosition, TSigOptions.TimeSigned);
EncodeUShort(messageData, ref tsigVariablesPosition, (ushort)TSigOptions.Fudge.TotalSeconds);
EncodeUShort(messageData, ref tsigVariablesPosition, (ushort)TSigOptions.Error);
EncodeUShort(messageData, ref tsigVariablesPosition, (ushort)TSigOptions.OtherData.Length);
EncodeByteArray(messageData, ref tsigVariablesPosition, TSigOptions.OtherData);
}
KeyedHashAlgorithm hashAlgorithm = TSigAlgorithmHelper.GetHashAlgorithm(TSigOptions.Algorithm);
//byte[] mac;
if ((hashAlgorithm != null) && (TSigOptions.KeyData != null) && (TSigOptions.KeyData.Length > 0))
{
hashAlgorithm.Key = TSigOptions.KeyData;
newTSigMac = hashAlgorithm.ComputeHash(messageData, messageOffset, tsigVariablesPosition);
}
else
{
newTSigMac = new byte[] { };
}
EncodeUShort(messageData, offset, TransactionID);
EncodeUShort(messageData, offset + 10, (ushort)(_additionalRecords.Count + 1));
TSigOptions.Encode(messageData, offset, ref currentPosition, domainNames, newTSigMac);
if (!IsQuery)
{
Buffer.BlockCopy(messageData, offset, messageData, messageOffset, (currentPosition - offset));
currentPosition -= (2 + originalTsigMac.Length);
}
}
if (addLengthPrefix)
{
Buffer.BlockCopy(messageData, 0, messageData, 2, currentPosition);
EncodeUShort(messageData, 0, (ushort)(currentPosition));
currentPosition += 2;
}
return currentPosition;
}
internal static void EncodeUShort(byte[] buffer, int currentPosition, ushort value)
{
EncodeUShort(buffer, ref currentPosition, value);
}
internal static void EncodeUShort(byte[] buffer, ref int currentPosition, ushort value)
{
if (BitConverter.IsLittleEndian)
{
buffer[currentPosition++] = (byte)((value >> 8) & 0xff);
buffer[currentPosition++] = (byte)(value & 0xff);
}
else
{
buffer[currentPosition++] = (byte)(value & 0xff);
buffer[currentPosition++] = (byte)((value >> 8) & 0xff);
}
}
internal static void EncodeInt(byte[] buffer, ref int currentPosition, int value)
{
if (BitConverter.IsLittleEndian)
{
buffer[currentPosition++] = (byte)((value >> 24) & 0xff);
buffer[currentPosition++] = (byte)((value >> 16) & 0xff);
buffer[currentPosition++] = (byte)((value >> 8) & 0xff);
buffer[currentPosition++] = (byte)(value & 0xff);
}
else
{
buffer[currentPosition++] = (byte)(value & 0xff);
buffer[currentPosition++] = (byte)((value >> 8) & 0xff);
buffer[currentPosition++] = (byte)((value >> 16) & 0xff);
buffer[currentPosition++] = (byte)((value >> 24) & 0xff);
}
}
internal static void EncodeUInt(byte[] buffer, ref int currentPosition, uint value)
{
if (BitConverter.IsLittleEndian)
{
buffer[currentPosition++] = (byte)((value >> 24) & 0xff);
buffer[currentPosition++] = (byte)((value >> 16) & 0xff);
buffer[currentPosition++] = (byte)((value >> 8) & 0xff);
buffer[currentPosition++] = (byte)(value & 0xff);
}
else
{
buffer[currentPosition++] = (byte)(value & 0xff);
buffer[currentPosition++] = (byte)((value >> 8) & 0xff);
buffer[currentPosition++] = (byte)((value >> 16) & 0xff);
buffer[currentPosition++] = (byte)((value >> 24) & 0xff);
}
}
internal static void EncodeULong(byte[] buffer, ref int currentPosition, ulong value)
{
if (BitConverter.IsLittleEndian)
{
EncodeUInt(buffer, ref currentPosition, (uint)((value >> 32) & 0xffffffff));
EncodeUInt(buffer, ref currentPosition, (uint)(value & 0xffffffff));
}
else
{
EncodeUInt(buffer, ref currentPosition, (uint)(value & 0xffffffff));
EncodeUInt(buffer, ref currentPosition, (uint)((value >> 32) & 0xffffffff));
}
}
internal static void EncodeDomainName(byte[] messageData, int offset, ref int currentPosition, string name,
bool isCompressionAllowed, Dictionary<string, ushort> domainNames)
{
EncodeDomainName(messageData, offset, ref currentPosition, name, isCompressionAllowed, false, domainNames);
}
internal static void EncodeDomainName(byte[] messageData, int offset, ref int currentPosition, string name, bool isCompressionAllowed, bool useCompressionMutation, Dictionary<string, ushort> domainNames)
{
if (String.IsNullOrEmpty(name) || (name == "."))
{
if (useCompressionMutation)
{
messageData[currentPosition++] = 0xc0;
messageData[currentPosition++] = 0x04;
}
else
messageData[currentPosition++] = 0;
return;
}
ushort pointer;
if (isCompressionAllowed && domainNames.TryGetValue(name, out pointer))
{
EncodeUShort(messageData, ref currentPosition, pointer);
return;
}
int labelLength = name.IndexOf('.');
if (labelLength == -1)
labelLength = name.Length;
if (isCompressionAllowed)
domainNames[name] = (ushort)((currentPosition | 0xc000) - offset);
messageData[currentPosition++] = (byte)labelLength;
EncodeByteArray(messageData, ref currentPosition, Encoding.ASCII.GetBytes(name.ToCharArray(0, labelLength)));
EncodeDomainName(messageData, offset, ref currentPosition, labelLength == name.Length ? "." : name.Substring(labelLength + 1), isCompressionAllowed, useCompressionMutation, domainNames);
}
internal static void EncodeTextBlock(byte[] messageData, ref int currentPosition, string text)
{
byte[] textData = Encoding.ASCII.GetBytes(text);
for (int i = 0; i < textData.Length; i += 255)
{
int blockLength = Math.Min(255, (textData.Length - i));
messageData[currentPosition++] = (byte)blockLength;
Buffer.BlockCopy(textData, i, messageData, currentPosition, blockLength);
currentPosition += blockLength;
}
}
internal static void EncodeTextWithoutLength(byte[] messageData, ref int currentPosition, string text)
{
byte[] textData = Encoding.ASCII.GetBytes(text);
Buffer.BlockCopy(textData, 0, messageData, currentPosition, textData.Length);
currentPosition += textData.Length;
}
internal static void EncodeByteArray(byte[] messageData, ref int currentPosition, byte[] data)
{
if (data != null)
{
EncodeByteArray(messageData, ref currentPosition, data, data.Length);
}
}
internal static void EncodeByteArray(byte[] messageData, ref int currentPosition, byte[] data, int length)
{
if ((data != null) && (length > 0))
{
Buffer.BlockCopy(data, 0, messageData, currentPosition, length);
currentPosition += length;
}
}
#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.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
using Xunit.NetCore.Extensions;
namespace System.IO.Ports.Tests
{
public class SerialStream_WriteByte_Generic : PortsTest
{
// Set bounds fore random timeout values.
// If the min is to low write will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
// If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
// If the percentage difference between the expected timeout and the actual timeout
// found through Stopwatch is greater then 10% then the timeout value was not correctly
// to the write method and the testcase fails.
private const double maxPercentageDifference = .15;
private const int NUM_TRYS = 5;
private const byte DEFAULT_BYTE = 0;
#region Test Cases
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying write method throws exception after a call to Cloes()");
com.Open();
Stream serialStream = com.BaseStream;
com.Close();
VerifyWriteException(serialStream, typeof(ObjectDisposedException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterBaseStreamClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying write method throws exception after a call to BaseStream.Close()");
com.Open();
Stream serialStream = com.BaseStream;
com.BaseStream.Close();
VerifyWriteException(serialStream, typeof(ObjectDisposedException));
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Timeout()
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var rndGen = new Random(-55);
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.XOnXOff;
Debug.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout);
com1.Open();
com2.Open();
com2.BaseStream.WriteByte(XOnOff.XOFF);
Thread.Sleep(250);
com2.Close();
VerifyTimeout(com1);
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void SuccessiveReadTimeout()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
var rndGen = new Random(-55);
com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com.Handshake = Handshake.RequestToSendXOnXOff;
// com.Encoding = new System.Text.UTF7Encoding();
com.Encoding = Encoding.Unicode;
Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method",
com.WriteTimeout);
com.Open();
try
{
com.BaseStream.WriteByte(DEFAULT_BYTE);
}
catch (TimeoutException)
{
}
VerifyTimeout(com);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void SuccessiveReadTimeoutWithWriteSucceeding()
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
var rndGen = new Random(-55);
var asyncEnableRts = new AsyncEnableRts();
var t = new Task(asyncEnableRts.EnableRTS);
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.RequestToSend;
com1.Encoding = new UTF8Encoding();
Debug.WriteLine(
"Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before it's timeout",
com1.WriteTimeout);
com1.Open();
// Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed
// before the timeout is reached
t.Start();
TCSupport.WaitForTaskToStart(t);
try
{
com1.BaseStream.WriteByte(DEFAULT_BYTE);
}
catch (TimeoutException)
{
}
asyncEnableRts.Stop();
TCSupport.WaitForTaskCompletion(t);
VerifyTimeout(com1);
}
}
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void BytesToWrite()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying BytesToWrite with one call to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 200;
// Write a random byte[] asynchronously so we can verify some things while the write call is blocking
Task task = Task.Run(() => WriteRandomDataBlock(com, TCSupport.MinimumBlockingByteCount));
TCSupport.WaitForTaskToStart(task);
TCSupport.WaitForWriteBufferToLoad(com, TCSupport.MinimumBlockingByteCount);
// Wait for write method to timeout and complete the task
TCSupport.WaitForTaskCompletion(task);
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void BytesToWriteSuccessive()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying BytesToWrite with successive calls to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 4000;
int blockLength = TCSupport.MinimumBlockingByteCount;
// Write a random byte[] asynchronously so we can verify some things while the write call is blocking
Task t1 = Task.Run(() => WriteRandomDataBlock(com, blockLength));
TCSupport.WaitForTaskToStart(t1);
TCSupport.WaitForWriteBufferToLoad(com, blockLength);
// Write a random byte[] asynchronously so we can verify some things while the write call is blocking
Task t2 = Task.Run(() => WriteRandomDataBlock(com, blockLength));
TCSupport.WaitForTaskToStart(t2);
TCSupport.WaitForWriteBufferToLoad(com, blockLength * 2);
// Wait for both write methods to timeout
TCSupport.WaitForTaskCompletion(t1);
TCSupport.WaitForTaskCompletion(t2);
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Handshake_None()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying Handshake=None");
com.Open();
// Write a random byte[] asynchronously so we can verify some things while the write call is blocking
Task task = Task.Run(() => WriteRandomDataBlock(com, TCSupport.MinimumBlockingByteCount));
TCSupport.WaitForTaskToStart(task);
// Wait for write methods to complete
TCSupport.WaitForTaskCompletion(task);
Assert.Equal(0, com.BytesToWrite);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Handshake_RequestToSend()
{
Verify_Handshake(Handshake.RequestToSend);
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_XOnXOff()
{
Verify_Handshake(Handshake.XOnXOff);
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Handshake_RequestToSendXOnXOff()
{
Verify_Handshake(Handshake.RequestToSendXOnXOff);
}
private class AsyncEnableRts
{
private bool _stop;
public void EnableRTS()
{
lock (this)
{
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var rndGen = new Random(-55);
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
// Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.RtsEnable = true;
while (!_stop)
Monitor.Wait(this);
com2.RtsEnable = false;
}
}
}
public void Stop()
{
lock (this)
{
_stop = true;
Monitor.Pulse(this);
}
}
}
#endregion
#region Verification for Test Cases
private static void VerifyWriteException(Stream serialStream, Type expectedException)
{
Assert.Throws(expectedException, () => serialStream.WriteByte(DEFAULT_BYTE));
}
private void VerifyTimeout(SerialPort com)
{
var timer = new Stopwatch();
int expectedTime = com.WriteTimeout;
var actualTime = 0;
double percentageDifference;
try
{
com.BaseStream.WriteByte(DEFAULT_BYTE); // Warm up write method
}
catch (TimeoutException) { }
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (var i = 0; i < NUM_TRYS; i++)
{
timer.Start();
try
{
com.BaseStream.WriteByte(DEFAULT_BYTE);
}
catch (TimeoutException)
{
}
timer.Stop();
actualTime += (int)timer.ElapsedMilliseconds;
timer.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime);
// Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference
if (maxPercentageDifference < percentageDifference)
{
Fail("ERROR!!!: The write method timed-out in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference);
}
}
private void Verify_Handshake(Handshake handshake)
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Debug.WriteLine("Verifying Handshake={0}", handshake);
com1.Handshake = handshake;
com1.Open();
com2.Open();
// Setup to ensure write will bock with type of handshake method being used
if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.RtsEnable = false;
}
if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.BaseStream.WriteByte(XOnOff.XOFF);
Thread.Sleep(250);
}
// Write a block of random data asynchronously so we can verify some things while the write call is blocking
Task task = Task.Run(() => WriteRandomDataBlock(com1, TCSupport.MinimumBlockingByteCount));
TCSupport.WaitForTaskToStart(task);
TCSupport.WaitForWriteBufferToLoad(com1, TCSupport.MinimumBlockingByteCount);
// Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used
if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) &&
com1.CtsHolding)
{
Fail("ERROR!!! Expected CtsHolding={0} actual {1}", false, com1.CtsHolding);
}
// Setup to ensure write will succeed
if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.RtsEnable = true;
}
if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.BaseStream.WriteByte(XOnOff.XON);
}
// Wait till write finishes
TCSupport.WaitForTaskCompletion(task);
// Verify that the correct number of bytes are in the buffer
// (There should be nothing because it's all been transmitted after the flow control was released)
Assert.Equal(0, com1.BytesToWrite);
// Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used
if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) &&
!com1.CtsHolding)
{
Fail("ERROR!!! Expected CtsHolding={0} actual {1}", true, com1.CtsHolding);
}
}
}
private static void WriteRandomDataBlock(SerialPort com, int blockLength)
{
var rndGen = new Random(-55);
byte[] randomData = new byte[blockLength];
rndGen.NextBytes(randomData);
try
{
com.BaseStream.Write(randomData, 0, randomData.Length);
}
catch (TimeoutException)
{
}
}
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestRunnerInterop;
namespace ReplWindowUITestsRunner {
[TestClass, Ignore]
public abstract class ReplWindowAdvancedUITests {
#region UI test boilerplate
public VsTestInvoker _vs => new VsTestInvoker(
VsTestContext.Instance,
// Remote container (DLL) name
"Microsoft.PythonTools.Tests.ReplWindowUITests",
// Remote class name
$"ReplWindowUITests.{nameof(ReplWindowUITests)}"
);
public TestContext TestContext { get; set; }
[TestInitialize]
public void TestInitialize() => VsTestContext.Instance.TestInitialize(TestContext.DeploymentDirectory);
[TestCleanup]
public void TestCleanup() => VsTestContext.Instance.TestCleanup();
[ClassCleanup]
public static void ClassCleanup() => VsTestContext.Instance.Dispose();
#endregion
protected abstract string Interpreter { get; }
#region Advanced Miscellaneous tests
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void ClearInputHelper() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.ClearInputHelper), Interpreter);
}
#endregion
#region Advanced Signature Help tests
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void SimpleSignatureHelp() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.SimpleSignatureHelp), Interpreter);
}
[Ignore] // https://github.com/Microsoft/PTVS/issues/2689
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void SignatureHelpDefaultValue() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.SignatureHelpDefaultValue), Interpreter);
}
#endregion
#region Advanced Completion tests
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void SimpleCompletion() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.SimpleCompletion), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void SimpleCompletionSpaceNoCompletion() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.SimpleCompletionSpaceNoCompletion), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void CompletionWrongText() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CompletionWrongText), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void CompletionFullTextWithoutNewLine() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CompletionFullTextWithoutNewLine), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void CompletionFullTextWithNewLine() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CompletionFullTextWithNewLine), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void AutoListIdentifierCompletions() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.AutoListIdentifierCompletions), Interpreter);
}
#endregion
#region Advanced Input/Output redirection tests
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void TestStdOutRedirected() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.TestStdOutRedirected), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void TestRawInput() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.TestRawInput), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void OnlyTypeInRawInput() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.OnlyTypeInRawInput), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void DeleteCharactersInRawInput() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.DeleteCharactersInRawInput), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void TestIndirectInput() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.TestIndirectInput), Interpreter);
}
#endregion
#region Advanced Keyboard tests
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void EnterInMiddleOfLine() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.EnterInMiddleOfLine), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void LineBreak() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.LineBreak), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void LineBreakInMiddleOfLine() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.LineBreakInMiddleOfLine), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void CtrlEnterCommits() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CtrlEnterCommits), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void EscapeClearsMultipleLines() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.EscapeClearsMultipleLines), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void CtrlEnterOnPreviousInput() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CtrlEnterOnPreviousInput), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void CtrlEnterForceCommit() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CtrlEnterForceCommit), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void CtrlEnterMultiLineForceCommit() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CtrlEnterMultiLineForceCommit), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void BackspacePrompt() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.BackspacePrompt), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void BackspaceSmartDedent() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.BackspaceSmartDedent), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void BackspaceSecondaryPrompt() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.BackspaceSecondaryPrompt), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void BackspaceSecondaryPromptSelected() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.BackspaceSecondaryPromptSelected), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void DeleteSecondaryPromptSelected() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.DeleteSecondaryPromptSelected), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void EditTypeSecondaryPromptSelected() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.EditTypeSecondaryPromptSelected), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void TestDelNoTextSelected() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.TestDelNoTextSelected), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void TestDelAtEndOfLine() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.TestDelAtEndOfLine), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void TestDelAtEndOfBuffer() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.TestDelAtEndOfBuffer), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void TestDelInOutput() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.TestDelInOutput), Interpreter);
}
#endregion
#region Advanced Cancel tests
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void CtrlBreakInterrupts() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CtrlBreakInterrupts), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void CtrlBreakInterruptsLongRunning() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CtrlBreakInterruptsLongRunning), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void CtrlBreakNotRunning() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CtrlBreakNotRunning), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void CursorWhileCodeIsRunning() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CursorWhileCodeIsRunning), Interpreter);
}
#endregion
#region Advanced History tests
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void HistoryUpdateDef() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.HistoryUpdateDef), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Interactive")]
[TestCategory("Installed")]
public void HistoryAppendDef() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.HistoryAppendDef), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void HistoryBackForward() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.HistoryBackForward), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void HistoryMaximumLength() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.HistoryMaximumLength), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void HistoryUncommittedInput1() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.HistoryUncommittedInput1), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void HistoryUncommittedInput2() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.HistoryUncommittedInput2), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void HistorySearch() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.HistorySearch), Interpreter);
}
#endregion
#region Advanced Clipboard tests
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void CommentPaste() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CommentPaste), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void CsvPaste() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CsvPaste), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void EditCutIncludingPrompt() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.EditCutIncludingPrompt), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void EditPasteSecondaryPromptSelected() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.EditPasteSecondaryPromptSelected), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void EditPasteSecondaryPromptSelectedInPromptMargin() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.EditPasteSecondaryPromptSelectedInPromptMargin), Interpreter);
}
#endregion
#region Advanced Command tests
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void ReplCommandUnknown() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.ReplCommandUnknown), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void ReplCommandComment() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.ReplCommandComment), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void ClearScreenCommand() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.ClearScreenCommand), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void ReplCommandHelp() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.ReplCommandHelp), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void CommandsLoadScript() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CommandsLoadScript), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void CommandsLoadScriptWithQuotes() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CommandsLoadScriptWithQuotes), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void CommandsLoadScriptWithClass() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CommandsLoadScriptWithClass), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void CommandsLoadScriptMultipleSubmissions() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CommandsLoadScriptMultipleSubmissions), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void CommandsLoadScriptMultipleSubmissionsWithClearScreen() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.CommandsLoadScriptMultipleSubmissionsWithClearScreen), Interpreter);
}
#endregion
#region Advanced Insert Code tests
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void InsertCode() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.InsertCode), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void InsertCodeWhileRunning() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.InsertCodeWhileRunning), Interpreter);
}
#endregion
#region Advanced Launch Configuration Tests
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void PythonPathIgnored() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.PythonPathIgnored), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void PythonPathNotIgnored() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.PythonPathNotIgnored), Interpreter);
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void PythonPathNotIgnoredButMissing() {
_vs.RunTest(nameof(ReplWindowUITests.ReplWindowUITests.PythonPathNotIgnoredButMissing), Interpreter);
}
#endregion
}
[TestClass]
public class ReplWindowAdvancedUITests27 : ReplWindowAdvancedUITests {
protected override string Interpreter => "Python27|Python27_x64";
}
}
| |
using System;
using Bridge.Contract;
using Bridge.Contract.Constants;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.Resolver;
namespace Bridge.Translator
{
public class FieldBlock : AbstractEmitterBlock
{
public FieldBlock(IEmitter emitter, ITypeInfo typeInfo, bool staticBlock, bool fieldsOnly, bool isObjectLiteral = false)
: base(emitter, typeInfo.TypeDeclaration)
{
this.Emitter = emitter;
this.TypeInfo = typeInfo;
this.StaticBlock = staticBlock;
this.FieldsOnly = fieldsOnly;
this.Injectors = new List<string>();
this.IsObjectLiteral = isObjectLiteral;
this.ClearTempVariables = true;
}
public bool IsObjectLiteral
{
get;
set;
}
public ITypeInfo TypeInfo
{
get;
set;
}
public bool StaticBlock
{
get;
set;
}
public bool FieldsOnly
{
get;
set;
}
public List<string> Injectors
{
get;
private set;
}
public int BeginCounter
{
get;
private set;
}
public bool WasEmitted
{
get;
private set;
}
public bool ClearTempVariables
{
get; set;
}
protected override void DoEmit()
{
if (this.Emitter.TempVariables != null && this.ClearTempVariables)
{
this.Emitter.TempVariables = new Dictionary<string, bool>();
}
this.EmitFields(this.StaticBlock ? this.TypeInfo.StaticConfig : this.TypeInfo.InstanceConfig);
/*if (this.Injectors.Count > 0 && this.Emitter.TempVariables != null && this.Emitter.TempVariables.Count > 0)
{
var writer = this.SaveWriter();
this.NewWriter();
this.SimpleEmitTempVars(false);
this.Injectors.Insert(0, this.Emitter.Output.ToString());
this.Emitter.TempVariables.Clear();
this.RestoreWriter(writer);
}*/
}
protected virtual void EmitFields(TypeConfigInfo info)
{
if (this.FieldsOnly || this.IsObjectLiteral)
{
if (info.Fields.Count > 0)
{
var hasFields = this.WriteObject(JS.Fields.FIELDS, info.Fields.Where(f => f.IsConst).Concat(info.Fields.Where(f => !f.IsConst)).ToList(), "this.{0} = {1};", "this[{0}] = {1};");
if (hasFields)
{
this.Emitter.Comma = true;
this.WasEmitted = true;
}
}
if (!this.IsObjectLiteral)
{
return;
}
}
if (info.Events.Count > 0 && !this.IsObjectLiteral)
{
var hasProperties = this.WriteObject(JS.Fields.EVENTS, info.Events, JS.Funcs.BRIDGE_EVENT + "(this, \"{0}\", {1});", JS.Funcs.BRIDGE_EVENT + "(this, {0}, {1});");
if (hasProperties)
{
this.Emitter.Comma = true;
this.WasEmitted = true;
}
}
if (info.Properties.Count > 0)
{
var hasProperties = this.WriteObject(JS.Fields.PROPERTIES, info.Properties, "this.{0} = {1};", "this[{0}] = {1};");
if (hasProperties)
{
this.Emitter.Comma = true;
this.WasEmitted = true;
}
}
if (info.Alias.Count > 0 && !this.IsObjectLiteral)
{
this.WriteAlias("alias", info.Alias);
this.Emitter.Comma = true;
}
}
protected virtual bool WriteObject(string objectName, List<TypeConfigItem> members, string format, string interfaceFormat)
{
bool hasProperties = this.HasProperties(objectName, members);
int pos = 0;
IWriterInfo writer = null;
bool beginBlock = false;
if (hasProperties && objectName != null && !this.IsObjectLiteral)
{
beginBlock = true;
pos = this.Emitter.Output.Length;
writer = this.SaveWriter();
this.EnsureComma();
this.Write(objectName);
this.WriteColon();
this.BeginBlock();
}
bool isProperty = JS.Fields.PROPERTIES == objectName;
bool isField = JS.Fields.FIELDS == objectName;
int count = 0;
foreach (var member in members)
{
object constValue = null;
bool isPrimitive = false;
var primitiveExpr = member.Initializer as PrimitiveExpression;
bool write = false;
bool writeScript = false;
if (primitiveExpr != null)
{
//isPrimitive = true;
constValue = primitiveExpr.Value;
ResolveResult rr = null;
if (member.VarInitializer != null)
{
rr = this.Emitter.Resolver.ResolveNode(member.VarInitializer, this.Emitter);
}
else
{
rr = this.Emitter.Resolver.ResolveNode(member.Entity, this.Emitter);
}
if (rr != null && rr.Type.Kind == TypeKind.Enum)
{
constValue = Helpers.GetEnumValue(this.Emitter, rr.Type, constValue);
writeScript = true;
}
}
if (constValue is RawValue)
{
constValue = constValue.ToString();
write = true;
writeScript = false;
}
var isNull = member.Initializer.IsNull || member.Initializer is NullReferenceExpression || member.Initializer.Parent == null;
if (!isNull && !isPrimitive)
{
var constrr = this.Emitter.Resolver.ResolveNode(member.Initializer, this.Emitter);
if (constrr != null && constrr.IsCompileTimeConstant)
{
//isPrimitive = true;
constValue = constrr.ConstantValue;
var expectedType = this.Emitter.Resolver.Resolver.GetExpectedType(member.Initializer);
if (!expectedType.Equals(constrr.Type) && expectedType.Kind != TypeKind.Dynamic)
{
try
{
constValue = Convert.ChangeType(constValue, ReflectionHelper.GetTypeCode(expectedType));
}
catch (Exception)
{
this.Emitter.Log.Warn($"FieldBlock: Convert.ChangeType is failed. Value type: {constrr.Type.FullName}, Target type: {expectedType.FullName}");
}
}
if (constrr.Type.Kind == TypeKind.Enum)
{
constValue = Helpers.GetEnumValue(this.Emitter, constrr.Type, constrr.ConstantValue);
}
writeScript = true;
}
}
var isNullable = false;
if (isPrimitive && constValue is AstType)
{
var itype = this.Emitter.Resolver.ResolveNode((AstType)constValue, this.Emitter);
if (NullableType.IsNullable(itype.Type))
{
isNullable = true;
}
}
string tpl = null;
IMember templateMember = null;
MemberResolveResult init_rr = null;
if (isField && member.VarInitializer != null)
{
init_rr = this.Emitter.Resolver.ResolveNode(member.VarInitializer, this.Emitter) as MemberResolveResult;
tpl = init_rr != null ? this.Emitter.GetInline(init_rr.Member) : null;
if (tpl != null)
{
templateMember = init_rr.Member;
}
}
bool isAutoProperty = false;
if (isProperty)
{
var member_rr = this.Emitter.Resolver.ResolveNode(member.Entity, this.Emitter) as MemberResolveResult;
var property = (IProperty)member_rr.Member;
isAutoProperty = Helpers.IsAutoProperty(property);
}
bool written = false;
if (!isNull && (!isPrimitive || constValue is AstType || tpl != null) && !(isProperty && !IsObjectLiteral && !isAutoProperty))
{
string value = null;
bool needContinue = false;
string defValue = "";
if (!isPrimitive)
{
var oldWriter = this.SaveWriter();
this.NewWriter();
member.Initializer.AcceptVisitor(this.Emitter);
value = this.Emitter.Output.ToString();
this.RestoreWriter(oldWriter);
ResolveResult rr = null;
AstType astType = null;
if (member.VarInitializer != null)
{
rr = this.Emitter.Resolver.ResolveNode(member.VarInitializer, this.Emitter);
}
else
{
astType = member.Entity.ReturnType;
rr = this.Emitter.Resolver.ResolveNode(member.Entity, this.Emitter);
}
constValue = Inspector.GetDefaultFieldValue(rr.Type, astType);
if (rr.Type.Kind == TypeKind.Enum)
{
constValue = Helpers.GetEnumValue(this.Emitter, rr.Type, constValue);
}
isNullable = NullableType.IsNullable(rr.Type);
needContinue = constValue is IType;
writeScript = true;
/*if (needContinue && !(member.Initializer is ObjectCreateExpression))
{
defValue = " || " + Inspector.GetStructDefaultValue((IType)constValue, this.Emitter);
}*/
}
else if (constValue is AstType)
{
value = isNullable
? "null"
: Inspector.GetStructDefaultValue((AstType)constValue, this.Emitter);
constValue = value;
write = true;
needContinue = !isProperty && !isNullable;
}
var name = member.GetName(this.Emitter);
bool isValidIdentifier = Helpers.IsValidIdentifier(name);
if (isProperty && isPrimitive)
{
constValue = "null";
if (this.IsObjectLiteral)
{
written = true;
if (isValidIdentifier)
{
this.Write(string.Format("this.{0} = {1};", name, value));
}
else
{
this.Write(string.Format("this[{0}] = {1};", AbstractEmitterBlock.ToJavaScript(name, this.Emitter), value));
}
this.WriteNewLine();
}
else
{
this.Injectors.Add(string.Format(name.StartsWith("\"") || !isValidIdentifier ? "this[{0}] = {1};" : "this.{0} = {1};", isValidIdentifier ? name : AbstractEmitterBlock.ToJavaScript(name, this.Emitter), value));
}
}
else
{
if (this.IsObjectLiteral)
{
written = true;
if (isValidIdentifier)
{
this.Write(string.Format("this.{0} = {1};", name, value + defValue));
}
else
{
this.Write(string.Format("this[{0}] = {1};", AbstractEmitterBlock.ToJavaScript(name, this.Emitter), value + defValue));
}
this.WriteNewLine();
}
else if (tpl != null)
{
if (!tpl.Contains("{0}"))
{
tpl = tpl + " = {0};";
}
string v = null;
if (!isNull && (!isPrimitive || constValue is AstType))
{
v = value + defValue;
}
else
{
if (write)
{
v = constValue != null ? constValue.ToString() : "";
}
else if (writeScript)
{
v = AbstractEmitterBlock.ToJavaScript(constValue, this.Emitter);
}
else
{
var oldWriter = this.SaveWriter();
this.NewWriter();
member.Initializer.AcceptVisitor(this.Emitter);
v = this.Emitter.Output.ToString();
this.RestoreWriter(oldWriter);
}
}
tpl = Helpers.ConvertTokens(this.Emitter, tpl, templateMember);
tpl = tpl.Replace("{this}", "this").Replace("{0}", v);
if (!tpl.EndsWith(";"))
{
tpl += ";";
}
this.Injectors.Add(tpl);
}
else
{
var rr = this.Emitter.Resolver.ResolveNode(member.Initializer, this.Emitter) as CSharpInvocationResolveResult;
bool isDefaultInstance = rr != null &&
rr.Member.SymbolKind == SymbolKind.Constructor &&
rr.Arguments.Count == 0 &&
rr.InitializerStatements.Count == 0 &&
rr.Type.Kind == TypeKind.Struct;
if (!isDefaultInstance)
{
if (isField && !isValidIdentifier)
{
this.Injectors.Add(string.Format("this[{0}] = {1};", name.StartsWith("\"") ? name : AbstractEmitterBlock.ToJavaScript(name, this.Emitter), value + defValue));
}
else
{
this.Injectors.Add(string.Format(name.StartsWith("\"") ? interfaceFormat : format, name, value + defValue));
}
}
}
}
}
count++;
if (written)
{
continue;
}
bool withoutTypeParams = true;
MemberResolveResult m_rr = null;
if (member.Entity != null)
{
m_rr = this.Emitter.Resolver.ResolveNode(member.Entity, this.Emitter) as MemberResolveResult;
if (m_rr != null)
{
withoutTypeParams = OverloadsCollection.ExcludeTypeParameterForDefinition(m_rr);
}
}
var mname = member.GetName(this.Emitter, withoutTypeParams);
if (this.TypeInfo.IsEnum && m_rr != null)
{
mname = this.Emitter.GetEntityName(m_rr.Member);
}
bool isValid = Helpers.IsValidIdentifier(mname);
if (!isValid)
{
if (this.IsObjectLiteral)
{
mname = "[" + AbstractEmitterBlock.ToJavaScript(mname, this.Emitter) + "]";
}
else
{
mname = AbstractEmitterBlock.ToJavaScript(mname, this.Emitter);
}
}
if (this.IsObjectLiteral)
{
this.WriteThis();
if (isValid)
{
this.WriteDot();
}
this.Write(mname);
this.Write(" = ");
}
else
{
this.EnsureComma();
XmlToJsDoc.EmitComment(this, member.Entity, null, member.Entity is FieldDeclaration ? member.VarInitializer : null);
this.Write(mname);
this.WriteColon();
}
bool close = false;
if (isProperty && !IsObjectLiteral && !isAutoProperty)
{
var oldTempVars = this.Emitter.TempVariables;
this.BeginBlock();
new VisitorPropertyBlock(this.Emitter, (PropertyDeclaration)member.Entity).Emit();
this.WriteNewLine();
this.EndBlock();
this.Emitter.Comma = true;
this.Emitter.TempVariables = oldTempVars;
continue;
}
if (constValue is AstType || constValue is IType)
{
this.Write("null");
if (!isNullable)
{
var name = member.GetName(this.Emitter);
bool isValidIdentifier = Helpers.IsValidIdentifier(name);
var value = constValue is AstType ? Inspector.GetStructDefaultValue((AstType)constValue, this.Emitter) : Inspector.GetStructDefaultValue((IType)constValue, this.Emitter);
if (!isValidIdentifier)
{
this.Injectors.Insert(BeginCounter++, string.Format("this[{0}] = {1};", name.StartsWith("\"") ? name : AbstractEmitterBlock.ToJavaScript(name, this.Emitter), value));
}
else
{
this.Injectors.Insert(BeginCounter++, string.Format(name.StartsWith("\"") ? interfaceFormat : format, name, value));
}
}
}
else if (write)
{
this.Write(constValue);
}
else if (writeScript)
{
this.WriteScript(constValue);
}
else
{
member.Initializer.AcceptVisitor(this.Emitter);
}
if (close)
{
this.Write(" }");
}
if (this.IsObjectLiteral)
{
this.WriteSemiColon(true);
}
this.Emitter.Comma = true;
}
if (count > 0 && objectName != null && !IsObjectLiteral)
{
this.WriteNewLine();
this.EndBlock();
}
else if (beginBlock)
{
this.Emitter.IsNewLine = writer.IsNewLine;
this.Emitter.ResetLevel(writer.Level);
this.Emitter.Comma = writer.Comma;
this.Emitter.Output.Length = pos;
}
return count > 0;
}
protected virtual bool HasProperties(string objectName, List<TypeConfigItem> members)
{
foreach (var member in members)
{
object constValue = null;
bool isPrimitive = false;
var primitiveExpr = member.Initializer as PrimitiveExpression;
if (primitiveExpr != null)
{
isPrimitive = true;
constValue = primitiveExpr.Value;
}
var isNull = member.Initializer.IsNull || member.Initializer is NullReferenceExpression;
if (!isNull && !isPrimitive)
{
var constrr = this.Emitter.Resolver.ResolveNode(member.Initializer, this.Emitter) as ConstantResolveResult;
if (constrr != null)
{
isPrimitive = true;
constValue = constrr.ConstantValue;
}
}
if (isNull)
{
return true;
}
if (objectName != JS.Fields.PROPERTIES && objectName != JS.Fields.FIELDS && objectName != JS.Fields.EVENTS)
{
if (!isPrimitive || constValue is AstType)
{
continue;
}
}
return true;
}
return false;
}
protected virtual void WriteAlias(string objectName, List<TypeConfigItem> members)
{
int pos = this.Emitter.Output.Length;
bool oldComma = this.Emitter.Comma;
bool oldNewLine = this.Emitter.IsNewLine;
bool nonEmpty = false;
var changedIndenting = false;
bool newLine = members.Count > 1;
if (objectName != null)
{
this.EnsureComma();
this.Write(objectName);
this.WriteColon();
this.WriteOpenBracket();
if (newLine)
{
this.WriteNewLine();
this.Indent();
changedIndenting = true;
}
}
foreach (var member in members)
{
if (member.DerivedMember != null)
{
if (this.EmitMemberAlias(member.DerivedMember, member.InterfaceMember))
{
nonEmpty = true;
}
continue;
}
var rr = Emitter.Resolver.ResolveNode(member.Entity, Emitter) as MemberResolveResult;
if (rr == null && member.VarInitializer != null)
{
rr = Emitter.Resolver.ResolveNode(member.VarInitializer, Emitter) as MemberResolveResult;
}
if (rr != null)
{
foreach (var interfaceMember in rr.Member.ImplementedInterfaceMembers)
{
if (this.EmitMemberAlias(rr.Member, interfaceMember))
{
nonEmpty = true;
}
}
}
}
if (newLine)
{
this.WriteNewLine();
if (changedIndenting)
{
this.Outdent();
}
}
this.WriteCloseBracket();
if (!nonEmpty)
{
this.Emitter.Output.Length = pos;
this.Emitter.Comma = oldComma;
this.Emitter.IsNewLine = oldNewLine;
}
}
protected bool EmitMemberAlias(IMember member, IMember interfaceMember)
{
bool nonEmpty = false;
if (member.IsShadowing || !member.IsOverride)
{
var baseMember = InheritanceHelper.GetBaseMember(member);
if (baseMember != null && baseMember.ImplementedInterfaceMembers.Contains(interfaceMember))
{
return false;
}
}
var excludeTypeParam = OverloadsCollection.ExcludeTypeParameterForDefinition(member);
var excludeAliasTypeParam = member.IsExplicitInterfaceImplementation && !excludeTypeParam;
var pair = false;
var itypeDef = interfaceMember.DeclaringTypeDefinition;
if (!member.IsExplicitInterfaceImplementation &&
MetadataUtils.IsJsGeneric(itypeDef, this.Emitter) &&
itypeDef.TypeParameters != null &&
itypeDef.TypeParameters.Any(typeParameter => typeParameter.Variance != VarianceModifier.Invariant))
{
pair = true;
}
if (member is IProperty && ((IProperty)member).IsIndexer)
{
var property = (IProperty)member;
if (property.CanGet)
{
nonEmpty = true;
this.EnsureComma();
this.WriteScript(Helpers.GetPropertyRef(member, this.Emitter, false, false, false, excludeTypeParam));
this.WriteComma();
var alias = Helpers.GetPropertyRef(interfaceMember, this.Emitter, false, false, false, withoutTypeParams: excludeAliasTypeParam);
if (pair)
{
this.WriteOpenBracket();
}
if (alias.StartsWith("\""))
{
this.Write(alias);
}
else
{
this.WriteScript(alias);
}
if (pair)
{
this.WriteComma();
this.WriteScript(Helpers.GetPropertyRef(interfaceMember, this.Emitter, withoutTypeParams: true));
this.WriteCloseBracket();
}
this.Emitter.Comma = true;
}
if (property.CanSet)
{
nonEmpty = true;
this.EnsureComma();
this.WriteScript(Helpers.GetPropertyRef(member, this.Emitter, true, false, false, excludeTypeParam));
this.WriteComma();
var alias = Helpers.GetPropertyRef(interfaceMember, this.Emitter, true, false, false, withoutTypeParams: excludeAliasTypeParam);
if (pair)
{
this.WriteOpenBracket();
}
if (alias.StartsWith("\""))
{
this.Write(alias);
}
else
{
this.WriteScript(alias);
}
if (pair)
{
this.WriteComma();
this.WriteScript(Helpers.GetPropertyRef(interfaceMember, this.Emitter, true, withoutTypeParams: true));
this.WriteCloseBracket();
}
this.Emitter.Comma = true;
}
}
else if (member is IEvent)
{
var ev = (IEvent)member;
if (ev.CanAdd)
{
nonEmpty = true;
this.EnsureComma();
this.WriteScript(Helpers.GetEventRef(member, this.Emitter, false, false, false, excludeTypeParam));
this.WriteComma();
var alias = Helpers.GetEventRef(interfaceMember, this.Emitter, false, false, false, excludeAliasTypeParam);
if (pair)
{
this.WriteOpenBracket();
}
if (alias.StartsWith("\""))
{
this.Write(alias);
}
else
{
this.WriteScript(alias);
}
if (pair)
{
this.WriteComma();
this.WriteScript(Helpers.GetEventRef(interfaceMember, this.Emitter, withoutTypeParams: true));
this.WriteCloseBracket();
}
this.Emitter.Comma = true;
}
if (ev.CanRemove)
{
nonEmpty = true;
this.EnsureComma();
this.WriteScript(Helpers.GetEventRef(member, this.Emitter, true, false, false, excludeTypeParam));
this.WriteComma();
var alias = Helpers.GetEventRef(interfaceMember, this.Emitter, true, false, false, excludeAliasTypeParam);
if (pair)
{
this.WriteOpenBracket();
}
if (alias.StartsWith("\""))
{
this.Write(alias);
}
else
{
this.WriteScript(alias);
}
if (pair)
{
this.WriteComma();
this.WriteScript(Helpers.GetEventRef(interfaceMember, this.Emitter, true, withoutTypeParams: true));
this.WriteCloseBracket();
}
this.Emitter.Comma = true;
}
}
else
{
nonEmpty = true;
this.EnsureComma();
this.WriteScript(OverloadsCollection.Create(Emitter, member).GetOverloadName(false, null, excludeTypeOnly: excludeTypeParam));
this.WriteComma();
var alias = OverloadsCollection.Create(Emitter, interfaceMember).GetOverloadName(withoutTypeParams: excludeAliasTypeParam);
if (pair)
{
this.WriteOpenBracket();
}
if (alias.StartsWith("\""))
{
this.Write(alias);
}
else
{
this.WriteScript(alias);
}
if (pair)
{
this.WriteComma();
this.WriteScript(OverloadsCollection.Create(Emitter, interfaceMember).GetOverloadName(withoutTypeParams: true));
this.WriteCloseBracket();
}
}
this.Emitter.Comma = true;
return nonEmpty;
}
}
}
| |
// 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.
/*============================================================
**
**
**
** Provides a way for an app to not start an operation unless
** there's a reasonable chance there's enough memory
** available for the operation to succeed.
**
**
===========================================================*/
using System;
using System.IO;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics;
/*
This class allows an application to fail before starting certain
activities. The idea is to fail early instead of failing in the middle
of some long-running operation to increase the survivability of the
application and ensure you don't have to write tricky code to handle an
OOM anywhere in your app's code (which implies state corruption, meaning you
should unload the appdomain, if you have a transacted environment to ensure
rollback of individual transactions). This is an incomplete tool to attempt
hoisting all your OOM failures from anywhere in your worker methods to one
particular point where it is easier to handle an OOM failure, and you can
optionally choose to not start a workitem if it will likely fail. This does
not help the performance of your code directly (other than helping to avoid
AD unloads). The point is to avoid starting work if it is likely to fail.
The Enterprise Services team has used these memory gates effectively in the
unmanaged world for a decade.
In Whidbey, we will simply check to see if there is enough memory available
in the OS's page file & attempt to ensure there might be enough space free
within the process's address space (checking for address space fragmentation
as well). We will not commit or reserve any memory. To avoid race conditions with
other threads using MemoryFailPoints, we'll also keep track of a
process-wide amount of memory "reserved" via all currently-active
MemoryFailPoints. This has two problems:
1) This can account for memory twice. If a thread creates a
MemoryFailPoint for 100 MB then allocates 99 MB, we'll see 99 MB
less free memory and 100 MB less reserved memory. Yet, subtracting
off the 100 MB is necessary because the thread may not have started
allocating memory yet. Disposing of this class immediately after
front-loaded allocations have completed is a great idea.
2) This is still vulnerable to race conditions with other threads that don't use
MemoryFailPoints.
So this class is far from perfect. But it may be good enough to
meaningfully reduce the frequency of OutOfMemoryExceptions in managed apps.
In Orcas or later, we might allocate some memory from the OS and add it
to a allocation context for this thread. Obviously, at that point we need
some way of conveying when we release this block of memory. So, we
implemented IDisposable on this type in Whidbey and expect all users to call
this from within a using block to provide lexical scope for their memory
usage. The call to Dispose (implicit with the using block) will give us an
opportunity to release this memory, perhaps. We anticipate this will give
us the possibility of a more effective design in a future version.
In Orcas, we may also need to differentiate between allocations that would
go into the normal managed heap vs. the large object heap, or we should
consider checking for enough free space in both locations (with any
appropriate adjustments to ensure the memory is contiguous).
*/
namespace System.Runtime
{
public sealed class MemoryFailPoint : CriticalFinalizerObject, IDisposable
{
// Find the top section of user mode memory. Avoid the last 64K.
// Windows reserves that block for the kernel, apparently, and doesn't
// let us ask about that memory. But since we ask for memory in 1 MB
// chunks, we don't have to special case this. Also, we need to
// deal with 32 bit machines in 3 GB mode.
// Using Win32's GetSystemInfo should handle all this for us.
private static readonly ulong TopOfMemory;
// Walking the address space is somewhat expensive, taking around half
// a millisecond. Doing that per transaction limits us to a max of
// ~2000 transactions/second. Instead, let's do this address space
// walk once every 10 seconds, or when we will likely fail. This
// amortization scheme can reduce the cost of a memory gate by about
// a factor of 100.
private static long hiddenLastKnownFreeAddressSpace = 0;
private static long hiddenLastTimeCheckingAddressSpace = 0;
private const int CheckThreshold = 10 * 1000; // 10 seconds
private static long LastKnownFreeAddressSpace
{
get { return Volatile.Read(ref hiddenLastKnownFreeAddressSpace); }
set { Volatile.Write(ref hiddenLastKnownFreeAddressSpace, value); }
}
private static long AddToLastKnownFreeAddressSpace(long addend)
{
return Interlocked.Add(ref hiddenLastKnownFreeAddressSpace, addend);
}
private static long LastTimeCheckingAddressSpace
{
get { return Volatile.Read(ref hiddenLastTimeCheckingAddressSpace); }
set { Volatile.Write(ref hiddenLastTimeCheckingAddressSpace, value); }
}
// When allocating memory segment by segment, we've hit some cases
// where there are only 22 MB of memory available on the machine,
// we need 1 16 MB segment, and the OS does not succeed in giving us
// that memory. Reasons for this could include:
// 1) The GC does allocate memory when doing a collection.
// 2) Another process on the machine could grab that memory.
// 3) Some other part of the runtime might grab this memory.
// If we build in a little padding, we can help protect
// ourselves against some of these cases, and we want to err on the
// conservative side with this class.
private const int LowMemoryFudgeFactor = 16 << 20;
// Round requested size to a 16MB multiple to have a better granularity
// when checking for available memory.
private const int MemoryCheckGranularity = 16;
// Note: This may become dynamically tunable in the future.
// Also note that we can have different segment sizes for the normal vs.
// large object heap. We currently use the max of the two.
private static readonly ulong GCSegmentSize;
// For multi-threaded workers, we want to ensure that if two workers
// use a MemoryFailPoint at the same time, and they both succeed, that
// they don't trample over each other's memory. Keep a process-wide
// count of "reserved" memory, and decrement this in Dispose and
// in the critical finalizer. See
// SharedStatics.MemoryFailPointReservedMemory
private ulong _reservedMemory; // The size of this request (from user)
private bool _mustSubtractReservation; // Did we add data to SharedStatics?
static MemoryFailPoint()
{
GetMemorySettings(out GCSegmentSize, out TopOfMemory);
}
// We can remove this link demand in a future version - we will
// have scenarios for this in partial trust in the future, but
// we're doing this just to restrict this in case the code below
// is somehow incorrect.
public MemoryFailPoint(int sizeInMegabytes)
{
if (sizeInMegabytes <= 0)
throw new ArgumentOutOfRangeException(nameof(sizeInMegabytes), SR.ArgumentOutOfRange_NeedNonNegNum);
#if !FEATURE_PAL // Remove this when CheckForAvailableMemory is able to provide legitimate estimates
ulong size = ((ulong)sizeInMegabytes) << 20;
_reservedMemory = size;
// Check to see that we both have enough memory on the system
// and that we have enough room within the user section of the
// process's address space. Also, we need to use the GC segment
// size, not the amount of memory the user wants to allocate.
// Consider correcting this to reflect free memory within the GC
// heap, and to check both the normal & large object heaps.
ulong segmentSize = (ulong)(Math.Ceiling((double)size / GCSegmentSize) * GCSegmentSize);
if (segmentSize >= TopOfMemory)
throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_TooBig);
ulong requestedSizeRounded = (ulong)(Math.Ceiling((double)sizeInMegabytes / MemoryCheckGranularity) * MemoryCheckGranularity);
//re-convert into bytes
requestedSizeRounded <<= 20;
ulong availPageFile = 0; // available VM (physical + page file)
ulong totalAddressSpaceFree = 0; // non-contiguous free address space
// Check for available memory, with 2 attempts at getting more
// memory.
// Stage 0: If we don't have enough, trigger a GC.
// Stage 1: If we don't have enough, try growing the swap file.
// Stage 2: Update memory state, then fail or leave loop.
//
// (In the future, we could consider adding another stage after
// Stage 0 to run finalizers. However, before doing that make sure
// that we could abort this constructor when we call
// GC.WaitForPendingFinalizers, noting that this method uses a CER
// so it can't be aborted, and we have a critical finalizer. It
// would probably work, but do some thinking first.)
for (int stage = 0; stage < 3; stage++)
{
CheckForAvailableMemory(out availPageFile, out totalAddressSpaceFree);
// If we have enough room, then skip some stages.
// Note that multiple threads can still lead to a race condition for our free chunk
// of address space, which can't be easily solved.
ulong reserved = SharedStatics.MemoryFailPointReservedMemory;
ulong segPlusReserved = segmentSize + reserved;
bool overflow = segPlusReserved < segmentSize || segPlusReserved < reserved;
bool needPageFile = availPageFile < (requestedSizeRounded + reserved + LowMemoryFudgeFactor) || overflow;
bool needAddressSpace = totalAddressSpaceFree < segPlusReserved || overflow;
// Ensure our cached amount of free address space is not stale.
long now = Environment.TickCount; // Handle wraparound.
if ((now > LastTimeCheckingAddressSpace + CheckThreshold || now < LastTimeCheckingAddressSpace) ||
LastKnownFreeAddressSpace < (long)segmentSize)
{
CheckForFreeAddressSpace(segmentSize, false);
}
bool needContiguousVASpace = (ulong)LastKnownFreeAddressSpace < segmentSize;
BCLDebug.Trace("MEMORYFAILPOINT", "MemoryFailPoint: Checking for {0} MB, for allocation size of {1} MB, stage {9}. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved via process's MemoryFailPoints: {8} MB",
segmentSize >> 20, sizeInMegabytes, needPageFile,
needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved, stage);
if (!needPageFile && !needAddressSpace && !needContiguousVASpace)
break;
switch (stage)
{
case 0:
// The GC will release empty segments to the OS. This will
// relieve us from having to guess whether there's
// enough memory in either GC heap, and whether
// internal fragmentation will prevent those
// allocations from succeeding.
GC.Collect();
continue;
case 1:
// Do this step if and only if the page file is too small.
if (!needPageFile)
continue;
// Attempt to grow the OS's page file. Note that we ignore
// any allocation routines from the host intentionally.
RuntimeHelpers.PrepareConstrainedRegions();
// This shouldn't overflow due to the if clauses above.
UIntPtr numBytes = new UIntPtr(segmentSize);
unsafe
{
void* pMemory = Win32Native.VirtualAlloc(null, numBytes, Win32Native.MEM_COMMIT, Win32Native.PAGE_READWRITE);
if (pMemory != null)
{
bool r = Win32Native.VirtualFree(pMemory, UIntPtr.Zero, Win32Native.MEM_RELEASE);
if (!r)
throw Win32Marshal.GetExceptionForLastWin32Error();
}
}
continue;
case 2:
// The call to CheckForAvailableMemory above updated our
// state.
if (needPageFile || needAddressSpace)
{
InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint);
#if _DEBUG
e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
needPageFile, needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved);
#endif
throw e;
}
if (needContiguousVASpace)
{
InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag);
#if _DEBUG
e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
needPageFile, needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved);
#endif
throw e;
}
break;
default:
Debug.Assert(false, "Fell through switch statement!");
break;
}
}
// Success - we have enough room the last time we checked.
// Now update our shared state in a somewhat atomic fashion
// and handle a simple race condition with other MemoryFailPoint instances.
AddToLastKnownFreeAddressSpace(-((long)size));
if (LastKnownFreeAddressSpace < 0)
CheckForFreeAddressSpace(segmentSize, true);
RuntimeHelpers.PrepareConstrainedRegions();
SharedStatics.AddMemoryFailPointReservation((long)size);
_mustSubtractReservation = true;
#endif
}
private static void CheckForAvailableMemory(out ulong availPageFile, out ulong totalAddressSpaceFree)
{
bool r;
Win32Native.MEMORYSTATUSEX memory = new Win32Native.MEMORYSTATUSEX();
r = Win32Native.GlobalMemoryStatusEx(ref memory);
if (!r)
throw Win32Marshal.GetExceptionForLastWin32Error();
availPageFile = memory.availPageFile;
totalAddressSpaceFree = memory.availVirtual;
//Console.WriteLine("Memory gate: Mem load: {0}% Available memory (physical + page file): {1} MB Total free address space: {2} MB GC Heap: {3} MB", memory.memoryLoad, memory.availPageFile >> 20, memory.availVirtual >> 20, GC.GetTotalMemory(true) >> 20);
}
// Based on the shouldThrow parameter, this will throw an exception, or
// returns whether there is enough space. In all cases, we update
// our last known free address space, hopefully avoiding needing to
// probe again.
private static unsafe bool CheckForFreeAddressSpace(ulong size, bool shouldThrow)
{
// Start walking the address space at 0. VirtualAlloc may wrap
// around the address space. We don't need to find the exact
// pages that VirtualAlloc would return - we just need to
// know whether VirtualAlloc could succeed.
ulong freeSpaceAfterGCHeap = MemFreeAfterAddress(null, size);
BCLDebug.Trace("MEMORYFAILPOINT", "MemoryFailPoint: Checked for free VA space. Found enough? {0} Asked for: {1} Found: {2}", (freeSpaceAfterGCHeap >= size), size, freeSpaceAfterGCHeap);
// We may set these without taking a lock - I don't believe
// this will hurt, as long as we never increment this number in
// the Dispose method. If we do an extra bit of checking every
// once in a while, but we avoid taking a lock, we may win.
LastKnownFreeAddressSpace = (long)freeSpaceAfterGCHeap;
LastTimeCheckingAddressSpace = Environment.TickCount;
if (freeSpaceAfterGCHeap < size && shouldThrow)
throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag);
return freeSpaceAfterGCHeap >= size;
}
// Returns the amount of consecutive free memory available in a block
// of pages. If we didn't have enough address space, we still return
// a positive value < size, to help potentially avoid the overhead of
// this check if we use a MemoryFailPoint with a smaller size next.
private static unsafe ulong MemFreeAfterAddress(void* address, ulong size)
{
if (size >= TopOfMemory)
return 0;
ulong largestFreeRegion = 0;
Win32Native.MEMORY_BASIC_INFORMATION memInfo = new Win32Native.MEMORY_BASIC_INFORMATION();
UIntPtr sizeOfMemInfo = (UIntPtr)Marshal.SizeOf(memInfo);
while (((ulong)address) + size < TopOfMemory)
{
UIntPtr r = Win32Native.VirtualQuery(address, ref memInfo, sizeOfMemInfo);
if (r == UIntPtr.Zero)
throw Win32Marshal.GetExceptionForLastWin32Error();
ulong regionSize = memInfo.RegionSize.ToUInt64();
if (memInfo.State == Win32Native.MEM_FREE)
{
if (regionSize >= size)
return regionSize;
else
largestFreeRegion = Math.Max(largestFreeRegion, regionSize);
}
address = (void*)((ulong)address + regionSize);
}
return largestFreeRegion;
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void GetMemorySettings(out ulong maxGCSegmentSize, out ulong topOfMemory);
~MemoryFailPoint()
{
Dispose(false);
}
// Applications must call Dispose, which conceptually "releases" the
// memory that was "reserved" by the MemoryFailPoint. This affects a
// global count of reserved memory in this version (helping to throttle
// future MemoryFailPoints) in this version. We may in the
// future create an allocation context and release it in the Dispose
// method. While the finalizer will eventually free this block of
// memory, apps will help their performance greatly by calling Dispose.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
// This is just bookkeeping to ensure multiple threads can really
// get enough memory, and this does not actually reserve memory
// within the GC heap.
if (_mustSubtractReservation)
{
RuntimeHelpers.PrepareConstrainedRegions();
SharedStatics.AddMemoryFailPointReservation(-((long)_reservedMemory));
_mustSubtractReservation = false;
}
/*
// Prototype performance
// Let's pretend that we returned at least some free memory to
// the GC heap. We don't know this is true - the objects could
// have a longer lifetime, and the memory could be elsewhere in the
// GC heap. Additionally, we subtracted off the segment size, not
// this size. That's ok - we don't mind if this slowly degrades
// and requires us to refresh the value a little bit sooner.
// But releasing the memory here should help us avoid probing for
// free address space excessively with large workItem sizes.
Interlocked.Add(ref LastKnownFreeAddressSpace, _reservedMemory);
*/
}
#if _DEBUG
[Serializable]
internal sealed class MemoryFailPointState
{
private ulong _segmentSize;
private int _allocationSizeInMB;
private bool _needPageFile;
private bool _needAddressSpace;
private bool _needContiguousVASpace;
private ulong _availPageFile;
private ulong _totalFreeAddressSpace;
private long _lastKnownFreeAddressSpace;
private ulong _reservedMem;
private String _stackTrace; // Where did we fail, for additional debugging.
internal MemoryFailPointState(int allocationSizeInMB, ulong segmentSize, bool needPageFile, bool needAddressSpace, bool needContiguousVASpace, ulong availPageFile, ulong totalFreeAddressSpace, long lastKnownFreeAddressSpace, ulong reservedMem)
{
_allocationSizeInMB = allocationSizeInMB;
_segmentSize = segmentSize;
_needPageFile = needPageFile;
_needAddressSpace = needAddressSpace;
_needContiguousVASpace = needContiguousVASpace;
_availPageFile = availPageFile;
_totalFreeAddressSpace = totalFreeAddressSpace;
_lastKnownFreeAddressSpace = lastKnownFreeAddressSpace;
_reservedMem = reservedMem;
try
{
_stackTrace = Environment.StackTrace;
}
catch (System.Security.SecurityException)
{
_stackTrace = "no permission";
}
catch (OutOfMemoryException)
{
_stackTrace = "out of memory";
}
}
public override String ToString()
{
return String.Format(System.Globalization.CultureInfo.InvariantCulture, "MemoryFailPoint detected insufficient memory to guarantee an operation could complete. Checked for {0} MB, for allocation size of {1} MB. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved by process's MemoryFailPoints: {8} MB",
_segmentSize >> 20, _allocationSizeInMB, _needPageFile,
_needAddressSpace, _needContiguousVASpace,
_availPageFile >> 20, _totalFreeAddressSpace >> 20,
_lastKnownFreeAddressSpace >> 20, _reservedMem);
}
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryNullableLogicalTests
{
#region Test methods
[Fact]
public static void CheckNullableBoolAndTest()
{
bool?[] array = new bool?[] { null, true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableBoolAnd(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableBoolAndAlsoTest()
{
bool?[] array = new bool?[] { null, true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableBoolAndAlso(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableBoolOrTest()
{
bool?[] array = new bool?[] { null, true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableBoolOr(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableBoolOrElseTest()
{
bool?[] array = new bool?[] { null, true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableBoolOrElse(array[i], array[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyNullableBoolAnd(bool? a, bool? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.And(
Expression.Constant(a, typeof(bool?)),
Expression.Constant(b, typeof(bool?))),
Enumerable.Empty<ParameterExpression>());
Func<bool?> f = e.Compile();
// compute with expression tree
bool? etResult = default(bool?);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
bool? csResult = default(bool?);
Exception csException = null;
try
{
csResult = (bool?)(a & b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableBoolAndAlso(bool? a, bool? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.AndAlso(
Expression.Constant(a, typeof(bool?)),
Expression.Constant(b, typeof(bool?))),
Enumerable.Empty<ParameterExpression>());
Func<bool?> f = e.Compile();
// compute with expression tree
bool? etResult = default(bool?);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
bool? csResult = default(bool?);
Exception csException = null;
try
{
csResult = (bool?)(a & b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableBoolOr(bool? a, bool? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.Or(
Expression.Constant(a, typeof(bool?)),
Expression.Constant(b, typeof(bool?))),
Enumerable.Empty<ParameterExpression>());
Func<bool?> f = e.Compile();
// compute with expression tree
bool? etResult = default(bool?);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
bool? csResult = default(bool?);
Exception csException = null;
try
{
csResult = (bool?)(a | b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
private static void VerifyNullableBoolOrElse(bool? a, bool? b)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.OrElse(
Expression.Constant(a, typeof(bool?)),
Expression.Constant(b, typeof(bool?))),
Enumerable.Empty<ParameterExpression>());
Func<bool?> f = e.Compile();
// compute with expression tree
bool? etResult = default(bool?);
Exception etException = null;
try
{
etResult = f();
}
catch (Exception ex)
{
etException = ex;
}
// compute with real IL
bool? csResult = default(bool?);
Exception csException = null;
try
{
csResult = (bool?)(a | b);
}
catch (Exception ex)
{
csException = ex;
}
// either both should have failed the same way or they should both produce the same result
if (etException != null || csException != null)
{
Assert.NotNull(etException);
Assert.NotNull(csException);
Assert.Equal(csException.GetType(), etException.GetType());
}
else
{
Assert.Equal(csResult, etResult);
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime;
using Xunit;
public static class GCTests
{
private static bool s_is32Bits = IntPtr.Size == 4; // Skip IntPtr tests on 32-bit platforms
[Fact]
public static void TestAddMemoryPressure_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.AddMemoryPressure(-1)); // Bytes allocated < 0
if (s_is32Bits)
{
Assert.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.AddMemoryPressure((long)int.MaxValue + 1)); // Bytes allocated > int.MaxValue on 32 bit platforms
}
}
[Fact]
public static void TestCollect_Int()
{
for (int i = 0; i < GC.MaxGeneration + 10; i++)
{
GC.Collect(i);
}
}
[Fact]
public static void TestCollect_Int_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1)); // Generation < 0
}
[Theory]
[InlineData(GCCollectionMode.Default)]
[InlineData(GCCollectionMode.Forced)]
public static void TestCollect_Int_GCCollectionMode(GCCollectionMode mode)
{
for (int gen = 0; gen <= 2; gen++)
{
var b = new byte[1024 * 1024 * 10];
int oldCollectionCount = GC.CollectionCount(gen);
b = null;
GC.Collect(gen, GCCollectionMode.Default);
Assert.True(GC.CollectionCount(gen) > oldCollectionCount);
}
}
[Fact]
public static void TestCollect_Int_GCCollectionMode_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1, GCCollectionMode.Default)); // Generation < 0
Assert.Throws<ArgumentOutOfRangeException>("mode", () => GC.Collect(2, GCCollectionMode.Default - 1)); // Invalid collection mode
Assert.Throws<ArgumentOutOfRangeException>("mode", () => GC.Collect(2, GCCollectionMode.Optimized + 1)); // Invalid collection mode
}
[Fact]
public static void TestCollect_Int_GCCollectionMode_Bool_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1, GCCollectionMode.Default, false)); // Generation < 0
Assert.Throws<ArgumentOutOfRangeException>("mode", () => GC.Collect(2, GCCollectionMode.Default - 1, false)); // Invalid collection mode
Assert.Throws<ArgumentOutOfRangeException>("mode", () => GC.Collect(2, GCCollectionMode.Optimized + 1, false)); // Invalid collection mode
}
[Fact]
public static void TestCollect_CallsFinalizer()
{
FinalizerTest.Run();
}
private class FinalizerTest
{
public static void Run()
{
var obj = new TestObject();
obj = null;
GC.Collect();
// Make sure Finalize() is called
GC.WaitForPendingFinalizers();
Assert.True(TestObject.Finalized);
}
private class TestObject
{
public static bool Finalized { get; private set; }
~TestObject()
{
Finalized = true;
}
}
}
[Fact]
public static void KeepAlive()
{
KeepAliveTest.Run();
}
private class KeepAliveTest
{
public static void Run()
{
var keepAlive = new KeepAliveObject();
var doNotKeepAlive = new DoNotKeepAliveObject();
doNotKeepAlive = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(DoNotKeepAliveObject.Finalized);
Assert.False(KeepAliveObject.Finalized);
GC.KeepAlive(keepAlive);
}
private class KeepAliveObject
{
public static bool Finalized { get; private set; }
~KeepAliveObject()
{
Finalized = true;
}
}
private class DoNotKeepAliveObject
{
public static bool Finalized { get; private set; }
~DoNotKeepAliveObject()
{
Finalized = true;
}
}
}
[Fact]
public static void KeepAlive_Null()
{
KeepAliveNullTest.Run();
}
private class KeepAliveNullTest
{
public static void Run()
{
var obj = new TestObject();
obj = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.KeepAlive(obj);
Assert.True(TestObject.Finalized);
}
private class TestObject
{
public static bool Finalized { get; private set; }
~TestObject()
{
Finalized = true;
}
}
}
[Fact]
public static void KeepAliveRecursive()
{
KeepAliveRecursiveTest.Run();
}
private class KeepAliveRecursiveTest
{
public static void Run()
{
int recursionCount = 0;
RunWorker(new TestObject(), ref recursionCount);
}
private static void RunWorker(object obj, ref int recursionCount)
{
if (recursionCount++ == 10)
return;
GC.Collect();
GC.WaitForPendingFinalizers();
RunWorker(obj, ref recursionCount);
Assert.False(TestObject.Finalized);
GC.KeepAlive(obj);
}
private class TestObject
{
public static bool Finalized { get; private set; }
~TestObject()
{
Finalized = true;
}
}
}
[Fact]
public static void TestSuppressFinalizer()
{
SuppressFinalizerTest.Run();
}
private class SuppressFinalizerTest
{
public static void Run()
{
var obj = new TestObject();
GC.SuppressFinalize(obj);
obj = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(TestObject.Finalized);
}
private class TestObject
{
public static bool Finalized { get; private set; }
~TestObject()
{
Finalized = true;
}
}
}
[Fact]
public static void TestSuppressFinalizer_Invalid()
{
Assert.Throws<ArgumentNullException>("obj", () => GC.SuppressFinalize(null)); // Obj is null
}
[Fact]
public static void TestReRegisterForFinalize()
{
ReRegisterForFinalizeTest.Run();
}
[Fact]
public static void TestReRegisterFoFinalize()
{
Assert.Throws<ArgumentNullException>("obj", () => GC.ReRegisterForFinalize(null)); // Obj is null
}
private class ReRegisterForFinalizeTest
{
public static void Run()
{
TestObject.Finalized = false;
CreateObject();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(TestObject.Finalized);
}
private static void CreateObject()
{
using (var obj = new TestObject())
{
GC.SuppressFinalize(obj);
}
}
private class TestObject : IDisposable
{
public static bool Finalized { get; set; }
~TestObject()
{
Finalized = true;
}
public void Dispose()
{
GC.ReRegisterForFinalize(this);
}
}
}
[Fact]
public static void TestCollectionCount_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("generation", () => GC.CollectionCount(-1)); // Generation < 0
}
[Fact]
public static void TestRemoveMemoryPressure_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.RemoveMemoryPressure(-1)); // Bytes allocated < 0
if (s_is32Bits)
{
Assert.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.RemoveMemoryPressure((long)int.MaxValue + 1)); // Bytes allocated > int.MaxValue on 32 bit platforms
}
}
[Fact]
public static void TestGetTotalMemoryTest_ForceCollection()
{
// We don't test GetTotalMemory(false) at all because a collection
// could still occur even if not due to the GetTotalMemory call,
// and as such there's no way to validate the behavior. We also
// don't verify a tighter bound for the result of GetTotalMemory
// because collections could cause significant fluctuations.
GC.Collect();
int gen0 = GC.CollectionCount(0);
int gen1 = GC.CollectionCount(1);
int gen2 = GC.CollectionCount(2);
Assert.InRange(GC.GetTotalMemory(true), 1, long.MaxValue);
Assert.InRange(GC.CollectionCount(0), gen0 + 1, int.MaxValue);
Assert.InRange(GC.CollectionCount(1), gen1 + 1, int.MaxValue);
Assert.InRange(GC.CollectionCount(2), gen2 + 1, int.MaxValue);
}
[Fact]
public static void TestGetGeneration()
{
// We don't test a tighter bound on GetGeneration as objects
// can actually get demoted or stay in the same generation
// across collections.
GC.Collect();
var obj = new object();
for (int i = 0; i <= GC.MaxGeneration + 1; i++)
{
Assert.InRange(GC.GetGeneration(obj), 0, GC.MaxGeneration);
GC.Collect();
}
}
[Theory]
[InlineData(GCLargeObjectHeapCompactionMode.CompactOnce)]
[InlineData(GCLargeObjectHeapCompactionMode.Default)]
public static void TestLargeObjectHeapCompactionModeRoundTrips(GCLargeObjectHeapCompactionMode value)
{
GCLargeObjectHeapCompactionMode orig = GCSettings.LargeObjectHeapCompactionMode;
try
{
GCSettings.LargeObjectHeapCompactionMode = value;
Assert.Equal(value, GCSettings.LargeObjectHeapCompactionMode);
}
finally
{
GCSettings.LargeObjectHeapCompactionMode = orig;
Assert.Equal(orig, GCSettings.LargeObjectHeapCompactionMode);
}
}
[Theory]
[InlineData(GCLatencyMode.Batch)]
[InlineData(GCLatencyMode.Interactive)]
public static void TestLatencyRoundtrips(GCLatencyMode value)
{
GCLatencyMode orig = GCSettings.LatencyMode;
try
{
GCSettings.LatencyMode = value;
Assert.Equal(value, GCSettings.LatencyMode);
}
finally
{
GCSettings.LatencyMode = orig;
Assert.Equal(orig, GCSettings.LatencyMode);
}
}
[Theory]
[PlatformSpecific(PlatformID.Windows)] //Concurent GC is not enabled on Unix. Recombine to TestLatencyRoundTrips once addressed.
[InlineData(GCLatencyMode.LowLatency)]
[InlineData(GCLatencyMode.SustainedLowLatency)]
public static void TestLatencyRoundtrips_LowLatency(GCLatencyMode value) => TestLatencyRoundtrips(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.
/*============================================================
**
**
**
** Purpose: Some floating-point math operations
**
**
===========================================================*/
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System
{
public static class Math
{
private static double s_doubleRoundLimit = 1e16d;
private const int maxRoundingDigits = 15;
// This table is required for the Round function which can specify the number of digits to round to
private static double[] s_roundPower10Double = new double[] {
1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8,
1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15
};
public const double PI = 3.14159265358979323846;
public const double E = 2.7182818284590452354;
[Intrinsic]
public static double Acos(double d)
{
return RuntimeImports.acos(d);
}
[Intrinsic]
public static double Asin(double d)
{
return RuntimeImports.asin(d);
}
[Intrinsic]
public static double Atan(double d)
{
return RuntimeImports.atan(d);
}
[Intrinsic]
public static double Atan2(double y, double x)
{
if (Double.IsInfinity(x) && Double.IsInfinity(y))
return Double.NaN;
return RuntimeImports.atan2(y, x);
}
public static Decimal Ceiling(Decimal d)
{
return Decimal.Ceiling(d);
}
[Intrinsic]
public static double Ceiling(double a)
{
return RuntimeImports.ceil(a);
}
[Intrinsic]
public static double Cos(double d)
{
return RuntimeImports.cos(d);
}
[Intrinsic]
public static double Cosh(double value)
{
return RuntimeImports.cosh(value);
}
public static Decimal Floor(Decimal d)
{
return Decimal.Floor(d);
}
[Intrinsic]
public static double Floor(double d)
{
return RuntimeImports.floor(d);
}
private static unsafe double InternalRound(double value, int digits, MidpointRounding mode)
{
if (Abs(value) < s_doubleRoundLimit)
{
Double power10 = s_roundPower10Double[digits];
value *= power10;
if (mode == MidpointRounding.AwayFromZero)
{
double fraction = RuntimeImports.modf(value, &value);
if (Abs(fraction) >= 0.5d)
{
value += Sign(fraction);
}
}
else
{
// On X86 this can be inlined to just a few instructions
value = Round(value);
}
value /= power10;
}
return value;
}
[Intrinsic]
public static double Sin(double a)
{
return RuntimeImports.sin(a);
}
[Intrinsic]
public static double Tan(double a)
{
return RuntimeImports.tan(a);
}
[Intrinsic]
public static double Sinh(double value)
{
return RuntimeImports.sinh(value);
}
[Intrinsic]
public static double Tanh(double value)
{
return RuntimeImports.tanh(value);
}
[Intrinsic]
public static double Round(double a)
{
// If the number has no fractional part do nothing
// This shortcut is necessary to workaround precision loss in borderline cases on some platforms
if (a == (double)(Int64)a)
return a;
double tempVal = a + 0.5;
// We had a number that was equally close to 2 integers.
// We need to return the even one.
double flrTempVal = RuntimeImports.floor(tempVal);
if (flrTempVal == tempVal)
{
if (0.0 != RuntimeImports.fmod(tempVal, 2.0))
{
flrTempVal -= 1.0;
}
}
if (flrTempVal == 0 && Double.IsNegative(a))
{
flrTempVal = Double.NegativeZero;
}
return flrTempVal;
}
public static double Round(double value, int digits)
{
if ((digits < 0) || (digits > maxRoundingDigits))
throw new ArgumentOutOfRangeException(nameof(digits), SR.ArgumentOutOfRange_RoundingDigits);
Contract.EndContractBlock();
return InternalRound(value, digits, MidpointRounding.ToEven);
}
public static double Round(double value, MidpointRounding mode)
{
return Round(value, 0, mode);
}
public static double Round(double value, int digits, MidpointRounding mode)
{
if ((digits < 0) || (digits > maxRoundingDigits))
throw new ArgumentOutOfRangeException(nameof(digits), SR.ArgumentOutOfRange_RoundingDigits);
if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero)
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, "MidpointRounding"), nameof(mode));
}
Contract.EndContractBlock();
return InternalRound(value, digits, mode);
}
public static Decimal Round(Decimal d)
{
return Decimal.Round(d, 0);
}
public static Decimal Round(Decimal d, int decimals)
{
return Decimal.Round(d, decimals);
}
public static Decimal Round(Decimal d, MidpointRounding mode)
{
return Decimal.Round(d, 0, mode);
}
public static Decimal Round(Decimal d, int decimals, MidpointRounding mode)
{
return Decimal.Round(d, decimals, mode);
}
public static Decimal Truncate(Decimal d)
{
return Decimal.Truncate(d);
}
public static unsafe double Truncate(double d)
{
double intpart;
RuntimeImports.modf(d, &intpart);
return intpart;
}
[Intrinsic]
public static double Sqrt(double d)
{
return RuntimeImports.sqrt(d);
}
[Intrinsic]
public static double Log(double d)
{
return RuntimeImports.log(d);
}
[Intrinsic]
public static double Log10(double d)
{
return RuntimeImports.log10(d);
}
[Intrinsic]
public static double Exp(double d)
{
if (Double.IsInfinity(d))
{
if (d < 0)
return +0.0;
return d;
}
return RuntimeImports.exp(d);
}
[Intrinsic]
public static double Pow(double x, double y)
{
if (Double.IsNaN(y))
return y;
if (Double.IsNaN(x))
return x;
if (Double.IsInfinity(y))
{
if (x == 1.0)
{
return x;
}
if (x == -1.0)
{
return Double.NaN;
}
}
return RuntimeImports.pow(x, y);
}
public static double IEEERemainder(double x, double y)
{
if (Double.IsNaN(x))
{
return x; // IEEE 754-2008: NaN payload must be preserved
}
if (Double.IsNaN(y))
{
return y; // IEEE 754-2008: NaN payload must be preserved
}
double regularMod = x % y;
if (Double.IsNaN(regularMod))
{
return Double.NaN;
}
if (regularMod == 0)
{
if (Double.IsNegative(x))
{
return Double.NegativeZero;
}
}
double alternativeResult;
alternativeResult = regularMod - (Math.Abs(y) * Math.Sign(x));
if (Math.Abs(alternativeResult) == Math.Abs(regularMod))
{
double divisionResult = x / y;
double roundedResult = Math.Round(divisionResult);
if (Math.Abs(roundedResult) > Math.Abs(divisionResult))
{
return alternativeResult;
}
else
{
return regularMod;
}
}
if (Math.Abs(alternativeResult) < Math.Abs(regularMod))
{
return alternativeResult;
}
else
{
return regularMod;
}
}
/*================================Abs=========================================
**Returns the absolute value of it's argument.
============================================================================*/
[CLSCompliant(false)]
public static sbyte Abs(sbyte value)
{
if (value >= 0)
return value;
else
return AbsHelper(value);
}
private static sbyte AbsHelper(sbyte value)
{
Debug.Assert(value < 0, "AbsHelper should only be called for negative values!");
if (value == SByte.MinValue)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
Contract.EndContractBlock();
return ((sbyte)(-value));
}
public static short Abs(short value)
{
if (value >= 0)
return value;
else
return AbsHelper(value);
}
private static short AbsHelper(short value)
{
Debug.Assert(value < 0, "AbsHelper should only be called for negative values!");
if (value == Int16.MinValue)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
Contract.EndContractBlock();
return (short)-value;
}
public static int Abs(int value)
{
if (value >= 0)
return value;
else
return AbsHelper(value);
}
private static int AbsHelper(int value)
{
Debug.Assert(value < 0, "AbsHelper should only be called for negative values!");
if (value == Int32.MinValue)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
Contract.EndContractBlock();
return -value;
}
public static long Abs(long value)
{
if (value >= 0)
return value;
else
return AbsHelper(value);
}
private static long AbsHelper(long value)
{
Debug.Assert(value < 0, "AbsHelper should only be called for negative values!");
if (value == Int64.MinValue)
throw new OverflowException(SR.Overflow_NegateTwosCompNum);
Contract.EndContractBlock();
return -value;
}
[Intrinsic]
public static float Abs(float value)
{
return (float)RuntimeImports.fabs(value);
}
[Intrinsic]
public static double Abs(double value)
{
return RuntimeImports.fabs(value);
}
public static Decimal Abs(Decimal value)
{
return Decimal.Abs(value);
}
/*================================MAX=========================================
**Returns the larger of val1 and val2
============================================================================*/
[CLSCompliant(false)]
[NonVersionable]
public static sbyte Max(sbyte val1, sbyte val2)
{
return (val1 >= val2) ? val1 : val2;
}
[NonVersionable]
public static byte Max(byte val1, byte val2)
{
return (val1 >= val2) ? val1 : val2;
}
[NonVersionable]
public static short Max(short val1, short val2)
{
return (val1 >= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[NonVersionable]
public static ushort Max(ushort val1, ushort val2)
{
return (val1 >= val2) ? val1 : val2;
}
[NonVersionable]
public static int Max(int val1, int val2)
{
return (val1 >= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[NonVersionable]
public static uint Max(uint val1, uint val2)
{
return (val1 >= val2) ? val1 : val2;
}
[NonVersionable]
public static long Max(long val1, long val2)
{
return (val1 >= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[NonVersionable]
public static ulong Max(ulong val1, ulong val2)
{
return (val1 >= val2) ? val1 : val2;
}
public static float Max(float val1, float val2)
{
if (val1 > val2)
return val1;
if (Single.IsNaN(val1))
return val1;
return val2;
}
public static double Max(double val1, double val2)
{
if (val1 > val2)
return val1;
if (Double.IsNaN(val1))
return val1;
return val2;
}
public static Decimal Max(Decimal val1, Decimal val2)
{
return Decimal.Max(val1, val2);
}
/*================================MIN=========================================
**Returns the smaller of val1 and val2.
============================================================================*/
[CLSCompliant(false)]
[NonVersionable]
public static sbyte Min(sbyte val1, sbyte val2)
{
return (val1 <= val2) ? val1 : val2;
}
[NonVersionable]
public static byte Min(byte val1, byte val2)
{
return (val1 <= val2) ? val1 : val2;
}
[NonVersionable]
public static short Min(short val1, short val2)
{
return (val1 <= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[NonVersionable]
public static ushort Min(ushort val1, ushort val2)
{
return (val1 <= val2) ? val1 : val2;
}
[NonVersionable]
public static int Min(int val1, int val2)
{
return (val1 <= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[NonVersionable]
public static uint Min(uint val1, uint val2)
{
return (val1 <= val2) ? val1 : val2;
}
[NonVersionable]
public static long Min(long val1, long val2)
{
return (val1 <= val2) ? val1 : val2;
}
[CLSCompliant(false)]
[NonVersionable]
public static ulong Min(ulong val1, ulong val2)
{
return (val1 <= val2) ? val1 : val2;
}
public static float Min(float val1, float val2)
{
if (val1 < val2)
return val1;
if (Single.IsNaN(val1))
return val1;
return val2;
}
public static double Min(double val1, double val2)
{
if (val1 < val2)
return val1;
if (Double.IsNaN(val1))
return val1;
return val2;
}
public static Decimal Min(Decimal val1, Decimal val2)
{
return Decimal.Min(val1, val2);
}
/*=====================================Log======================================
**
==============================================================================*/
public static double Log(double a, double newBase)
{
if (Double.IsNaN(a))
{
return a; // IEEE 754-2008: NaN payload must be preserved
}
if (Double.IsNaN(newBase))
{
return newBase; // IEEE 754-2008: NaN payload must be preserved
}
if (newBase == 1)
return Double.NaN;
if (a != 1 && (newBase == 0 || Double.IsPositiveInfinity(newBase)))
return Double.NaN;
return (Log(a) / Log(newBase));
}
// Sign function for VB. Returns -1, 0, or 1 if the sign of the number
// is negative, 0, or positive. Throws for floating point NaN's.
[CLSCompliant(false)]
public static int Sign(sbyte value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else
return 0;
}
// Sign function for VB. Returns -1, 0, or 1 if the sign of the number
// is negative, 0, or positive. Throws for floating point NaN's.
public static int Sign(short value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else
return 0;
}
// Sign function for VB. Returns -1, 0, or 1 if the sign of the number
// is negative, 0, or positive. Throws for floating point NaN's.
public static int Sign(int value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else
return 0;
}
public static int Sign(long value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else
return 0;
}
public static int Sign(float value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else if (value == 0)
return 0;
throw new ArithmeticException(SR.Arithmetic_NaN);
}
public static int Sign(double value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else if (value == 0)
return 0;
throw new ArithmeticException(SR.Arithmetic_NaN);
}
public static int Sign(Decimal value)
{
if (value < 0)
return -1;
else if (value > 0)
return 1;
else
return 0;
}
public static long BigMul(int a, int b)
{
return ((long)a) * b;
}
public static int DivRem(int a, int b, out int result)
{
// TODO https://github.com/dotnet/coreclr/issues/3439:
// Restore to using % and / when the JIT is able to eliminate one of the idivs.
// In the meantime, a * and - is measurably faster than an extra /.
int div = a / b;
result = a - (div * b);
return div;
}
public static long DivRem(long a, long b, out long result)
{
// TODO https://github.com/dotnet/coreclr/issues/3439:
// Restore to using % and / when the JIT is able to eliminate one of the idivs.
// In the meantime, a * and - is measurably faster than an extra /.
long div = a / b;
result = a - (div * b);
return div;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
using System;
using System.Linq;
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 Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// VirtualNetworksOperations operations.
/// </summary>
internal partial class VirtualNetworksOperations : IServiceOperations<DevTestLabsClient>, IVirtualNetworksOperations
{
/// <summary>
/// Initializes a new instance of the VirtualNetworksOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal VirtualNetworksOperations(DevTestLabsClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the DevTestLabsClient
/// </summary>
public DevTestLabsClient Client { get; private set; }
/// <summary>
/// List virtual networks in a given lab.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListWithHttpMessagesAsync(string labName, ODataQuery<VirtualNetwork> odataQuery = default(ODataQuery<VirtualNetwork>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("labName", labName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualNetwork>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get virtual network.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual network.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example: 'properties($expand=externalSubnets)'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualNetwork>> GetWithHttpMessagesAsync(string labName, string name, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualNetwork>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create or replace an existing virtual network. This operation can take a
/// while to complete.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetwork'>
/// A virtual network.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<VirtualNetwork>> CreateOrUpdateWithHttpMessagesAsync(string labName, string name, VirtualNetwork virtualNetwork, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<VirtualNetwork> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(
labName, name, virtualNetwork, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// Create or replace an existing virtual network. This operation can take a
/// while to complete.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetwork'>
/// A virtual network.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualNetwork>> BeginCreateOrUpdateWithHttpMessagesAsync(string labName, string name, VirtualNetwork virtualNetwork, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (virtualNetwork == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetwork");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("virtualNetwork", virtualNetwork);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(virtualNetwork != null)
{
_requestContent = SafeJsonConvert.SerializeObject(virtualNetwork, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualNetwork>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete virtual network. This operation can take a while to complete.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(
labName, name, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// Delete virtual network. This operation can take a while to complete.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual network.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Modify properties of virtual networks.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the virtual network.
/// </param>
/// <param name='virtualNetwork'>
/// A virtual network.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<VirtualNetwork>> UpdateWithHttpMessagesAsync(string labName, string name, VirtualNetworkFragment virtualNetwork, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (virtualNetwork == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetwork");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("virtualNetwork", virtualNetwork);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualnetworks/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(virtualNetwork != null)
{
_requestContent = SafeJsonConvert.SerializeObject(virtualNetwork, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<VirtualNetwork>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// List virtual networks in a given lab.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<VirtualNetwork>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Orleans.CodeGeneration;
namespace Orleans.Runtime
{
/// <summary>
/// A collection of utility functions for dealing with Type information.
/// </summary>
internal static class TypeUtils
{
/// <summary>
/// The assembly name of the core Orleans assembly.
/// </summary>
private static readonly AssemblyName OrleansCoreAssembly = typeof(RuntimeVersion).GetTypeInfo().Assembly.GetName();
private static readonly ConcurrentDictionary<Tuple<Type, TypeFormattingOptions>, string> ParseableNameCache = new ConcurrentDictionary<Tuple<Type, TypeFormattingOptions>, string>();
private static readonly ConcurrentDictionary<Tuple<Type, bool>, List<Type>> ReferencedTypes = new ConcurrentDictionary<Tuple<Type, bool>, List<Type>>();
private static readonly CachedReflectionOnlyTypeResolver ReflectionOnlyTypeResolver = new CachedReflectionOnlyTypeResolver();
public static string GetSimpleTypeName(Type t, Predicate<Type> fullName = null)
{
return GetSimpleTypeName(t.GetTypeInfo(), fullName);
}
public static string GetSimpleTypeName(TypeInfo typeInfo, Predicate<Type> fullName = null)
{
if (typeInfo.IsNestedPublic || typeInfo.IsNestedPrivate)
{
if (typeInfo.DeclaringType.GetTypeInfo().IsGenericType)
{
return GetTemplatedName(
GetUntemplatedTypeName(typeInfo.DeclaringType.Name),
typeInfo.DeclaringType,
typeInfo.GetGenericArguments(),
_ => true) + "." + GetUntemplatedTypeName(typeInfo.Name);
}
return GetTemplatedName(typeInfo.DeclaringType) + "." + GetUntemplatedTypeName(typeInfo.Name);
}
var type = typeInfo.AsType();
if (typeInfo.IsGenericType) return GetSimpleTypeName(fullName != null && fullName(type) ? GetFullName(type) : typeInfo.Name);
return fullName != null && fullName(type) ? GetFullName(type) : typeInfo.Name;
}
public static string GetUntemplatedTypeName(string typeName)
{
int i = typeName.IndexOf('`');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('<');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
return typeName;
}
public static string GetSimpleTypeName(string typeName)
{
int i = typeName.IndexOf('`');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('[');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('<');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
return typeName;
}
public static bool IsConcreteTemplateType(Type t)
{
if (t.GetTypeInfo().IsGenericType) return true;
return t.IsArray && IsConcreteTemplateType(t.GetElementType());
}
public static string GetTemplatedName(Type t, Predicate<Type> fullName = null)
{
if (fullName == null)
fullName = _ => true; // default to full type names
var typeInfo = t.GetTypeInfo();
if (typeInfo.IsGenericType) return GetTemplatedName(GetSimpleTypeName(typeInfo, fullName), t, typeInfo.GetGenericArguments(), fullName);
if (t.IsArray)
{
return GetTemplatedName(t.GetElementType(), fullName)
+ "["
+ new string(',', t.GetArrayRank() - 1)
+ "]";
}
return GetSimpleTypeName(typeInfo, fullName);
}
public static bool IsConstructedGenericType(this TypeInfo typeInfo)
{
// is there an API that returns this info without converting back to type already?
return typeInfo.AsType().IsConstructedGenericType;
}
internal static IEnumerable<TypeInfo> GetTypeInfos(this Type[] types)
{
return types.Select(t => t.GetTypeInfo());
}
public static string GetTemplatedName(string baseName, Type t, Type[] genericArguments, Predicate<Type> fullName)
{
var typeInfo = t.GetTypeInfo();
if (!typeInfo.IsGenericType || (t.DeclaringType != null && t.DeclaringType.GetTypeInfo().IsGenericType)) return baseName;
string s = baseName;
s += "<";
s += GetGenericTypeArgs(genericArguments, fullName);
s += ">";
return s;
}
public static string GetGenericTypeArgs(IEnumerable<Type> args, Predicate<Type> fullName)
{
string s = string.Empty;
bool first = true;
foreach (var genericParameter in args)
{
if (!first)
{
s += ",";
}
if (!genericParameter.GetTypeInfo().IsGenericType)
{
s += GetSimpleTypeName(genericParameter, fullName);
}
else
{
s += GetTemplatedName(genericParameter, fullName);
}
first = false;
}
return s;
}
public static string GetParameterizedTemplateName(TypeInfo typeInfo, bool applyRecursively = false, Predicate<Type> fullName = null)
{
if (fullName == null)
fullName = tt => true;
return GetParameterizedTemplateName(typeInfo, fullName, applyRecursively);
}
public static string GetParameterizedTemplateName(TypeInfo typeInfo, Predicate<Type> fullName, bool applyRecursively = false)
{
if (typeInfo.IsGenericType)
{
return GetParameterizedTemplateName(GetSimpleTypeName(typeInfo, fullName), typeInfo, applyRecursively, fullName);
}
var t = typeInfo.AsType();
if (fullName != null && fullName(t) == true)
{
return t.FullName;
}
return t.Name;
}
public static string GetParameterizedTemplateName(string baseName, TypeInfo typeInfo, bool applyRecursively = false, Predicate<Type> fullName = null)
{
if (fullName == null)
fullName = tt => false;
if (!typeInfo.IsGenericType) return baseName;
string s = baseName;
s += "<";
bool first = true;
foreach (var genericParameter in typeInfo.GetGenericArguments())
{
if (!first)
{
s += ",";
}
var genericParameterTypeInfo = genericParameter.GetTypeInfo();
if (applyRecursively && genericParameterTypeInfo.IsGenericType)
{
s += GetParameterizedTemplateName(genericParameterTypeInfo, applyRecursively);
}
else
{
s += genericParameter.FullName == null || !fullName(genericParameter)
? genericParameter.Name
: genericParameter.FullName;
}
first = false;
}
s += ">";
return s;
}
public static string GetRawClassName(string baseName, Type t)
{
var typeInfo = t.GetTypeInfo();
return typeInfo.IsGenericType ? baseName + '`' + typeInfo.GetGenericArguments().Length : baseName;
}
public static string GetRawClassName(string typeName)
{
int i = typeName.IndexOf('[');
return i <= 0 ? typeName : typeName.Substring(0, i);
}
public static Type[] GenericTypeArgsFromClassName(string className)
{
return GenericTypeArgsFromArgsString(GenericTypeArgsString(className));
}
public static Type[] GenericTypeArgsFromArgsString(string genericArgs)
{
if (string.IsNullOrEmpty(genericArgs)) return Type.EmptyTypes;
var genericTypeDef = genericArgs.Replace("[]", "##"); // protect array arguments
return InnerGenericTypeArgs(genericTypeDef);
}
private static Type[] InnerGenericTypeArgs(string className)
{
var typeArgs = new List<Type>();
var innerTypes = GetInnerTypes(className);
foreach (var innerType in innerTypes)
{
if (innerType.StartsWith("[[")) // Resolve and load generic types recursively
{
InnerGenericTypeArgs(GenericTypeArgsString(innerType));
string genericTypeArg = className.Trim('[', ']');
typeArgs.Add(Type.GetType(genericTypeArg.Replace("##", "[]")));
}
else
{
string nonGenericTypeArg = innerType.Trim('[', ']');
typeArgs.Add(Type.GetType(nonGenericTypeArg.Replace("##", "[]")));
}
}
return typeArgs.ToArray();
}
private static string[] GetInnerTypes(string input)
{
// Iterate over strings of length 2 positionwise.
var charsWithPositions = input.Zip(Enumerable.Range(0, input.Length), (c, i) => new { Ch = c, Pos = i });
var candidatesWithPositions = charsWithPositions.Zip(charsWithPositions.Skip(1), (c1, c2) => new { Str = c1.Ch.ToString() + c2.Ch, Pos = c1.Pos });
var results = new List<string>();
int startPos = -1;
int endPos = -1;
int endTokensNeeded = 0;
string curStartToken = "";
string curEndToken = "";
var tokenPairs = new[] { new { Start = "[[", End = "]]" }, new { Start = "[", End = "]" } }; // Longer tokens need to come before shorter ones
foreach (var candidate in candidatesWithPositions)
{
if (startPos == -1)
{
foreach (var token in tokenPairs)
{
if (candidate.Str.StartsWith(token.Start))
{
curStartToken = token.Start;
curEndToken = token.End;
startPos = candidate.Pos;
break;
}
}
}
if (curStartToken != "" && candidate.Str.StartsWith(curStartToken))
endTokensNeeded++;
if (curEndToken != "" && candidate.Str.EndsWith(curEndToken))
{
endPos = candidate.Pos;
endTokensNeeded--;
}
if (endTokensNeeded == 0 && startPos != -1)
{
results.Add(input.Substring(startPos, endPos - startPos + 2));
startPos = -1;
curStartToken = "";
}
}
return results.ToArray();
}
public static string GenericTypeArgsString(string className)
{
int startIndex = className.IndexOf('[');
int endIndex = className.LastIndexOf(']');
return className.Substring(startIndex + 1, endIndex - startIndex - 1);
}
public static bool IsGenericClass(string name)
{
return name.Contains("`") || name.Contains("[");
}
public static string GetFullName(TypeInfo typeInfo)
{
if (typeInfo == null) throw new ArgumentNullException(nameof(typeInfo));
return GetFullName(typeInfo.AsType());
}
public static string GetFullName(Type t)
{
if (t == null) throw new ArgumentNullException(nameof(t));
if (t.IsNested && !t.IsGenericParameter)
{
return t.Namespace + "." + t.DeclaringType.Name + "." + t.Name;
}
if (t.IsArray)
{
return GetFullName(t.GetElementType())
+ "["
+ new string(',', t.GetArrayRank() - 1)
+ "]";
}
return t.FullName ?? (t.IsGenericParameter ? t.Name : t.Namespace + "." + t.Name);
}
/// <summary>
/// Returns all fields of the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>All fields of the specified type.</returns>
public static IEnumerable<FieldInfo> GetAllFields(this Type type)
{
const BindingFlags AllFields =
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
var current = type;
while ((current != typeof(object)) && (current != null))
{
var fields = current.GetFields(AllFields);
foreach (var field in fields)
{
yield return field;
}
current = current.GetTypeInfo().BaseType;
}
}
/// <summary>
/// Returns <see langword="true"/> if <paramref name="field"/> is marked as
/// <see cref="FieldAttributes.NotSerialized"/>, <see langword="false"/> otherwise.
/// </summary>
/// <param name="field">The field.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="field"/> is marked as
/// <see cref="FieldAttributes.NotSerialized"/>, <see langword="false"/> otherwise.
/// </returns>
public static bool IsNotSerialized(this FieldInfo field)
=> (field.Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized;
/// <summary>
/// decide whether the class is derived from Grain
/// </summary>
public static bool IsGrainClass(Type type)
{
var grainType = typeof(Grain);
var grainChevronType = typeof(Grain<>);
if (type.Assembly.ReflectionOnly)
{
grainType = ToReflectionOnlyType(grainType);
grainChevronType = ToReflectionOnlyType(grainChevronType);
}
if (grainType == type || grainChevronType == type) return false;
if (!grainType.IsAssignableFrom(type)) return false;
// exclude generated classes.
return !IsGeneratedType(type);
}
public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints, bool complain)
{
complaints = null;
if (!IsGrainClass(type)) return false;
if (!type.GetTypeInfo().IsAbstract) return true;
complaints = complain ? new[] { string.Format("Grain type {0} is abstract and cannot be instantiated.", type.FullName) } : null;
return false;
}
public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints)
{
return IsConcreteGrainClass(type, out complaints, complain: true);
}
public static bool IsConcreteGrainClass(Type type)
{
IEnumerable<string> complaints;
return IsConcreteGrainClass(type, out complaints, complain: false);
}
public static bool IsGeneratedType(Type type)
{
return TypeHasAttribute(type, typeof(GeneratedCodeAttribute));
}
/// <summary>
/// Returns true if the provided <paramref name="type"/> is in any of the provided
/// <paramref name="namespaces"/>, false otherwise.
/// </summary>
/// <param name="type">The type to check.</param>
/// <param name="namespaces"></param>
/// <returns>
/// true if the provided <paramref name="type"/> is in any of the provided <paramref name="namespaces"/>, false
/// otherwise.
/// </returns>
public static bool IsInNamespace(Type type, List<string> namespaces)
{
if (type.Namespace == null)
{
return false;
}
foreach (var ns in namespaces)
{
if (ns.Length > type.Namespace.Length)
{
continue;
}
// If the candidate namespace is a prefix of the type's namespace, return true.
if (type.Namespace.StartsWith(ns, StringComparison.Ordinal)
&& (type.Namespace.Length == ns.Length || type.Namespace[ns.Length] == '.'))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns true if <paramref name="type"/> has implementations of all serialization methods, false otherwise.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// true if <paramref name="type"/> has implementations of all serialization methods, false otherwise.
/// </returns>
public static bool HasAllSerializationMethods(Type type)
{
// Check if the type has any of the serialization methods.
var hasCopier = false;
var hasSerializer = false;
var hasDeserializer = false;
foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
{
hasSerializer |= method.GetCustomAttribute<SerializerMethodAttribute>(false) != null;
hasDeserializer |= method.GetCustomAttribute<DeserializerMethodAttribute>(false) != null;
hasCopier |= method.GetCustomAttribute<CopierMethodAttribute>(false) != null;
}
var hasAllSerializationMethods = hasCopier && hasSerializer && hasDeserializer;
return hasAllSerializationMethods;
}
public static bool IsGrainMethodInvokerType(Type type)
{
var generalType = typeof(IGrainMethodInvoker);
if (type.Assembly.ReflectionOnly)
{
generalType = ToReflectionOnlyType(generalType);
}
return generalType.IsAssignableFrom(type) && TypeHasAttribute(type, typeof(MethodInvokerAttribute));
}
private static readonly Lazy<bool> canUseReflectionOnly = new Lazy<bool>(() =>
{
try
{
ReflectionOnlyTypeResolver.TryResolveType(typeof(TypeUtils).AssemblyQualifiedName, out _);
return true;
}
catch (PlatformNotSupportedException)
{
return false;
}
catch (Exception)
{
// if other exceptions not related to platform ocurr, assume that ReflectionOnly is supported
return true;
}
});
public static bool CanUseReflectionOnly => canUseReflectionOnly.Value;
public static Type ResolveReflectionOnlyType(string assemblyQualifiedName)
{
return ReflectionOnlyTypeResolver.ResolveType(assemblyQualifiedName);
}
public static Type ToReflectionOnlyType(Type type)
{
if (CanUseReflectionOnly)
{
return type.Assembly.ReflectionOnly ? type : ResolveReflectionOnlyType(type.AssemblyQualifiedName);
}
else
{
return type;
}
}
public static IEnumerable<Type> GetTypes(Assembly assembly, Predicate<Type> whereFunc, Logger logger)
{
return assembly.IsDynamic ? Enumerable.Empty<Type>() : GetDefinedTypes(assembly, logger).Select(t => t.AsType()).Where(type => !type.GetTypeInfo().IsNestedPrivate && whereFunc(type));
}
public static IEnumerable<TypeInfo> GetDefinedTypes(Assembly assembly, Logger logger)
{
try
{
return assembly.DefinedTypes;
}
catch (Exception exception)
{
if (logger != null && logger.IsWarning)
{
var message =
$"Exception loading types from assembly '{assembly.FullName}': {LogFormatter.PrintException(exception)}.";
logger.Warn(ErrorCode.Loader_TypeLoadError_5, message, exception);
}
var typeLoadException = exception as ReflectionTypeLoadException;
if (typeLoadException != null)
{
return typeLoadException.Types?.Where(type => type != null).Select(type => type.GetTypeInfo()) ??
Enumerable.Empty<TypeInfo>();
}
return Enumerable.Empty<TypeInfo>();
}
}
/// <summary>
/// Returns a value indicating whether or not the provided <paramref name="methodInfo"/> is a grain method.
/// </summary>
/// <param name="methodInfo">The method.</param>
/// <returns>A value indicating whether or not the provided <paramref name="methodInfo"/> is a grain method.</returns>
public static bool IsGrainMethod(MethodInfo methodInfo)
{
if (methodInfo == null) throw new ArgumentNullException("methodInfo", "Cannot inspect null method info");
if (methodInfo.IsStatic || methodInfo.IsSpecialName || methodInfo.DeclaringType == null)
{
return false;
}
return methodInfo.DeclaringType.GetTypeInfo().IsInterface
&& typeof(IAddressable).IsAssignableFrom(methodInfo.DeclaringType);
}
public static bool TypeHasAttribute(Type type, Type attribType)
{
if (type.Assembly.ReflectionOnly || attribType.Assembly.ReflectionOnly)
{
type = ToReflectionOnlyType(type);
attribType = ToReflectionOnlyType(attribType);
// we can't use Type.GetCustomAttributes here because we could potentially be working with a reflection-only type.
return CustomAttributeData.GetCustomAttributes(type).Any(
attrib => attribType.IsAssignableFrom(attrib.AttributeType));
}
return TypeHasAttribute(type.GetTypeInfo(), attribType);
}
public static bool TypeHasAttribute(TypeInfo typeInfo, Type attribType)
{
return typeInfo.GetCustomAttributes(attribType, true).Any();
}
/// <summary>
/// Returns a sanitized version of <paramref name="type"/>s name which is suitable for use as a class name.
/// </summary>
/// <param name="type">
/// The grain type.
/// </param>
/// <returns>
/// A sanitized version of <paramref name="type"/>s name which is suitable for use as a class name.
/// </returns>
public static string GetSuitableClassName(Type type)
{
return GetClassNameFromInterfaceName(type.GetUnadornedTypeName());
}
/// <summary>
/// Returns a class-like version of <paramref name="interfaceName"/>.
/// </summary>
/// <param name="interfaceName">
/// The interface name.
/// </param>
/// <returns>
/// A class-like version of <paramref name="interfaceName"/>.
/// </returns>
public static string GetClassNameFromInterfaceName(string interfaceName)
{
string cleanName;
if (interfaceName.StartsWith("i", StringComparison.OrdinalIgnoreCase))
{
cleanName = interfaceName.Substring(1);
}
else
{
cleanName = interfaceName;
}
return cleanName;
}
/// <summary>
/// Returns the non-generic type name without any special characters.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <returns>
/// The non-generic type name without any special characters.
/// </returns>
public static string GetUnadornedTypeName(this Type type)
{
var index = type.Name.IndexOf('`');
// An ampersand can appear as a suffix to a by-ref type.
return (index > 0 ? type.Name.Substring(0, index) : type.Name).TrimEnd('&');
}
/// <summary>
/// Returns the non-generic method name without any special characters.
/// </summary>
/// <param name="method">
/// The method.
/// </param>
/// <returns>
/// The non-generic method name without any special characters.
/// </returns>
public static string GetUnadornedMethodName(this MethodInfo method)
{
var index = method.Name.IndexOf('`');
return index > 0 ? method.Name.Substring(0, index) : method.Name;
}
/// <summary>Returns a string representation of <paramref name="type"/>.</summary>
/// <param name="type">The type.</param>
/// <param name="options">The type formatting options.</param>
/// <param name="getNameFunc">The delegate used to get the unadorned, simple type name of <paramref name="type"/>.</param>
/// <returns>A string representation of the <paramref name="type"/>.</returns>
public static string GetParseableName(this Type type, TypeFormattingOptions options = null, Func<Type, string> getNameFunc = null)
{
options = options ?? TypeFormattingOptions.Default;
// If a naming function has been specified, skip the cache.
if (getNameFunc != null) return BuildParseableName();
return ParseableNameCache.GetOrAdd(Tuple.Create(type, options), _ => BuildParseableName());
string BuildParseableName()
{
var builder = new StringBuilder();
var typeInfo = type.GetTypeInfo();
GetParseableName(
type,
builder,
new Queue<Type>(
typeInfo.IsGenericTypeDefinition
? typeInfo.GetGenericArguments()
: typeInfo.GenericTypeArguments),
options,
getNameFunc ?? (t => t.GetUnadornedTypeName() + options.NameSuffix));
return builder.ToString();
}
}
/// <summary>Returns a string representation of <paramref name="type"/>.</summary>
/// <param name="type">The type.</param>
/// <param name="builder">The <see cref="StringBuilder"/> to append results to.</param>
/// <param name="typeArguments">The type arguments of <paramref name="type"/>.</param>
/// <param name="options">The type formatting options.</param>
private static void GetParseableName(
Type type,
StringBuilder builder,
Queue<Type> typeArguments,
TypeFormattingOptions options,
Func<Type, string> getNameFunc)
{
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsArray)
{
var elementType = typeInfo.GetElementType().GetParseableName(options);
if (!string.IsNullOrWhiteSpace(elementType))
{
builder.AppendFormat(
"{0}[{1}]",
elementType,
string.Concat(Enumerable.Range(0, type.GetArrayRank() - 1).Select(_ => ',')));
}
return;
}
if (typeInfo.IsGenericParameter)
{
if (options.IncludeGenericTypeParameters)
{
builder.Append(type.GetUnadornedTypeName());
}
return;
}
if (typeInfo.DeclaringType != null)
{
// This is not the root type.
GetParseableName(typeInfo.DeclaringType, builder, typeArguments, options, t => t.GetUnadornedTypeName());
builder.Append(options.NestedTypeSeparator);
}
else if (!string.IsNullOrWhiteSpace(type.Namespace) && options.IncludeNamespace)
{
// This is the root type, so include the namespace.
var namespaceName = type.Namespace;
if (options.NestedTypeSeparator != '.')
{
namespaceName = namespaceName.Replace('.', options.NestedTypeSeparator);
}
if (options.IncludeGlobal)
{
builder.AppendFormat("global::");
}
builder.AppendFormat("{0}{1}", namespaceName, options.NestedTypeSeparator);
}
if (type.IsConstructedGenericType)
{
// Get the unadorned name, the generic parameters, and add them together.
var unadornedTypeName = getNameFunc(type);
builder.Append(EscapeIdentifier(unadornedTypeName));
var generics =
Enumerable.Range(0, Math.Min(typeInfo.GetGenericArguments().Count(), typeArguments.Count))
.Select(_ => typeArguments.Dequeue())
.ToList();
if (generics.Count > 0 && options.IncludeTypeParameters)
{
var genericParameters = string.Join(
",",
generics.Select(generic => GetParseableName(generic, options)));
builder.AppendFormat("<{0}>", genericParameters);
}
}
else if (typeInfo.IsGenericTypeDefinition)
{
// Get the unadorned name, the generic parameters, and add them together.
var unadornedTypeName = getNameFunc(type);
builder.Append(EscapeIdentifier(unadornedTypeName));
var generics =
Enumerable.Range(0, Math.Min(type.GetGenericArguments().Count(), typeArguments.Count))
.Select(_ => typeArguments.Dequeue())
.ToList();
if (generics.Count > 0 && options.IncludeTypeParameters)
{
var genericParameters = string.Join(
",",
generics.Select(_ => options.IncludeGenericTypeParameters ? _.ToString() : string.Empty));
builder.AppendFormat("<{0}>", genericParameters);
}
}
else
{
builder.Append(EscapeIdentifier(getNameFunc(type)));
}
}
/// <summary>
/// Returns the namespaces of the specified types.
/// </summary>
/// <param name="types">
/// The types to include.
/// </param>
/// <returns>
/// The namespaces of the specified types.
/// </returns>
public static IEnumerable<string> GetNamespaces(params Type[] types)
{
return types.Select(type => "global::" + type.Namespace).Distinct();
}
/// <summary>
/// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the method.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the method.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </returns>
public static MethodInfo Method<T, TResult>(Expression<Func<T, TResult>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="PropertyInfo"/> for the simple member access in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the property.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the property.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="PropertyInfo"/> for the simple member access call in the provided <paramref name="expression"/>.
/// </returns>
public static PropertyInfo Property<T, TResult>(Expression<Func<T, TResult>> expression)
{
var property = expression.Body as MemberExpression;
if (property != null)
{
return property.Member as PropertyInfo;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="PropertyInfo"/> for the simple member access in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="TResult">
/// The return type of the property.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="PropertyInfo"/> for the simple member access call in the provided <paramref name="expression"/>.
/// </returns>
public static PropertyInfo Property<TResult>(Expression<Func<TResult>> expression)
{
var property = expression.Body as MemberExpression;
if (property != null)
{
return property.Member as PropertyInfo;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="MemberInfo"/> for the simple member access in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the method.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the method.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MemberInfo"/> for the simple member access call in the provided <paramref name="expression"/>.
/// </returns>
public static MemberInfo Member<T, TResult>(Expression<Func<T, TResult>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
var property = expression.Body as MemberExpression;
if (property != null)
{
return property.Member;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>Returns the <see cref="MemberInfo"/> for the simple member access in the provided <paramref name="expression"/>.</summary>
/// <typeparam name="TResult">The return type of the method.</typeparam>
/// <param name="expression">The expression.</param>
/// <returns>The <see cref="MemberInfo"/> for the simple member access call in the provided <paramref name="expression"/>.</returns>
public static MemberInfo Member<TResult>(Expression<Func<TResult>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
var property = expression.Body as MemberExpression;
if (property != null)
{
return property.Member;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</summary>
/// <typeparam name="T">The containing type of the method.</typeparam>
/// <param name="expression">The expression.</param>
/// <returns>The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</returns>
public static MethodInfo Method<T>(Expression<Func<T>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">The containing type of the method.</typeparam>
/// <param name="expression">The expression.</param>
/// <returns>The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</returns>
public static MethodInfo Method<T>(Expression<Action<T>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </summary>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </returns>
public static MethodInfo Method(Expression<Action> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>Returns the namespace of the provided type, or <see cref="string.Empty"/> if the type has no namespace.</summary>
/// <param name="type">The type.</param>
/// <returns>The namespace of the provided type, or <see cref="string.Empty"/> if the type has no namespace.</returns>
public static string GetNamespaceOrEmpty(this Type type)
{
if (type == null || string.IsNullOrEmpty(type.Namespace))
{
return string.Empty;
}
return type.Namespace;
}
/// <summary>Returns the types referenced by the provided <paramref name="type"/>.</summary>
/// <param name="type">The type.</param>
/// <param name="includeMethods">Whether or not to include the types referenced in the methods of this type.</param>
/// <returns>The types referenced by the provided <paramref name="type"/>.</returns>
public static IList<Type> GetTypes(this Type type, bool includeMethods = false)
{
List<Type> results;
var key = Tuple.Create(type, includeMethods);
if (!ReferencedTypes.TryGetValue(key, out results))
{
results = GetTypes(type, includeMethods, null).ToList();
ReferencedTypes.TryAdd(key, results);
}
return results;
}
/// <summary>
/// Get a public or non-public constructor that matches the constructor arguments signature
/// </summary>
/// <param name="type">The type to use.</param>
/// <param name="constructorArguments">The constructor argument types to match for the signature.</param>
/// <returns>A constructor that matches the signature or <see langword="null"/>.</returns>
public static ConstructorInfo GetConstructorThatMatches(Type type, Type[] constructorArguments)
{
var constructorInfo = type.GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
constructorArguments,
null);
return constructorInfo;
}
/// <summary>
/// Returns a value indicating whether or not the provided assembly is the Orleans assembly or references it.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>A value indicating whether or not the provided assembly is the Orleans assembly or references it.</returns>
internal static bool IsOrleansOrReferencesOrleans(Assembly assembly)
{
// We want to be loosely coupled to the assembly version if an assembly depends on an older Orleans,
// but we want a strong assembly match for the Orleans binary itself
// (so we don't load 2 different versions of Orleans by mistake)
return DoReferencesContain(assembly.GetReferencedAssemblies(), OrleansCoreAssembly)
|| string.Equals(assembly.GetName().FullName, OrleansCoreAssembly.FullName, StringComparison.Ordinal);
}
/// <summary>
/// Returns a value indicating whether or not the specified references contain the provided assembly name.
/// </summary>
/// <param name="references">The references.</param>
/// <param name="assemblyName">The assembly name.</param>
/// <returns>A value indicating whether or not the specified references contain the provided assembly name.</returns>
private static bool DoReferencesContain(IReadOnlyCollection<AssemblyName> references, AssemblyName assemblyName)
{
if (references.Count == 0)
{
return false;
}
return references.Any(asm => string.Equals(asm.Name, assemblyName.Name, StringComparison.Ordinal));
}
/// <summary>Returns the types referenced by the provided <paramref name="type"/>.</summary>
/// <param name="type">The type.</param>
/// <param name="includeMethods">Whether or not to include the types referenced in the methods of this type.</param>
/// <param name="exclude">Types to exclude</param>
/// <returns>The types referenced by the provided <paramref name="type"/>.</returns>
private static IEnumerable<Type> GetTypes(
this Type type,
bool includeMethods,
HashSet<Type> exclude)
{
exclude = exclude ?? new HashSet<Type>();
if (!exclude.Add(type))
{
yield break;
}
yield return type;
if (type.IsArray)
{
foreach (var elementType in type.GetElementType().GetTypes(false, exclude: exclude))
{
yield return elementType;
}
}
if (type.IsConstructedGenericType)
{
foreach (var genericTypeArgument in
type.GetGenericArguments().SelectMany(_ => GetTypes(_, false, exclude: exclude)))
{
yield return genericTypeArgument;
}
}
if (!includeMethods)
{
yield break;
}
foreach (var method in type.GetMethods())
{
foreach (var referencedType in GetTypes(method.ReturnType, false, exclude: exclude))
{
yield return referencedType;
}
foreach (var parameter in method.GetParameters())
{
foreach (var referencedType in GetTypes(parameter.ParameterType, false, exclude: exclude))
{
yield return referencedType;
}
}
}
}
private static string EscapeIdentifier(string identifier)
{
if (IsCSharpKeyword(identifier)) return "@" + identifier;
return identifier;
}
internal static bool IsCSharpKeyword(string identifier)
{
switch (identifier)
{
case "abstract":
case "add":
case "alias":
case "as":
case "ascending":
case "async":
case "await":
case "base":
case "bool":
case "break":
case "byte":
case "case":
case "catch":
case "char":
case "checked":
case "class":
case "const":
case "continue":
case "decimal":
case "default":
case "delegate":
case "descending":
case "do":
case "double":
case "dynamic":
case "else":
case "enum":
case "event":
case "explicit":
case "extern":
case "false":
case "finally":
case "fixed":
case "float":
case "for":
case "foreach":
case "from":
case "get":
case "global":
case "goto":
case "group":
case "if":
case "implicit":
case "in":
case "int":
case "interface":
case "internal":
case "into":
case "is":
case "join":
case "let":
case "lock":
case "long":
case "nameof":
case "namespace":
case "new":
case "null":
case "object":
case "operator":
case "orderby":
case "out":
case "override":
case "params":
case "partial":
case "private":
case "protected":
case "public":
case "readonly":
case "ref":
case "remove":
case "return":
case "sbyte":
case "sealed":
case "select":
case "set":
case "short":
case "sizeof":
case "stackalloc":
case "static":
case "string":
case "struct":
case "switch":
case "this":
case "throw":
case "true":
case "try":
case "typeof":
case "uint":
case "ulong":
case "unchecked":
case "unsafe":
case "ushort":
case "using":
case "value":
case "var":
case "virtual":
case "void":
case "volatile":
case "when":
case "where":
case "while":
case "yield":
return true;
default:
return false;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Lucene.Net.Support;
using Document = Lucene.Net.Documents.Document;
using FieldSelector = Lucene.Net.Documents.FieldSelector;
using FieldSelectorResult = Lucene.Net.Documents.FieldSelectorResult;
namespace Lucene.Net.Index
{
/// <summary>An IndexReader which reads multiple, parallel indexes. Each index added
/// must have the same number of documents, but typically each contains
/// different fields. Each document contains the union of the fields of all
/// documents with the same document number. When searching, matches for a
/// query term are from the first index added that has the field.
///
/// <p/>This is useful, e.g., with collections that have large fields which
/// change rarely and small fields that change more frequently. The smaller
/// fields may be re-indexed in a new index and both indexes may be searched
/// together.
///
/// <p/><strong>Warning:</strong> It is up to you to make sure all indexes
/// are created and modified the same way. For example, if you add
/// documents to one index, you need to add the same documents in the
/// same order to the other indexes. <em>Failure to do so will result in
/// undefined behavior</em>.
/// </summary>
public class ParallelReader:IndexReader, System.ICloneable
{
private List<IndexReader> readers = new List<IndexReader>();
private List<bool> decrefOnClose = new List<bool>(); // remember which subreaders to decRef on close
internal bool incRefReaders = false;
private SortedDictionary<string, IndexReader> fieldToReader = new SortedDictionary<string, IndexReader>();
private IDictionary<IndexReader, ICollection<string>> readerToFields = new HashMap<IndexReader, ICollection<string>>();
private List<IndexReader> storedFieldReaders = new List<IndexReader>();
private int maxDoc;
private int numDocs;
private bool hasDeletions;
/// <summary>Construct a ParallelReader.
/// <p/>Note that all subreaders are closed if this ParallelReader is closed.<p/>
/// </summary>
public ParallelReader():this(true)
{
}
/// <summary>Construct a ParallelReader. </summary>
/// <param name="closeSubReaders">indicates whether the subreaders should be closed
/// when this ParallelReader is closed
/// </param>
public ParallelReader(bool closeSubReaders):base()
{
this.incRefReaders = !closeSubReaders;
}
/// <summary>Add an IndexReader.</summary>
/// <throws> IOException if there is a low-level IO error </throws>
public virtual void Add(IndexReader reader)
{
EnsureOpen();
Add(reader, false);
}
/// <summary>Add an IndexReader whose stored fields will not be returned. This can
/// accellerate search when stored fields are only needed from a subset of
/// the IndexReaders.
///
/// </summary>
/// <throws> IllegalArgumentException if not all indexes contain the same number </throws>
/// <summary> of documents
/// </summary>
/// <throws> IllegalArgumentException if not all indexes have the same value </throws>
/// <summary> of <see cref="IndexReader.MaxDoc" />
/// </summary>
/// <throws> IOException if there is a low-level IO error </throws>
public virtual void Add(IndexReader reader, bool ignoreStoredFields)
{
EnsureOpen();
if (readers.Count == 0)
{
this.maxDoc = reader.MaxDoc;
this.numDocs = reader.NumDocs();
this.hasDeletions = reader.HasDeletions;
}
if (reader.MaxDoc != maxDoc)
// check compatibility
throw new System.ArgumentException("All readers must have same maxDoc: " + maxDoc + "!=" + reader.MaxDoc);
if (reader.NumDocs() != numDocs)
throw new System.ArgumentException("All readers must have same numDocs: " + numDocs + "!=" + reader.NumDocs());
ICollection<string> fields = reader.GetFieldNames(IndexReader.FieldOption.ALL);
readerToFields[reader] = fields;
foreach(var field in fields)
{
// update fieldToReader map
// Do a containskey firt to mimic java behavior
if (!fieldToReader.ContainsKey(field) || fieldToReader[field] == null)
fieldToReader[field] = reader;
}
if (!ignoreStoredFields)
storedFieldReaders.Add(reader); // add to storedFieldReaders
readers.Add(reader);
if (incRefReaders)
{
reader.IncRef();
}
decrefOnClose.Add(incRefReaders);
}
public override System.Object Clone()
{
try
{
return DoReopen(true);
}
catch (System.Exception ex)
{
throw new System.SystemException(ex.Message, ex);
}
}
/// <summary> Tries to reopen the subreaders.
/// <br/>
/// If one or more subreaders could be re-opened (i. e. subReader.reopen()
/// returned a new instance != subReader), then a new ParallelReader instance
/// is returned, otherwise this instance is returned.
/// <p/>
/// A re-opened instance might share one or more subreaders with the old
/// instance. Index modification operations result in undefined behavior
/// when performed before the old instance is closed.
/// (see <see cref="IndexReader.Reopen()" />).
/// <p/>
/// If subreaders are shared, then the reference count of those
/// readers is increased to ensure that the subreaders remain open
/// until the last referring reader is closed.
///
/// </summary>
/// <throws> CorruptIndexException if the index is corrupt </throws>
/// <throws> IOException if there is a low-level IO error </throws>
public override IndexReader Reopen()
{
lock (this)
{
return DoReopen(false);
}
}
protected internal virtual IndexReader DoReopen(bool doClone)
{
EnsureOpen();
bool reopened = false;
IList<IndexReader> newReaders = new List<IndexReader>();
bool success = false;
try
{
foreach(var oldReader in readers)
{
IndexReader newReader = null;
if (doClone)
{
newReader = (IndexReader) oldReader.Clone();
}
else
{
newReader = oldReader.Reopen();
}
newReaders.Add(newReader);
// if at least one of the subreaders was updated we remember that
// and return a new ParallelReader
if (newReader != oldReader)
{
reopened = true;
}
}
success = true;
}
finally
{
if (!success && reopened)
{
for (int i = 0; i < newReaders.Count; i++)
{
IndexReader r = newReaders[i];
if (r != readers[i])
{
try
{
r.Close();
}
catch (System.IO.IOException)
{
// keep going - we want to clean up as much as possible
}
}
}
}
}
if (reopened)
{
List<bool> newDecrefOnClose = new List<bool>();
ParallelReader pr = new ParallelReader();
for (int i = 0; i < readers.Count; i++)
{
IndexReader oldReader = readers[i];
IndexReader newReader = newReaders[i];
if (newReader == oldReader)
{
newDecrefOnClose.Add(true);
newReader.IncRef();
}
else
{
// this is a new subreader instance, so on close() we don't
// decRef but close it
newDecrefOnClose.Add(false);
}
pr.Add(newReader, !storedFieldReaders.Contains(oldReader));
}
pr.decrefOnClose = newDecrefOnClose;
pr.incRefReaders = incRefReaders;
return pr;
}
else
{
// No subreader was refreshed
return this;
}
}
public override int NumDocs()
{
// Don't call ensureOpen() here (it could affect performance)
return numDocs;
}
public override int MaxDoc
{
get
{
// Don't call ensureOpen() here (it could affect performance)
return maxDoc;
}
}
public override bool HasDeletions
{
get
{
// Don't call ensureOpen() here (it could affect performance)
return hasDeletions;
}
}
// check first reader
public override bool IsDeleted(int n)
{
// Don't call ensureOpen() here (it could affect performance)
if (readers.Count > 0)
return readers[0].IsDeleted(n);
return false;
}
// delete in all readers
protected internal override void DoDelete(int n)
{
foreach(var reader in readers)
{
reader.DeleteDocument(n);
}
hasDeletions = true;
}
// undeleteAll in all readers
protected internal override void DoUndeleteAll()
{
foreach(var reader in readers)
{
reader.UndeleteAll();
}
hasDeletions = false;
}
// append fields from storedFieldReaders
public override Document Document(int n, FieldSelector fieldSelector)
{
EnsureOpen();
Document result = new Document();
foreach(IndexReader reader in storedFieldReaders)
{
bool include = (fieldSelector == null);
if (!include)
{
var fields = readerToFields[reader];
foreach(var field in fields)
{
if (fieldSelector.Accept(field) != FieldSelectorResult.NO_LOAD)
{
include = true;
break;
}
}
}
if (include)
{
var fields = reader.Document(n, fieldSelector).GetFields();
foreach(var field in fields)
{
result.Add(field);
}
}
}
return result;
}
// get all vectors
public override ITermFreqVector[] GetTermFreqVectors(int n)
{
EnsureOpen();
IList<ITermFreqVector> results = new List<ITermFreqVector>();
foreach(var e in fieldToReader)
{
System.String field = e.Key;
IndexReader reader = e.Value;
ITermFreqVector vector = reader.GetTermFreqVector(n, field);
if (vector != null)
results.Add(vector);
}
return results.ToArray();
}
public override ITermFreqVector GetTermFreqVector(int n, System.String field)
{
EnsureOpen();
IndexReader reader = (fieldToReader[field]);
return reader == null?null:reader.GetTermFreqVector(n, field);
}
public override void GetTermFreqVector(int docNumber, System.String field, TermVectorMapper mapper)
{
EnsureOpen();
IndexReader reader = (fieldToReader[field]);
if (reader != null)
{
reader.GetTermFreqVector(docNumber, field, mapper);
}
}
public override void GetTermFreqVector(int docNumber, TermVectorMapper mapper)
{
EnsureOpen();
foreach(var e in fieldToReader)
{
System.String field = e.Key;
IndexReader reader = e.Value;
reader.GetTermFreqVector(docNumber, field, mapper);
}
}
public override bool HasNorms(System.String field)
{
EnsureOpen();
IndexReader reader = fieldToReader[field];
return reader != null && reader.HasNorms(field);
}
public override byte[] Norms(System.String field)
{
EnsureOpen();
IndexReader reader = fieldToReader[field];
return reader == null?null:reader.Norms(field);
}
public override void Norms(System.String field, byte[] result, int offset)
{
EnsureOpen();
IndexReader reader = fieldToReader[field];
if (reader != null)
reader.Norms(field, result, offset);
}
protected internal override void DoSetNorm(int n, System.String field, byte value_Renamed)
{
IndexReader reader = fieldToReader[field];
if (reader != null)
reader.DoSetNorm(n, field, value_Renamed);
}
public override TermEnum Terms()
{
EnsureOpen();
return new ParallelTermEnum(this);
}
public override TermEnum Terms(Term term)
{
EnsureOpen();
return new ParallelTermEnum(this, term);
}
public override int DocFreq(Term term)
{
EnsureOpen();
IndexReader reader = fieldToReader[term.Field];
return reader == null?0:reader.DocFreq(term);
}
public override TermDocs TermDocs(Term term)
{
EnsureOpen();
return new ParallelTermDocs(this, term);
}
public override TermDocs TermDocs()
{
EnsureOpen();
return new ParallelTermDocs(this);
}
public override TermPositions TermPositions(Term term)
{
EnsureOpen();
return new ParallelTermPositions(this, term);
}
public override TermPositions TermPositions()
{
EnsureOpen();
return new ParallelTermPositions(this);
}
/// <summary> Checks recursively if all subreaders are up to date. </summary>
public override bool IsCurrent()
{
foreach (var reader in readers)
{
if (!reader.IsCurrent())
{
return false;
}
}
// all subreaders are up to date
return true;
}
/// <summary> Checks recursively if all subindexes are optimized </summary>
public override bool IsOptimized()
{
foreach (var reader in readers)
{
if (!reader.IsOptimized())
{
return false;
}
}
// all subindexes are optimized
return true;
}
/// <summary>Not implemented.</summary>
/// <throws> UnsupportedOperationException </throws>
public override long Version
{
get { throw new System.NotSupportedException("ParallelReader does not support this method."); }
}
// for testing
public /*internal*/ virtual IndexReader[] GetSubReaders()
{
return readers.ToArray();
}
protected internal override void DoCommit(IDictionary<string, string> commitUserData)
{
foreach(var reader in readers)
reader.Commit(commitUserData);
}
protected internal override void DoClose()
{
lock (this)
{
for (int i = 0; i < readers.Count; i++)
{
if (decrefOnClose[i])
{
readers[i].DecRef();
}
else
{
readers[i].Close();
}
}
}
Lucene.Net.Search.FieldCache_Fields.DEFAULT.Purge(this);
}
public override System.Collections.Generic.ICollection<string> GetFieldNames(IndexReader.FieldOption fieldNames)
{
EnsureOpen();
ISet<string> fieldSet = Lucene.Net.Support.Compatibility.SetFactory.CreateHashSet<string>();
foreach(var reader in readers)
{
ICollection<string> names = reader.GetFieldNames(fieldNames);
fieldSet.UnionWith(names);
}
return fieldSet;
}
private class ParallelTermEnum : TermEnum
{
private void InitBlock(ParallelReader enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private ParallelReader enclosingInstance;
public ParallelReader Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private System.String field;
private IEnumerator<string> fieldIterator;
private TermEnum termEnum;
private bool isDisposed;
public ParallelTermEnum(ParallelReader enclosingInstance)
{
InitBlock(enclosingInstance);
try
{
field = Enclosing_Instance.fieldToReader.Keys.First();
}
catch (ArgumentOutOfRangeException)
{
// No fields, so keep field == null, termEnum == null
return;
}
if (field != null)
termEnum = Enclosing_Instance.fieldToReader[field].Terms();
}
public ParallelTermEnum(ParallelReader enclosingInstance, Term term)
{
InitBlock(enclosingInstance);
field = term.Field;
IndexReader reader = Enclosing_Instance.fieldToReader[field];
if (reader != null)
termEnum = reader.Terms(term);
}
public override bool Next()
{
if (termEnum == null)
return false;
// another term in this field?
if (termEnum.Next() && (System.Object) termEnum.Term.Field == (System.Object) field)
return true; // yes, keep going
termEnum.Close(); // close old termEnum
// find the next field with terms, if any
if (fieldIterator == null)
{
var newList = new List<string>();
if (Enclosing_Instance.fieldToReader != null && Enclosing_Instance.fieldToReader.Count > 0)
{
var comparer = Enclosing_Instance.fieldToReader.Comparer;
foreach(var entry in Enclosing_Instance.fieldToReader.Keys.Where(x => comparer.Compare(x, field) >= 0))
newList.Add(entry);
}
fieldIterator = newList.Skip(1).GetEnumerator(); // Skip field to get next one
}
while (fieldIterator.MoveNext())
{
field = fieldIterator.Current;
termEnum = Enclosing_Instance.fieldToReader[field].Terms(new Term(field));
Term term = termEnum.Term;
if (term != null && (System.Object) term.Field == (System.Object) field)
return true;
else
termEnum.Close();
}
return false; // no more fields
}
public override Term Term
{
get
{
if (termEnum == null)
return null;
return termEnum.Term;
}
}
public override int DocFreq()
{
if (termEnum == null)
return 0;
return termEnum.DocFreq();
}
protected override void Dispose(bool disposing)
{
if (isDisposed) return;
if (disposing)
{
if (termEnum != null)
termEnum.Close();
}
isDisposed = true;
}
}
// wrap a TermDocs in order to support seek(Term)
private class ParallelTermDocs : TermDocs
{
private void InitBlock(ParallelReader enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private ParallelReader enclosingInstance;
public ParallelReader Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
protected internal TermDocs termDocs;
private bool isDisposed;
public ParallelTermDocs(ParallelReader enclosingInstance)
{
InitBlock(enclosingInstance);
}
public ParallelTermDocs(ParallelReader enclosingInstance, Term term)
{
InitBlock(enclosingInstance);
if(term == null)
termDocs = (Enclosing_Instance.readers.Count == 0)
? null
: Enclosing_Instance.readers[0].TermDocs(null);
else
Seek(term);
}
public virtual int Doc
{
get { return termDocs.Doc; }
}
public virtual int Freq
{
get { return termDocs.Freq; }
}
public virtual void Seek(Term term)
{
IndexReader reader = Enclosing_Instance.fieldToReader[term.Field];
termDocs = reader != null?reader.TermDocs(term):null;
}
public virtual void Seek(TermEnum termEnum)
{
Seek(termEnum.Term);
}
public virtual bool Next()
{
if (termDocs == null)
return false;
return termDocs.Next();
}
public virtual int Read(int[] docs, int[] freqs)
{
if (termDocs == null)
return 0;
return termDocs.Read(docs, freqs);
}
public virtual bool SkipTo(int target)
{
if (termDocs == null)
return false;
return termDocs.SkipTo(target);
}
[Obsolete("Use Dispose() instead")]
public virtual void Close()
{
Dispose();
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (isDisposed) return;
if (disposing)
{
if (termDocs != null)
termDocs.Close();
}
isDisposed = true;
}
}
private class ParallelTermPositions:ParallelTermDocs, TermPositions
{
private void InitBlock(ParallelReader enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private ParallelReader enclosingInstance;
public new ParallelReader Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
public ParallelTermPositions(ParallelReader enclosingInstance):base(enclosingInstance)
{
InitBlock(enclosingInstance);
}
public ParallelTermPositions(ParallelReader enclosingInstance, Term term):base(enclosingInstance)
{
InitBlock(enclosingInstance);
Seek(term);
}
public override void Seek(Term term)
{
IndexReader reader = Enclosing_Instance.fieldToReader[term.Field];
termDocs = reader != null?reader.TermPositions(term):null;
}
public virtual int NextPosition()
{
// It is an error to call this if there is no next position, e.g. if termDocs==null
return ((TermPositions) termDocs).NextPosition();
}
public virtual int PayloadLength
{
get { return ((TermPositions) termDocs).PayloadLength; }
}
public virtual byte[] GetPayload(byte[] data, int offset)
{
return ((TermPositions) termDocs).GetPayload(data, offset);
}
// TODO: Remove warning after API has been finalized
public virtual bool IsPayloadAvailable
{
get { return ((TermPositions) termDocs).IsPayloadAvailable; }
}
}
}
}
| |
using System.Net;
using Microsoft.Azure.Management.Network;
using Microsoft.Azure.Management.Network.Models;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Test;
using Networks.Tests.Helpers;
using ResourceGroups.Tests;
using Xunit;
namespace Network.Tests.Tests
{
using System.Linq;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Helpers;
using Microsoft.Azure.Management.Compute.Models;
public class ConnectionMonitorTests
{
[Fact(Skip = "Disable tests")]
public void PutConnectionMonitorTest()
{
var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler2 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler3 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType()))
{
var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1, true);
var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);
var computeManagementClient = NetworkManagementTestUtilities.GetComputeManagementClientWithHandler(context, handler3);
string location = "centraluseuap";
string resourceGroupName = TestUtilities.GenerateName();
resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
new ResourceGroup
{
Location = location
});
string virtualMachineName = TestUtilities.GenerateName();
string networkInterfaceName = TestUtilities.GenerateName();
string networkSecurityGroupName = virtualMachineName + "-nsg";
//Deploy VM with a template
DeploymentUpdate.CreateVm(
resourcesClient: resourcesClient,
resourceGroupName: resourceGroupName,
location: location,
virtualMachineName: virtualMachineName,
storageAccountName: TestUtilities.GenerateName(),
networkInterfaceName: networkInterfaceName,
networkSecurityGroupName: networkSecurityGroupName,
diagnosticsStorageAccountName: TestUtilities.GenerateName(),
deploymentName: TestUtilities.GenerateName()
);
var getVm = computeManagementClient.VirtualMachines.Get(resourceGroupName, virtualMachineName);
//Deploy networkWatcherAgent on VM
VirtualMachineExtension parameters = new VirtualMachineExtension
{
Publisher = "Microsoft.Azure.NetworkWatcher",
TypeHandlerVersion = "1.4",
VirtualMachineExtensionType = "NetworkWatcherAgentWindows",
Location = location
};
var addExtension = computeManagementClient.VirtualMachineExtensions.CreateOrUpdate(resourceGroupName, getVm.Name, "NetworkWatcherAgent", parameters);
string networkWatcherName = TestUtilities.GenerateName();
NetworkWatcher properties = new NetworkWatcher
{
Location = location
};
//Create network Watcher
var createNetworkWatcher = networkManagementClient.NetworkWatchers.CreateOrUpdate(resourceGroupName, networkWatcherName, properties);
string connectionMonitorName = "cm";
ConnectionMonitor cm = new ConnectionMonitor
{
Location = location,
Source = new ConnectionMonitorSource
{
ResourceId = getVm.Id
},
Destination = new ConnectionMonitorDestination
{
Address = "bing.com",
Port = 80
},
MonitoringIntervalInSeconds = 30
};
var putConnectionMonitor = networkManagementClient.ConnectionMonitors.CreateOrUpdate(resourceGroupName, networkWatcherName, connectionMonitorName, cm);
Assert.Equal("Running", putConnectionMonitor.MonitoringStatus);
Assert.Equal("centraluseuap", putConnectionMonitor.Location);
Assert.Equal(30, putConnectionMonitor.MonitoringIntervalInSeconds);
Assert.Equal(connectionMonitorName, putConnectionMonitor.Name);
Assert.Equal(getVm.Id, putConnectionMonitor.Source.ResourceId);
Assert.Equal("bing.com", putConnectionMonitor.Destination.Address);
Assert.Equal(80, putConnectionMonitor.Destination.Port);
}
}
[Fact(Skip = "Disable tests")]
public void StartConnectionMonitorTest()
{
var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler2 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler3 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType()))
{
var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1, true);
var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);
var computeManagementClient = NetworkManagementTestUtilities.GetComputeManagementClientWithHandler(context, handler3);
string location = "centraluseuap";
string resourceGroupName = TestUtilities.GenerateName();
resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
new ResourceGroup
{
Location = location
});
string virtualMachineName = TestUtilities.GenerateName();
string networkInterfaceName = TestUtilities.GenerateName();
string networkSecurityGroupName = virtualMachineName + "-nsg";
//Deploy VM with a template
DeploymentUpdate.CreateVm(
resourcesClient: resourcesClient,
resourceGroupName: resourceGroupName,
location: location,
virtualMachineName: virtualMachineName,
storageAccountName: TestUtilities.GenerateName(),
networkInterfaceName: networkInterfaceName,
networkSecurityGroupName: networkSecurityGroupName,
diagnosticsStorageAccountName: TestUtilities.GenerateName(),
deploymentName: TestUtilities.GenerateName()
);
var getVm = computeManagementClient.VirtualMachines.Get(resourceGroupName, virtualMachineName);
//Deploy networkWatcherAgent on VM
VirtualMachineExtension parameters = new VirtualMachineExtension
{
Publisher = "Microsoft.Azure.NetworkWatcher",
TypeHandlerVersion = "1.4",
VirtualMachineExtensionType = "NetworkWatcherAgentWindows",
Location = location
};
var addExtension = computeManagementClient.VirtualMachineExtensions.CreateOrUpdate(resourceGroupName, getVm.Name, "NetworkWatcherAgent", parameters);
string networkWatcherName = TestUtilities.GenerateName();
NetworkWatcher properties = new NetworkWatcher
{
Location = location
};
//Create network Watcher
var createNetworkWatcher = networkManagementClient.NetworkWatchers.CreateOrUpdate(resourceGroupName, networkWatcherName, properties);
string connectionMonitorName = TestUtilities.GenerateName();
ConnectionMonitor cm = new ConnectionMonitor
{
Location = location,
Source = new ConnectionMonitorSource
{
ResourceId = getVm.Id
},
Destination = new ConnectionMonitorDestination
{
Address = "bing.com",
Port = 80
},
MonitoringIntervalInSeconds = 30,
AutoStart = false
};
var putConnectionMonitor = networkManagementClient.ConnectionMonitors.CreateOrUpdate(resourceGroupName, networkWatcherName, connectionMonitorName, cm);
Assert.Equal("NotStarted", putConnectionMonitor.MonitoringStatus);
networkManagementClient.ConnectionMonitors.Start(resourceGroupName, networkWatcherName, connectionMonitorName);
var getConnectionMonitor = networkManagementClient.ConnectionMonitors.Get(resourceGroupName, networkWatcherName, connectionMonitorName);
Assert.Equal("Running", getConnectionMonitor.MonitoringStatus);
}
}
[Fact(Skip = "Disable tests")]
public void StopConnectionMonitorTest()
{
var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler2 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler3 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType()))
{
var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1, true);
var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);
var computeManagementClient = NetworkManagementTestUtilities.GetComputeManagementClientWithHandler(context, handler3);
string location = "centraluseuap";
string resourceGroupName = TestUtilities.GenerateName();
resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
new ResourceGroup
{
Location = location
});
string virtualMachineName = TestUtilities.GenerateName();
string networkInterfaceName = TestUtilities.GenerateName();
string networkSecurityGroupName = virtualMachineName + "-nsg";
//Deploy VM with a template
DeploymentUpdate.CreateVm(
resourcesClient: resourcesClient,
resourceGroupName: resourceGroupName,
location: location,
virtualMachineName: virtualMachineName,
storageAccountName: TestUtilities.GenerateName(),
networkInterfaceName: networkInterfaceName,
networkSecurityGroupName: networkSecurityGroupName,
diagnosticsStorageAccountName: TestUtilities.GenerateName(),
deploymentName: TestUtilities.GenerateName()
);
var getVm = computeManagementClient.VirtualMachines.Get(resourceGroupName, virtualMachineName);
//Deploy networkWatcherAgent on VM
VirtualMachineExtension parameters = new VirtualMachineExtension
{
Publisher = "Microsoft.Azure.NetworkWatcher",
TypeHandlerVersion = "1.4",
VirtualMachineExtensionType = "NetworkWatcherAgentWindows",
Location = location
};
var addExtension = computeManagementClient.VirtualMachineExtensions.CreateOrUpdate(resourceGroupName, getVm.Name, "NetworkWatcherAgent", parameters);
string networkWatcherName = TestUtilities.GenerateName();
NetworkWatcher properties = new NetworkWatcher
{
Location = location
};
//Create network Watcher
var createNetworkWatcher = networkManagementClient.NetworkWatchers.CreateOrUpdate(resourceGroupName, networkWatcherName, properties);
string connectionMonitorName = TestUtilities.GenerateName();
ConnectionMonitor cm = new ConnectionMonitor
{
Location = location,
Source = new ConnectionMonitorSource
{
ResourceId = getVm.Id
},
Destination = new ConnectionMonitorDestination
{
Address = "bing.com",
Port = 80
},
MonitoringIntervalInSeconds = 30
};
var putConnectionMonitor = networkManagementClient.ConnectionMonitors.CreateOrUpdate(resourceGroupName, networkWatcherName, connectionMonitorName, cm);
Assert.Equal("Running", putConnectionMonitor.MonitoringStatus);
networkManagementClient.ConnectionMonitors.Stop(resourceGroupName, networkWatcherName, connectionMonitorName);
var getConnectionMonitor = networkManagementClient.ConnectionMonitors.Get(resourceGroupName, networkWatcherName, connectionMonitorName);
Assert.Equal("Stopped", getConnectionMonitor.MonitoringStatus);
}
}
[Fact(Skip = "Disable tests")]
public void QueryConnectionMonitorTest()
{
var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler2 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler3 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType()))
{
var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1, true);
var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);
var computeManagementClient = NetworkManagementTestUtilities.GetComputeManagementClientWithHandler(context, handler3);
string location = "centraluseuap";
string resourceGroupName = TestUtilities.GenerateName();
resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
new ResourceGroup
{
Location = location
});
string virtualMachineName = TestUtilities.GenerateName();
string networkInterfaceName = TestUtilities.GenerateName();
string networkSecurityGroupName = virtualMachineName + "-nsg";
//Deploy VM with a template
DeploymentUpdate.CreateVm(
resourcesClient: resourcesClient,
resourceGroupName: resourceGroupName,
location: location,
virtualMachineName: virtualMachineName,
storageAccountName: TestUtilities.GenerateName(),
networkInterfaceName: networkInterfaceName,
networkSecurityGroupName: networkSecurityGroupName,
diagnosticsStorageAccountName: TestUtilities.GenerateName(),
deploymentName: TestUtilities.GenerateName()
);
var getVm = computeManagementClient.VirtualMachines.Get(resourceGroupName, virtualMachineName);
//Deploy networkWatcherAgent on VM
VirtualMachineExtension parameters = new VirtualMachineExtension
{
Publisher = "Microsoft.Azure.NetworkWatcher",
TypeHandlerVersion = "1.4",
VirtualMachineExtensionType = "NetworkWatcherAgentWindows",
Location = location
};
var addExtension = computeManagementClient.VirtualMachineExtensions.CreateOrUpdate(resourceGroupName, getVm.Name, "NetworkWatcherAgent", parameters);
string networkWatcherName = TestUtilities.GenerateName();
NetworkWatcher properties = new NetworkWatcher
{
Location = location
};
//Create network Watcher
var createNetworkWatcher = networkManagementClient.NetworkWatchers.CreateOrUpdate(resourceGroupName, networkWatcherName, properties);
string connectionMonitorName = TestUtilities.GenerateName();
ConnectionMonitor cm = new ConnectionMonitor
{
Location = location,
Source = new ConnectionMonitorSource
{
ResourceId = getVm.Id
},
Destination = new ConnectionMonitorDestination
{
Address = "bing.com",
Port = 80
},
MonitoringIntervalInSeconds = 30
};
var putConnectionMonitor = networkManagementClient.ConnectionMonitors.CreateOrUpdate(resourceGroupName, networkWatcherName, connectionMonitorName, cm);
networkManagementClient.ConnectionMonitors.Start(resourceGroupName, networkWatcherName, connectionMonitorName);
networkManagementClient.ConnectionMonitors.Stop(resourceGroupName, networkWatcherName, connectionMonitorName);
var queryResult = networkManagementClient.ConnectionMonitors.Query(resourceGroupName, networkWatcherName, connectionMonitorName);
Assert.Single(queryResult.States);
Assert.Equal("Reachable", queryResult.States[0].ConnectionState);
Assert.Equal("InProgress", queryResult.States[0].EvaluationState);
Assert.Equal(2, queryResult.States[0].Hops.Count());
}
}
[Fact(Skip = "Disable tests")]
public void UpdateConnectionMonitorTest()
{
var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler2 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler3 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType()))
{
var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1, true);
var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);
var computeManagementClient = NetworkManagementTestUtilities.GetComputeManagementClientWithHandler(context, handler3);
string location = "centraluseuap";
string resourceGroupName = TestUtilities.GenerateName();
resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
new ResourceGroup
{
Location = location
});
string virtualMachineName = TestUtilities.GenerateName();
string networkInterfaceName = TestUtilities.GenerateName();
string networkSecurityGroupName = virtualMachineName + "-nsg";
//Deploy VM with a template
DeploymentUpdate.CreateVm(
resourcesClient: resourcesClient,
resourceGroupName: resourceGroupName,
location: location,
virtualMachineName: virtualMachineName,
storageAccountName: TestUtilities.GenerateName(),
networkInterfaceName: networkInterfaceName,
networkSecurityGroupName: networkSecurityGroupName,
diagnosticsStorageAccountName: TestUtilities.GenerateName(),
deploymentName: TestUtilities.GenerateName()
);
var getVm = computeManagementClient.VirtualMachines.Get(resourceGroupName, virtualMachineName);
//Deploy networkWatcherAgent on VM
VirtualMachineExtension parameters = new VirtualMachineExtension
{
Publisher = "Microsoft.Azure.NetworkWatcher",
TypeHandlerVersion = "1.4",
VirtualMachineExtensionType = "NetworkWatcherAgentWindows",
Location = location
};
var addExtension = computeManagementClient.VirtualMachineExtensions.CreateOrUpdate(resourceGroupName, getVm.Name, "NetworkWatcherAgent", parameters);
string networkWatcherName = TestUtilities.GenerateName();
NetworkWatcher properties = new NetworkWatcher
{
Location = location
};
//Create network Watcher
var createNetworkWatcher = networkManagementClient.NetworkWatchers.CreateOrUpdate(resourceGroupName, networkWatcherName, properties);
string connectionMonitorName = TestUtilities.GenerateName();
ConnectionMonitor cm = new ConnectionMonitor
{
Location = location,
Source = new ConnectionMonitorSource
{
ResourceId = getVm.Id
},
Destination = new ConnectionMonitorDestination
{
Address = "bing.com",
Port = 80
},
MonitoringIntervalInSeconds = 30
};
var putConnectionMonitor = networkManagementClient.ConnectionMonitors.CreateOrUpdate(resourceGroupName, networkWatcherName, connectionMonitorName, cm);
Assert.Equal(30, putConnectionMonitor.MonitoringIntervalInSeconds);
cm.MonitoringIntervalInSeconds = 60;
var updateConnectionMonitor = networkManagementClient.ConnectionMonitors.CreateOrUpdate(resourceGroupName, networkWatcherName, connectionMonitorName, cm);
Assert.Equal(60, updateConnectionMonitor.MonitoringIntervalInSeconds);
}
}
[Fact(Skip = "Disable tests")]
public void DeleteConnectionMonitorTest()
{
var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler2 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler3 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType()))
{
var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1, true);
var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);
var computeManagementClient = NetworkManagementTestUtilities.GetComputeManagementClientWithHandler(context, handler3);
string location = "centraluseuap";
string resourceGroupName = TestUtilities.GenerateName();
resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
new ResourceGroup
{
Location = location
});
string virtualMachineName = TestUtilities.GenerateName();
string networkInterfaceName = TestUtilities.GenerateName();
string networkSecurityGroupName = virtualMachineName + "-nsg";
//Deploy VM with a template
DeploymentUpdate.CreateVm(
resourcesClient: resourcesClient,
resourceGroupName: resourceGroupName,
location: location,
virtualMachineName: virtualMachineName,
storageAccountName: TestUtilities.GenerateName(),
networkInterfaceName: networkInterfaceName,
networkSecurityGroupName: networkSecurityGroupName,
diagnosticsStorageAccountName: TestUtilities.GenerateName(),
deploymentName: TestUtilities.GenerateName()
);
var getVm = computeManagementClient.VirtualMachines.Get(resourceGroupName, virtualMachineName);
//Deploy networkWatcherAgent on VM
VirtualMachineExtension parameters = new VirtualMachineExtension
{
Publisher = "Microsoft.Azure.NetworkWatcher",
TypeHandlerVersion = "1.4",
VirtualMachineExtensionType = "NetworkWatcherAgentWindows",
Location = location
};
var addExtension = computeManagementClient.VirtualMachineExtensions.CreateOrUpdate(resourceGroupName, getVm.Name, "NetworkWatcherAgent", parameters);
string networkWatcherName = TestUtilities.GenerateName();
NetworkWatcher properties = new NetworkWatcher
{
Location = location
};
//Create network Watcher
var createNetworkWatcher = networkManagementClient.NetworkWatchers.CreateOrUpdate(resourceGroupName, networkWatcherName, properties);
string connectionMonitorName1 = TestUtilities.GenerateName();
string connectionMonitorName2 = TestUtilities.GenerateName();
ConnectionMonitor cm = new ConnectionMonitor
{
Location = location,
Source = new ConnectionMonitorSource
{
ResourceId = getVm.Id
},
Destination = new ConnectionMonitorDestination
{
Address = "bing.com",
Port = 80
},
MonitoringIntervalInSeconds = 30,
AutoStart = false
};
var connectionMonitor1 = networkManagementClient.ConnectionMonitors.CreateOrUpdate(resourceGroupName, networkWatcherName, connectionMonitorName1, cm);
var connectionMonitor2 = networkManagementClient.ConnectionMonitors.CreateOrUpdate(resourceGroupName, networkWatcherName, connectionMonitorName2, cm);
var getConnectionMonitors1 = networkManagementClient.ConnectionMonitors.List(resourceGroupName, networkWatcherName);
Assert.Equal(2, getConnectionMonitors1.Count());
networkManagementClient.ConnectionMonitors.Delete(resourceGroupName, networkWatcherName, connectionMonitorName2);
var getConnectionMonitors2 = networkManagementClient.ConnectionMonitors.List(resourceGroupName, networkWatcherName);
Assert.Single(getConnectionMonitors2);
}
}
}
}
| |
#region Licence...
/*
The MIT License (MIT)
Copyright (c) 2014 Oleg Shilo
Permission is hereby granted,
free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion Licence...
using System;
using System.Collections.Generic;
using System.Xml.Linq;
namespace WixSharp
{
/// <summary>
/// This class defines website attributes. It is a close equivalent of WebSite WiX element.
/// </summary>
public partial class WebSite : WixEntity
{
/// <summary>
/// This is the name of the web site that will show up in the IIS management console.
/// </summary>
public string Description = "";
/// <summary>
/// Indicates if the WebSite is to be installed (created on IIS) or existing WebSite should be used to install the corresponding
/// WebApplication. The default <see cref="InstallWebSite"/> value is <c>false</c>
/// <para>Developers should be aware of the WebSite installation model imposed by WiX/MSI and use <see cref="InstallWebSite"/> carefully.</para>
/// <para>If <see cref="InstallWebSite"/> value is set to <c>false</c> the parent WebApplication (<see cref="T:WixSharp.IISVirtualDir"/>)
/// will be installed in the brand new (freshly created) WebSite or in the existing one if a site with the same address/port combination already exists
/// on IIS). The undesirable side affect of this deployment scenario is that if the existing WebSite was used to install the WebApplication it will be
/// deleted on IIS during uninstallation even if this WebSite has other WebApplications installed.</para>
/// <para>The "safer" option is to set <see cref="InstallWebSite"/> value to <c>true</c> (default value). In this case the WebApplication will
/// be installed in an existing WebSite with matching address/port. If the match is not found the installation will fail. During the uninstallation
/// only installed WebApplication will be removed from IIS.</para>
/// </summary>
public bool InstallWebSite = false;
/// <summary>
/// Initializes a new instance of the <see cref="WebSite" /> class.
/// </summary>
public WebSite()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSite"/> class.
/// </summary>
/// <param name="id">The name.</param>
/// <param name="description">The description of the web site (as it shows up in the IIS management console).</param>
public WebSite(Id id, string description)
{
this.Id = id;
this.Description = description;
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSite"/> class.
/// </summary>
/// <param name="description">The description of the web site (as it shows up in the IIS management console).</param>
public WebSite(string description)
{
this.Name = "WebSite"; //to become a prefix of the auto-generated Id
this.Description = description;
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSite"/> class.
/// </summary>
/// <param name="id">The id.</param>
public WebSite(Id id)
{
this.Id = id;
}
///// <summary>
///// Collection of <see cref="T:WebSite.Certificate"/> associated with website.
///// </summary>
//public Certificate[] Certificates = new Certificate[0];
/// <summary>
/// Initializes a new instance of the <see cref="WebSite"/> class.
/// </summary>
/// <param name="description">The description of the web site (as it shows up in the IIS management console).</param>
/// <param name="addressDefinition">The address definition.</param>
public WebSite(string description, string addressDefinition)
{
this.Name = "WebSite"; //to become a prffix of the auto-generated Id
this.Description = description;
this.AddressesDefinition = addressDefinition;
}
/// <summary>
/// Initializes a new instance of the <see cref="WebSite"/> class.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="description">The description.</param>
/// <param name="addressDefinition">The address definition.</param>
public WebSite(Id id, string description, string addressDefinition)
{
this.Id = id;
this.AddressesDefinition = addressDefinition;
this.Description = description;
}
internal void ProcessAddressesDefinition()
{
if (!AddressesDefinition.IsEmpty())
{
List<WebAddress> addressesToAdd = new List<WebAddress>();
foreach (string addressDef in AddressesDefinition.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
{
try
{
string[] tokens = addressDef.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
string address = tokens[0];
string port = tokens[1];
if (tokens[1].ContainsWixConstants())
{
addressesToAdd.Add(new WebAddress { Address = address, AttributesDefinition = "Port=" + port });
}
else
{
addressesToAdd.Add(new WebAddress { Address = address, Port = Convert.ToInt32(port) });
}
}
catch (Exception e)
{
throw new Exception("Invalid AddressesDefinition", e);
}
}
this.addresses = addressesToAdd.ToArray();
}
}
/// <summary>
/// This class defines website address. It is a close equivalent of WebAddress WiX element.
/// </summary>
public partial class WebAddress : WixEntity
{
/// <summary>
/// The IP address for the web address. To specify the "All Unassigned" IP address, do not specify
/// this attribute or specify its value as "*". The IP address is also used to determine if the WebSite is already installed.
/// The IP address must match exactly (empty value matches "All Unassigned") unless "*" is used which will match any existing IP (including "All Unassigned").
/// </summary>
public string Address = "*";
/// <summary>
/// Sets the port number.
/// </summary>
public int Port = 0;
/// <summary>
/// Optional attributes of the <c>WebAddress Element</c> (e.g. Secure:YesNoPath).
/// </summary>
/// <example>
/// <code>
/// var address = new WebAddress
/// {
/// Port = 80,
/// Attributes = new Dictionary<string, string> { { "Secure", "Yes" } };
/// ...
/// </code>
/// </example>
public new Dictionary<string, string> Attributes { get { return base.Attributes; } set { base.Attributes = value; } }
}
/// <summary>
/// Specification for auto-generating the <see cref="T:WebSite.WebAddresses"/> collection.
/// <para>If <see cref="AddressesDefinition"/> is specified, the existing content of <see cref="Addresses"/> will be ignored
/// and replaced with the auto-generated one at compile time.</para>
/// </summary>
/// <example>
/// <c>webSite.AddressesDefinition = "*:80;*90";</c> will be parsed and converted to an array of <see cref="T:WixSharp.WebSite.WebAddress"/> as follows:
/// <code>
/// ...
/// webSite.Addresses = new []
/// {
/// new WebSite.WebAddress
/// {
/// Address = "*",
/// Port = 80
/// },
/// new WebSite.WebAddress
/// {
/// Address = "*",
/// Port = 80
/// }
/// }
/// </code>
/// </example>
public string AddressesDefinition = "";
/// <summary>
/// Reference to a WebApplication that is to be installed as part of this web site.
/// </summary>
public string WebApplication = null;
/// <summary>
/// Collection of <see cref="T:WebSite.WebAddresses"/> associated with website.
/// <para>
/// The user specified values of <see cref="Addresses"/> will be ignored and replaced with the
/// auto-generated addresses if <see cref="AddressesDefinition"/> is specified either directly or via appropriate <see cref="WebSite"/> constructor.
/// </para>
/// </summary>
public WebAddress[] Addresses
{
get
{
ProcessAddressesDefinition();
return addresses;
}
set
{
addresses = value;
}
}
WebAddress[] addresses = new WebAddress[0];
}
/// <summary>
/// This class defines WebAppPool WiX element. It is used to specify the application pool for this application in IIS 6 applications.
/// </summary>
public partial class WebAppPool : WixEntity
{
/// <summary>
/// Initializes a new instance of the <see cref="WebAppPool"/> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="attributesDefinition">The attributes definition. This parameter is used to set encapsulated <see cref="T:WixSharp.WixEntity.AttributesDefinition"/>.</param>
public WebAppPool(string name, string attributesDefinition)
{
base.Name = name;
base.AttributesDefinition = attributesDefinition;
}
/// <summary>
/// Initializes a new instance of the <see cref="WebAppPool"/> class.
/// </summary>
/// <param name="name">The name.</param>
public WebAppPool(string name)
{
base.Name = name;
}
/// <summary>
/// Initializes a new instance of the <see cref="WebAppPool"/> class.
/// </summary>
public WebAppPool()
{
}
}
/// <summary>
/// This class defines WebDirProperites WiX element. The class itself has no distinctive behaviour nor schema. It is fully relying on
/// encapsulated <see cref="T:WixSharp.WixEntity.AttributesDefinition"/>.
/// </summary>
public partial class WebDirProperties : WixEntity
{
/// <summary>
/// Initializes a new instance of the <see cref="WebDirProperties"/> class.
/// </summary>
/// <param name="attributesDefinition">The attributes definition. This parameter is used to set encapsulated <see cref="T:WixSharp.WixEntity.AttributesDefinition"/>.</param>
public WebDirProperties(string attributesDefinition)
{
base.AttributesDefinition = attributesDefinition;
}
/// <summary>
/// Performs an implicit conversion from <see cref="System.String"/> to <see cref="WebDirProperties"/>.
/// </summary>
/// <param name="attributesDefinition">The attributes definition.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator WebDirProperties(string attributesDefinition)
{
return new WebDirProperties(attributesDefinition);
}
}
/// <summary>
/// This class defines IIS Virtual Directory. It is a close equivalent of WebVirtualDirectory WiX element.
/// </summary>
public class IISVirtualDir : WixEntity
{
/// <summary>
/// Initializes a new instance of the <see cref="IISVirtualDir" /> class.
/// </summary>
public IISVirtualDir()
{
base.Name = "VirtDir"; //to become a prffix of the auto-generated Id
}
/// <summary>
/// WebSite in which this virtual directory belongs.
/// </summary>
public WebSite WebSite = null;
#region WebVirtualDir Element Attributes
/// <summary>
/// Gets or sets the application name, which is the URL relative path used to access this virtual directory.
/// <para>
/// It is a full equivalent of <see cref="WixSharp.IISVirtualDir.Alias"/>.
/// </para>
/// </summary>
/// <value>The name.</value>
public new string Name
{
get { return Alias; }
set { Alias = value; }
}
/// <summary>
/// Sets the application name, which is the URL relative path used to access this virtual directory. If not set, the <see cref="AppName"/> will be used.
/// </summary>
public string Alias = "";
#endregion WebVirtualDir Element Attributes
//IISVirtualDir-to-WebAppliction is one-to-one relationship
#region WebApplication Element attributes
/// <summary>
/// Sets the name of this Web application.
/// </summary>
public string AppName = "MyWebApp"; //WebApplication element attribute
/// <summary>
/// Sets the Enable Session State option. When enabled, you can set the session timeout using the SessionTimeout attribute.
/// </summary>
public bool? AllowSessions;// YesNoDefaultType //WebApplication element attribute
/// <summary>
/// Sets the option that enables response buffering in the application, which allows ASP script to set response headers anywhere in the script.
/// </summary>
public bool? Buffer;// YesNoDefaultType //WebApplication element attribute
/// <summary>
/// Enable ASP client-side script debugging.
/// </summary>
public bool? ClientDebugging;// YesNoDefaultType //WebApplication element attribute
/// <summary>
/// Sets the default script language for the site.
/// </summary>
public DefaultScript? DefaultScript; //WebApplication element attribute
/// <summary>
/// Sets the application isolation level for this application for pre-IIS 6 applications.
/// </summary>
public Isolation? Isolation; //WebApplication element attribute
/// <summary>
/// Sets the parent paths option, which allows a client to use relative paths to reach parent directories from this application.
/// </summary>
public bool? ParentPaths;// YesNoDefaultType //WebApplication element attribute
/// <summary>
/// Sets the timeout value for executing ASP scripts.
/// </summary>
public int? ScriptTimeout; //WebApplication element attribute
/// <summary>
/// Enable ASP server-side script debugging.
/// </summary>
public bool? ServerDebugging;// YesNoDefaultType //WebApplication element attribute
/// <summary>
/// Sets the timeout value for sessions in minutes.
/// </summary>
public int? SessionTimeout; //WebApplication element attribute
/// <summary>
/// References a WebAppPool instance to use as the application pool for this application in IIS 6 applications.
/// </summary>
public WebAppPool WebAppPool; //WebApplication element attribute
/// <summary>
/// WebDirProperites used by one or more WebSites.
/// </summary>
public WebDirProperties WebDirProperties;
#endregion WebApplication Element attributes
}
}
| |
// <copyright file="OtlpExporterOptionsExtensionsTests.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry 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.
// </copyright>
using System;
using System.Collections.Generic;
using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.ExportClient;
using Xunit;
using Xunit.Sdk;
namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests
{
public class OtlpExporterOptionsExtensionsTests : Http2UnencryptedSupportTests
{
[Theory]
[InlineData("key=value", new string[] { "key" }, new string[] { "value" })]
[InlineData("key1=value1,key2=value2", new string[] { "key1", "key2" }, new string[] { "value1", "value2" })]
[InlineData("key1 = value1, key2=value2 ", new string[] { "key1", "key2" }, new string[] { "value1", "value2" })]
[InlineData("key==value", new string[] { "key" }, new string[] { "=value" })]
[InlineData("access-token=abc=/123,timeout=1234", new string[] { "access-token", "timeout" }, new string[] { "abc=/123", "1234" })]
[InlineData("key1=value1;key2=value2", new string[] { "key1" }, new string[] { "value1;key2=value2" })] // semicolon is not treated as a delimeter (https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#specifying-headers-via-environment-variables)
public void GetMetadataFromHeadersWorksCorrectFormat(string headers, string[] keys, string[] values)
{
var options = new OtlpExporterOptions();
options.Headers = headers;
var metadata = options.GetMetadataFromHeaders();
Assert.Equal(keys.Length, metadata.Count);
for (int i = 0; i < keys.Length; i++)
{
Assert.Contains(metadata, entry => entry.Key == keys[i] && entry.Value == values[i]);
}
}
[Theory]
[InlineData("headers")]
[InlineData("key,value")]
public void GetMetadataFromHeadersThrowsExceptionOnInvalidFormat(string headers)
{
try
{
var options = new OtlpExporterOptions();
options.Headers = headers;
var metadata = options.GetMetadataFromHeaders();
}
catch (Exception ex)
{
Assert.IsType<ArgumentException>(ex);
Assert.Equal("Headers provided in an invalid format.", ex.Message);
return;
}
throw new XunitException("GetMetadataFromHeaders did not throw an exception for invalid input headers");
}
[Theory]
[InlineData("")]
[InlineData(null)]
public void GetHeaders_NoOptionHeaders_ReturnsEmptyHeadres(string optionHeaders)
{
var options = new OtlpExporterOptions
{
Headers = optionHeaders,
};
var headers = options.GetHeaders<Dictionary<string, string>>((d, k, v) => d.Add(k, v));
Assert.Empty(headers);
}
[Theory]
[InlineData(OtlpExportProtocol.Grpc, typeof(OtlpGrpcTraceExportClient))]
[InlineData(OtlpExportProtocol.HttpProtobuf, typeof(OtlpHttpTraceExportClient))]
public void GetTraceExportClient_SupportedProtocol_ReturnsCorrectExportClient(OtlpExportProtocol protocol, Type expectedExportClientType)
{
if (protocol == OtlpExportProtocol.Grpc && Environment.Version.Major == 3)
{
// Adding the OtlpExporter creates a GrpcChannel.
// This switch must be set before creating a GrpcChannel when calling an insecure HTTP/2 endpoint.
// See: https://docs.microsoft.com/aspnet/core/grpc/troubleshoot#call-insecure-grpc-services-with-net-core-client
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
}
var options = new OtlpExporterOptions
{
Protocol = protocol,
};
var exportClient = options.GetTraceExportClient();
Assert.Equal(expectedExportClientType, exportClient.GetType());
}
[Fact]
public void GetTraceExportClient_GetClientForGrpcWithoutUnencryptedFlag_ThrowsException()
{
// Adding the OtlpExporter creates a GrpcChannel.
// This switch must be set before creating a GrpcChannel when calling an insecure HTTP/2 endpoint.
// See: https://docs.microsoft.com/aspnet/core/grpc/troubleshoot#call-insecure-grpc-services-with-net-core-client
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", false);
var options = new OtlpExporterOptions
{
Protocol = OtlpExportProtocol.Grpc,
};
var exception = Record.Exception(() => options.GetTraceExportClient());
if (Environment.Version.Major == 3)
{
Assert.NotNull(exception);
Assert.IsType<InvalidOperationException>(exception);
}
else
{
Assert.Null(exception);
}
}
[Fact]
public void GetTraceExportClient_UnsupportedProtocol_Throws()
{
var options = new OtlpExporterOptions
{
Protocol = (OtlpExportProtocol)123,
};
Assert.Throws<NotSupportedException>(() => options.GetTraceExportClient());
}
[Theory]
[InlineData("grpc", OtlpExportProtocol.Grpc)]
[InlineData("http/protobuf", OtlpExportProtocol.HttpProtobuf)]
[InlineData("unsupported", null)]
public void ToOtlpExportProtocol_Protocol_MapsToCorrectValue(string protocol, OtlpExportProtocol? expectedExportProtocol)
{
var exportProtocol = protocol.ToOtlpExportProtocol();
Assert.Equal(expectedExportProtocol, exportProtocol);
}
[Theory]
[InlineData("http://test:8888", "http://test:8888/v1/traces")]
[InlineData("http://test:8888/", "http://test:8888/v1/traces")]
[InlineData("http://test:8888/v1/traces", "http://test:8888/v1/traces")]
[InlineData("http://test:8888/v1/traces/", "http://test:8888/v1/traces/")]
public void AppendPathIfNotPresent_TracesPath_AppendsCorrectly(string inputUri, string expectedUri)
{
var uri = new Uri(inputUri, UriKind.Absolute);
var resultUri = uri.AppendPathIfNotPresent(OtlpExporterOptions.TracesExportPath);
Assert.Equal(expectedUri, resultUri.AbsoluteUri);
}
[Fact]
public void AppendExportPath_EndpointNotSet_EnvironmentVariableNotDefined_NotAppended()
{
ClearEndpointEnvVar();
var options = new OtlpExporterOptions { Protocol = OtlpExportProtocol.HttpProtobuf };
options.AppendExportPath("test/path");
Assert.Equal("http://localhost:4318/", options.Endpoint.AbsoluteUri);
}
[Fact]
public void AppendExportPath_EndpointNotSet_EnvironmentVariableDefined_Appended()
{
Environment.SetEnvironmentVariable(OtlpExporterOptions.EndpointEnvVarName, "http://test:8888");
var options = new OtlpExporterOptions { Protocol = OtlpExportProtocol.HttpProtobuf };
options.AppendExportPath("test/path");
Assert.Equal("http://test:8888/test/path", options.Endpoint.AbsoluteUri);
ClearEndpointEnvVar();
}
[Fact]
public void AppendExportPath_EndpointSetEqualToEnvironmentVariable_EnvironmentVariableDefined_NotAppended()
{
Environment.SetEnvironmentVariable(OtlpExporterOptions.EndpointEnvVarName, "http://test:8888");
var options = new OtlpExporterOptions { Protocol = OtlpExportProtocol.HttpProtobuf };
options.Endpoint = new Uri("http://test:8888");
options.AppendExportPath("test/path");
Assert.Equal("http://test:8888/", options.Endpoint.AbsoluteUri);
ClearEndpointEnvVar();
}
[Theory]
[InlineData("http://localhost:4317/")]
[InlineData("http://test:8888/")]
public void AppendExportPath_EndpointSet_EnvironmentVariableNotDefined_NotAppended(string endpoint)
{
ClearEndpointEnvVar();
var options = new OtlpExporterOptions { Protocol = OtlpExportProtocol.HttpProtobuf };
var originalEndpoint = options.Endpoint;
options.Endpoint = new Uri(endpoint);
options.AppendExportPath("test/path");
Assert.Equal(endpoint, options.Endpoint.AbsoluteUri);
}
private static void ClearEndpointEnvVar()
{
Environment.SetEnvironmentVariable(OtlpExporterOptions.EndpointEnvVarName, null);
}
}
}
| |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
namespace EpicCommonUtilities
{
/// <summary>
/// The kinds of statistics that the StatisticalFloat class tracks (or can optionally track, in the case of Median)
/// </summary>
public enum EStatType
{
Minimum,
Maximum,
Average,
StDev,
Median,
Count
};
/// <summary>
/// Keeps a running set of first-order statistics for a single variable
/// </summary>
public class StatisticalFloat
{
/// <summary>
/// Should newly constructed StatisticalFloat instances track the median value?
/// This requires O(N) storage instead of O(1) storage and it is only checked on construction.
/// </summary>
public static bool bSupportMedian = true;
public double GetByType(EStatType Type)
{
switch (Type)
{
case EStatType.Minimum:
return Min;
case EStatType.Maximum:
return Max;
case EStatType.Average:
return Average;
case EStatType.StDev:
return StandardDeviation;
case EStatType.Median:
return Median;
case EStatType.Count:
return MyCount;
default:
return 0.0;
}
}
public double Average
{
get { return MySum / MyCount; }
}
public double Min
{
get { return MyMin; }
}
public double Max
{
get { return MyMax; }
}
public double Value
{
get { return Average; }
set { MyCount = 0; AddSample(value); }
}
/// <summary>
/// Returns the median if bSupportMedian was true at construction and NaN otherwise
/// </summary>
public double Median
{
get
{
if (MySamples != null)
{
MySamples.Sort();
if (MySamples.Count > 0)
{
return MySamples[MySamples.Count / 2];
}
}
return Math.Sqrt(-1.0);
}
}
public double StandardDeviation
{
get
{
double numerator = (MyCount * MySumOfSquares - MySum * MySum);
double denominator = MyCount * (MyCount - 1);
return (MyCount > 1) ? Math.Sqrt(numerator / denominator) : 0.0;
}
}
public double AggregateSum
{
get { return MySum; }
}
public StatisticalFloat()
{
if (bSupportMedian)
{
MySamples = new List<double>();
}
}
public StatisticalFloat Clone()
{
StatisticalFloat Result = new StatisticalFloat();
Result.AddSamples(this);
return Result;
}
public StatisticalFloat(double InValue)
{
if (bSupportMedian)
{
MySamples = new List<double>();
}
MyCount = 0;
AddSample(InValue);
}
public void AddSample(double InValue)
{
if (MyCount == 0)
{
MySum = InValue;
MySumOfSquares = InValue * InValue;
MyMin = InValue;
MyMax = InValue;
}
else
{
MySum += InValue;
MySumOfSquares += InValue * InValue;
MyMin = Math.Min(MyMin, InValue);
MyMax = Math.Max(MyMax, InValue);
}
if (MySamples != null)
{
MySamples.Add(InValue);
}
MyCount++;
}
public void AddSamples(StatisticalFloat Samples)
{
if (MyCount == 0)
{
MySum = Samples.MySum;
MySumOfSquares = Samples.MySumOfSquares;
MyMin = Samples.MyMin;
MyMax = Samples.MyMax;
MyCount = Samples.MyCount;
}
else
{
MySum += Samples.MySum;
MySumOfSquares += Samples.MySumOfSquares;
MyMin = Math.Min(MyMin, Samples.MyMin);
MyMax = Math.Max(MyMax, Samples.MyMax);
MyCount += Samples.MyCount;
}
if (MySamples != null)
{
MySamples.AddRange(Samples.MySamples);
}
}
public void AddDistribution(StatisticalFloat Samples)
{
if (MyCount == 0)
{
AddSamples(Samples);
}
else if (Samples.MyCount > 0)
{
MyMin = MyMin + Samples.MyMin;
MyMax = MyMax + Samples.MyMax;
MySum = Average + Samples.Average;
MySumOfSquares = MySum * MySum;
MyCount = 1;
if (MySamples != null)
{
MySamples.Clear();
MySamples.Add(MySum);
}
}
}
public void ScaleBy(double ScaleFactor)
{
MySum *= ScaleFactor;
MySumOfSquares *= Math.Abs(ScaleFactor);
MyMin *= ScaleFactor;
MyMax *= ScaleFactor;
if (MySamples != null)
{
for (int i = 0; i < MySamples.Count; ++i)
{
MySamples[i] = MySamples[i] * ScaleFactor;
}
}
}
public string ToStringSizesInKB()
{
return String.Format("avg={0:N1} KB [{1:N1}..{2:N1}]", Average/1024.0, MyMin/1024.0, MyMax/1024.0);
}
public string Min_ToStringInt()
{
return ((long)MyMin).ToString();
}
public string Max_ToStringInt()
{
return ((long)MyMax).ToString();
}
double MySumOfSquares = 0.0;
double MySum = 0.0;
double MyMin = 0.0;
double MyMax = 0.0;
long MyCount = 0;
// Simple wasteful implementation; Tool is for offline anaysis and N is only on the order of hundreds typically
// but the median tracking can be disabled by setting bSupportMedian to false before construction.
List<double> MySamples = null;
}
}
| |
//
// Copyright 2012-2013, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Threading.Tasks;
using MonoTouch.UIKit; using UIKit;
using MonoTouch.Foundation; using Foundation;
using Xamarin.Utilities.iOS;
using Xamarin.Controls;
namespace Xamarin.Auth
{
/// <summary>
/// The ViewController that the WebAuthenticator presents to the user.
/// </summary>
internal class WebAuthenticatorController : UIViewController
{
protected WebAuthenticator authenticator;
UIWebView webView;
UIActivityIndicatorView activity;
UIView authenticatingView;
ProgressLabel progress;
bool webViewVisible = true;
const double TransitionTime = 0.25;
bool keepTryingAfterError = true;
public WebAuthenticatorController (WebAuthenticator authenticator)
{
this.authenticator = authenticator;
authenticator.Error += HandleError;
authenticator.BrowsingCompleted += HandleBrowsingCompleted;
//
// Create the UI
//
Title = authenticator.Title;
NavigationItem.LeftBarButtonItem = new UIBarButtonItem (
UIBarButtonSystemItem.Cancel,
delegate {
Cancel ();
});
activity = new UIActivityIndicatorView (UIActivityIndicatorViewStyle.White);
NavigationItem.RightBarButtonItem = new UIBarButtonItem (activity);
webView = new UIWebView (View.Bounds) {
Delegate = new WebViewDelegate (this),
AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight,
};
View.AddSubview (webView);
View.BackgroundColor = UIColor.Black;
//
// Locate our initial URL
//
BeginLoadingInitialUrl ();
}
void Cancel ()
{
authenticator.OnCancelled ();
}
void BeginLoadingInitialUrl ()
{
authenticator.GetInitialUrlAsync ().ContinueWith (t => {
if (t.IsFaulted) {
keepTryingAfterError = false;
authenticator.OnError (t.Exception);
}
else {
// Delete cookies so we can work with multiple accounts
if (this.authenticator.ClearCookiesBeforeLogin)
WebAuthenticator.ClearCookies();
//
// Begin displaying the page
//
LoadInitialUrl (t.Result);
}
}, TaskScheduler.FromCurrentSynchronizationContext ());
}
void LoadInitialUrl (Uri url)
{
if (!webViewVisible) {
progress.StopAnimating ();
webViewVisible = true;
UIView.Transition (
fromView: authenticatingView,
toView: webView,
duration: TransitionTime,
options: UIViewAnimationOptions.TransitionCrossDissolve,
completion: null);
}
if (url != null) {
var request = new NSUrlRequest (new NSUrl (url.AbsoluteUri));
NSUrlCache.SharedCache.RemoveCachedResponse (request); // Always try
webView.LoadRequest (request);
}
}
void HandleBrowsingCompleted (object sender, EventArgs e)
{
if (!webViewVisible) return;
if (authenticatingView == null) {
authenticatingView = new UIView (View.Bounds) {
AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight,
BackgroundColor = UIColor.FromRGB (0x33, 0x33, 0x33),
};
progress = new ProgressLabel ("Authenticating...");
var f = progress.Frame;
var b = authenticatingView.Bounds;
f.X = (b.Width - f.Width) / 2;
f.Y = (b.Height - f.Height) / 2;
progress.Frame = f;
authenticatingView.Add (progress);
}
else {
authenticatingView.Frame = View.Bounds;
}
webViewVisible = false;
progress.StartAnimating ();
UIView.Transition (
fromView: webView,
toView: authenticatingView,
duration: TransitionTime,
options: UIViewAnimationOptions.TransitionCrossDissolve,
completion: null);
}
void HandleError (object sender, AuthenticatorErrorEventArgs e)
{
var after = keepTryingAfterError ?
(Action)BeginLoadingInitialUrl :
(Action)Cancel;
if (e.Exception != null) {
this.ShowError ("Authentication Error", e.Exception, after);
}
else {
this.ShowError ("Authentication Error", e.Message, after);
}
}
protected class WebViewDelegate : UIWebViewDelegate
{
protected WebAuthenticatorController controller;
Uri lastUrl;
public WebViewDelegate (WebAuthenticatorController controller)
{
this.controller = controller;
}
public override bool ShouldStartLoad (UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType)
{
var nsUrl = request.Url;
if (nsUrl != null) {
Uri url;
if (Uri.TryCreate (nsUrl.AbsoluteString, UriKind.Absolute, out url)) {
controller.authenticator.OnPageLoading (url);
}
}
return true;
}
public override void LoadStarted (UIWebView webView)
{
controller.activity.StartAnimating ();
webView.UserInteractionEnabled = false;
}
public override void LoadFailed (UIWebView webView, NSError error)
{
controller.activity.StopAnimating ();
webView.UserInteractionEnabled = true;
controller.authenticator.OnError (error.LocalizedDescription);
}
public override void LoadingFinished (UIWebView webView)
{
controller.activity.StopAnimating ();
webView.UserInteractionEnabled = true;
var url = new Uri (webView.Request.Url.AbsoluteString);
if (!url.Equals(lastUrl)) { // Prevent loading the same URL multiple times
lastUrl = url;
controller.authenticator.OnPageLoaded (url);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Core.Cache;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using umbraco.interfaces;
namespace Umbraco.Core.Sync
{
/// <summary>
/// An <see cref="IServerMessenger"/> that works by storing messages in the database.
/// </summary>
//
// abstract because it needs to be inherited by a class that will
// - trigger Boot() when appropriate
// - trigger Sync() when appropriate
//
// this messenger writes ALL instructions to the database,
// but only processes instructions coming from remote servers,
// thus ensuring that instructions run only once
//
public abstract class DatabaseServerMessenger : ServerMessengerBase
{
private readonly ApplicationContext _appContext;
private readonly DatabaseServerMessengerOptions _options;
private readonly object _lock = new object();
private int _lastId = -1;
private volatile bool _syncing;
private DateTime _lastSync;
private bool _initialized;
protected ApplicationContext ApplicationContext { get { return _appContext; } }
protected DatabaseServerMessenger(ApplicationContext appContext, bool distributedEnabled, DatabaseServerMessengerOptions options)
: base(distributedEnabled)
{
if (appContext == null) throw new ArgumentNullException("appContext");
if (options == null) throw new ArgumentNullException("options");
_appContext = appContext;
_options = options;
_lastSync = DateTime.UtcNow;
}
#region Messenger
protected override bool RequiresDistributed(IEnumerable<IServerAddress> servers, ICacheRefresher refresher, MessageType dispatchType)
{
// we don't care if there's servers listed or not,
// if distributed call is enabled we will make the call
return _initialized && DistributedEnabled;
}
protected override void DeliverRemote(
IEnumerable<IServerAddress> servers,
ICacheRefresher refresher,
MessageType messageType,
IEnumerable<object> ids = null,
string json = null)
{
var idsA = ids == null ? null : ids.ToArray();
Type idType;
if (GetArrayType(idsA, out idType) == false)
throw new ArgumentException("All items must be of the same type, either int or Guid.", "ids");
var instructions = RefreshInstruction.GetInstructions(refresher, messageType, idsA, idType, json);
var dto = new CacheInstructionDto
{
UtcStamp = DateTime.UtcNow,
Instructions = JsonConvert.SerializeObject(instructions, Formatting.None),
OriginIdentity = GetLocalIdentity()
};
ApplicationContext.DatabaseContext.Database.Insert(dto);
}
#endregion
#region Sync
/// <summary>
/// Boots the messenger.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// Callers MUST ensure thread-safety.
/// </remarks>
protected void Boot()
{
ReadLastSynced();
Initialize();
}
/// <summary>
/// Initializes a server that has never synchronized before.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// Callers MUST ensure thread-safety.
/// </remarks>
private void Initialize()
{
if (_lastId < 0) // never synced before
{
// we haven't synced - in this case we aren't going to sync the whole thing, we will assume this is a new
// server and it will need to rebuild it's own caches, eg Lucene or the xml cache file.
LogHelper.Warn<DatabaseServerMessenger>("No last synced Id found, this generally means this is a new server/install. The server will rebuild its caches and indexes and then adjust it's last synced id to the latest found in the database and will start maintaining cache updates based on that id");
// go get the last id in the db and store it
// note: do it BEFORE initializing otherwise some instructions might get lost
// when doing it before, some instructions might run twice - not an issue
var lastId = _appContext.DatabaseContext.Database.ExecuteScalar<int>("SELECT MAX(id) FROM umbracoCacheInstruction");
if (lastId > 0)
SaveLastSynced(lastId);
// execute initializing callbacks
if (_options.InitializingCallbacks != null)
foreach (var callback in _options.InitializingCallbacks)
callback();
}
_initialized = true;
}
/// <summary>
/// Synchronize the server (throttled).
/// </summary>
protected void Sync()
{
if ((DateTime.UtcNow - _lastSync).Seconds <= _options.ThrottleSeconds)
return;
if (_syncing) return;
lock (_lock)
{
if (_syncing) return;
_syncing = true; // lock other threads out
_lastSync = DateTime.UtcNow;
using (DisposableTimer.DebugDuration<DatabaseServerMessenger>("Syncing from database..."))
{
ProcessDatabaseInstructions();
PruneOldInstructions();
}
_syncing = false; // release
}
}
/// <summary>
/// Process instructions from the database.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// </remarks>
private void ProcessDatabaseInstructions()
{
// NOTE
// we 'could' recurse to ensure that no remaining instructions are pending in the table before proceeding but I don't think that
// would be a good idea since instructions could keep getting added and then all other threads will probably get stuck from serving requests
// (depending on what the cache refreshers are doing). I think it's best we do the one time check, process them and continue, if there are
// pending requests after being processed, they'll just be processed on the next poll.
//
// FIXME not true if we're running on a background thread, assuming we can?
var sql = new Sql().Select("*")
.From<CacheInstructionDto>()
.Where<CacheInstructionDto>(dto => dto.Id > _lastId)
.OrderBy<CacheInstructionDto>(dto => dto.Id);
var dtos = _appContext.DatabaseContext.Database.Fetch<CacheInstructionDto>(sql);
if (dtos.Count <= 0) return;
// only process instructions coming from a remote server, and ignore instructions coming from
// the local server as they've already been processed. We should NOT assume that the sequence of
// instructions in the database makes any sense whatsoever, because it's all async.
var localIdentity = GetLocalIdentity();
var lastId = 0;
foreach (var dto in dtos)
{
if (dto.OriginIdentity == localIdentity)
{
// just skip that local one but update lastId nevertheless
lastId = dto.Id;
continue;
}
// deserialize remote instructions & skip if it fails
JArray jsonA;
try
{
jsonA = JsonConvert.DeserializeObject<JArray>(dto.Instructions);
}
catch (JsonException ex)
{
LogHelper.Error<DatabaseServerMessenger>(string.Format("Failed to deserialize instructions ({0}: \"{1}\").", dto.Id, dto.Instructions), ex);
lastId = dto.Id; // skip
continue;
}
// execute remote instructions & update lastId
try
{
NotifyRefreshers(jsonA);
lastId = dto.Id;
}
catch (Exception ex)
{
LogHelper.Error<DatabaseServerMessenger>(string.Format("Failed to execute instructions ({0}: \"{1}\").", dto.Id, dto.Instructions), ex);
LogHelper.Warn<DatabaseServerMessenger>("BEWARE - DISTRIBUTED CACHE IS NOT UPDATED.");
throw;
}
}
if (lastId > 0)
SaveLastSynced(lastId);
}
/// <summary>
/// Remove old instructions from the database.
/// </summary>
private void PruneOldInstructions()
{
_appContext.DatabaseContext.Database.Delete<CacheInstructionDto>("WHERE utcStamp < @pruneDate",
new { pruneDate = DateTime.UtcNow.AddDays(-_options.DaysToRetainInstructions) });
}
/// <summary>
/// Reads the last-synced id from file into memory.
/// </summary>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// </remarks>
private void ReadLastSynced()
{
var path = SyncFilePath;
if (File.Exists(path) == false) return;
var content = File.ReadAllText(path);
int last;
if (int.TryParse(content, out last))
_lastId = last;
}
/// <summary>
/// Updates the in-memory last-synced id and persists it to file.
/// </summary>
/// <param name="id">The id.</param>
/// <remarks>
/// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded.
/// </remarks>
private void SaveLastSynced(int id)
{
File.WriteAllText(SyncFilePath, id.ToString(CultureInfo.InvariantCulture));
_lastId = id;
}
/// <summary>
/// Gets the local server unique identity.
/// </summary>
/// <returns>The unique identity of the local server.</returns>
protected string GetLocalIdentity()
{
return JsonConvert.SerializeObject(new
{
machineName = NetworkHelper.MachineName,
appDomainAppId = HttpRuntime.AppDomainAppId
});
}
/// <summary>
/// Gets the sync file path for the local server.
/// </summary>
/// <returns>The sync file path for the local server.</returns>
private static string SyncFilePath
{
get
{
var tempFolder = IOHelper.MapPath("~/App_Data/TEMP/DistCache/" + NetworkHelper.FileSafeMachineName);
if (Directory.Exists(tempFolder) == false)
Directory.CreateDirectory(tempFolder);
return Path.Combine(tempFolder, HttpRuntime.AppDomainAppId.ReplaceNonAlphanumericChars(string.Empty) + "-lastsynced.txt");
}
}
#endregion
#region Notify refreshers
private static ICacheRefresher GetRefresher(Guid id)
{
var refresher = CacheRefreshersResolver.Current.GetById(id);
if (refresher == null)
throw new InvalidOperationException("Cache refresher with ID \"" + id + "\" does not exist.");
return refresher;
}
private static IJsonCacheRefresher GetJsonRefresher(Guid id)
{
return GetJsonRefresher(GetRefresher(id));
}
private static IJsonCacheRefresher GetJsonRefresher(ICacheRefresher refresher)
{
var jsonRefresher = refresher as IJsonCacheRefresher;
if (jsonRefresher == null)
throw new InvalidOperationException("Cache refresher with ID \"" + refresher.UniqueIdentifier + "\" does not implement " + typeof(IJsonCacheRefresher) + ".");
return jsonRefresher;
}
private static void NotifyRefreshers(IEnumerable<JToken> jsonArray)
{
foreach (var jsonItem in jsonArray)
{
// could be a JObject in which case we can convert to a RefreshInstruction,
// otherwise it could be another JArray - in which case we'll iterate that.
var jsonObj = jsonItem as JObject;
if (jsonObj != null)
{
var instruction = jsonObj.ToObject<RefreshInstruction>();
switch (instruction.RefreshType)
{
case RefreshMethodType.RefreshAll:
RefreshAll(instruction.RefresherId);
break;
case RefreshMethodType.RefreshByGuid:
RefreshByGuid(instruction.RefresherId, instruction.GuidId);
break;
case RefreshMethodType.RefreshById:
RefreshById(instruction.RefresherId, instruction.IntId);
break;
case RefreshMethodType.RefreshByIds:
RefreshByIds(instruction.RefresherId, instruction.JsonIds);
break;
case RefreshMethodType.RefreshByJson:
RefreshByJson(instruction.RefresherId, instruction.JsonPayload);
break;
case RefreshMethodType.RemoveById:
RemoveById(instruction.RefresherId, instruction.IntId);
break;
}
}
else
{
var jsonInnerArray = (JArray) jsonItem;
NotifyRefreshers(jsonInnerArray); // recurse
}
}
}
private static void RefreshAll(Guid uniqueIdentifier)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.RefreshAll();
}
private static void RefreshByGuid(Guid uniqueIdentifier, Guid id)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.Refresh(id);
}
private static void RefreshById(Guid uniqueIdentifier, int id)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.Refresh(id);
}
private static void RefreshByIds(Guid uniqueIdentifier, string jsonIds)
{
var refresher = GetRefresher(uniqueIdentifier);
foreach (var id in JsonConvert.DeserializeObject<int[]>(jsonIds))
refresher.Refresh(id);
}
private static void RefreshByJson(Guid uniqueIdentifier, string jsonPayload)
{
var refresher = GetJsonRefresher(uniqueIdentifier);
refresher.Refresh(jsonPayload);
}
private static void RemoveById(Guid uniqueIdentifier, int id)
{
var refresher = GetRefresher(uniqueIdentifier);
refresher.Remove(id);
}
#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.Linq;
using Xunit;
namespace System.IO.Tests
{
public class Directory_CreateDirectory : FileSystemTest
{
#region Utilities
public virtual DirectoryInfo Create(string path)
{
return Directory.CreateDirectory(path);
}
#endregion
#region UniversalTests
[Fact]
public void NullAsPath_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => Create(null));
}
[Fact]
public void EmptyAsPath_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => Create(string.Empty));
}
[Fact]
public void PathWithInvalidCharactersAsPath_ThrowsArgumentException()
{
var paths = IOInputs.GetPathsWithInvalidCharacters();
Assert.All(paths, (path) =>
{
Assert.Throws<ArgumentException>(() => Create(path));
});
}
[Fact]
public void PathAlreadyExistsAsFile()
{
string path = GetTestFilePath();
File.Create(path).Dispose();
Assert.Throws<IOException>(() => Create(path));
Assert.Throws<IOException>(() => Create(IOServices.AddTrailingSlashIfNeeded(path)));
Assert.Throws<IOException>(() => Create(IOServices.RemoveTrailingSlash(path)));
}
[Theory]
[InlineData(FileAttributes.Hidden)]
[InlineData(FileAttributes.ReadOnly)]
[InlineData(FileAttributes.Normal)]
public void PathAlreadyExistsAsDirectory(FileAttributes attributes)
{
DirectoryInfo testDir = Create(GetTestFilePath());
FileAttributes original = testDir.Attributes;
try
{
testDir.Attributes = attributes;
Assert.Equal(testDir.FullName, Create(testDir.FullName).FullName);
}
finally
{
testDir.Attributes = original;
}
}
[Fact]
public void RootPath()
{
string dirName = Path.GetPathRoot(Directory.GetCurrentDirectory());
DirectoryInfo dir = Create(dirName);
Assert.Equal(dir.FullName, dirName);
}
[Fact]
public void DotIsCurrentDirectory()
{
string path = GetTestFilePath();
DirectoryInfo result = Create(Path.Combine(path, "."));
Assert.Equal(IOServices.RemoveTrailingSlash(path), result.FullName);
result = Create(Path.Combine(path, ".") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(path), result.FullName);
}
[Fact]
public void CreateCurrentDirectory()
{
DirectoryInfo result = Create(Directory.GetCurrentDirectory());
Assert.Equal(Directory.GetCurrentDirectory(), result.FullName);
}
[Fact]
public void DotDotIsParentDirectory()
{
DirectoryInfo result = Create(Path.Combine(GetTestFilePath(), ".."));
Assert.Equal(IOServices.RemoveTrailingSlash(TestDirectory), result.FullName);
result = Create(Path.Combine(GetTestFilePath(), "..") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(TestDirectory), result.FullName);
}
[Fact]
public void ValidPathWithTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetValidPathComponentNames();
Assert.All(components, (component) =>
{
string path = IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component));
DirectoryInfo result = Create(path);
Assert.Equal(path, result.FullName);
Assert.True(result.Exists);
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void ValidExtendedPathWithTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetValidPathComponentNames();
Assert.All(components, (component) =>
{
string path = IOInputs.ExtendedPrefix + IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component));
DirectoryInfo result = Create(path);
Assert.Equal(path, result.FullName);
Assert.True(result.Exists);
});
}
[Fact]
public void ValidPathWithoutTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetValidPathComponentNames();
Assert.All(components, (component) =>
{
string path = testDir.FullName + Path.DirectorySeparatorChar + component;
DirectoryInfo result = Create(path);
Assert.Equal(path, result.FullName);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
public void ValidPathWithMultipleSubdirectories()
{
string dirName = Path.Combine(GetTestFilePath(), "Test", "Test", "Test");
DirectoryInfo dir = Create(dirName);
Assert.Equal(dir.FullName, dirName);
}
[Fact]
public void AllowedSymbols()
{
string dirName = Path.Combine(TestDirectory, Path.GetRandomFileName() + "!@#$%^&");
DirectoryInfo dir = Create(dirName);
Assert.Equal(dir.FullName, dirName);
}
[Fact]
public void DirectoryEqualToMaxDirectory_CanBeCreated()
{
DirectoryInfo testDir = Create(GetTestFilePath());
PathInfo path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory, IOInputs.MaxComponent);
Assert.All(path.SubPaths, (subpath) =>
{
DirectoryInfo result = Create(subpath);
Assert.Equal(subpath, result.FullName);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
public void DirectoryEqualToMaxDirectory_CanBeCreatedAllAtOnce()
{
DirectoryInfo testDir = Create(GetTestFilePath());
PathInfo path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory, maxComponent: 10);
DirectoryInfo result = Create(path.FullPath);
Assert.Equal(path.FullPath, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
[Fact]
public void DirectoryWithComponentLongerThanMaxComponentAsPath_ThrowsPathTooLongException()
{
// While paths themselves can be up to 260 characters including trailing null, file systems
// limit each components of the path to a total of 255 characters.
var paths = IOInputs.GetPathsWithComponentLongerThanMaxComponent();
Assert.All(paths, (path) =>
{
Assert.Throws<PathTooLongException>(() => Create(path));
});
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void PathWithInvalidColons_ThrowsNotSupportedException()
{
var paths = IOInputs.GetPathsWithInvalidColons();
Assert.All(paths, (path) =>
{
Assert.Throws<NotSupportedException>(() => Create(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void DirectoryLongerThanMaxPath_Succeeds()
{
var paths = IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath());
Assert.All(paths, (path) =>
{
DirectoryInfo result = Create(path);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void DirectoryLongerThanMaxLongPath_ThrowsPathTooLongException()
{
var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath());
Assert.All(paths, (path) =>
{
Assert.Throws<PathTooLongException>(() => Create(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void DirectoryLongerThanMaxLongPathWithExtendedSyntax_ThrowsPathTooLongException()
{
var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath(), useExtendedSyntax: true);
Assert.All(paths, (path) =>
{
Assert.Throws<PathTooLongException>(() => Create(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void ExtendedDirectoryLongerThanLegacyMaxPath_Succeeds()
{
var paths = IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath(), useExtendedSyntax: true);
Assert.All(paths, (path) =>
{
Assert.True(Create(path).Exists);
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void DirectoryLongerThanMaxDirectoryAsPath_Succeeds()
{
var paths = IOInputs.GetPathsLongerThanMaxDirectory(GetTestFilePath());
Assert.All(paths, (path) =>
{
var result = Create(path);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixPathLongerThan256_Allowed()
{
DirectoryInfo testDir = Create(GetTestFilePath());
PathInfo path = IOServices.GetPath(testDir.FullName, 257, IOInputs.MaxComponent);
DirectoryInfo result = Create(path.FullPath);
Assert.Equal(path.FullPath, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixPathWithDeeplyNestedDirectories()
{
DirectoryInfo parent = Create(GetTestFilePath());
for (int i = 1; i <= 100; i++) // 100 == arbitrarily large number of directories
{
parent = Create(Path.Combine(parent.FullName, "dir" + i));
Assert.True(Directory.Exists(parent.FullName));
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsWhiteSpaceAsPath_ThrowsArgumentException()
{
var paths = IOInputs.GetWhiteSpace();
Assert.All(paths, (path) =>
{
Assert.Throws<ArgumentException>(() => Create(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixWhiteSpaceAsPath_Allowed()
{
var paths = IOInputs.GetWhiteSpace();
Assert.All(paths, (path) =>
{
Create(Path.Combine(TestDirectory, path));
Assert.True(Directory.Exists(Path.Combine(TestDirectory, path)));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsTrailingWhiteSpace()
{
// Windows will remove all non-significant whitespace in a path
DirectoryInfo testDir = Create(GetTestFilePath());
var components = IOInputs.GetWhiteSpace();
Assert.All(components, (component) =>
{
string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component;
DirectoryInfo result = Create(path);
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsExtendedSyntaxWhiteSpace()
{
var paths = IOInputs.GetSimpleWhiteSpace();
using (TemporaryDirectory directory = new TemporaryDirectory())
{
foreach (var path in paths)
{
string extendedPath = Path.Combine(IOInputs.ExtendedPrefix + directory.Path, path);
Directory.CreateDirectory(extendedPath);
Assert.True(Directory.Exists(extendedPath), extendedPath);
}
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixNonSignificantTrailingWhiteSpace()
{
// Unix treats trailing/prename whitespace as significant and a part of the name.
DirectoryInfo testDir = Create(GetTestFilePath());
var components = IOInputs.GetWhiteSpace();
Assert.All(components, (component) =>
{
string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component;
DirectoryInfo result = Create(path);
Assert.True(Directory.Exists(result.FullName));
Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // alternate data streams
public void PathWithAlternateDataStreams_ThrowsNotSupportedException()
{
var paths = IOInputs.GetPathsWithAlternativeDataStreams();
Assert.All(paths, (path) =>
{
Assert.Throws<NotSupportedException>(() => Create(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // device name prefixes
public void PathWithReservedDeviceNameAsPath_ThrowsDirectoryNotFoundException()
{ // Throws DirectoryNotFoundException, when the behavior really should be an invalid path
var paths = IOInputs.GetPathsWithReservedDeviceNames();
Assert.All(paths, (path) =>
{
Assert.Throws<DirectoryNotFoundException>(() => Create(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // device name prefixes
public void PathWithReservedDeviceNameAsExtendedPath()
{
var paths = IOInputs.GetReservedDeviceNames();
using (TemporaryDirectory directory = new TemporaryDirectory())
{
Assert.All(paths, (path) =>
{
Assert.True(Create(IOInputs.ExtendedPrefix + Path.Combine(directory.Path, path)).Exists, path);
});
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // UNC shares
public void UncPathWithoutShareNameAsPath_ThrowsArgumentException()
{
var paths = IOInputs.GetUncPathsWithoutShareName();
foreach (var path in paths)
{
Assert.Throws<ArgumentException>(() => Create(path));
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // UNC shares
public void UNCPathWithOnlySlashes()
{
Assert.Throws<ArgumentException>(() => Create("//"));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public void CDriveCase()
{
DirectoryInfo dir = Create("c:\\");
DirectoryInfo dir2 = Create("C:\\");
Assert.NotEqual(dir.FullName, dir2.FullName);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void DriveLetter_Windows()
{
// On Windows, DirectoryInfo will replace "<DriveLetter>:" with "."
var driveLetter = Create(Directory.GetCurrentDirectory()[0] + ":");
var current = Create(".");
Assert.Equal(current.Name, driveLetter.Name);
Assert.Equal(current.FullName, driveLetter.FullName);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void DriveLetter_Unix()
{
// On Unix, there's no special casing for drive letters, which are valid file names
var driveLetter = Create("C:");
var current = Create(".");
Assert.Equal("C:", driveLetter.Name);
Assert.Equal(Path.Combine(current.FullName, "C:"), driveLetter.FullName);
try
{
// If this test is inherited then it's possible this call will fail due to the "C:" directory
// being deleted in that other test before this call. What we care about testing (proper path
// handling) is unaffected by this race condition.
Directory.Delete("C:");
}
catch (DirectoryNotFoundException) { }
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // testing drive labels
public void NonExistentDriveAsPath_ThrowsDirectoryNotFoundException()
{
Assert.Throws<DirectoryNotFoundException>(() =>
{
Create(IOServices.GetNonExistentDrive());
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // testing drive labels
public void SubdirectoryOnNonExistentDriveAsPath_ThrowsDirectoryNotFoundException()
{
Assert.Throws<DirectoryNotFoundException>(() =>
{
Create(Path.Combine(IOServices.GetNonExistentDrive(), "Subdirectory"));
});
}
[Fact]
[ActiveIssue(1221)]
[PlatformSpecific(PlatformID.Windows)] // testing drive labels
public void NotReadyDriveAsPath_ThrowsDirectoryNotFoundException()
{ // Behavior is suspect, should really have thrown IOException similar to the SubDirectory case
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
Assert.Throws<DirectoryNotFoundException>(() =>
{
Create(drive);
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // testing drive labels
[ActiveIssue(1221)]
public void SubdirectoryOnNotReadyDriveAsPath_ThrowsIOException()
{
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
// 'Device is not ready'
Assert.Throws<IOException>(() =>
{
Create(Path.Combine(drive, "Subdirectory"));
});
}
#if !TEST_WINRT // Cannot set current directory to root from appcontainer with it's default ACL
/*
[Fact]
[ActiveIssue(1220)] // SetCurrentDirectory
public void DotDotAsPath_WhenCurrentDirectoryIsRoot_DoesNotThrow()
{
string root = Path.GetPathRoot(Directory.GetCurrentDirectory());
using (CurrentDirectoryContext context = new CurrentDirectoryContext(root))
{
DirectoryInfo result = Create("..");
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(root, result.FullName);
}
}
*/
#endif
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.WindowsAzure.Storage.Table;
using Xunit;
using Xunit.Abstractions;
using Orleans;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Providers;
using Orleans.Storage;
using TestExtensions;
using UnitTests.StorageTests;
using UnitTests.Persistence;
using Samples.StorageProviders;
namespace Tester.AzureUtils.Persistence
{
[Collection(TestEnvironmentFixture.DefaultCollection)]
[TestCategory("Persistence")]
public class PersistenceProviderTests_Local
{
private readonly IProviderRuntime providerRuntime;
private readonly Dictionary<string, string> providerCfgProps = new Dictionary<string, string>();
private readonly ITestOutputHelper output;
private readonly TestEnvironmentFixture fixture;
public PersistenceProviderTests_Local(ITestOutputHelper output, TestEnvironmentFixture fixture)
{
this.output = output;
this.fixture = fixture;
this.providerRuntime = new ClientProviderRuntime(fixture.InternalGrainFactory, fixture.Services, NullLoggerFactory.Instance);
this.providerCfgProps.Clear();
}
[Fact, TestCategory("Functional")]
public async Task PersistenceProvider_Mock_WriteRead()
{
const string testName = nameof(PersistenceProvider_Mock_WriteRead);
IStorageProvider store = new MockStorageProvider();
var cfg = new ProviderConfiguration(this.providerCfgProps);
await store.Init(testName, this.providerRuntime, cfg);
await Test_PersistenceProvider_WriteRead(testName, store);
}
[Fact, TestCategory("Functional")]
public async Task PersistenceProvider_FileStore_WriteRead()
{
const string testName = nameof(PersistenceProvider_FileStore_WriteRead);
IStorageProvider store = new OrleansFileStorage();
this.providerCfgProps.Add("RootDirectory", "Data");
var cfg = new ProviderConfiguration(this.providerCfgProps);
await store.Init(testName, this.providerRuntime, cfg);
await Test_PersistenceProvider_WriteRead(testName, store);
}
[SkippableFact, TestCategory("Functional"), TestCategory("Azure")]
public async Task PersistenceProvider_Azure_Read()
{
TestUtils.CheckForAzureStorage();
const string testName = nameof(PersistenceProvider_Azure_Read);
AzureTableGrainStorage store = await InitAzureTableGrainStorage();
await Test_PersistenceProvider_Read(testName, store);
}
[SkippableTheory, TestCategory("Functional"), TestCategory("Azure")]
[InlineData(null, false)]
[InlineData(null, true)]
[InlineData(15 * 64 * 1024 - 256, false)]
[InlineData(15 * 32 * 1024 - 256, true)]
public async Task PersistenceProvider_Azure_WriteRead(int? stringLength, bool useJson)
{
var testName = string.Format("{0}({1} = {2}, {3} = {4})",
nameof(PersistenceProvider_Azure_WriteRead),
nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(),
nameof(useJson), useJson);
var grainState = TestStoreGrainState.NewRandomState(stringLength);
EnsureEnvironmentSupportsState(grainState);
var store = await InitAzureTableGrainStorage(useJson);
await Test_PersistenceProvider_WriteRead(testName, store, grainState);
}
[SkippableTheory, TestCategory("Functional"), TestCategory("Azure")]
[InlineData(null, false)]
[InlineData(null, true)]
[InlineData(15 * 64 * 1024 - 256, false)]
[InlineData(15 * 32 * 1024 - 256, true)]
public async Task PersistenceProvider_Azure_WriteClearRead(int? stringLength, bool useJson)
{
var testName = string.Format("{0}({1} = {2}, {3} = {4})",
nameof(PersistenceProvider_Azure_WriteClearRead),
nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(),
nameof(useJson), useJson);
var grainState = TestStoreGrainState.NewRandomState(stringLength);
EnsureEnvironmentSupportsState(grainState);
var store = await InitAzureTableGrainStorage(useJson);
await Test_PersistenceProvider_WriteClearRead(testName, store, grainState);
}
[SkippableTheory, TestCategory("Functional"), TestCategory("Azure")]
[InlineData(null, true, false)]
[InlineData(null, false, true)]
[InlineData(15 * 32 * 1024 - 256, true, false)]
[InlineData(15 * 32 * 1024 - 256, false, true)]
public async Task PersistenceProvider_Azure_ChangeReadFormat(int? stringLength, bool useJsonForWrite, bool useJsonForRead)
{
var testName = string.Format("{0}({1} = {2}, {3} = {4}, {5} = {6})",
nameof(PersistenceProvider_Azure_ChangeReadFormat),
nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(),
nameof(useJsonForWrite), useJsonForWrite,
nameof(useJsonForRead), useJsonForRead);
var grainState = TestStoreGrainState.NewRandomState(stringLength);
EnsureEnvironmentSupportsState(grainState);
var grainId = GrainId.NewId();
var store = await InitAzureTableGrainStorage(useJsonForWrite);
grainState = await Test_PersistenceProvider_WriteRead(testName, store,
grainState, grainId);
store = await InitAzureTableGrainStorage(useJsonForRead);
await Test_PersistenceProvider_Read(testName, store, grainState, grainId);
}
[SkippableTheory, TestCategory("Functional"), TestCategory("Azure")]
[InlineData(null, true, false)]
[InlineData(null, false, true)]
[InlineData(15 * 32 * 1024 - 256, true, false)]
[InlineData(15 * 32 * 1024 - 256, false, true)]
public async Task PersistenceProvider_Azure_ChangeWriteFormat(int? stringLength, bool useJsonForFirstWrite, bool useJsonForSecondWrite)
{
var testName = string.Format("{0}({1}={2},{3}={4},{5}={6})",
nameof(PersistenceProvider_Azure_ChangeWriteFormat),
nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(),
"json1stW", useJsonForFirstWrite,
"json2ndW", useJsonForSecondWrite);
var grainState = TestStoreGrainState.NewRandomState(stringLength);
EnsureEnvironmentSupportsState(grainState);
var grainId = GrainId.NewId();
var store = await InitAzureTableGrainStorage(useJsonForFirstWrite);
await Test_PersistenceProvider_WriteRead(testName, store, grainState, grainId);
grainState = TestStoreGrainState.NewRandomState(stringLength);
grainState.ETag = "*";
store = await InitAzureTableGrainStorage(useJsonForSecondWrite);
await Test_PersistenceProvider_WriteRead(testName, store, grainState, grainId);
}
[SkippableTheory, TestCategory("Functional"), TestCategory("Azure")]
[InlineData(null, false)]
[InlineData(null, true)]
[InlineData(15 * 64 * 1024 - 256, false)]
[InlineData(15 * 32 * 1024 - 256, true)]
public async Task AzureTableStorage_ConvertToFromStorageFormat(int? stringLength, bool useJson)
{
var testName = string.Format("{0}({1} = {2}, {3} = {4})",
nameof(AzureTableStorage_ConvertToFromStorageFormat),
nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(),
nameof(useJson), useJson);
var state = TestStoreGrainState.NewRandomState(stringLength);
EnsureEnvironmentSupportsState(state);
var storage = await InitAzureTableGrainStorage(useJson);
var initialState = state.State;
var entity = new DynamicTableEntity();
storage.ConvertToStorageFormat(initialState, entity);
var convertedState = (TestStoreGrainState)storage.ConvertFromStorageFormat(entity);
Assert.NotNull(convertedState);
Assert.Equal(initialState.A, convertedState.A);
Assert.Equal(initialState.B, convertedState.B);
Assert.Equal(initialState.C, convertedState.C);
}
[Fact, TestCategory("Functional"), TestCategory("MemoryStore")]
public async Task PersistenceProvider_Memory_FixedLatency_WriteRead()
{
const string testName = nameof(PersistenceProvider_Memory_FixedLatency_WriteRead);
TimeSpan expectedLatency = TimeSpan.FromMilliseconds(200);
MemoryGrainStorageWithLatency store = new MemoryGrainStorageWithLatency(testName, new MemoryStorageWithLatencyOptions()
{
Latency = expectedLatency,
MockCallsOnly = true
}, NullLoggerFactory.Instance, this.providerRuntime.ServiceProvider.GetService<IGrainFactory>());
GrainReference reference = this.fixture.InternalGrainFactory.GetGrain(GrainId.NewId());
var state = TestStoreGrainState.NewRandomState();
Stopwatch sw = new Stopwatch();
sw.Start();
await store.WriteStateAsync(testName, reference, state);
TimeSpan writeTime = sw.Elapsed;
this.output.WriteLine("{0} - Write time = {1}", store.GetType().FullName, writeTime);
Assert.True(writeTime >= expectedLatency, $"Write: Expected minimum latency = {expectedLatency} Actual = {writeTime}");
sw.Restart();
var storedState = new GrainState<TestStoreGrainState>();
await store.ReadStateAsync(testName, reference, storedState);
TimeSpan readTime = sw.Elapsed;
this.output.WriteLine("{0} - Read time = {1}", store.GetType().FullName, readTime);
Assert.True(readTime >= expectedLatency, $"Read: Expected minimum latency = {expectedLatency} Actual = {readTime}");
}
[Fact, TestCategory("Performance"), TestCategory("JSON")]
public void Json_Perf_Newtonsoft_vs_Net()
{
const int numIterations = 10000;
Dictionary<string, object> dataValues = new Dictionary<string, object>();
var dotnetJsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string jsonData = null;
int[] idx = { 0 };
TimeSpan baseline = TestUtils.TimeRun(numIterations, TimeSpan.Zero, ".Net JavaScriptSerializer",
() =>
{
dataValues.Clear();
dataValues.Add("A", idx[0]++);
dataValues.Add("B", idx[0]++);
dataValues.Add("C", idx[0]++);
jsonData = dotnetJsonSerializer.Serialize(dataValues);
});
idx[0] = 0;
TimeSpan elapsed = TestUtils.TimeRun(numIterations, baseline, "Newtonsoft Json JavaScriptSerializer",
() =>
{
dataValues.Clear();
dataValues.Add("A", idx[0]++);
dataValues.Add("B", idx[0]++);
dataValues.Add("C", idx[0]++);
jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(dataValues);
});
this.output.WriteLine("Elapsed: {0} Date: {1}", elapsed, jsonData);
}
[Fact, TestCategory("Functional")]
public void LoadClassByName()
{
string className = typeof(MockStorageProvider).FullName;
Type classType = new CachedTypeResolver().ResolveType(className);
Assert.NotNull(classType); // Type
Assert.True(typeof(IStorageProvider).IsAssignableFrom(classType), $"Is an IStorageProvider : {classType.FullName}");
}
#region Utility functions
private async Task<AzureTableGrainStorage> InitAzureTableGrainStorage(AzureTableStorageOptions options)
{
AzureTableGrainStorage store = ActivatorUtilities.CreateInstance<AzureTableGrainStorage>(this.providerRuntime.ServiceProvider, options, "TestStorage");
SiloLifecycle lifecycle = ActivatorUtilities.CreateInstance<SiloLifecycle>(this.providerRuntime.ServiceProvider);
store.Participate(lifecycle);
await lifecycle.OnStart();
return store;
}
private Task<AzureTableGrainStorage> InitAzureTableGrainStorage(bool useJson = false)
{
var options = new AzureTableStorageOptions
{
ConnectionString = TestDefaultConfiguration.DataConnectionString,
UseJson = useJson
};
return InitAzureTableGrainStorage(options);
}
private async Task Test_PersistenceProvider_Read(string grainTypeName, IGrainStorage store,
GrainState<TestStoreGrainState> grainState = null, GrainId grainId = null)
{
var reference = this.fixture.InternalGrainFactory.GetGrain(grainId ?? GrainId.NewId());
if (grainState == null)
{
grainState = new GrainState<TestStoreGrainState>(new TestStoreGrainState());
}
var storedGrainState = new GrainState<TestStoreGrainState>(new TestStoreGrainState());
Stopwatch sw = new Stopwatch();
sw.Start();
await store.ReadStateAsync(grainTypeName, reference, storedGrainState);
TimeSpan readTime = sw.Elapsed;
this.output.WriteLine("{0} - Read time = {1}", store.GetType().FullName, readTime);
var storedState = storedGrainState.State;
Assert.Equal(grainState.State.A, storedState.A);
Assert.Equal(grainState.State.B, storedState.B);
Assert.Equal(grainState.State.C, storedState.C);
}
private async Task<GrainState<TestStoreGrainState>> Test_PersistenceProvider_WriteRead(string grainTypeName,
IGrainStorage store, GrainState<TestStoreGrainState> grainState = null, GrainId grainId = null)
{
GrainReference reference = this.fixture.InternalGrainFactory.GetGrain(grainId ?? GrainId.NewId());
if (grainState == null)
{
grainState = TestStoreGrainState.NewRandomState();
}
Stopwatch sw = new Stopwatch();
sw.Start();
await store.WriteStateAsync(grainTypeName, reference, grainState);
TimeSpan writeTime = sw.Elapsed;
sw.Restart();
var storedGrainState = new GrainState<TestStoreGrainState>
{
State = new TestStoreGrainState()
};
await store.ReadStateAsync(grainTypeName, reference, storedGrainState);
TimeSpan readTime = sw.Elapsed;
this.output.WriteLine("{0} - Write time = {1} Read time = {2}", store.GetType().FullName, writeTime, readTime);
Assert.Equal(grainState.State.A, storedGrainState.State.A);
Assert.Equal(grainState.State.B, storedGrainState.State.B);
Assert.Equal(grainState.State.C, storedGrainState.State.C);
return storedGrainState;
}
private async Task<GrainState<TestStoreGrainState>> Test_PersistenceProvider_WriteClearRead(string grainTypeName,
IGrainStorage store, GrainState<TestStoreGrainState> grainState = null, GrainId grainId = null)
{
GrainReference reference = this.fixture.InternalGrainFactory.GetGrain(grainId ?? GrainId.NewId());
if (grainState == null)
{
grainState = TestStoreGrainState.NewRandomState();
}
Stopwatch sw = new Stopwatch();
sw.Start();
await store.WriteStateAsync(grainTypeName, reference, grainState);
TimeSpan writeTime = sw.Elapsed;
sw.Restart();
await store.ClearStateAsync(grainTypeName, reference, grainState);
var storedGrainState = new GrainState<TestStoreGrainState>
{
State = new TestStoreGrainState()
};
await store.ReadStateAsync(grainTypeName, reference, storedGrainState);
TimeSpan readTime = sw.Elapsed;
this.output.WriteLine("{0} - Write time = {1} Read time = {2}", store.GetType().FullName, writeTime, readTime);
Assert.NotNull(storedGrainState.State);
Assert.Equal(default(string), storedGrainState.State.A);
Assert.Equal(default(int), storedGrainState.State.B);
Assert.Equal(default(long), storedGrainState.State.C);
return storedGrainState;
}
private static void EnsureEnvironmentSupportsState(GrainState<TestStoreGrainState> grainState)
{
if (grainState.State.A.Length > 400 * 1024)
{
StorageEmulatorUtilities.EnsureEmulatorIsNotUsed();
}
TestUtils.CheckForAzureStorage();
}
#endregion Utility functions
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.XWPF.UserModel
{
using System;
using System.Collections.Generic;
using NPOI.OpenXmlFormats.Wordprocessing;
using System.Text;
using NPOI.Util;
using System.Collections;
using NPOI.WP.UserModel;
/**
* <p>A Paragraph within a Document, Table, Header etc.</p>
*
* <p>A paragraph has a lot of styling information, but the
* actual text (possibly along with more styling) is held on
* the child {@link XWPFRun}s.</p>
*/
public class XWPFParagraph : IBodyElement, IRunBody, ISDTContents, IParagraph
{
private CT_P paragraph;
protected IBody part;
/** For access to the document's hyperlink, comments, tables etc */
protected XWPFDocument document;
protected List<XWPFRun> runs;
protected List<IRunElement> iRuns;
private StringBuilder footnoteText = new StringBuilder();
public XWPFParagraph(CT_P prgrph, IBody part)
{
this.paragraph = prgrph;
this.part = part;
this.document = part.GetXWPFDocument();
if (document == null)
{
throw new NullReferenceException();
}
// Build up the character runs
runs = new List<XWPFRun>();
iRuns = new List<IRunElement>();
BuildRunsInOrderFromXml(paragraph.Items);
// Look for bits associated with the runs
foreach (XWPFRun run in runs)
{
CT_R r = run.GetCTR();
if (document != null)
{
for (int i = 0; i < r.Items.Count; i++)
{
object o = r.Items[i];
if (o is CT_FtnEdnRef)
{
CT_FtnEdnRef ftn = (CT_FtnEdnRef)o;
footnoteText.Append("[").Append(ftn.id).Append(": ");
XWPFFootnote footnote = null;
if (r.ItemsElementName.Count > i && r.ItemsElementName[i] == RunItemsChoiceType.endnoteReference)
{
footnote = document.GetEndnoteByID(int.Parse(ftn.id));
if (footnote == null)
footnote = document.GetFootnoteByID(int.Parse(ftn.id));
}
else
{
footnote = document.GetFootnoteByID(int.Parse(ftn.id));
if (footnote == null)
footnote = document.GetEndnoteByID(int.Parse(ftn.id));
}
if (footnote != null)
{
bool first = true;
foreach (XWPFParagraph p in footnote.Paragraphs)
{
if (!first)
{
footnoteText.Append("\n");
first = false;
}
footnoteText.Append(p.Text);
}
}
footnoteText.Append("]");
}
}
}
}
}
/**
* Identifies (in order) the parts of the paragraph /
* sub-paragraph that correspond to character text
* runs, and builds the appropriate runs for these.
*/
private void BuildRunsInOrderFromXml(ArrayList items)
{
foreach (object o in items)
{
if (o is CT_R)
{
XWPFRun r = new XWPFRun((CT_R)o, this);
runs.Add(r);
iRuns.Add(r);
}
if (o is CT_Hyperlink1)
{
CT_Hyperlink1 link = (CT_Hyperlink1)o;
foreach (CT_R r in link.GetRList())
{
//runs.Add(new XWPFHyperlinkRun(link, r, this));
XWPFHyperlinkRun hr = new XWPFHyperlinkRun(link, r, this);
runs.Add(hr);
iRuns.Add(hr);
}
}
if (o is CT_SdtBlock)
{
XWPFSDT cc = new XWPFSDT((CT_SdtBlock)o, part);
iRuns.Add(cc);
}
if (o is CT_SdtRun)
{
XWPFSDT cc = new XWPFSDT((CT_SdtRun)o, part);
iRuns.Add(cc);
}
if (o is CT_RunTrackChange)
{
foreach (CT_R r in ((CT_RunTrackChange)o).GetRList())
{
XWPFRun cr = new XWPFRun(r, this);
runs.Add(cr);
iRuns.Add(cr);
}
}
if (o is CT_SimpleField)
{
foreach (CT_R r in ((CT_SimpleField)o).GetRList())
{
XWPFRun cr = new XWPFRun(r, this);
runs.Add(cr);
iRuns.Add(cr);
}
}
if (o is CT_SmartTagRun)
{
// Smart Tags can be nested many times.
// This implementation does not preserve the tagging information
BuildRunsInOrderFromXml((o as CT_SmartTagRun).Items);
}
}
}
internal CT_P GetCTP()
{
return paragraph;
}
public IList<XWPFRun> Runs
{
get
{
return runs.AsReadOnly();
}
}
/**
* Return literal runs and sdt/content control objects.
* @return List<IRunElement>
*/
public List<IRunElement> IRuns
{
get
{
return iRuns;
}
}
public bool IsEmpty
{
get
{
//!paragraph.getDomNode().hasChildNodes();
//inner xml include objects holded by Items and pPr object
//should use children of pPr node, but we didn't keep reference to it.
//return paragraph.Items.Count == 0 && (paragraph.pPr == null ||
// paragraph.pPr != null && paragraph.pPr.rPr == null && paragraph.pPr.sectPr == null && paragraph.pPr.pPrChange == null
// );
return paragraph.Items.Count == 0 && (paragraph.pPr == null || paragraph.pPr.IsEmpty);
}
}
public XWPFDocument Document
{
get
{
return document;
}
}
/**
* Return the textual content of the paragraph, including text from pictures
* and std element in it.
*/
public String Text
{
get
{
StringBuilder out1 = new StringBuilder();
foreach (IRunElement run in iRuns)
{
if (run is XWPFSDT)
{
out1.Append(((XWPFSDT)run).Content.Text);
}
else
{
out1.Append(run.ToString());
}
}
out1.Append(footnoteText);
return out1.ToString();
}
}
/**
* Return styleID of the paragraph if style exist for this paragraph
* if not, null will be returned
* @return styleID as String
*/
public String StyleID
{
get
{
if (paragraph.pPr != null)
{
if (paragraph.pPr.pStyle != null)
{
if (paragraph.pPr.pStyle.val != null)
return paragraph.pPr.pStyle.val;
}
}
return null;
}
}
/**
* If style exist for this paragraph
* NumId of the paragraph will be returned.
* If style not exist null will be returned
* @return NumID as Bigint
*/
public string GetNumID()
{
if (paragraph.pPr != null)
{
if (paragraph.pPr.numPr != null)
{
if (paragraph.pPr.numPr.numId != null)
return paragraph.pPr.numPr.numId.val;
}
}
return null;
}
/**
* Returns Ilvl of the numeric style for this paragraph.
* Returns null if this paragraph does not have numeric style.
* @return Ilvl as BigInteger
*/
public string GetNumIlvl()
{
if (paragraph.pPr != null)
{
if (paragraph.pPr.numPr != null)
{
if (paragraph.pPr.numPr.ilvl != null)
return paragraph.pPr.numPr.ilvl.val;
}
}
return null;
}
/**
* Returns numbering format for this paragraph, eg bullet or
* lowerLetter.
* Returns null if this paragraph does not have numeric style.
*/
public String GetNumFmt()
{
string numID = GetNumID();
XWPFNumbering numbering = document.GetNumbering();
if (numID != null && numbering != null)
{
XWPFNum num = numbering.GetNum(numID);
if (num != null)
{
string ilvl = GetNumIlvl();
string abstractNumId = num.GetCTNum().abstractNumId.val;
CT_AbstractNum anum = numbering.GetAbstractNum(abstractNumId).GetAbstractNum();
CT_Lvl level = null;
for (int i = 0; i < anum.lvl.Count; i++)
{
CT_Lvl lvl = anum.lvl[i];
if (lvl.ilvl.Equals(ilvl))
{
level = lvl;
break;
}
}
if (level != null && level.numFmt != null)
return level.numFmt.val.ToString();
}
}
return null;
}
/**
* Returns the text that should be used around the paragraph level numbers.
*
* @return a string (e.g. "%1.") or null if the value is not found.
*/
public String NumLevelText
{
get
{
string numID = GetNumID();
XWPFNumbering numbering = document.CreateNumbering();
if (numID != null && numbering != null)
{
XWPFNum num = numbering.GetNum(numID);
if (num != null)
{
string ilvl = GetNumIlvl();
CT_Num ctNum = num.GetCTNum();
if (ctNum == null)
return null;
CT_DecimalNumber ctDecimalNumber = ctNum.abstractNumId;
if (ctDecimalNumber == null)
return null;
string abstractNumId = ctDecimalNumber.val;
if (abstractNumId == null)
return null;
XWPFAbstractNum xwpfAbstractNum = numbering.GetAbstractNum(abstractNumId);
if (xwpfAbstractNum == null)
return null;
CT_AbstractNum anum = xwpfAbstractNum.GetCTAbstractNum();
if (anum == null)
return null;
CT_Lvl level = null;
for (int i = 0; i < anum.SizeOfLvlArray(); i++)
{
CT_Lvl lvl = anum.GetLvlArray(i);
if (lvl != null && lvl.ilvl != null && lvl.ilvl.Equals(ilvl))
{
level = lvl;
break;
}
}
if (level != null && level.lvlText != null
&& level.lvlText.val != null)
return level.lvlText.val.ToString();
}
}
return null;
}
}
/**
* Gets the numstartOverride for the paragraph numbering for this paragraph.
* @return returns the overridden start number or null if there is no override for this paragraph.
*/
public string GetNumStartOverride()
{
string numID = GetNumID();
XWPFNumbering numbering = document.CreateNumbering();
if (numID != null && numbering != null)
{
XWPFNum num = numbering.GetNum(numID);
if (num != null)
{
CT_Num ctNum = num.GetCTNum();
if (ctNum == null)
{
return null;
}
string ilvl = GetNumIlvl();
CT_NumLvl level = null;
for (int i = 0; i < ctNum.SizeOfLvlOverrideArray(); i++)
{
CT_NumLvl ctNumLvl = ctNum.GetLvlOverrideArray(i);
if (ctNumLvl != null && ctNumLvl.ilvl != null &&
ctNumLvl.ilvl.Equals(ilvl))
{
level = ctNumLvl;
break;
}
}
if (level != null && level.startOverride != null)
{
return level.startOverride.val;
}
}
}
return null;
}
/**
* SetNumID of Paragraph
* @param numPos
*/
public void SetNumID(string numId)
{
if (paragraph.pPr == null)
paragraph.AddNewPPr();
if (paragraph.pPr.numPr == null)
paragraph.pPr.AddNewNumPr();
if (paragraph.pPr.numPr.numId == null)
{
paragraph.pPr.numPr.AddNewNumId();
}
paragraph.pPr.numPr.ilvl = new CT_DecimalNumber();
paragraph.pPr.numPr.ilvl.val = "0";
paragraph.pPr.numPr.numId.val = numId;
}
/// <summary>
/// Set NumID and level of Paragraph
/// </summary>
/// <param name="numId"></param>
/// <param name="ilvl"></param>
public void SetNumID(string numId, string ilvl)
{
if (paragraph.pPr == null)
paragraph.AddNewPPr();
if (paragraph.pPr.numPr == null)
paragraph.pPr.AddNewNumPr();
if (paragraph.pPr.numPr.numId == null)
{
paragraph.pPr.numPr.AddNewNumId();
}
paragraph.pPr.numPr.ilvl = new CT_DecimalNumber();
paragraph.pPr.numPr.ilvl.val = ilvl;
paragraph.pPr.numPr.numId.val = (numId);
}
/**
* Returns the text of the paragraph, but not of any objects in the
* paragraph
*/
public String ParagraphText
{
get
{
StringBuilder text = new StringBuilder();
foreach (XWPFRun run in runs)
{
text.Append(run.ToString());
}
return text.ToString();
}
}
/**
* Returns any text from any suitable pictures in the paragraph
*/
public String PictureText
{
get
{
StringBuilder text = new StringBuilder();
foreach (XWPFRun run in runs)
{
text.Append(run.PictureText);
}
return text.ToString();
}
}
/**
* Returns the footnote text of the paragraph
*
* @return the footnote text or empty string if the paragraph does not have footnotes
*/
public String FootnoteText
{
get
{
return footnoteText.ToString();
}
}
/**
* Returns the paragraph alignment which shall be applied to text in this
* paragraph.
* <p>
* If this element is not Set on a given paragraph, its value is determined
* by the Setting previously Set at any level of the style hierarchy (i.e.
* that previous Setting remains unChanged). If this Setting is never
* specified in the style hierarchy, then no alignment is applied to the
* paragraph.
* </p>
*
* @return the paragraph alignment of this paragraph.
*/
public ParagraphAlignment Alignment
{
get
{
CT_PPr pr = GetCTPPr();
return pr == null || !pr.IsSetJc() ? ParagraphAlignment.LEFT : EnumConverter.ValueOf<ParagraphAlignment, ST_Jc>(pr.jc.val);
}
set
{
CT_PPr pr = GetCTPPr();
CT_Jc jc = pr.IsSetJc() ? pr.jc : pr.AddNewJc();
jc.val = EnumConverter.ValueOf<ST_Jc, ParagraphAlignment>(value);
}
}
/**
* @return The raw alignment value, {@link #getAlignment()} is suggested
*/
public int FontAlignment
{
get
{
return (int)Alignment;
}
set
{
Alignment = (ParagraphAlignment)value;
}
}
/**
* Returns the text vertical alignment which shall be applied to text in
* this paragraph.
* <p>
* If the line height (before any Added spacing) is larger than one or more
* characters on the line, all characters will be aligned to each other as
* specified by this element.
* </p>
* <p>
* If this element is omitted on a given paragraph, its value is determined
* by the Setting previously Set at any level of the style hierarchy (i.e.
* that previous Setting remains unChanged). If this Setting is never
* specified in the style hierarchy, then the vertical alignment of all
* characters on the line shall be automatically determined by the consumer.
* </p>
*
* @return the vertical alignment of this paragraph.
*/
public TextAlignment VerticalAlignment
{
get
{
CT_PPr pr = GetCTPPr();
return (pr == null || !pr.IsSetTextAlignment()) ? TextAlignment.AUTO
: EnumConverter.ValueOf<TextAlignment, ST_TextAlignment>(pr.textAlignment.val);
}
set
{
CT_PPr pr = GetCTPPr();
CT_TextAlignment textAlignment = pr.IsSetTextAlignment() ? pr
.textAlignment : pr.AddNewTextAlignment();
//STTextAlignment.Enum en = STTextAlignment.Enum
// .forInt(valign.Value);
textAlignment.val = EnumConverter.ValueOf<ST_TextAlignment, TextAlignment>(value);
}
}
/// <summary>
/// the top border for the paragraph
/// </summary>
public Borders BorderTop
{
get
{
CT_PBdr border = GetCTPBrd(false);
CT_Border ct = null;
if (border != null)
{
ct = border.top;
}
ST_Border ptrn = (ct != null) ? ct.val : ST_Border.none;
return EnumConverter.ValueOf<Borders, ST_Border>(ptrn);
}
set
{
CT_PBdr ct = GetCTPBrd(true);
if (ct == null)
{
throw new RuntimeException("invalid paragraph state");
}
CT_Border pr = ct.IsSetTop() ? ct.top : ct.AddNewTop();
if (value == Borders.None)
ct.UnsetTop();
else
pr.val = EnumConverter.ValueOf<ST_Border, Borders>(value);
}
}
/// <summary>
///Specifies the border which shall be displayed below a Set of
/// paragraphs which have the same Set of paragraph border Settings.
/// </summary>
/// <returns>the bottom border for the paragraph</returns>
public Borders BorderBottom
{
get
{
CT_PBdr border = GetCTPBrd(false);
CT_Border ct = null;
if (border != null)
{
ct = border.bottom;
}
ST_Border ptrn = ct != null ? ct.val : ST_Border.none;
return EnumConverter.ValueOf<Borders, ST_Border>(ptrn);
}
set
{
CT_PBdr ct = GetCTPBrd(true);
CT_Border pr = ct.IsSetBottom() ? ct.bottom : ct.AddNewBottom();
if (value == Borders.None)
ct.UnsetBottom();
else
pr.val = EnumConverter.ValueOf<ST_Border, Borders>(value);
}
}
/// <summary>
/// Specifies the border which shall be displayed on the left side of the
/// page around the specified paragraph.
/// </summary>
/// <returns>the left border for the paragraph</returns>
public Borders BorderLeft
{
get
{
CT_PBdr border = GetCTPBrd(false);
CT_Border ct = null;
if (border != null)
{
ct = border.left;
}
ST_Border ptrn = ct != null ? ct.val : ST_Border.none;
return EnumConverter.ValueOf<Borders, ST_Border>(ptrn);
}
set
{
CT_PBdr ct = GetCTPBrd(true);
CT_Border pr = ct.IsSetLeft() ? ct.left : ct.AddNewLeft();
if (value == Borders.None)
ct.UnsetLeft();
else
pr.val = EnumConverter.ValueOf<ST_Border, Borders>(value);
}
}
/**
* Specifies the border which shall be displayed on the right side of the
* page around the specified paragraph.
*
* @return ParagraphBorder - the right border for the paragraph
* @see #setBorderRight(Borders)
* @see Borders for a list of all possible borders
*/
public Borders BorderRight
{
get
{
CT_PBdr border = GetCTPBrd(false);
CT_Border ct = null;
if (border != null)
{
ct = border.right;
}
ST_Border ptrn = ct != null ? ct.val : ST_Border.none;
return EnumConverter.ValueOf<Borders, ST_Border>(ptrn);
}
set
{
CT_PBdr ct = GetCTPBrd(true);
CT_Border pr = ct.IsSetRight() ? ct.right : ct.AddNewRight();
if (value == Borders.None)
ct.UnsetRight();
else
pr.val = EnumConverter.ValueOf<ST_Border, Borders>(value);
}
}
public ST_Shd FillPattern
{
get
{
if (!this.GetCTPPr().IsSetShd())
return ST_Shd.nil;
return this.GetCTPPr().shd.val;
}
set
{
CT_Shd ctShd = null;
if (!this.GetCTPPr().IsSetShd())
{
ctShd = this.GetCTPPr().AddNewShd();
}
else
{
ctShd = this.GetCTPPr().shd;
}
ctShd.val = value;
}
}
public string FillBackgroundColor
{
get
{
if (!this.GetCTPPr().IsSetShd())
return null;
return this.GetCTPPr().shd.fill;
}
set
{
CT_Shd ctShd = null;
if (!this.GetCTPPr().IsSetShd())
{
ctShd = this.GetCTPPr().AddNewShd();
}
else
{
ctShd = this.GetCTPPr().shd;
}
ctShd.color = "auto";
ctShd.fill = value;
}
}
/**
* Specifies the border which shall be displayed between each paragraph in a
* Set of paragraphs which have the same Set of paragraph border Settings.
*
* @return ParagraphBorder - the between border for the paragraph
* @see #setBorderBetween(Borders)
* @see Borders for a list of all possible borders
*/
public Borders BorderBetween
{
get
{
CT_PBdr border = GetCTPBrd(false);
CT_Border ct = null;
if (border != null)
{
ct = border.between;
}
ST_Border ptrn = ct != null ? ct.val : ST_Border.none;
return EnumConverter.ValueOf<Borders, ST_Border>(ptrn);
}
set
{
CT_PBdr ct = GetCTPBrd(true);
CT_Border pr = ct.IsSetBetween() ? ct.between : ct.AddNewBetween();
if (value == Borders.None)
ct.UnsetBetween();
else
pr.val = EnumConverter.ValueOf<ST_Border, Borders>(value);
}
}
/**
* Specifies that when rendering this document in a paginated
* view, the contents of this paragraph are rendered on the start of a new
* page in the document.
* <p>
* If this element is omitted on a given paragraph,
* its value is determined by the Setting previously Set at any level of the
* style hierarchy (i.e. that previous Setting remains unChanged). If this
* Setting is never specified in the style hierarchy, then this property
* shall not be applied. Since the paragraph is specified to start on a new
* page, it begins page two even though it could have fit on page one.
* </p>
*
* @return bool - if page break is Set
*/
public bool IsPageBreak
{
get
{
CT_PPr ppr = GetCTPPr();
CT_OnOff ct_pageBreak = ppr.IsSetPageBreakBefore() ? ppr
.pageBreakBefore : null;
if (ct_pageBreak != null
&& ct_pageBreak.val)
{
return true;
}
return false;
}
set
{
CT_PPr ppr = GetCTPPr();
CT_OnOff ct_pageBreak = ppr.IsSetPageBreakBefore() ? ppr
.pageBreakBefore : ppr.AddNewPageBreakBefore();
ct_pageBreak.val = value;
}
}
/**
* Specifies the spacing that should be Added After the last line in this
* paragraph in the document in absolute units.
*
* @return int - value representing the spacing After the paragraph
*/
public int SpacingAfter
{
get
{
CT_Spacing spacing = GetCTSpacing(false);
return (spacing != null && spacing.IsSetAfter()) ? (int)spacing.after : -1;
}
set
{
CT_Spacing spacing = GetCTSpacing(true);
if (spacing != null)
{
//BigInteger bi = new BigInteger(spaces);
spacing.after = (ulong)value;
}
}
}
/**
* Specifies the spacing that should be Added After the last line in this
* paragraph in the document in absolute units.
*
* @return bigint - value representing the spacing After the paragraph
* @see #setSpacingAfterLines(int)
*/
public int SpacingAfterLines
{
get
{
CT_Spacing spacing = GetCTSpacing(false);
return (spacing != null && spacing.IsSetAfterLines()) ? int.Parse(spacing.afterLines) : -1;
}
set
{
CT_Spacing spacing = GetCTSpacing(true);
//BigInteger bi = new BigInteger("" + spaces);
spacing.afterLines = value.ToString();
}
}
/**
* Specifies the spacing that should be Added above the first line in this
* paragraph in the document in absolute units.
*
* @return the spacing that should be Added above the first line
* @see #setSpacingBefore(int)
*/
public int SpacingBefore
{
get
{
CT_Spacing spacing = GetCTSpacing(false);
return (spacing != null && spacing.IsSetBefore()) ? (int)spacing.before : -1;
}
set
{
CT_Spacing spacing = GetCTSpacing(true);
//BigInteger bi = new BigInteger("" + spaces);
spacing.before = (ulong)value;
}
}
/**
* Specifies the spacing that should be Added before the first line in this paragraph in the
* document in line units.
* The value of this attribute is specified in one hundredths of a line.
*
* @return the spacing that should be Added before the first line in this paragraph
* @see #setSpacingBeforeLines(int)
*/
public int SpacingBeforeLines
{
get
{
CT_Spacing spacing = GetCTSpacing(false);
return (spacing != null && spacing.IsSetBeforeLines()) ? int.Parse(spacing.beforeLines) : -1;
}
set
{
CT_Spacing spacing = GetCTSpacing(true);
//BigInteger bi = new BigInteger("" + spaces);
spacing.beforeLines = value.ToString();
}
}
/// <summary>
///Specifies how the spacing between lines is calculated as stored in the
/// line attribute. If this attribute is omitted, then it shall be assumed to
/// be of a value auto if a line attribute value is present.
/// </summary>
public LineSpacingRule SpacingLineRule
{
get
{
CT_Spacing spacing = GetCTSpacing(false);
return (spacing != null && spacing.IsSetLineRule()) ?
EnumConverter.ValueOf<LineSpacingRule, ST_LineSpacingRule>(spacing.lineRule) : LineSpacingRule.AUTO;
}
set
{
CT_Spacing spacing = GetCTSpacing(true);
spacing.lineRule = EnumConverter.ValueOf<ST_LineSpacingRule, LineSpacingRule>(value);
}
}
/**
* Specifies the indentation which shall be placed between the left text
* margin for this paragraph and the left edge of that paragraph's content
* in a left to right paragraph, and the right text margin and the right
* edge of that paragraph's text in a right to left paragraph
* <p>
* If this attribute is omitted, its value shall be assumed to be zero.
* Negative values are defined such that the text is Moved past the text margin,
* positive values Move the text inside the text margin.
* </p>
*
* @return indentation or null if indentation is not Set
*/
public int IndentationLeft
{
get
{
CT_Ind indentation = GetCTInd(false);
return (indentation != null && indentation.IsSetLeft()) ? int.Parse(indentation.left)
: -1;
}
set
{
CT_Ind indent = GetCTInd(true);
//BigInteger bi = new BigInteger("" + indentation);
indent.left = value.ToString();
}
}
/**
* Specifies the indentation which shall be placed between the right text
* margin for this paragraph and the right edge of that paragraph's content
* in a left to right paragraph, and the right text margin and the right
* edge of that paragraph's text in a right to left paragraph
* <p>
* If this attribute is omitted, its value shall be assumed to be zero.
* Negative values are defined such that the text is Moved past the text margin,
* positive values Move the text inside the text margin.
* </p>
*
* @return indentation or null if indentation is not Set
*/
public int IndentationRight
{
get
{
CT_Ind indentation = GetCTInd(false);
return (indentation != null && indentation.IsSetRight()) ? int.Parse(indentation.right)
: -1;
}
set
{
CT_Ind indent = GetCTInd(true);
//BigInteger bi = new BigInteger("" + indentation);
indent.right = value.ToString();
}
}
/**
* Specifies the indentation which shall be Removed from the first line of
* the parent paragraph, by moving the indentation on the first line back
* towards the beginning of the direction of text flow.
* This indentation is
* specified relative to the paragraph indentation which is specified for
* all other lines in the parent paragraph.
* The firstLine and hanging
* attributes are mutually exclusive, if both are specified, then the
* firstLine value is ignored.
*
* @return indentation or null if indentation is not Set
*/
public int IndentationHanging
{
get
{
CT_Ind indentation = GetCTInd(false);
return (indentation != null && indentation.IsSetHanging()) ? (int)indentation.hanging : -1;
}
set
{
CT_Ind indent = GetCTInd(true);
//BigInteger bi = new BigInteger("" + indentation);
indent.hanging = (ulong)value;
}
}
/**
* Specifies the Additional indentation which shall be applied to the first
* line of the parent paragraph. This Additional indentation is specified
* relative to the paragraph indentation which is specified for all other
* lines in the parent paragraph.
* The firstLine and hanging attributes are
* mutually exclusive, if both are specified, then the firstLine value is
* ignored.
* If the firstLineChars attribute is also specified, then this
* value is ignored.
* If this attribute is omitted, then its value shall be
* assumed to be zero (if needed).
*
* @return indentation or null if indentation is not Set
*/
public int IndentationFirstLine
{
get
{
CT_Ind indentation = GetCTInd(false);
return (indentation != null && indentation.IsSetFirstLine()) ? (int)indentation.firstLine
: -1;
}
set
{
CT_Ind indent = GetCTInd(true);
//BigInteger bi = new BigInteger("" + indentation);
indent.firstLine = (long)value;
}
}
public int IndentFromLeft
{
get
{
return IndentationLeft;
}
set
{
IndentationLeft = value;
}
}
public int IndentFromRight
{
get
{
return IndentationRight;
}
set
{
IndentationRight = value;
}
}
public int FirstLineIndent
{
get
{
return IndentationFirstLine;
}
set
{
IndentationFirstLine = (value);
}
}
/**
* This element specifies whether a consumer shall break Latin text which
* exceeds the text extents of a line by breaking the word across two lines
* (breaking on the character level) or by moving the word to the following
* line (breaking on the word level).
*
* @return bool
*/
public bool IsWordWrapped
{
get
{
CT_OnOff wordWrap = GetCTPPr().IsSetWordWrap() ? GetCTPPr()
.wordWrap : null;
if (wordWrap != null)
{
return wordWrap.val;
}
return false;
}
set
{
CT_OnOff wordWrap = GetCTPPr().IsSetWordWrap() ? GetCTPPr()
.wordWrap : GetCTPPr().AddNewWordWrap();
if (value)
wordWrap.val = true;
else
wordWrap.UnSetVal();
}
}
[Obsolete]
public bool IsWordWrap
{
get { return IsWordWrapped; }
set { IsWordWrapped = value; }
}
/**
* @return the style of the paragraph
*/
public String Style
{
get
{
CT_PPr pr = GetCTPPr();
CT_String style = pr.IsSetPStyle() ? pr.pStyle : null;
return style != null ? style.val : null;
}
set
{
CT_PPr pr = GetCTPPr();
CT_String style = pr.pStyle != null ? pr.pStyle : pr.AddNewPStyle();
style.val = value;
}
}
/**
* Get a <b>copy</b> of the currently used CTPBrd, if none is used, return
* a new instance.
*/
private CT_PBdr GetCTPBrd(bool create)
{
CT_PPr pr = GetCTPPr();
CT_PBdr ct = pr.IsSetPBdr() ? pr.pBdr : null;
if (create && ct == null)
ct = pr.AddNewPBdr();
return ct;
}
/**
* Get a <b>copy</b> of the currently used CTSpacing, if none is used,
* return a new instance.
*/
private CT_Spacing GetCTSpacing(bool create)
{
CT_PPr pr = GetCTPPr();
CT_Spacing ct = pr.spacing == null ? null : pr.spacing;
if (create && ct == null)
ct = pr.AddNewSpacing();
return ct;
}
/**
* Get a <b>copy</b> of the currently used CTPInd, if none is used, return
* a new instance.
*/
private CT_Ind GetCTInd(bool create)
{
CT_PPr pr = GetCTPPr();
CT_Ind ct = pr.ind == null ? null : pr.ind;
if (create && ct == null)
ct = pr.AddNewInd();
return ct;
}
/**
* Get a <b>copy</b> of the currently used CTPPr, if none is used, return
* a new instance.
*/
internal CT_PPr GetCTPPr()
{
CT_PPr pr = paragraph.pPr == null ? paragraph.AddNewPPr()
: paragraph.pPr;
return pr;
}
/**
* add a new run at the end of the position of
* the content of parameter run
* @param run
*/
protected internal void AddRun(CT_R run)
{
int pos= paragraph.GetRList().Count;
paragraph.AddNewR();
paragraph.SetRArray(pos, run);
}
/// <summary>
/// Replace text inside each run (cross run is not supported yet)
/// </summary>
/// <param name="oldText">target text</param>
/// <param name="newText">replacement text</param>
public void ReplaceText(string oldText, string newText)
{
TextSegment ts= this.SearchText(oldText, new PositionInParagraph() { Run = 0 });
if (ts.BeginRun == ts.EndRun)
{
this.runs[ts.BeginRun].ReplaceText(oldText, newText);
}
else
{
this.runs[ts.BeginRun].ReplaceText(this.runs[ts.BeginRun].Text.Substring(ts.BeginChar), newText);
this.runs[ts.EndRun].ReplaceText(this.runs[ts.EndRun].Text.Substring(0, ts.EndChar + 1), "");
for (int i = ts.EndRun-1; i > ts.BeginRun; i--)
{
RemoveRun(i);
}
}
}
/// <summary>
/// this methods parse the paragraph and search for the string searched.
/// If it finds the string, it will return true and the position of the String will be saved in the parameter startPos.
/// </summary>
/// <param name="searched"></param>
/// <param name="startPos"></param>
/// <returns></returns>
public TextSegment SearchText(String searched, PositionInParagraph startPos)
{
int startRun = startPos.Run,
startText = startPos.Text,
startChar = startPos.Char;
int beginRunPos = 0, candCharPos = 0;
bool newList = false;
for (int runPos = startRun; runPos < paragraph.GetRList().Count; runPos++)
{
int beginTextPos = 0, beginCharPos = 0, textPos = 0, charPos = 0;
CT_R ctRun = paragraph.GetRList()[runPos];
foreach (object o in ctRun.Items)
{
if (o is CT_Text)
{
if (textPos >= startText)
{
String candidate = ((CT_Text)o).Value;
if (runPos == startRun)
charPos = startChar;
else
charPos = 0;
for (; charPos < candidate.Length; charPos++)
{
if ((candidate[charPos] == searched[0]) && (candCharPos == 0))
{
beginTextPos = textPos;
beginCharPos = charPos;
beginRunPos = runPos;
newList = true;
}
if (candidate[charPos] == searched[candCharPos])
{
if (candCharPos + 1 < searched.Length)
{
candCharPos++;
}
else if (newList)
{
TextSegment segement = new TextSegment();
segement.BeginRun = (beginRunPos);
segement.BeginText = (beginTextPos);
segement.BeginChar = (beginCharPos);
segement.EndRun = (runPos);
segement.EndText = (textPos);
segement.EndChar = (charPos);
return segement;
}
}
else
candCharPos = 0;
}
}
textPos++;
}
else if (o is CT_ProofErr)
{
//c.RemoveXml();
}
else if (o is CT_RPr)
{
//do nothing
}
else
candCharPos = 0;
}
}
return null;
}
/**
* Appends a new run to this paragraph
*
* @return a new text run
*/
public XWPFRun CreateRun()
{
XWPFRun xwpfRun = new XWPFRun(paragraph.AddNewR(), this);
runs.Add(xwpfRun);
iRuns.Add(xwpfRun);
return xwpfRun;
}
/**
* Appends a new hyperlink run to this paragraph
*
* @return a new hyperlink run
*/
public XWPFHyperlinkRun CreateHyperlinkRun(string rId)
{
CT_R r = new CT_R();
r.AddNewRPr().rStyle = new CT_String() { val = "Hyperlink" };
CT_Hyperlink1 hl = paragraph.AddNewHyperlink();
hl.history = ST_OnOff.on;
hl.id = rId;
hl.Items.Add(r);
XWPFHyperlinkRun xwpfRun = new XWPFHyperlinkRun(hl, r, this);
runs.Add(xwpfRun);
iRuns.Add(xwpfRun);
return xwpfRun;
}
/**
* insert a new Run in RunArray
* @param pos
* @return the inserted run
*/
public XWPFRun InsertNewRun(int pos)
{
if (pos >= 0 && pos <= paragraph.SizeOfRArray())
{
CT_R ctRun = paragraph.InsertNewR(pos);
XWPFRun newRun = new XWPFRun(ctRun, this);
// To update the iRuns, find where we're going
// in the normal Runs, and go in there
int iPos = iRuns.Count;
if (pos < runs.Count)
{
XWPFRun oldAtPos = runs[(pos)];
int oldAt = iRuns.IndexOf(oldAtPos);
if (oldAt != -1)
{
iPos = oldAt;
}
}
iRuns.Insert(iPos, newRun);
// Runs itself is easy to update
runs.Insert(pos, newRun);
return newRun;
}
return null;
}
/**
* Get a Text
* @param segment
*/
public String GetText(TextSegment segment)
{
int RunBegin = segment.BeginRun;
int textBegin = segment.BeginText;
int charBegin = segment.BeginChar;
int RunEnd = segment.EndRun;
int textEnd = segment.EndText;
int charEnd = segment.EndChar;
StringBuilder text = new StringBuilder();
for (int i = RunBegin; i <= RunEnd; i++)
{
int startText = 0, endText = paragraph.GetRList()[i].GetTList().Count - 1;
if (i == RunBegin)
startText = textBegin;
if (i == RunEnd)
endText = textEnd;
for (int j = startText; j <= endText; j++)
{
String tmpText = paragraph.GetRList()[i].GetTArray(j).Value;
int startChar = 0, endChar = tmpText.Length - 1;
if ((j == textBegin) && (i == RunBegin))
startChar = charBegin;
if ((j == textEnd) && (i == RunEnd))
{
endChar = charEnd;
}
text.Append(tmpText.Substring(startChar, endChar - startChar + 1));
}
}
return text.ToString();
}
/**
* Removes a Run at the position pos in the paragraph
* @param pos
* @return true if the run was Removed
*/
public bool RemoveRun(int pos)
{
if (pos >= 0 && pos < paragraph.SizeOfRArray())
{
// Remove the run from our high level lists
XWPFRun run = runs[(pos)];
runs.RemoveAt(pos);
iRuns.Remove(run);
// Remove the run from the low-level XML
GetCTP().RemoveR(pos);
return true;
}
return false;
}
/**
* returns the type of the BodyElement Paragraph
* @see NPOI.XWPF.UserModel.IBodyElement#getElementType()
*/
public BodyElementType ElementType
{
get
{
return BodyElementType.PARAGRAPH;
}
}
public IBody Body
{
get
{
return part;
}
}
/**
* returns the part of the bodyElement
* @see NPOI.XWPF.UserModel.IBody#getPart()
*/
public POIXMLDocumentPart Part
{
get
{
if (part != null)
{
return part.Part;
}
return null;
}
}
/**
* returns the partType of the bodyPart which owns the bodyElement
*
* @see NPOI.XWPF.UserModel.IBody#getPartType()
*/
public BodyType PartType
{
get
{
return part.PartType;
}
}
/**
* Adds a new Run to the Paragraph
*
* @param r
*/
public void AddRun(XWPFRun r)
{
if (!runs.Contains(r))
{
runs.Add(r);
}
}
/**
* return the XWPFRun-Element which owns the CTR Run-Element
*
* @param r
*/
public XWPFRun GetRun(CT_R r)
{
for (int i = 0; i < runs.Count; i++)
{
if (runs[i].GetCTR() == r)
{
return runs[i];
}
}
return null;
}
}//end class
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// 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 Google Inc. 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.
#endregion
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Provides access to all native methods provided by <c>NativeExtension</c>.
/// An extra level of indirection is added to P/Invoke calls to allow intelligent loading
/// of the right configuration of the native extension based on current platform, architecture etc.
/// </summary>
internal class NativeMethods
{
#region Native methods
public readonly Delegates.grpcsharp_init_delegate grpcsharp_init;
public readonly Delegates.grpcsharp_shutdown_delegate grpcsharp_shutdown;
public readonly Delegates.grpcsharp_version_string_delegate grpcsharp_version_string;
public readonly Delegates.grpcsharp_batch_context_create_delegate grpcsharp_batch_context_create;
public readonly Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate grpcsharp_batch_context_recv_initial_metadata;
public readonly Delegates.grpcsharp_batch_context_recv_message_length_delegate grpcsharp_batch_context_recv_message_length;
public readonly Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate grpcsharp_batch_context_recv_message_to_buffer;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate grpcsharp_batch_context_recv_status_on_client_status;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate grpcsharp_batch_context_recv_status_on_client_details;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate grpcsharp_batch_context_recv_status_on_client_trailing_metadata;
public readonly Delegates.grpcsharp_batch_context_server_rpc_new_call_delegate grpcsharp_batch_context_server_rpc_new_call;
public readonly Delegates.grpcsharp_batch_context_server_rpc_new_method_delegate grpcsharp_batch_context_server_rpc_new_method;
public readonly Delegates.grpcsharp_batch_context_server_rpc_new_host_delegate grpcsharp_batch_context_server_rpc_new_host;
public readonly Delegates.grpcsharp_batch_context_server_rpc_new_deadline_delegate grpcsharp_batch_context_server_rpc_new_deadline;
public readonly Delegates.grpcsharp_batch_context_server_rpc_new_request_metadata_delegate grpcsharp_batch_context_server_rpc_new_request_metadata;
public readonly Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate grpcsharp_batch_context_recv_close_on_server_cancelled;
public readonly Delegates.grpcsharp_batch_context_destroy_delegate grpcsharp_batch_context_destroy;
public readonly Delegates.grpcsharp_composite_call_credentials_create_delegate grpcsharp_composite_call_credentials_create;
public readonly Delegates.grpcsharp_call_credentials_release_delegate grpcsharp_call_credentials_release;
public readonly Delegates.grpcsharp_call_cancel_delegate grpcsharp_call_cancel;
public readonly Delegates.grpcsharp_call_cancel_with_status_delegate grpcsharp_call_cancel_with_status;
public readonly Delegates.grpcsharp_call_start_unary_delegate grpcsharp_call_start_unary;
public readonly Delegates.grpcsharp_call_start_client_streaming_delegate grpcsharp_call_start_client_streaming;
public readonly Delegates.grpcsharp_call_start_server_streaming_delegate grpcsharp_call_start_server_streaming;
public readonly Delegates.grpcsharp_call_start_duplex_streaming_delegate grpcsharp_call_start_duplex_streaming;
public readonly Delegates.grpcsharp_call_send_message_delegate grpcsharp_call_send_message;
public readonly Delegates.grpcsharp_call_send_close_from_client_delegate grpcsharp_call_send_close_from_client;
public readonly Delegates.grpcsharp_call_send_status_from_server_delegate grpcsharp_call_send_status_from_server;
public readonly Delegates.grpcsharp_call_recv_message_delegate grpcsharp_call_recv_message;
public readonly Delegates.grpcsharp_call_recv_initial_metadata_delegate grpcsharp_call_recv_initial_metadata;
public readonly Delegates.grpcsharp_call_start_serverside_delegate grpcsharp_call_start_serverside;
public readonly Delegates.grpcsharp_call_send_initial_metadata_delegate grpcsharp_call_send_initial_metadata;
public readonly Delegates.grpcsharp_call_set_credentials_delegate grpcsharp_call_set_credentials;
public readonly Delegates.grpcsharp_call_get_peer_delegate grpcsharp_call_get_peer;
public readonly Delegates.grpcsharp_call_destroy_delegate grpcsharp_call_destroy;
public readonly Delegates.grpcsharp_channel_args_create_delegate grpcsharp_channel_args_create;
public readonly Delegates.grpcsharp_channel_args_set_string_delegate grpcsharp_channel_args_set_string;
public readonly Delegates.grpcsharp_channel_args_set_integer_delegate grpcsharp_channel_args_set_integer;
public readonly Delegates.grpcsharp_channel_args_destroy_delegate grpcsharp_channel_args_destroy;
public readonly Delegates.grpcsharp_override_default_ssl_roots grpcsharp_override_default_ssl_roots;
public readonly Delegates.grpcsharp_ssl_credentials_create_delegate grpcsharp_ssl_credentials_create;
public readonly Delegates.grpcsharp_composite_channel_credentials_create_delegate grpcsharp_composite_channel_credentials_create;
public readonly Delegates.grpcsharp_channel_credentials_release_delegate grpcsharp_channel_credentials_release;
public readonly Delegates.grpcsharp_insecure_channel_create_delegate grpcsharp_insecure_channel_create;
public readonly Delegates.grpcsharp_secure_channel_create_delegate grpcsharp_secure_channel_create;
public readonly Delegates.grpcsharp_channel_create_call_delegate grpcsharp_channel_create_call;
public readonly Delegates.grpcsharp_channel_check_connectivity_state_delegate grpcsharp_channel_check_connectivity_state;
public readonly Delegates.grpcsharp_channel_watch_connectivity_state_delegate grpcsharp_channel_watch_connectivity_state;
public readonly Delegates.grpcsharp_channel_get_target_delegate grpcsharp_channel_get_target;
public readonly Delegates.grpcsharp_channel_destroy_delegate grpcsharp_channel_destroy;
public readonly Delegates.grpcsharp_sizeof_grpc_event_delegate grpcsharp_sizeof_grpc_event;
public readonly Delegates.grpcsharp_completion_queue_create_delegate grpcsharp_completion_queue_create;
public readonly Delegates.grpcsharp_completion_queue_shutdown_delegate grpcsharp_completion_queue_shutdown;
public readonly Delegates.grpcsharp_completion_queue_next_delegate grpcsharp_completion_queue_next;
public readonly Delegates.grpcsharp_completion_queue_pluck_delegate grpcsharp_completion_queue_pluck;
public readonly Delegates.grpcsharp_completion_queue_destroy_delegate grpcsharp_completion_queue_destroy;
public readonly Delegates.gprsharp_free_delegate gprsharp_free;
public readonly Delegates.grpcsharp_metadata_array_create_delegate grpcsharp_metadata_array_create;
public readonly Delegates.grpcsharp_metadata_array_add_delegate grpcsharp_metadata_array_add;
public readonly Delegates.grpcsharp_metadata_array_count_delegate grpcsharp_metadata_array_count;
public readonly Delegates.grpcsharp_metadata_array_get_key_delegate grpcsharp_metadata_array_get_key;
public readonly Delegates.grpcsharp_metadata_array_get_value_delegate grpcsharp_metadata_array_get_value;
public readonly Delegates.grpcsharp_metadata_array_get_value_length_delegate grpcsharp_metadata_array_get_value_length;
public readonly Delegates.grpcsharp_metadata_array_destroy_full_delegate grpcsharp_metadata_array_destroy_full;
public readonly Delegates.grpcsharp_redirect_log_delegate grpcsharp_redirect_log;
public readonly Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate grpcsharp_metadata_credentials_create_from_plugin;
public readonly Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate grpcsharp_metadata_credentials_notify_from_plugin;
public readonly Delegates.grpcsharp_ssl_server_credentials_create_delegate grpcsharp_ssl_server_credentials_create;
public readonly Delegates.grpcsharp_server_credentials_release_delegate grpcsharp_server_credentials_release;
public readonly Delegates.grpcsharp_server_create_delegate grpcsharp_server_create;
public readonly Delegates.grpcsharp_server_register_completion_queue_delegate grpcsharp_server_register_completion_queue;
public readonly Delegates.grpcsharp_server_add_insecure_http2_port_delegate grpcsharp_server_add_insecure_http2_port;
public readonly Delegates.grpcsharp_server_add_secure_http2_port_delegate grpcsharp_server_add_secure_http2_port;
public readonly Delegates.grpcsharp_server_start_delegate grpcsharp_server_start;
public readonly Delegates.grpcsharp_server_request_call_delegate grpcsharp_server_request_call;
public readonly Delegates.grpcsharp_server_cancel_all_calls_delegate grpcsharp_server_cancel_all_calls;
public readonly Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate grpcsharp_server_shutdown_and_notify_callback;
public readonly Delegates.grpcsharp_server_destroy_delegate grpcsharp_server_destroy;
public readonly Delegates.gprsharp_now_delegate gprsharp_now;
public readonly Delegates.gprsharp_inf_future_delegate gprsharp_inf_future;
public readonly Delegates.gprsharp_inf_past_delegate gprsharp_inf_past;
public readonly Delegates.gprsharp_convert_clock_type_delegate gprsharp_convert_clock_type;
public readonly Delegates.gprsharp_sizeof_timespec_delegate gprsharp_sizeof_timespec;
public readonly Delegates.grpcsharp_test_callback_delegate grpcsharp_test_callback;
public readonly Delegates.grpcsharp_test_nop_delegate grpcsharp_test_nop;
#endregion
public NativeMethods(UnmanagedLibrary library)
{
if (PlatformApis.IsLinux || PlatformApis.IsMacOSX)
{
this.grpcsharp_init = GetMethodDelegate<Delegates.grpcsharp_init_delegate>(library);
this.grpcsharp_shutdown = GetMethodDelegate<Delegates.grpcsharp_shutdown_delegate>(library);
this.grpcsharp_version_string = GetMethodDelegate<Delegates.grpcsharp_version_string_delegate>(library);
this.grpcsharp_batch_context_create = GetMethodDelegate<Delegates.grpcsharp_batch_context_create_delegate>(library);
this.grpcsharp_batch_context_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate>(library);
this.grpcsharp_batch_context_recv_message_length = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_length_delegate>(library);
this.grpcsharp_batch_context_recv_message_to_buffer = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_status = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_details = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_trailing_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate>(library);
this.grpcsharp_batch_context_server_rpc_new_call = GetMethodDelegate<Delegates.grpcsharp_batch_context_server_rpc_new_call_delegate>(library);
this.grpcsharp_batch_context_server_rpc_new_method = GetMethodDelegate<Delegates.grpcsharp_batch_context_server_rpc_new_method_delegate>(library);
this.grpcsharp_batch_context_server_rpc_new_host = GetMethodDelegate<Delegates.grpcsharp_batch_context_server_rpc_new_host_delegate>(library);
this.grpcsharp_batch_context_server_rpc_new_deadline = GetMethodDelegate<Delegates.grpcsharp_batch_context_server_rpc_new_deadline_delegate>(library);
this.grpcsharp_batch_context_server_rpc_new_request_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_server_rpc_new_request_metadata_delegate>(library);
this.grpcsharp_batch_context_recv_close_on_server_cancelled = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate>(library);
this.grpcsharp_batch_context_destroy = GetMethodDelegate<Delegates.grpcsharp_batch_context_destroy_delegate>(library);
this.grpcsharp_composite_call_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_call_credentials_create_delegate>(library);
this.grpcsharp_call_credentials_release = GetMethodDelegate<Delegates.grpcsharp_call_credentials_release_delegate>(library);
this.grpcsharp_call_cancel = GetMethodDelegate<Delegates.grpcsharp_call_cancel_delegate>(library);
this.grpcsharp_call_cancel_with_status = GetMethodDelegate<Delegates.grpcsharp_call_cancel_with_status_delegate>(library);
this.grpcsharp_call_start_unary = GetMethodDelegate<Delegates.grpcsharp_call_start_unary_delegate>(library);
this.grpcsharp_call_start_client_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_client_streaming_delegate>(library);
this.grpcsharp_call_start_server_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_server_streaming_delegate>(library);
this.grpcsharp_call_start_duplex_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_duplex_streaming_delegate>(library);
this.grpcsharp_call_send_message = GetMethodDelegate<Delegates.grpcsharp_call_send_message_delegate>(library);
this.grpcsharp_call_send_close_from_client = GetMethodDelegate<Delegates.grpcsharp_call_send_close_from_client_delegate>(library);
this.grpcsharp_call_send_status_from_server = GetMethodDelegate<Delegates.grpcsharp_call_send_status_from_server_delegate>(library);
this.grpcsharp_call_recv_message = GetMethodDelegate<Delegates.grpcsharp_call_recv_message_delegate>(library);
this.grpcsharp_call_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_recv_initial_metadata_delegate>(library);
this.grpcsharp_call_start_serverside = GetMethodDelegate<Delegates.grpcsharp_call_start_serverside_delegate>(library);
this.grpcsharp_call_send_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_send_initial_metadata_delegate>(library);
this.grpcsharp_call_set_credentials = GetMethodDelegate<Delegates.grpcsharp_call_set_credentials_delegate>(library);
this.grpcsharp_call_get_peer = GetMethodDelegate<Delegates.grpcsharp_call_get_peer_delegate>(library);
this.grpcsharp_call_destroy = GetMethodDelegate<Delegates.grpcsharp_call_destroy_delegate>(library);
this.grpcsharp_channel_args_create = GetMethodDelegate<Delegates.grpcsharp_channel_args_create_delegate>(library);
this.grpcsharp_channel_args_set_string = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_string_delegate>(library);
this.grpcsharp_channel_args_set_integer = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_integer_delegate>(library);
this.grpcsharp_channel_args_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_args_destroy_delegate>(library);
this.grpcsharp_override_default_ssl_roots = GetMethodDelegate<Delegates.grpcsharp_override_default_ssl_roots>(library);
this.grpcsharp_ssl_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_credentials_create_delegate>(library);
this.grpcsharp_composite_channel_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_channel_credentials_create_delegate>(library);
this.grpcsharp_channel_credentials_release = GetMethodDelegate<Delegates.grpcsharp_channel_credentials_release_delegate>(library);
this.grpcsharp_insecure_channel_create = GetMethodDelegate<Delegates.grpcsharp_insecure_channel_create_delegate>(library);
this.grpcsharp_secure_channel_create = GetMethodDelegate<Delegates.grpcsharp_secure_channel_create_delegate>(library);
this.grpcsharp_channel_create_call = GetMethodDelegate<Delegates.grpcsharp_channel_create_call_delegate>(library);
this.grpcsharp_channel_check_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_check_connectivity_state_delegate>(library);
this.grpcsharp_channel_watch_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_watch_connectivity_state_delegate>(library);
this.grpcsharp_channel_get_target = GetMethodDelegate<Delegates.grpcsharp_channel_get_target_delegate>(library);
this.grpcsharp_channel_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_destroy_delegate>(library);
this.grpcsharp_sizeof_grpc_event = GetMethodDelegate<Delegates.grpcsharp_sizeof_grpc_event_delegate>(library);
this.grpcsharp_completion_queue_create = GetMethodDelegate<Delegates.grpcsharp_completion_queue_create_delegate>(library);
this.grpcsharp_completion_queue_shutdown = GetMethodDelegate<Delegates.grpcsharp_completion_queue_shutdown_delegate>(library);
this.grpcsharp_completion_queue_next = GetMethodDelegate<Delegates.grpcsharp_completion_queue_next_delegate>(library);
this.grpcsharp_completion_queue_pluck = GetMethodDelegate<Delegates.grpcsharp_completion_queue_pluck_delegate>(library);
this.grpcsharp_completion_queue_destroy = GetMethodDelegate<Delegates.grpcsharp_completion_queue_destroy_delegate>(library);
this.gprsharp_free = GetMethodDelegate<Delegates.gprsharp_free_delegate>(library);
this.grpcsharp_metadata_array_create = GetMethodDelegate<Delegates.grpcsharp_metadata_array_create_delegate>(library);
this.grpcsharp_metadata_array_add = GetMethodDelegate<Delegates.grpcsharp_metadata_array_add_delegate>(library);
this.grpcsharp_metadata_array_count = GetMethodDelegate<Delegates.grpcsharp_metadata_array_count_delegate>(library);
this.grpcsharp_metadata_array_get_key = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_key_delegate>(library);
this.grpcsharp_metadata_array_get_value = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_value_delegate>(library);
this.grpcsharp_metadata_array_get_value_length = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_value_length_delegate>(library);
this.grpcsharp_metadata_array_destroy_full = GetMethodDelegate<Delegates.grpcsharp_metadata_array_destroy_full_delegate>(library);
this.grpcsharp_redirect_log = GetMethodDelegate<Delegates.grpcsharp_redirect_log_delegate>(library);
this.grpcsharp_metadata_credentials_create_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate>(library);
this.grpcsharp_metadata_credentials_notify_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate>(library);
this.grpcsharp_ssl_server_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_server_credentials_create_delegate>(library);
this.grpcsharp_server_credentials_release = GetMethodDelegate<Delegates.grpcsharp_server_credentials_release_delegate>(library);
this.grpcsharp_server_create = GetMethodDelegate<Delegates.grpcsharp_server_create_delegate>(library);
this.grpcsharp_server_register_completion_queue = GetMethodDelegate<Delegates.grpcsharp_server_register_completion_queue_delegate>(library);
this.grpcsharp_server_add_insecure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_insecure_http2_port_delegate>(library);
this.grpcsharp_server_add_secure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_secure_http2_port_delegate>(library);
this.grpcsharp_server_start = GetMethodDelegate<Delegates.grpcsharp_server_start_delegate>(library);
this.grpcsharp_server_request_call = GetMethodDelegate<Delegates.grpcsharp_server_request_call_delegate>(library);
this.grpcsharp_server_cancel_all_calls = GetMethodDelegate<Delegates.grpcsharp_server_cancel_all_calls_delegate>(library);
this.grpcsharp_server_shutdown_and_notify_callback = GetMethodDelegate<Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate>(library);
this.grpcsharp_server_destroy = GetMethodDelegate<Delegates.grpcsharp_server_destroy_delegate>(library);
this.gprsharp_now = GetMethodDelegate<Delegates.gprsharp_now_delegate>(library);
this.gprsharp_inf_future = GetMethodDelegate<Delegates.gprsharp_inf_future_delegate>(library);
this.gprsharp_inf_past = GetMethodDelegate<Delegates.gprsharp_inf_past_delegate>(library);
this.gprsharp_convert_clock_type = GetMethodDelegate<Delegates.gprsharp_convert_clock_type_delegate>(library);
this.gprsharp_sizeof_timespec = GetMethodDelegate<Delegates.gprsharp_sizeof_timespec_delegate>(library);
this.grpcsharp_test_callback = GetMethodDelegate<Delegates.grpcsharp_test_callback_delegate>(library);
this.grpcsharp_test_nop = GetMethodDelegate<Delegates.grpcsharp_test_nop_delegate>(library);
}
else
{
// Windows or fallback
this.grpcsharp_init = PInvokeMethods.grpcsharp_init;
this.grpcsharp_shutdown = PInvokeMethods.grpcsharp_shutdown;
this.grpcsharp_version_string = PInvokeMethods.grpcsharp_version_string;
this.grpcsharp_batch_context_create = PInvokeMethods.grpcsharp_batch_context_create;
this.grpcsharp_batch_context_recv_initial_metadata = PInvokeMethods.grpcsharp_batch_context_recv_initial_metadata;
this.grpcsharp_batch_context_recv_message_length = PInvokeMethods.grpcsharp_batch_context_recv_message_length;
this.grpcsharp_batch_context_recv_message_to_buffer = PInvokeMethods.grpcsharp_batch_context_recv_message_to_buffer;
this.grpcsharp_batch_context_recv_status_on_client_status = PInvokeMethods.grpcsharp_batch_context_recv_status_on_client_status;
this.grpcsharp_batch_context_recv_status_on_client_details = PInvokeMethods.grpcsharp_batch_context_recv_status_on_client_details;
this.grpcsharp_batch_context_recv_status_on_client_trailing_metadata = PInvokeMethods.grpcsharp_batch_context_recv_status_on_client_trailing_metadata;
this.grpcsharp_batch_context_server_rpc_new_call = PInvokeMethods.grpcsharp_batch_context_server_rpc_new_call;
this.grpcsharp_batch_context_server_rpc_new_method = PInvokeMethods.grpcsharp_batch_context_server_rpc_new_method;
this.grpcsharp_batch_context_server_rpc_new_host = PInvokeMethods.grpcsharp_batch_context_server_rpc_new_host;
this.grpcsharp_batch_context_server_rpc_new_deadline = PInvokeMethods.grpcsharp_batch_context_server_rpc_new_deadline;
this.grpcsharp_batch_context_server_rpc_new_request_metadata = PInvokeMethods.grpcsharp_batch_context_server_rpc_new_request_metadata;
this.grpcsharp_batch_context_recv_close_on_server_cancelled = PInvokeMethods.grpcsharp_batch_context_recv_close_on_server_cancelled;
this.grpcsharp_batch_context_destroy = PInvokeMethods.grpcsharp_batch_context_destroy;
this.grpcsharp_composite_call_credentials_create = PInvokeMethods.grpcsharp_composite_call_credentials_create;
this.grpcsharp_call_credentials_release = PInvokeMethods.grpcsharp_call_credentials_release;
this.grpcsharp_call_cancel = PInvokeMethods.grpcsharp_call_cancel;
this.grpcsharp_call_cancel_with_status = PInvokeMethods.grpcsharp_call_cancel_with_status;
this.grpcsharp_call_start_unary = PInvokeMethods.grpcsharp_call_start_unary;
this.grpcsharp_call_start_client_streaming = PInvokeMethods.grpcsharp_call_start_client_streaming;
this.grpcsharp_call_start_server_streaming = PInvokeMethods.grpcsharp_call_start_server_streaming;
this.grpcsharp_call_start_duplex_streaming = PInvokeMethods.grpcsharp_call_start_duplex_streaming;
this.grpcsharp_call_send_message = PInvokeMethods.grpcsharp_call_send_message;
this.grpcsharp_call_send_close_from_client = PInvokeMethods.grpcsharp_call_send_close_from_client;
this.grpcsharp_call_send_status_from_server = PInvokeMethods.grpcsharp_call_send_status_from_server;
this.grpcsharp_call_recv_message = PInvokeMethods.grpcsharp_call_recv_message;
this.grpcsharp_call_recv_initial_metadata = PInvokeMethods.grpcsharp_call_recv_initial_metadata;
this.grpcsharp_call_start_serverside = PInvokeMethods.grpcsharp_call_start_serverside;
this.grpcsharp_call_send_initial_metadata = PInvokeMethods.grpcsharp_call_send_initial_metadata;
this.grpcsharp_call_set_credentials = PInvokeMethods.grpcsharp_call_set_credentials;
this.grpcsharp_call_get_peer = PInvokeMethods.grpcsharp_call_get_peer;
this.grpcsharp_call_destroy = PInvokeMethods.grpcsharp_call_destroy;
this.grpcsharp_channel_args_create = PInvokeMethods.grpcsharp_channel_args_create;
this.grpcsharp_channel_args_set_string = PInvokeMethods.grpcsharp_channel_args_set_string;
this.grpcsharp_channel_args_set_integer = PInvokeMethods.grpcsharp_channel_args_set_integer;
this.grpcsharp_channel_args_destroy = PInvokeMethods.grpcsharp_channel_args_destroy;
this.grpcsharp_override_default_ssl_roots = PInvokeMethods.grpcsharp_override_default_ssl_roots;
this.grpcsharp_ssl_credentials_create = PInvokeMethods.grpcsharp_ssl_credentials_create;
this.grpcsharp_composite_channel_credentials_create = PInvokeMethods.grpcsharp_composite_channel_credentials_create;
this.grpcsharp_channel_credentials_release = PInvokeMethods.grpcsharp_channel_credentials_release;
this.grpcsharp_insecure_channel_create = PInvokeMethods.grpcsharp_insecure_channel_create;
this.grpcsharp_secure_channel_create = PInvokeMethods.grpcsharp_secure_channel_create;
this.grpcsharp_channel_create_call = PInvokeMethods.grpcsharp_channel_create_call;
this.grpcsharp_channel_check_connectivity_state = PInvokeMethods.grpcsharp_channel_check_connectivity_state;
this.grpcsharp_channel_watch_connectivity_state = PInvokeMethods.grpcsharp_channel_watch_connectivity_state;
this.grpcsharp_channel_get_target = PInvokeMethods.grpcsharp_channel_get_target;
this.grpcsharp_channel_destroy = PInvokeMethods.grpcsharp_channel_destroy;
this.grpcsharp_sizeof_grpc_event = PInvokeMethods.grpcsharp_sizeof_grpc_event;
this.grpcsharp_completion_queue_create = PInvokeMethods.grpcsharp_completion_queue_create;
this.grpcsharp_completion_queue_shutdown = PInvokeMethods.grpcsharp_completion_queue_shutdown;
this.grpcsharp_completion_queue_next = PInvokeMethods.grpcsharp_completion_queue_next;
this.grpcsharp_completion_queue_pluck = PInvokeMethods.grpcsharp_completion_queue_pluck;
this.grpcsharp_completion_queue_destroy = PInvokeMethods.grpcsharp_completion_queue_destroy;
this.gprsharp_free = PInvokeMethods.gprsharp_free;
this.grpcsharp_metadata_array_create = PInvokeMethods.grpcsharp_metadata_array_create;
this.grpcsharp_metadata_array_add = PInvokeMethods.grpcsharp_metadata_array_add;
this.grpcsharp_metadata_array_count = PInvokeMethods.grpcsharp_metadata_array_count;
this.grpcsharp_metadata_array_get_key = PInvokeMethods.grpcsharp_metadata_array_get_key;
this.grpcsharp_metadata_array_get_value = PInvokeMethods.grpcsharp_metadata_array_get_value;
this.grpcsharp_metadata_array_get_value_length = PInvokeMethods.grpcsharp_metadata_array_get_value_length;
this.grpcsharp_metadata_array_destroy_full = PInvokeMethods.grpcsharp_metadata_array_destroy_full;
this.grpcsharp_redirect_log = PInvokeMethods.grpcsharp_redirect_log;
this.grpcsharp_metadata_credentials_create_from_plugin = PInvokeMethods.grpcsharp_metadata_credentials_create_from_plugin;
this.grpcsharp_metadata_credentials_notify_from_plugin = PInvokeMethods.grpcsharp_metadata_credentials_notify_from_plugin;
this.grpcsharp_ssl_server_credentials_create = PInvokeMethods.grpcsharp_ssl_server_credentials_create;
this.grpcsharp_server_credentials_release = PInvokeMethods.grpcsharp_server_credentials_release;
this.grpcsharp_server_create = PInvokeMethods.grpcsharp_server_create;
this.grpcsharp_server_register_completion_queue = PInvokeMethods.grpcsharp_server_register_completion_queue;
this.grpcsharp_server_add_insecure_http2_port = PInvokeMethods.grpcsharp_server_add_insecure_http2_port;
this.grpcsharp_server_add_secure_http2_port = PInvokeMethods.grpcsharp_server_add_secure_http2_port;
this.grpcsharp_server_start = PInvokeMethods.grpcsharp_server_start;
this.grpcsharp_server_request_call = PInvokeMethods.grpcsharp_server_request_call;
this.grpcsharp_server_cancel_all_calls = PInvokeMethods.grpcsharp_server_cancel_all_calls;
this.grpcsharp_server_shutdown_and_notify_callback = PInvokeMethods.grpcsharp_server_shutdown_and_notify_callback;
this.grpcsharp_server_destroy = PInvokeMethods.grpcsharp_server_destroy;
this.gprsharp_now = PInvokeMethods.gprsharp_now;
this.gprsharp_inf_future = PInvokeMethods.gprsharp_inf_future;
this.gprsharp_inf_past = PInvokeMethods.gprsharp_inf_past;
this.gprsharp_convert_clock_type = PInvokeMethods.gprsharp_convert_clock_type;
this.gprsharp_sizeof_timespec = PInvokeMethods.gprsharp_sizeof_timespec;
this.grpcsharp_test_callback = PInvokeMethods.grpcsharp_test_callback;
this.grpcsharp_test_nop = PInvokeMethods.grpcsharp_test_nop;
}
}
/// <summary>
/// Gets singleton instance of this class.
/// </summary>
public static NativeMethods Get()
{
return NativeExtension.Get().NativeMethods;
}
static T GetMethodDelegate<T>(UnmanagedLibrary library)
where T : class
{
var methodName = RemoveStringSuffix(typeof(T).Name, "_delegate");
return library.GetNativeMethodDelegate<T>(methodName);
}
static string RemoveStringSuffix(string str, string toRemove)
{
if (!str.EndsWith(toRemove))
{
return str;
}
return str.Substring(0, str.Length - toRemove.Length);
}
/// <summary>
/// Delegate types for all published native methods. Declared under inner class to prevent scope pollution.
/// </summary>
public class Delegates
{
public delegate void grpcsharp_init_delegate();
public delegate void grpcsharp_shutdown_delegate();
public delegate IntPtr grpcsharp_version_string_delegate(); // returns not-owned const char*
public delegate BatchContextSafeHandle grpcsharp_batch_context_create_delegate();
public delegate IntPtr grpcsharp_batch_context_recv_initial_metadata_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_recv_message_length_delegate(BatchContextSafeHandle ctx);
public delegate void grpcsharp_batch_context_recv_message_to_buffer_delegate(BatchContextSafeHandle ctx, byte[] buffer, UIntPtr bufferLen);
public delegate StatusCode grpcsharp_batch_context_recv_status_on_client_status_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_details_delegate(BatchContextSafeHandle ctx); // returns const char*
public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate(BatchContextSafeHandle ctx);
public delegate CallSafeHandle grpcsharp_batch_context_server_rpc_new_call_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_server_rpc_new_method_delegate(BatchContextSafeHandle ctx); // returns const char*
public delegate IntPtr grpcsharp_batch_context_server_rpc_new_host_delegate(BatchContextSafeHandle ctx); // returns const char*
public delegate Timespec grpcsharp_batch_context_server_rpc_new_deadline_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_server_rpc_new_request_metadata_delegate(BatchContextSafeHandle ctx);
public delegate int grpcsharp_batch_context_recv_close_on_server_cancelled_delegate(BatchContextSafeHandle ctx);
public delegate void grpcsharp_batch_context_destroy_delegate(IntPtr ctx);
public delegate CallCredentialsSafeHandle grpcsharp_composite_call_credentials_create_delegate(CallCredentialsSafeHandle creds1, CallCredentialsSafeHandle creds2);
public delegate void grpcsharp_call_credentials_release_delegate(IntPtr credentials);
public delegate CallError grpcsharp_call_cancel_delegate(CallSafeHandle call);
public delegate CallError grpcsharp_call_cancel_with_status_delegate(CallSafeHandle call, StatusCode status, string description);
public delegate CallError grpcsharp_call_start_unary_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags);
public delegate CallError grpcsharp_call_start_client_streaming_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
public delegate CallError grpcsharp_call_start_server_streaming_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen,
MetadataArraySafeHandle metadataArray, WriteFlags writeFlags);
public delegate CallError grpcsharp_call_start_duplex_streaming_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
public delegate CallError grpcsharp_call_send_message_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, bool sendEmptyInitialMetadata);
public delegate CallError grpcsharp_call_send_close_from_client_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate CallError grpcsharp_call_send_status_from_server_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, StatusCode statusCode, string statusMessage, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata,
byte[] optionalSendBuffer, UIntPtr optionalSendBufferLen, WriteFlags writeFlags);
public delegate CallError grpcsharp_call_recv_message_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate CallError grpcsharp_call_recv_initial_metadata_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate CallError grpcsharp_call_start_serverside_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate CallError grpcsharp_call_send_initial_metadata_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
public delegate CallError grpcsharp_call_set_credentials_delegate(CallSafeHandle call, CallCredentialsSafeHandle credentials);
public delegate CStringSafeHandle grpcsharp_call_get_peer_delegate(CallSafeHandle call);
public delegate void grpcsharp_call_destroy_delegate(IntPtr call);
public delegate ChannelArgsSafeHandle grpcsharp_channel_args_create_delegate(UIntPtr numArgs);
public delegate void grpcsharp_channel_args_set_string_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, string value);
public delegate void grpcsharp_channel_args_set_integer_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, int value);
public delegate void grpcsharp_channel_args_destroy_delegate(IntPtr args);
public delegate void grpcsharp_override_default_ssl_roots(string pemRootCerts);
public delegate ChannelCredentialsSafeHandle grpcsharp_ssl_credentials_create_delegate(string pemRootCerts, string keyCertPairCertChain, string keyCertPairPrivateKey);
public delegate ChannelCredentialsSafeHandle grpcsharp_composite_channel_credentials_create_delegate(ChannelCredentialsSafeHandle channelCreds, CallCredentialsSafeHandle callCreds);
public delegate void grpcsharp_channel_credentials_release_delegate(IntPtr credentials);
public delegate ChannelSafeHandle grpcsharp_insecure_channel_create_delegate(string target, ChannelArgsSafeHandle channelArgs);
public delegate ChannelSafeHandle grpcsharp_secure_channel_create_delegate(ChannelCredentialsSafeHandle credentials, string target, ChannelArgsSafeHandle channelArgs);
public delegate CallSafeHandle grpcsharp_channel_create_call_delegate(ChannelSafeHandle channel, CallSafeHandle parentCall, ContextPropagationFlags propagationMask, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline);
public delegate ChannelState grpcsharp_channel_check_connectivity_state_delegate(ChannelSafeHandle channel, int tryToConnect);
public delegate void grpcsharp_channel_watch_connectivity_state_delegate(ChannelSafeHandle channel, ChannelState lastObservedState,
Timespec deadline, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
public delegate CStringSafeHandle grpcsharp_channel_get_target_delegate(ChannelSafeHandle call);
public delegate void grpcsharp_channel_destroy_delegate(IntPtr channel);
public delegate int grpcsharp_sizeof_grpc_event_delegate();
public delegate CompletionQueueSafeHandle grpcsharp_completion_queue_create_delegate();
public delegate void grpcsharp_completion_queue_shutdown_delegate(CompletionQueueSafeHandle cq);
public delegate CompletionQueueEvent grpcsharp_completion_queue_next_delegate(CompletionQueueSafeHandle cq);
public delegate CompletionQueueEvent grpcsharp_completion_queue_pluck_delegate(CompletionQueueSafeHandle cq, IntPtr tag);
public delegate void grpcsharp_completion_queue_destroy_delegate(IntPtr cq);
public delegate void gprsharp_free_delegate(IntPtr ptr);
public delegate MetadataArraySafeHandle grpcsharp_metadata_array_create_delegate(UIntPtr capacity);
public delegate void grpcsharp_metadata_array_add_delegate(MetadataArraySafeHandle array, string key, byte[] value, UIntPtr valueLength);
public delegate UIntPtr grpcsharp_metadata_array_count_delegate(IntPtr metadataArray);
public delegate IntPtr grpcsharp_metadata_array_get_key_delegate(IntPtr metadataArray, UIntPtr index);
public delegate IntPtr grpcsharp_metadata_array_get_value_delegate(IntPtr metadataArray, UIntPtr index);
public delegate UIntPtr grpcsharp_metadata_array_get_value_length_delegate(IntPtr metadataArray, UIntPtr index);
public delegate void grpcsharp_metadata_array_destroy_full_delegate(IntPtr array);
public delegate void grpcsharp_redirect_log_delegate(GprLogDelegate callback);
public delegate CallCredentialsSafeHandle grpcsharp_metadata_credentials_create_from_plugin_delegate(NativeMetadataInterceptor interceptor);
public delegate void grpcsharp_metadata_credentials_notify_from_plugin_delegate(IntPtr callbackPtr, IntPtr userData, MetadataArraySafeHandle metadataArray, StatusCode statusCode, string errorDetails);
public delegate ServerCredentialsSafeHandle grpcsharp_ssl_server_credentials_create_delegate(string pemRootCerts, string[] keyCertPairCertChainArray, string[] keyCertPairPrivateKeyArray, UIntPtr numKeyCertPairs, bool forceClientAuth);
public delegate void grpcsharp_server_credentials_release_delegate(IntPtr credentials);
public delegate ServerSafeHandle grpcsharp_server_create_delegate(ChannelArgsSafeHandle args);
public delegate void grpcsharp_server_register_completion_queue_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq);
public delegate int grpcsharp_server_add_insecure_http2_port_delegate(ServerSafeHandle server, string addr);
public delegate int grpcsharp_server_add_secure_http2_port_delegate(ServerSafeHandle server, string addr, ServerCredentialsSafeHandle creds);
public delegate void grpcsharp_server_start_delegate(ServerSafeHandle server);
public delegate CallError grpcsharp_server_request_call_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
public delegate void grpcsharp_server_cancel_all_calls_delegate(ServerSafeHandle server);
public delegate void grpcsharp_server_shutdown_and_notify_callback_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
public delegate void grpcsharp_server_destroy_delegate(IntPtr server);
public delegate Timespec gprsharp_now_delegate(ClockType clockType);
public delegate Timespec gprsharp_inf_future_delegate(ClockType clockType);
public delegate Timespec gprsharp_inf_past_delegate(ClockType clockType);
public delegate Timespec gprsharp_convert_clock_type_delegate(Timespec t, ClockType targetClock);
public delegate int gprsharp_sizeof_timespec_delegate();
public delegate CallError grpcsharp_test_callback_delegate([MarshalAs(UnmanagedType.FunctionPtr)] OpCompletionDelegate callback);
public delegate IntPtr grpcsharp_test_nop_delegate(IntPtr ptr);
}
/// <summary>
/// Default PInvoke bindings for native methods that are used on Windows.
/// Alternatively, they can also be used as a fallback on Mono
/// (if libgrpc_csharp_ext is installed on your system, or is made accessible through e.g. LD_LIBRARY_PATH environment variable
/// or using Mono's dllMap feature).
/// </summary>
private class PInvokeMethods
{
// Environment
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_init();
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_shutdown();
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_version_string(); // returns not-owned const char*
// BatchContextSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern BatchContextSafeHandle grpcsharp_batch_context_create();
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_recv_initial_metadata(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_recv_message_length(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_batch_context_recv_message_to_buffer(BatchContextSafeHandle ctx, byte[] buffer, UIntPtr bufferLen);
[DllImport("grpc_csharp_ext.dll")]
public static extern StatusCode grpcsharp_batch_context_recv_status_on_client_status(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_recv_status_on_client_details(BatchContextSafeHandle ctx); // returns const char*
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallSafeHandle grpcsharp_batch_context_server_rpc_new_call(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_server_rpc_new_method(BatchContextSafeHandle ctx); // returns const char*
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_server_rpc_new_host(BatchContextSafeHandle ctx); // returns const char*
[DllImport("grpc_csharp_ext.dll")]
public static extern Timespec grpcsharp_batch_context_server_rpc_new_deadline(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_server_rpc_new_request_metadata(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern int grpcsharp_batch_context_recv_close_on_server_cancelled(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_batch_context_destroy(IntPtr ctx);
// CallCredentialsSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern CallCredentialsSafeHandle grpcsharp_composite_call_credentials_create(CallCredentialsSafeHandle creds1, CallCredentialsSafeHandle creds2);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_call_credentials_release(IntPtr credentials);
// CallSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern CallError grpcsharp_call_cancel(CallSafeHandle call);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallError grpcsharp_call_cancel_with_status(CallSafeHandle call, StatusCode status, string description);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallError grpcsharp_call_start_unary(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallError grpcsharp_call_start_client_streaming(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallError grpcsharp_call_start_server_streaming(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen,
MetadataArraySafeHandle metadataArray, WriteFlags writeFlags);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallError grpcsharp_call_start_duplex_streaming(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallError grpcsharp_call_send_message(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, bool sendEmptyInitialMetadata);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallError grpcsharp_call_send_close_from_client(CallSafeHandle call,
BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallError grpcsharp_call_send_status_from_server(CallSafeHandle call,
BatchContextSafeHandle ctx, StatusCode statusCode, string statusMessage, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata,
byte[] optionalSendBuffer, UIntPtr optionalSendBufferLen, WriteFlags writeFlags);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallError grpcsharp_call_recv_message(CallSafeHandle call,
BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallError grpcsharp_call_recv_initial_metadata(CallSafeHandle call,
BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallError grpcsharp_call_start_serverside(CallSafeHandle call,
BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallError grpcsharp_call_send_initial_metadata(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallError grpcsharp_call_set_credentials(CallSafeHandle call, CallCredentialsSafeHandle credentials);
[DllImport("grpc_csharp_ext.dll")]
public static extern CStringSafeHandle grpcsharp_call_get_peer(CallSafeHandle call);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_call_destroy(IntPtr call);
// ChannelArgsSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern ChannelArgsSafeHandle grpcsharp_channel_args_create(UIntPtr numArgs);
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern void grpcsharp_channel_args_set_string(ChannelArgsSafeHandle args, UIntPtr index, string key, string value);
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern void grpcsharp_channel_args_set_integer(ChannelArgsSafeHandle args, UIntPtr index, string key, int value);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_channel_args_destroy(IntPtr args);
// ChannelCredentialsSafeHandle
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern void grpcsharp_override_default_ssl_roots(string pemRootCerts);
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern ChannelCredentialsSafeHandle grpcsharp_ssl_credentials_create(string pemRootCerts, string keyCertPairCertChain, string keyCertPairPrivateKey);
[DllImport("grpc_csharp_ext.dll")]
public static extern ChannelCredentialsSafeHandle grpcsharp_composite_channel_credentials_create(ChannelCredentialsSafeHandle channelCreds, CallCredentialsSafeHandle callCreds);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_channel_credentials_release(IntPtr credentials);
// ChannelSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern ChannelSafeHandle grpcsharp_insecure_channel_create(string target, ChannelArgsSafeHandle channelArgs);
[DllImport("grpc_csharp_ext.dll")]
public static extern ChannelSafeHandle grpcsharp_secure_channel_create(ChannelCredentialsSafeHandle credentials, string target, ChannelArgsSafeHandle channelArgs);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallSafeHandle grpcsharp_channel_create_call(ChannelSafeHandle channel, CallSafeHandle parentCall, ContextPropagationFlags propagationMask, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline);
[DllImport("grpc_csharp_ext.dll")]
public static extern ChannelState grpcsharp_channel_check_connectivity_state(ChannelSafeHandle channel, int tryToConnect);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_channel_watch_connectivity_state(ChannelSafeHandle channel, ChannelState lastObservedState,
Timespec deadline, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern CStringSafeHandle grpcsharp_channel_get_target(ChannelSafeHandle call);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_channel_destroy(IntPtr channel);
// CompletionQueueEvent
[DllImport("grpc_csharp_ext.dll")]
public static extern int grpcsharp_sizeof_grpc_event();
// CompletionQueueSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern CompletionQueueSafeHandle grpcsharp_completion_queue_create();
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_completion_queue_shutdown(CompletionQueueSafeHandle cq);
[DllImport("grpc_csharp_ext.dll")]
public static extern CompletionQueueEvent grpcsharp_completion_queue_next(CompletionQueueSafeHandle cq);
[DllImport("grpc_csharp_ext.dll")]
public static extern CompletionQueueEvent grpcsharp_completion_queue_pluck(CompletionQueueSafeHandle cq, IntPtr tag);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_completion_queue_destroy(IntPtr cq);
// CStringSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern void gprsharp_free(IntPtr ptr);
// MetadataArraySafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern MetadataArraySafeHandle grpcsharp_metadata_array_create(UIntPtr capacity);
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern void grpcsharp_metadata_array_add(MetadataArraySafeHandle array, string key, byte[] value, UIntPtr valueLength);
[DllImport("grpc_csharp_ext.dll")]
public static extern UIntPtr grpcsharp_metadata_array_count(IntPtr metadataArray);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_metadata_array_get_key(IntPtr metadataArray, UIntPtr index);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_metadata_array_get_value(IntPtr metadataArray, UIntPtr index);
[DllImport("grpc_csharp_ext.dll")]
public static extern UIntPtr grpcsharp_metadata_array_get_value_length(IntPtr metadataArray, UIntPtr index);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_metadata_array_destroy_full(IntPtr array);
// NativeLogRedirector
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_redirect_log(GprLogDelegate callback);
// NativeMetadataCredentialsPlugin
[DllImport("grpc_csharp_ext.dll")]
public static extern CallCredentialsSafeHandle grpcsharp_metadata_credentials_create_from_plugin(NativeMetadataInterceptor interceptor);
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern void grpcsharp_metadata_credentials_notify_from_plugin(IntPtr callbackPtr, IntPtr userData, MetadataArraySafeHandle metadataArray, StatusCode statusCode, string errorDetails);
// ServerCredentialsSafeHandle
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern ServerCredentialsSafeHandle grpcsharp_ssl_server_credentials_create(string pemRootCerts, string[] keyCertPairCertChainArray, string[] keyCertPairPrivateKeyArray, UIntPtr numKeyCertPairs, bool forceClientAuth);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_server_credentials_release(IntPtr credentials);
// ServerSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern ServerSafeHandle grpcsharp_server_create(ChannelArgsSafeHandle args);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_server_register_completion_queue(ServerSafeHandle server, CompletionQueueSafeHandle cq);
[DllImport("grpc_csharp_ext.dll")]
public static extern int grpcsharp_server_add_insecure_http2_port(ServerSafeHandle server, string addr);
[DllImport("grpc_csharp_ext.dll")]
public static extern int grpcsharp_server_add_secure_http2_port(ServerSafeHandle server, string addr, ServerCredentialsSafeHandle creds);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_server_start(ServerSafeHandle server);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallError grpcsharp_server_request_call(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_server_cancel_all_calls(ServerSafeHandle server);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_server_shutdown_and_notify_callback(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_server_destroy(IntPtr server);
// Timespec
[DllImport("grpc_csharp_ext.dll")]
public static extern Timespec gprsharp_now(ClockType clockType);
[DllImport("grpc_csharp_ext.dll")]
public static extern Timespec gprsharp_inf_future(ClockType clockType);
[DllImport("grpc_csharp_ext.dll")]
public static extern Timespec gprsharp_inf_past(ClockType clockType);
[DllImport("grpc_csharp_ext.dll")]
public static extern Timespec gprsharp_convert_clock_type(Timespec t, ClockType targetClock);
[DllImport("grpc_csharp_ext.dll")]
public static extern int gprsharp_sizeof_timespec();
// Testing
[DllImport("grpc_csharp_ext.dll")]
public static extern CallError grpcsharp_test_callback([MarshalAs(UnmanagedType.FunctionPtr)] OpCompletionDelegate callback);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_test_nop(IntPtr ptr);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OleDb;
using System.Threading;
using System.Data;
using System.Data.OracleClient;
using System.Data.Sql;
using System.Data.SqlClient;
//using Oracle.DataAccess.Client;
public enum DataConnectionType : int
{
Oracle = 1,
};
namespace DataAccess
{
[Serializable]
public class CDataConnection
{
//private oracleconnection member
[NonSerialized]
private OracleConnection m_OracleConnection;
//connection type, 1= oracle, 2=oledb etc...
private int m_nConnectionType;
//todo:
public bool AddStatusOutputParams { get; private set; }
//should we audit transactions?
private bool m_bAudit;
public bool Audit
{
get
{
return m_bAudit;
}
}
//status member
private string m_strStatus;
//status code member
private long m_lStatusCode;
/// <summary>
/// constructor
/// </summary>
public CDataConnection()
{
m_OracleConnection = null;
m_strStatus = "";
m_nConnectionType = -1;
AddStatusOutputParams = true;
}
/// <summary>
/// connection type property
/// </summary>
public int ConnectionType
{
get
{
return m_nConnectionType;
}
}
/// <summary>
/// status property
/// </summary>
public string Status
{
get
{
return m_strStatus;
}
}
/// <summary>
/// status code property
/// </summary>
public long StatusCode
{
get
{
return m_lStatusCode;
}
}
/// <summary>
/// audits a transaction
/// </summary>
/// <param name="strSPName"></param>
/// <param name="ParamList"></param>
/// <param name="lStatusCode"></param>
/// <param name="strStatus"></param>
/// <returns></returns>
public bool AuditTransaction(string strSPName,
CDataParameterList ParamList,
long lTxnStatusCode,
string strTxnStatusComment,
out long lStatusCode,
out string strStatus)
{
//init status info 0 = good/ok
strStatus = "";
lStatusCode = 0;
//some transactions do not get audited such as the AUDIT itself, LOGIN is audited seperately
string strSP = strSPName.ToUpper();
if (strSP.IndexOf("AUDIT") > -1 ||
strSP.IndexOf("GETSESSIONVALUE") > -1 ||
strSP.IndexOf("SETSESSIONVALUE") > -1 ||
strSP.IndexOf("LOGIN") > -1)
{
//ignore the audit
return true;
}
//data utils
CDataUtils utils = new CDataUtils();
//full audit string
StringBuilder sbAudit = new StringBuilder();
sbAudit.Append(strSPName);
sbAudit.Append("|");
//return null if no conn
if (m_OracleConnection == null)
{
lStatusCode = 1;
strStatus = "Unable to connect to data source, CDataConnection is null";
return false;
}
//add the parameters from the parameter list to the audit string
for (int i = 0; i < ParamList.Count; i++)
{
CDataParameter parameter = ParamList.GetItemByIndex(i);
if (parameter != null)
{
if (parameter.ParameterName.ToLower() == "pi_vkey")
{
//do not include encryption key in the audit
sbAudit.Append(":key");
}
else
{
if (parameter.ParameterType == (int)DataParameterType.StringParameter)
{
sbAudit.Append(parameter.StringParameterValue);
}
else if (parameter.ParameterType == (int)DataParameterType.LongParameter)
{
sbAudit.Append(Convert.ToString(parameter.LongParameterValue));
}
else if (parameter.ParameterType == (int)DataParameterType.DoubleParameter)
{
sbAudit.Append(Convert.ToString(parameter.DoubleParameterValue));
}
else if (parameter.ParameterType == (int)DataParameterType.IntParameter)
{
sbAudit.Append(Convert.ToString(parameter.IntParameterValue));
}
else if (parameter.ParameterType == (int)DataParameterType.DateParameter)
{
sbAudit.Append(utils.GetDateTimeAsString(parameter.DateParameterValue));
}
else if (parameter.ParameterType == (int)DataParameterType.CLOBParameter)
{
sbAudit.Append(parameter.CLOBParameterValue);
}
else if (parameter.ParameterType == (int)DataParameterType.BLOBParameter)
{
sbAudit.Append("BLOB Data");
}
else
{
sbAudit.Append(parameter.StringParameterValue);
}
}
sbAudit.Append("|");
}
}
//add in the txn status
sbAudit.Append(Convert.ToString(lTxnStatusCode));
sbAudit.Append("|");
sbAudit.Append(strTxnStatusComment);
//call the audit SP
CDataParameterList plistAudit = new CDataParameterList();
plistAudit.AddInputParameter("pi_vSessionID", ParamList.GetItemByName("pi_vSessionID").StringParameterValue);
plistAudit.AddInputParameter("pi_vSessionClientIP", ParamList.GetItemByName("pi_vSessionClientIP").StringParameterValue);
plistAudit.AddInputParameter("pi_nUserID", ParamList.GetItemByName("pi_nUserID").LongParameterValue);
plistAudit.AddInputParameter("pi_vSPName", strSPName);
plistAudit.AddInputParameterCLOB("pi_clAuditXML", sbAudit.ToString());
try
{
ExecuteOracleSP("PCK_FX_SEC.AuditTransaction",
plistAudit,
out lStatusCode,
out strStatus);
}
catch (InvalidOperationException e)
{
strStatus = e.Message;
lStatusCode = 1;
}
catch (OracleException e)
{
strStatus = e.Message;
lStatusCode = 1;
}
if (lStatusCode != 0)
{
return false;
}
return true;
}
/// <summary>
/// set a session value
/// </summary>
/// <param name="lAppUserID"></param>
/// <param name="strSessionSource"></param>
/// <param name="strKeySessionID"></param>
/// <param name="strKey"></param>
/// <param name="strKeyValue"></param>
/// <returns></returns>
public bool SetSessionValue( long lAppUserID,
string strSessionSource,
string strKeySessionID,
string strKey,
string strKeyValue)
{
m_strStatus = "";
m_lStatusCode = 0;
//get the SQL for employee lookup from oracle sp
CDataParameterList parameterList = new CDataParameterList();
parameterList.AddParameter("pi_nAppUserID", lAppUserID, ParameterDirection.Input);
parameterList.AddParameter("pi_vAppSessionSource", strSessionSource, ParameterDirection.Input);
parameterList.AddParameter("pi_vKeySessionID", strKeySessionID, ParameterDirection.Input);
parameterList.AddParameter("pi_vKey", strKey, ParameterDirection.Input);
parameterList.AddParameter("pi_vKeyValue", strKeyValue, ParameterDirection.Input);
if (!ExecuteOracleSP("PCK_SESSION.setSessionValue",
parameterList,
out m_lStatusCode,
out m_strStatus))
{
return false;
}
return true;
}
/// <summary>
/// clear a session values
/// </summary>
/// <param name="lAppUserID"></param>
/// <param name="strSessionSource"></param>
/// <param name="strKeySessionID"></param>
/// <returns></returns>
public bool ClearAllSessionValues( long lAppUserID,
string strSessionSource,
string strKeySessionID )
{
m_strStatus = "";
m_lStatusCode = 0;
//get the SQL for employee lookup from oracle sp
CDataParameterList parameterList = new CDataParameterList();
parameterList.AddParameter("pi_nAppUserID", lAppUserID, ParameterDirection.Input);
parameterList.AddParameter("pi_vAppSessionSource", strSessionSource, ParameterDirection.Input);
parameterList.AddParameter("pi_vKeySessionID", strKeySessionID, ParameterDirection.Input);
if (!ExecuteOracleSP("PCK_SESSION.clearAllSessionValues",
parameterList,
out m_lStatusCode,
out m_strStatus))
{
m_strStatus = "Error clearing session values.";
m_lStatusCode = 1;
return false;
}
return true;
}
/// <summary>
/// clear session values
/// </summary>
/// <param name="lAppUserID"></param>
/// <param name="strSessionSource"></param>
/// <param name="strKeySessionID"></param>
/// <param name="strKey"></param>
/// <returns></returns>
public bool ClearSessionValue( long lAppUserID,
string strSessionSource,
string strKeySessionID,
string strKey)
{
m_strStatus = "";
m_lStatusCode = 0;
//get the SQL for employee lookup from oracle sp
CDataParameterList parameterList = new CDataParameterList();
parameterList.AddParameter("pi_nAppUserID", lAppUserID, ParameterDirection.Input);
parameterList.AddParameter("pi_vAppSessionSource", strSessionSource, ParameterDirection.Input);
parameterList.AddParameter("pi_vKeySessionID", strKeySessionID, ParameterDirection.Input);
parameterList.AddParameter("pi_vKey", strKey, ParameterDirection.Input);
if (!ExecuteOracleSP("PCK_SESSION.deleteSessionValue",
parameterList,
out m_lStatusCode,
out m_strStatus))
{
m_strStatus = "Error getting session value.";
m_lStatusCode = 1;
return false;
}
return true;
}
/// <summary>
/// set a session value
/// </summary>
/// <param name="lAppUserID"></param>
/// <param name="strSessionSource"></param>
/// <param name="strKeySessionID"></param>
/// <param name="strKey"></param>
/// <param name="strKeyValue"></param>
/// <returns></returns>
public bool GetSessionValue( long lAppUserID,
string strSessionSource,
string strKeySessionID,
string strKey,
out string strKeyValue)
{
m_strStatus = "";
m_lStatusCode = 0;
strKeyValue = "";
//get the SQL for employee lookup from oracle sp
CDataParameterList parameterList = new CDataParameterList();
parameterList.AddParameter("pi_nAppUserID", lAppUserID, ParameterDirection.Input);
parameterList.AddParameter("pi_vAppSessionSource", strSessionSource, ParameterDirection.Input);
parameterList.AddParameter("pi_vKeySessionID", strKeySessionID, ParameterDirection.Input);
parameterList.AddParameter("pi_vKey", strKey, ParameterDirection.Input);
parameterList.AddParameter("po_vKeyValue", "", ParameterDirection.Output);
if (!ExecuteOracleSP("PCK_SESSION.getSessionValue",
parameterList,
out m_lStatusCode,
out m_strStatus))
{
m_strStatus = "Error getting session value.";
m_lStatusCode = 1;
return false;
}
CDataParameter param = new CDataParameter();
param = parameterList.GetItemByName("po_vKeyValue");
if (param != null)
{
strKeyValue = param.StringParameterValue;
}
return true;
}
/// <summary>
/// desctructor
/// </summary>
~CDataConnection()
{
//we should not really be closing here, the user must call close!!!!
if (m_OracleConnection != null)
{
try
{
m_OracleConnection.Close();
m_OracleConnection.Dispose();
m_OracleConnection = null;
}
catch (OracleException e)
{
string strError = e.Message;
m_OracleConnection = null;
}
//catch (InvalidOperationException e)
//{
// m_OracleConnection = null;
//}
}
}
/// <summary>
/// close the connection
/// </summary>
public void Close()
{
if (m_OracleConnection != null)
{
m_OracleConnection.Close();
m_OracleConnection.Dispose();
m_OracleConnection = null;
}
}
/// <summary>
/// get the underlying oracle connection
/// </summary>
/// <returns></returns>
public OracleConnection GetOracleConnection()
{
return m_OracleConnection;
}
/// <summary>
/// executes an oracle stored proc
/// </summary>
/// <param name="strSPName"></param>
/// <param name="ParamList"></param>
/// <param name="lStatusCode"></param>
/// <param name="strStatus"></param>
/// <returns></returns>
/* public bool ExecuteOracleSP(string strSPName,
CDataParameterList ParamList,
out long lStatusCode,
out string strStatus)
{
CDataUtils utils = new CDataUtils();
string strAuditXML = "";
strAuditXML += "<sp_name>" + strSPName + "</sp_name>";
m_strStatus = "";
m_lStatusCode = 0;
//return null if no conn
if (m_OracleConnection == null)
{
m_lStatusCode = 1;
m_strStatus = "Unable to connect to data source, CDataConnection is null";
lStatusCode = m_lStatusCode;
strStatus = m_strStatus;
return false;
}
//create a new command object and set the command objects connection, text and type
//must use OracleCommand or you cannot get back a ref cur out param which is how
//we do things in medbase
OracleCommand cmd = new OracleCommand();
cmd.Connection = m_OracleConnection;
cmd.CommandText = strSPName;
cmd.CommandType = CommandType.StoredProcedure;
//add the parameters from the parameter list to the command parameter list
for (int i = 0; i < ParamList.Count; i++)
{
CDataParameter parameter = ParamList.GetItemByIndex(i);
if (parameter != null)
{
//create a new oledb param from our param and add it to the list
//this follows how we currently do it in medbase
OracleParameter oraParameter = new OracleParameter();
oraParameter.ParameterName = parameter.ParameterName;
strAuditXML += "<" + oraParameter.ParameterName + ">";
//set the parameter value, default to string. Probably a better way than the
//if then else, but this works and we can find it later,
if (parameter.ParameterType == (int)DataParameterType.StringParameter)
{
oraParameter.Value = parameter.StringParameterValue;
oraParameter.OracleType = OracleType.VarChar;
oraParameter.Size = 4000;
//audit value
strAuditXML += parameter.StringParameterValue;
}
else if (parameter.ParameterType == (int)DataParameterType.LongParameter)
{
oraParameter.Value = parameter.LongParameterValue;
oraParameter.OracleType = OracleType.Int32;
//audit value
strAuditXML += Convert.ToString(parameter.LongParameterValue);
}
else if (parameter.ParameterType == (int)DataParameterType.DoubleParameter)
{
oraParameter.Value = parameter.DoubleParameterValue;
oraParameter.OracleType = OracleType.Double;
//audit value
strAuditXML += Convert.ToString(parameter.DoubleParameterValue);
}
else if (parameter.ParameterType == (int)DataParameterType.IntParameter)
{
oraParameter.Value = parameter.IntParameterValue;
oraParameter.OracleType = OracleType.Int32;
//audit value
strAuditXML += Convert.ToString(parameter.IntParameterValue);
}
else if (parameter.ParameterType == (int)DataParameterType.DateParameter)
{
oraParameter.Value = parameter.DateParameterValue;
oraParameter.OracleType = OracleType.DateTime;
//audit value
strAuditXML += utils.GetDateAsString(parameter.DateParameterValue);
}
else if (parameter.ParameterType == (int)DataParameterType.CLOBParameter)
{
//You must begin a transaction before obtaining a temporary LOB.
//Otherwise, the OracleDataReader may fail to obtain data later.
OracleTransaction transaction = m_OracleConnection.BeginTransaction();
//make a new command
OracleCommand command = m_OracleConnection.CreateCommand();
command.Connection = m_OracleConnection;
command.Transaction = transaction;
command.CommandText = "declare xx blob; begin dbms_lob.createtemporary(xx, false, 0); :tempblob := xx; end;";
command.Parameters.Add(new OracleParameter("tempblob", OracleType.Blob)).Direction = ParameterDirection.Output;
command.ExecuteNonQuery();
//get a temp lob
OracleLob tempLob = (OracleLob)command.Parameters[0].Value;
//begin batch
tempLob.BeginBatch(OracleLobOpenMode.ReadWrite);
//write the data to the lob
//old, really slow way!
//byte[] bt = new byte[1];
//for (int l = 0; l < parameter.CLOBParameterValue.Length; l++)
//{
// char c = Convert.ToChar(parameter.CLOBParameterValue.Substring(l, 1));
// bt[0] = Convert.ToByte(c);
// tempLob.Write(bt, 0, 1);
//}
//convert string to byte array and write to lob, FAST WAY!
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
tempLob.Write(encoding.GetBytes(parameter.CLOBParameterValue),
0,
parameter.CLOBParameterValue.Length);
//end batch
tempLob.EndBatch();
//set the value of the param = lob
oraParameter.OracleType = OracleType.Clob;
oraParameter.Value = tempLob;
//all done so commit;
transaction.Commit();
//audit value
strAuditXML += parameter.CLOBParameterValue;
}
else
{
oraParameter.Value = parameter.StringParameterValue;
oraParameter.OracleType = OracleType.VarChar;
oraParameter.Size = 4000;
//audit value
strAuditXML += parameter.StringParameterValue;
}
strAuditXML += "</" + oraParameter.ParameterName + ">";
oraParameter.Direction = parameter.Direction;
cmd.Parameters.Add(oraParameter);
}
}
//add in out params for stored proc, all sp's will return a status 0 = good, 1 = bad
//
//status
ParamList.AddParameter("po_nStatusCode", 0, ParameterDirection.Output);
OracleParameter oraStatusParameter = new OracleParameter("po_nStatusCode",
OracleType.Int32);
oraStatusParameter.Direction = ParameterDirection.Output;
cmd.Parameters.Add(oraStatusParameter);
//
//comment
ParamList.AddParameter("po_vStatusComment", "", ParameterDirection.Output);
OracleParameter oraCommentParameter = new OracleParameter("po_vStatusComment",
OracleType.VarChar,
4000);
oraCommentParameter.Direction = ParameterDirection.Output;
cmd.Parameters.Add(oraCommentParameter);
//
try
{
//execute the stored proc and move the out param values back into
//our list
cmd.ExecuteNonQuery();
for (int i = 0; i < ParamList.Count; i++)
{
CDataParameter parameter = ParamList.GetItemByIndex(i);
if (parameter != null)
{
if (parameter.Direction == ParameterDirection.Output ||
parameter.Direction == ParameterDirection.InputOutput)
{
foreach (OracleParameter oP in cmd.Parameters)
{
if (oP.ParameterName.Equals(parameter.ParameterName))
{
if (parameter.ParameterType == (int)DataParameterType.StringParameter)
{
if (oP.Value != null)
{
parameter.StringParameterValue = oP.Value.ToString();
parameter.StringParameterValue = parameter.StringParameterValue.Trim();
}
}
else if (parameter.ParameterType == (int)DataParameterType.LongParameter)
{
if (oP.Value != null)
{
if (oP.Value.ToString() != "")
{
parameter.LongParameterValue = Convert.ToInt64(oP.Value);
}
}
}
else if (parameter.ParameterType == (int)DataParameterType.DoubleParameter)
{
if (oP.Value != null)
{
if (oP.Value.ToString() != "")
{
parameter.DoubleParameterValue = Convert.ToDouble(oP.Value);
}
}
}
else if (parameter.ParameterType == (int)DataParameterType.BoolParameter)
{
if (oP.Value != null)
{
if (oP.Value.ToString() != "")
{
parameter.BoolParameterValue = Convert.ToBoolean(oP.Value);
}
}
}
else if (parameter.ParameterType == (int)DataParameterType.IntParameter)
{
if (oP.Value != null)
{
if (oP.Value.ToString() != "")
{
parameter.IntParameterValue = Convert.ToInt32(oP.Value);
}
}
}
else if (parameter.ParameterType == (int)DataParameterType.DateParameter)
{
if (oP.Value != null)
{
if (oP.Value.ToString() != "")
{
if (!oP.Value.ToString().Equals(""))
{
parameter.DateParameterValue = Convert.ToDateTime(oP.Value);
}
}
}
}
else
{
if (oP.Value != null)
{
parameter.StringParameterValue = oP.Value.ToString();
parameter.StringParameterValue = parameter.StringParameterValue.Trim();
}
}
}
}
}
}
}
CDataParameter param = ParamList.GetItemByName("po_nStatusCode");
if (param != null)
{
m_lStatusCode = param.LongParameterValue;
param = ParamList.GetItemByName("po_vStatusComment");
if (param != null)
{
m_strStatus = param.StringParameterValue;
}
}
else
{
m_lStatusCode = 0;
m_strStatus = "";
}
lStatusCode = m_lStatusCode;
strStatus = m_strStatus;
//now audit the call.... ignore audit and get/set session values or
//login is audited seperately
//audit the transaction
if (m_bAudit)
{
if (strSPName.ToUpper().IndexOf("AUDIT") > -1 ||
strSPName.ToUpper().IndexOf("GETSESSIONVALUE") > -1 ||
strSPName.ToUpper().IndexOf("SETSESSIONVALUE") > -1 ||
strSPName.ToUpper().IndexOf("LOGIN") > -1)
{
//ignore the audit
}
else
{
CDataParameterList plistAudit = new CDataParameterList();
plistAudit.AddInputParameter("pi_vSessionID", ParamList.GetItemByName("pi_vSessionID").StringParameterValue);
plistAudit.AddInputParameter("pi_vSessionClientIP", ParamList.GetItemByName("pi_vSessionClientIP").StringParameterValue);
plistAudit.AddInputParameter("pi_nUserID", ParamList.GetItemByName("pi_nUserID").LongParameterValue);
plistAudit.AddInputParameter("pi_vSPName", strSPName);
plistAudit.AddInputParameterCLOB("pi_clAuditXML", strAuditXML);
long lStat = 0;
string strStat = "";
ExecuteOracleSP("PCK_FX_SEC.AuditTransaction",
plistAudit,
out lStat,
out strStat);
}
}
if (lStatusCode != 0)
{
return false;
}
return true;
}
catch (InvalidOperationException e)
{
m_strStatus = e.Message;
m_lStatusCode = 1;
}
catch (OracleException e)
{
m_strStatus = e.Message;
m_lStatusCode = 1;
}
lStatusCode = m_lStatusCode;
strStatus = m_strStatus;
return false;
}*/
/// <summary>
/// executes an oracle stored proc
/// </summary>
/// <param name="strSPName"></param>
/// <param name="ParamList"></param>
/// <param name="lStatusCode"></param>
/// <param name="strStatus"></param>
/// <returns></returns>
public bool ExecuteOracleSP(string strSPName,
CDataParameterList ParamList,
out long lStatusCode,
out string strStatus)
{
CDataUtils utils = new CDataUtils();
m_strStatus = "";
m_lStatusCode = 0;
//return null if no conn
if (m_OracleConnection == null)
{
m_lStatusCode = 1;
m_strStatus = "Unable to connect to data source, CDataConnection is null";
lStatusCode = m_lStatusCode;
strStatus = m_strStatus;
return false;
}
//create a new command object and set the command objects connection, text and type
//must use OracleCommand or you cannot get back a ref cur out param which is how
//we do things in medbase
OracleCommand cmd = new OracleCommand();
cmd.Connection = m_OracleConnection;
cmd.CommandText = strSPName;
cmd.CommandType = CommandType.StoredProcedure;
//add the parameters from the parameter list to the command parameter list
for (int i = 0; i < ParamList.Count; i++)
{
CDataParameter parameter = ParamList.GetItemByIndex(i);
if (parameter != null)
{
//create a new oledb param from our param and add it to the list
//this follows how we currently do it in medbase
OracleParameter oraParameter = new OracleParameter();
oraParameter.ParameterName = parameter.ParameterName;
//set the parameter value, default to string. Probably a better way than the
//if then else, but this works and we can find it later,
if (parameter.ParameterType == (int)DataParameterType.StringParameter)
{
oraParameter.Value = parameter.StringParameterValue;
oraParameter.OracleType = OracleType.VarChar;
oraParameter.Size = 4000;
}
else if (parameter.ParameterType == (int)DataParameterType.LongParameter)
{
oraParameter.Value = parameter.LongParameterValue;
oraParameter.OracleType = OracleType.Int32;
}
else if (parameter.ParameterType == (int)DataParameterType.DoubleParameter)
{
oraParameter.Value = parameter.DoubleParameterValue;
oraParameter.OracleType = OracleType.Double;
}
else if (parameter.ParameterType == (int)DataParameterType.IntParameter)
{
oraParameter.Value = parameter.IntParameterValue;
oraParameter.OracleType = OracleType.Int32;
}
else if (parameter.ParameterType == (int)DataParameterType.DateParameter)
{
//pass in a "real" null date if the year is less than 1800
if (parameter.DateParameterValue.Year < 1800)
{
oraParameter.Value = System.DBNull.Value;
}
else
{
oraParameter.Value = parameter.DateParameterValue;
}
oraParameter.OracleType = OracleType.DateTime;
}
else if (parameter.ParameterType == (int)DataParameterType.CLOBParameter)
{
//You must begin a transaction before obtaining a temporary LOB.
//Otherwise, the OracleDataReader may fail to obtain data later.
OracleTransaction transaction = m_OracleConnection.BeginTransaction();
//make a new command
OracleCommand command = m_OracleConnection.CreateCommand();
command.Connection = m_OracleConnection;
command.Transaction = transaction;
command.CommandText = "declare xx blob; begin dbms_lob.createtemporary(xx, false, 0); :tempblob := xx; end;";
command.Parameters.Add(new OracleParameter("tempblob", OracleType.Blob)).Direction = ParameterDirection.Output;
command.ExecuteNonQuery();
//get a temp lob
OracleLob tempLob = (OracleLob)command.Parameters[0].Value;
//begin batch
tempLob.BeginBatch(OracleLobOpenMode.ReadWrite);
//write the data to the lob
//old, really slow way!
//byte[] bt = new byte[1];
//for (int l = 0; l < parameter.CLOBParameterValue.Length; l++)
//{
// char c = Convert.ToChar(parameter.CLOBParameterValue.Substring(l, 1));
// bt[0] = Convert.ToByte(c);
// tempLob.Write(bt, 0, 1);
//}
//convert string to byte array and write to lob, FAST WAY!
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
tempLob.Write(encoding.GetBytes(parameter.CLOBParameterValue),
0,
parameter.CLOBParameterValue.Length);
//end batch
tempLob.EndBatch();
//set the value of the param = lob
oraParameter.OracleType = OracleType.Clob;
oraParameter.Value = tempLob;
//all done so commit;
transaction.Commit();
}
else if (parameter.ParameterType == (int)DataParameterType.BLOBParameter)
{
//You must begin a transaction before obtaining a temporary LOB.
//Otherwise, the OracleDataReader may fail to obtain data later.
OracleTransaction transaction = m_OracleConnection.BeginTransaction();
//make a new command
OracleCommand command = m_OracleConnection.CreateCommand();
command.Connection = m_OracleConnection;
command.Transaction = transaction;
command.CommandText = "declare xx blob; begin dbms_lob.createtemporary(xx, false, 0); :tempblob := xx; end;";
command.Parameters.Add(new OracleParameter("tempblob", OracleType.Blob)).Direction = ParameterDirection.Output;
command.ExecuteNonQuery();
//get a temp lob
OracleLob tempLob = (OracleLob)command.Parameters[0].Value;
//begin batch
tempLob.BeginBatch(OracleLobOpenMode.ReadWrite);
//convert string to byte array and write to lob, FAST WAY!
tempLob.Write(parameter.BLOBParameterValue,
0,
parameter.BLOBParameterValue.Length);
//end batch
tempLob.EndBatch();
//set the value of the param = lob
oraParameter.OracleType = OracleType.Blob;
oraParameter.Value = tempLob;
//all done so commit;
transaction.Commit();
}
else
{
oraParameter.Value = parameter.StringParameterValue;
oraParameter.OracleType = OracleType.VarChar;
oraParameter.Size = 4000;
}
oraParameter.Direction = parameter.Direction;
cmd.Parameters.Add(oraParameter);
}
}
//add in out params for stored proc, all sp's will return a status 0 = good, 1 = bad
//
//status
if (AddStatusOutputParams) //defaults to true
{
ParamList.AddParameter("po_nStatusCode", 0, ParameterDirection.Output);
OracleParameter oraStatusParameter = new OracleParameter("po_nStatusCode",
OracleType.Int32);
oraStatusParameter.Direction = ParameterDirection.Output;
cmd.Parameters.Add(oraStatusParameter);
//
//comment
ParamList.AddParameter("po_vStatusComment", "", ParameterDirection.Output);
OracleParameter oraCommentParameter = new OracleParameter("po_vStatusComment",
OracleType.VarChar,
4000);
oraCommentParameter.Direction = ParameterDirection.Output;
cmd.Parameters.Add(oraCommentParameter);
}
//
try
{
//execute the stored proc and move the out param values back into
//our list
cmd.ExecuteNonQuery();
for (int i = 0; i < ParamList.Count; i++)
{
CDataParameter parameter = ParamList.GetItemByIndex(i);
if (parameter != null)
{
if (parameter.Direction == ParameterDirection.Output ||
parameter.Direction == ParameterDirection.InputOutput)
{
foreach (OracleParameter oP in cmd.Parameters)
{
if (oP.ParameterName.Equals(parameter.ParameterName))
{
if (parameter.ParameterType == (int)DataParameterType.StringParameter)
{
if (oP.Value != null)
{
parameter.StringParameterValue = oP.Value.ToString();
parameter.StringParameterValue = parameter.StringParameterValue.Trim();
}
}
else if (parameter.ParameterType == (int)DataParameterType.LongParameter)
{
if (oP.Value != null)
{
if (oP.Value.ToString() != "")
{
parameter.LongParameterValue = Convert.ToInt64(oP.Value);
}
}
}
else if (parameter.ParameterType == (int)DataParameterType.DoubleParameter)
{
if (oP.Value != null)
{
if (oP.Value.ToString() != "")
{
parameter.DoubleParameterValue = Convert.ToDouble(oP.Value);
}
}
}
else if (parameter.ParameterType == (int)DataParameterType.BoolParameter)
{
if (oP.Value != null)
{
if (oP.Value.ToString() != "")
{
parameter.BoolParameterValue = Convert.ToBoolean(oP.Value);
}
}
}
else if (parameter.ParameterType == (int)DataParameterType.IntParameter)
{
if (oP.Value != null)
{
if (oP.Value.ToString() != "")
{
parameter.IntParameterValue = Convert.ToInt32(oP.Value);
}
}
}
else if (parameter.ParameterType == (int)DataParameterType.DateParameter)
{
if (oP.Value != null)
{
if (oP.Value.ToString() != "")
{
if (!oP.Value.ToString().Equals(""))
{
parameter.DateParameterValue = Convert.ToDateTime(oP.Value);
}
}
}
}
else
{
if (oP.Value != null)
{
parameter.StringParameterValue = oP.Value.ToString();
parameter.StringParameterValue = parameter.StringParameterValue.Trim();
}
}
}
}
}
}
}
CDataParameter param = ParamList.GetItemByName("po_nStatusCode");
if (param != null)
{
m_lStatusCode = param.LongParameterValue;
param = ParamList.GetItemByName("po_vStatusComment");
if (param != null)
{
m_strStatus = param.StringParameterValue;
}
}
else
{
m_lStatusCode = 0;
m_strStatus = "";
}
lStatusCode = m_lStatusCode;
strStatus = m_strStatus;
//now audit the call if needed....
if (m_bAudit)
{
long lAuditStatusCode = 0;
string strAuditStatus = String.Empty;
AuditTransaction(strSPName,
ParamList,
lStatusCode,
strStatus,
out lAuditStatusCode,
out strAuditStatus);
}
if (lStatusCode != 0)
{
return false;
}
return true;
}
catch (InvalidOperationException e)
{
m_strStatus = e.Message;
m_lStatusCode = 1;
}
catch (OracleException e)
{
m_strStatus = e.Message;
m_lStatusCode = 1;
}
lStatusCode = m_lStatusCode;
strStatus = m_strStatus;
return false;
}
/// <summary>
/// connect the data connection
/// </summary>
/// <param name="strConnectionString"></param>
/// <param name="nConnectionType"></param>
/// <returns></returns>
public bool Connect(string strConnectionString, int nConnectionType, bool bAudit)
{
m_strStatus = "";
m_nConnectionType = nConnectionType;
m_bAudit = bAudit;
if (m_nConnectionType == (int)DataConnectionType.Oracle)
{
//close connection if it is open
if (m_OracleConnection != null)
{
try
{
m_OracleConnection.Close();
m_OracleConnection = null;
}
catch (OracleException e)
{
m_OracleConnection = null;
m_strStatus = e.Message;
}
}
//trim the connection string
string strConnString = strConnectionString;
strConnString.Trim();
try
{
m_OracleConnection = new OracleConnection(strConnString);
m_OracleConnection.Open();
return true;
}
catch (OracleException e)
{
m_strStatus = e.Message;
m_OracleConnection = null;
return false;
}
catch (ArgumentException ee)
{
m_strStatus = ee.Message;
m_OracleConnection = null;
return false;
}
catch (Exception eee)
{
m_strStatus = eee.Message;
m_OracleConnection = null;
return false;
}
finally
{
//
}
}
else
{
return false;
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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.Diagnostics;
using System.Linq;
using ASC.Common.Threading;
using ASC.Core;
using ASC.Mail.Core.Engine.Operations;
using ASC.Mail.Core.Engine.Operations.Base;
using ASC.Mail.Core.Entities;
using ASC.Mail.Data.Contracts;
using ASC.Web.Studio.Utility;
using SecurityContext = ASC.Core.SecurityContext;
namespace ASC.Mail.Core.Engine
{
public class OperationEngine
{
private readonly DistributedTaskQueue _mailOperations;
public DistributedTaskQueue MailOperations
{
get { return _mailOperations; }
}
public OperationEngine()
{
_mailOperations = new DistributedTaskQueue("mailOperations", Defines.MailOperationsLimit);
}
public MailOperationStatus RemoveMailbox(MailBoxData mailbox,
Func<DistributedTask, string> translateMailOperationStatus = null)
{
var tenant = CoreContext.TenantManager.GetCurrentTenant();
var user = SecurityContext.CurrentAccount;
var operations = MailOperations.GetTasks()
.Where(o =>
{
var oTenant = o.GetProperty<int>(MailOperation.TENANT);
var oUser = o.GetProperty<string>(MailOperation.OWNER);
var oType = o.GetProperty<MailOperationType>(MailOperation.OPERATION_TYPE);
return oTenant == tenant.TenantId &&
oUser == user.ID.ToString() &&
oType == MailOperationType.RemoveMailbox;
})
.ToList();
var sameOperation = operations.FirstOrDefault(o =>
{
var oSource = o.GetProperty<string>(MailOperation.SOURCE);
return oSource == mailbox.MailBoxId.ToString();
});
if (sameOperation != null)
{
return GetMailOperationStatus(sameOperation.Id, translateMailOperationStatus);
}
var runningOperation = operations.FirstOrDefault(o => o.Status <= DistributedTaskStatus.Running);
if (runningOperation != null)
throw new MailOperationAlreadyRunningException("Remove mailbox operation already running.");
var op = new MailRemoveMailboxOperation(tenant, user, mailbox);
return QueueTask(op, translateMailOperationStatus);
}
public MailOperationStatus DownloadAllAttachments(int messageId,
Func<DistributedTask, string> translateMailOperationStatus = null)
{
var tenant = CoreContext.TenantManager.GetCurrentTenant();
var user = SecurityContext.CurrentAccount;
var operations = MailOperations.GetTasks()
.Where(o =>
{
var oTenant = o.GetProperty<int>(MailOperation.TENANT);
var oUser = o.GetProperty<string>(MailOperation.OWNER);
var oType = o.GetProperty<MailOperationType>(MailOperation.OPERATION_TYPE);
return oTenant == tenant.TenantId &&
oUser == user.ID.ToString() &&
oType == MailOperationType.DownloadAllAttachments;
})
.ToList();
var sameOperation = operations.FirstOrDefault(o =>
{
var oSource = o.GetProperty<string>(MailOperation.SOURCE);
return oSource == messageId.ToString();
});
if (sameOperation != null)
{
return GetMailOperationStatus(sameOperation.Id, translateMailOperationStatus);
}
var runningOperation = operations.FirstOrDefault(o => o.Status <= DistributedTaskStatus.Running);
if (runningOperation != null)
throw new MailOperationAlreadyRunningException("Download all attachments operation already running.");
var op = new MailDownloadAllAttachmentsOperation(tenant, user, messageId);
return QueueTask(op, translateMailOperationStatus);
}
public MailOperationStatus RecalculateFolders(Func<DistributedTask, string> translateMailOperationStatus = null)
{
var tenant = CoreContext.TenantManager.GetCurrentTenant();
var user = SecurityContext.CurrentAccount;
var operations = MailOperations.GetTasks()
.Where(o =>
{
var oTenant = o.GetProperty<int>(MailOperation.TENANT);
var oUser = o.GetProperty<string>(MailOperation.OWNER);
var oType = o.GetProperty<MailOperationType>(MailOperation.OPERATION_TYPE);
return oTenant == tenant.TenantId &&
oUser == user.ID.ToString() &&
oType == MailOperationType.RecalculateFolders;
});
var runningOperation = operations.FirstOrDefault(o => o.Status <= DistributedTaskStatus.Running);
if (runningOperation != null)
return GetMailOperationStatus(runningOperation.Id, translateMailOperationStatus);
var op = new MailRecalculateFoldersOperation(tenant, user);
return QueueTask(op, translateMailOperationStatus);
}
public MailOperationStatus CheckDomainDns(string domainName, ServerDns dns,
Func<DistributedTask, string> translateMailOperationStatus = null)
{
var tenant = CoreContext.TenantManager.GetCurrentTenant();
var user = SecurityContext.CurrentAccount;
var operations = MailOperations.GetTasks()
.Where(o =>
{
var oTenant = o.GetProperty<int>(MailOperation.TENANT);
var oUser = o.GetProperty<string>(MailOperation.OWNER);
var oType = o.GetProperty<MailOperationType>(MailOperation.OPERATION_TYPE);
var oSource = o.GetProperty<string>(MailOperation.SOURCE);
return oTenant == tenant.TenantId &&
oUser == user.ID.ToString() &&
oType == MailOperationType.CheckDomainDns &&
oSource == domainName;
});
var runningOperation = operations.FirstOrDefault(o => o.Status <= DistributedTaskStatus.Running);
if (runningOperation != null)
return GetMailOperationStatus(runningOperation.Id, translateMailOperationStatus);
var op = new MailCheckMailserverDomainsDnsOperation(tenant, user, domainName, dns);
return QueueTask(op, translateMailOperationStatus);
}
public MailOperationStatus RemoveUserFolder(uint userFolderId,
Func<DistributedTask, string> translateMailOperationStatus = null)
{
var tenant = CoreContext.TenantManager.GetCurrentTenant();
var user = SecurityContext.CurrentAccount;
var operations = MailOperations.GetTasks()
.Where(o =>
{
var oTenant = o.GetProperty<int>(MailOperation.TENANT);
var oUser = o.GetProperty<string>(MailOperation.OWNER);
var oType = o.GetProperty<MailOperationType>(MailOperation.OPERATION_TYPE);
return oTenant == tenant.TenantId &&
oUser == user.ID.ToString() &&
oType == MailOperationType.RemoveUserFolder;
})
.ToList();
var sameOperation = operations.FirstOrDefault(o =>
{
var oSource = o.GetProperty<string>(MailOperation.SOURCE);
return oSource == userFolderId.ToString();
});
if (sameOperation != null)
{
return GetMailOperationStatus(sameOperation.Id, translateMailOperationStatus);
}
var runningOperation = operations.FirstOrDefault(o => o.Status <= DistributedTaskStatus.Running);
if (runningOperation != null)
throw new MailOperationAlreadyRunningException("Remove user folder operation already running.");
var op = new MailRemoveUserFolderOperation(tenant, user, userFolderId);
return QueueTask(op, translateMailOperationStatus);
}
public MailOperationStatus ApplyFilter(int filterId,
Func<DistributedTask, string> translateMailOperationStatus = null)
{
var tenant = CoreContext.TenantManager.GetCurrentTenant();
var user = SecurityContext.CurrentAccount;
var operations = MailOperations.GetTasks()
.Where(o =>
{
var oTenant = o.GetProperty<int>(MailOperation.TENANT);
var oUser = o.GetProperty<string>(MailOperation.OWNER);
var oType = o.GetProperty<MailOperationType>(MailOperation.OPERATION_TYPE);
return oTenant == tenant.TenantId &&
oUser == user.ID.ToString() &&
oType == MailOperationType.ApplyFilter;
})
.ToList();
var sameOperation = operations.FirstOrDefault(o =>
{
var oSource = o.GetProperty<string>(MailOperation.SOURCE);
return oSource == filterId.ToString();
});
if (sameOperation != null)
{
return GetMailOperationStatus(sameOperation.Id, translateMailOperationStatus);
}
var runningOperation = operations.FirstOrDefault(o => o.Status <= DistributedTaskStatus.Running);
if (runningOperation != null)
throw new MailOperationAlreadyRunningException("Apply filter operation already running.");
var op = new ApplyFilterOperation(tenant, user, filterId);
return QueueTask(op, translateMailOperationStatus);
}
public MailOperationStatus ApplyFilters(List<int> ids,
Func<DistributedTask, string> translateMailOperationStatus = null)
{
var tenant = CoreContext.TenantManager.GetCurrentTenant();
var user = SecurityContext.CurrentAccount;
var op = new ApplyFiltersOperation(tenant, user, ids);
return QueueTask(op, translateMailOperationStatus);
}
public MailOperationStatus QueueTask(MailOperation op, Func<DistributedTask, string> translateMailOperationStatus = null)
{
var task = op.GetDistributedTask();
MailOperations.QueueTask(op.RunJob, task);
return GetMailOperationStatus(task.Id, translateMailOperationStatus);
}
public List<MailOperationStatus> GetMailOperations(Func<DistributedTask, string> translateMailOperationStatus = null)
{
var operations = MailOperations.GetTasks().Where(
o =>
o.GetProperty<int>(MailOperation.TENANT) == TenantProvider.CurrentTenantID &&
o.GetProperty<string>(MailOperation.OWNER) == SecurityContext.CurrentAccount.ID.ToString());
var list = new List<MailOperationStatus>();
foreach (var o in operations)
{
if (string.IsNullOrEmpty(o.Id))
continue;
list.Add(GetMailOperationStatus(o.Id, translateMailOperationStatus));
}
return list;
}
public MailOperationStatus GetMailOperationStatus(string operationId, Func<DistributedTask, string> translateMailOperationStatus = null)
{
var defaultResult = new MailOperationStatus
{
Id = null,
Completed = true,
Percents = 100,
Status = "",
Error = "",
Source = "",
OperationType = -1
};
if (string.IsNullOrEmpty(operationId))
return defaultResult;
var operations = MailOperations.GetTasks().ToList();
foreach (var o in operations)
{
if (!string.IsNullOrEmpty(o.InstanseId) &&
Process.GetProcesses().Any(p => p.Id == int.Parse(o.InstanseId)))
continue;
o.SetProperty(MailOperation.PROGRESS, 100);
MailOperations.RemoveTask(o.Id);
}
var operation = operations
.FirstOrDefault(
o =>
o.GetProperty<int>(MailOperation.TENANT) == TenantProvider.CurrentTenantID &&
o.GetProperty<string>(MailOperation.OWNER) == SecurityContext.CurrentAccount.ID.ToString() &&
o.Id.Equals(operationId));
if (operation == null)
return defaultResult;
if (DistributedTaskStatus.Running < operation.Status)
{
operation.SetProperty(MailOperation.PROGRESS, 100);
MailOperations.RemoveTask(operation.Id);
}
var operationTypeIndex = (int)operation.GetProperty<MailOperationType>(MailOperation.OPERATION_TYPE);
var result = new MailOperationStatus
{
Id = operation.Id,
Completed = operation.GetProperty<bool>(MailOperation.FINISHED),
Percents = operation.GetProperty<int>(MailOperation.PROGRESS),
Status = translateMailOperationStatus != null
? translateMailOperationStatus(operation)
: operation.GetProperty<string>(MailOperation.STATUS),
Error = operation.GetProperty<string>(MailOperation.ERROR),
Source = operation.GetProperty<string>(MailOperation.SOURCE),
OperationType = operationTypeIndex,
Operation = Enum.GetName(typeof(MailOperationType), operationTypeIndex)
};
return result;
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using ArcGIS.Core.CIM;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Internal.Core;
using ArcGIS.Desktop.Mapping;
using ESRI.ArcGIS.ItemIndex;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Xml.Linq;
namespace ProjectCustomItemEarthQuake.Items
{
/// <summary>
/// Example custom project item. A custom project item is a custom item which
/// can be persisted in a project file
/// </summary>
/// <remarks>
/// As a <i>project</i> item, QuakeProjectItems can save state into the aprx. Conversely,
/// when a project is opened that contains a persisted QuakeProjectItem, QuakeProjectItem
/// is asked to re-hydrate itself (based on the name, catalogpath, and type that was
/// saved in the project)</remarks>
internal class QuakeProjectItem : ArcGIS.Desktop.Core.CustomProjectItemBase
{
// private static int event_count;
protected QuakeProjectItem() : base()
{
this._pathSaveRelative = true;
}
protected QuakeProjectItem(ItemInfoValue iiv) : base(FlipBrowseDialogOnly(iiv))
{
_pathSaveRelative = true;
}
/// <summary>
/// This constructor is called if the project item was saved into the project.
/// </summary>
/// <param name="name"></param>
/// <param name="catalogPath"></param>
/// <param name="typeID"></param>
/// <param name="containerTypeID"></param>
/// <remarks>Custom project items cannot <b>not</b> be saved into the project if
/// the user clicks (or executes) save</remarks>
public QuakeProjectItem(string name, string catalogPath, string typeID, string containerTypeID) :
base(name, catalogPath, typeID, containerTypeID)
{
_pathSaveRelative = true;
}
#region Icon override
/// <summary>
/// Gets whether the project item can contain child items
/// </summary>
public override bool IsContainer => true;
public override ImageSource LargeImage
{
get
{
return System.Windows.Application.Current.Resources["BexDog32"] as ImageSource;
}
}
public override Task<ImageSource> SmallImage
{
get
{
ImageSource smallImage = System.Windows.Application.Current.Resources["BexDog16"] as ImageSource;
if (smallImage == null) throw new ArgumentException("SmallImage for CustomProjectItem doesn't exist");
return Task.FromResult(smallImage as ImageSource);
}
}
#endregion Icon override
#region Rename override code
protected override bool CanRename => true;
protected override bool OnRename(string newName)
{
// have to do some work to actually change the name so if they call refresh it'll be there
// whether it's a file on disk or node in the xml
var new_ext = System.IO.Path.GetExtension(newName);
if (string.IsNullOrEmpty(new_ext))
{
new_ext = System.IO.Path.GetExtension(this.Path);
newName = System.IO.Path.ChangeExtension(newName, new_ext);
}
var new_file_path = System.IO.Path.Combine(
System.IO.Path.GetDirectoryName(this.Path), newName);
System.IO.File.Move(this.Path, new_file_path);
this.Path = new_file_path;
return base.OnRename(newName);
}
#endregion Rename override code
#region Fetch override to provide 'children'
/// <summary>
/// Fetch is called if <b>IsContainer</b> = <b>true</b> and the project item is being
/// expanded in the Catalog pane for the first time.
/// </summary>
/// <remarks>The project item should instantiate items for each of its children and
/// add them to its child collection (see <b>AddRangeToChildren</b>)</remarks>
public override void Fetch()
{
//This is where the quake item is located
string filePath = this.Path;
//Quake is an xml document, we parse it's content to provide the list of children
XDocument doc = XDocument.Load(filePath);
XNamespace aw = "http://quakeml.org/xmlns/bed/1.2";
IEnumerable<XElement> earthquakeEvents = from el in doc.Root.Descendants(aw + "event") select el;
List<QuakeEventCustomItem> events = new List<QuakeEventCustomItem>();
var existingChildren = this.GetChildren().ToList();
int event_count = 1;
//Parse out the child quake events
foreach (XElement earthquakeElement in earthquakeEvents)
{
var path = filePath + $"[{event_count}]";
XElement desc = earthquakeElement.Element(aw + "description");
XElement name = desc.Element(aw + "text");
string fullName = name.Value;
if (existingChildren.Any(i => i.Path == path)) continue;
XElement origin = earthquakeElement.Element(aw + "origin");
XElement time = origin.Element(aw + "time");
XElement value = time.Element(aw + "value");
string date = value.Value;
DateTime timestamp = Convert.ToDateTime(date);
XElement xLong = origin.Element(aw + "longitude");
value = xLong.Element(aw + "value");
var longitude = Convert.ToDouble(value.Value);
XElement xLat = origin.Element(aw + "latitude");
value = xLat.Element(aw + "value");
var latitude = Convert.ToDouble(value.Value);
//Make an "event" item for each child read from the quake file
QuakeEventCustomItem item = new QuakeEventCustomItem(
fullName, path, "acme_quake_event", timestamp.ToString(), longitude, latitude);
//if (events.Any(s => s.Name == fullName))
// continue;
events.Add(item);
event_count++;
}
//Add the event "child" items to the children collection
this.AddRangeToChildren(events);
}
#endregion Fetch override to provide 'children'
#region Uniquely identify each custom project item
public override ProjectItemInfo OnGetInfo()
{
var projectItemInfo = new ProjectItemInfo
{
Name = this.Name,
Path = this.Path,
Type = QuakeProjectItemContainer.ContainerName
};
return projectItemInfo;
}
#endregion Uniquely identify each custom project item
#region Private Helpers
private static ItemInfoValue FlipBrowseDialogOnly(ItemInfoValue iiv)
{
iiv.browseDialogOnly = "FALSE";
return iiv;
}
#endregion Helpers
}
/// <summary>
/// Quake event items. These are children of a QuakeProjectItem
/// </summary>
/// <remarks>QuakeEventCustomItems are, themselves, custom items</remarks>
internal class QuakeEventCustomItem : CustomItemBase, IMappableItem, IMappableItemEx
{
public MapPoint QuakeLocation;
public QuakeEventCustomItem(string name, string path, string type, string lastModifiedTime, double longitude, double latitude) : base(name, path, type, lastModifiedTime)
{
this.DisplayType = "QuakeEvent";
QuakeLocation = MapPointBuilder.CreateMapPoint(longitude, latitude, SpatialReferences.WGS84);
}
public void SetNewName(string newName)
{
this.Name = newName;
NotifyPropertyChanged("Name");
this.Title = newName;
NotifyPropertyChanged("Title");
this._itemInfoValue.name = newName;
this._itemInfoValue.description = newName;
}
public bool CanAddToMap(MapType? mapType)
{
return true;
}
public void OnAddToMap(Map map)
{
OnAddToMapEx(map);
}
public void OnAddToMap(Map map, ILayerContainerEdit groupLayer, int index)
{
OnAddToMapEx(map, groupLayer, index);
}
public string[] OnAddToMapEx(Map map)
{
return OnAddToMapEx (map, null, -1);
}
public string[] OnAddToMapEx(Map map, ILayerContainerEdit groupLayer, int index)
{
Module1.AddOrUpdateOverlay(this.QuakeLocation, Module1.GetPointSymbolRef());
return new string[] { this.Title };
}
public override ImageSource LargeImage
{
get
{
return System.Windows.Application.Current.Resources["T-Rex32"] as ImageSource;
}
}
public override Task<ImageSource> SmallImage
{
get
{
ImageSource img = System.Windows.Application.Current.Resources["T-Rex16"] as ImageSource;
return Task.FromResult(img);
}
}
}
}
| |
using System;
using System.Linq;
using System.Linq.Expressions;
using FluentNHibernate.Automapping.TestFixtures;
using FluentNHibernate.Conventions.Helpers.Builders;
using FluentNHibernate.Conventions.Instances;
using FluentNHibernate.Mapping;
using FluentNHibernate.MappingModel;
using FluentNHibernate.MappingModel.Identity;
using NUnit.Framework;
namespace FluentNHibernate.Testing.ConventionsTests.OverridingFluentInterface
{
[TestFixture]
public class ManyToOneConventionTests
{
private PersistenceModel model;
private IMappingProvider mapping;
private Type mappingType;
[SetUp]
public void CreatePersistenceModel()
{
model = new PersistenceModel();
}
[Test]
public void AccessShouldntBeOverwritten()
{
Mapping(x => x.Access.Field());
Convention(x => x.Access.Property());
VerifyModel(x => x.Access.ShouldEqual("field"));
}
[Test]
public void CascadeShouldntBeOverwritten()
{
Mapping(x => x.Cascade.All());
Convention(x => x.Cascade.None());
VerifyModel(x => x.Cascade.ShouldEqual("all"));
}
[Test]
public void ClassShouldntBeOverwritten()
{
Mapping(x => x.Class(typeof(string)));
Convention(x => x.CustomClass(typeof(int)));
VerifyModel(x => x.Class.GetUnderlyingSystemType().ShouldEqual(typeof(string)));
}
[Test]
public void ColumnShouldntBeOverwritten()
{
Mapping(x => x.Column("name"));
Convention(x => x.Column("xxx"));
VerifyModel(x => x.Columns.First().Name.ShouldEqual("name"));
}
[Test]
public void FetchShouldntBeOverwritten()
{
Mapping(x => x.Fetch.Join());
Convention(x => x.Fetch.Select());
VerifyModel(x => x.Fetch.ShouldEqual("join"));
}
[Test]
public void IndexShouldntBeOverwritten()
{
Mapping(x => x.Index("index"));
Convention(x => x.Index("value"));
VerifyModel(x => x.Columns.First().Index.ShouldEqual("index"));
}
[Test]
public void InsertShouldntBeOverwritten()
{
Mapping(x => x.Insert());
Convention(x => x.Not.Insert());
VerifyModel(x => x.Insert.ShouldBeTrue());
}
[Test]
public void LazyShouldntBeOverwritten()
{
Mapping(x => x.LazyLoad());
Convention(x => x.Not.LazyLoad());
VerifyModel(x => x.Lazy.ShouldEqual(Laziness.Proxy.ToString()));
}
[Test]
public void NotFoundShouldntBeOverwritten()
{
Mapping(x => x.NotFound.Exception());
Convention(x => x.NotFound.Ignore());
VerifyModel(x => x.NotFound.ShouldEqual("exception"));
}
[Test]
public void NullableShouldntBeOverwritten()
{
Mapping(x => x.Nullable());
Convention(x => x.Not.Nullable());
VerifyModel(x => x.Columns.First().NotNull.ShouldBeFalse());
}
[Test]
public void PropertyRefShouldntBeOverwritten()
{
Mapping(x => x.PropertyRef("ref"));
Convention(x => x.PropertyRef("xxx"));
VerifyModel(x => x.PropertyRef.ShouldEqual("ref"));
}
[Test]
public void ReadOnlyShouldntBeOverwritten()
{
Mapping(x => x.ReadOnly());
Convention(x => x.Not.ReadOnly());
VerifyModel(x =>
{
x.Insert.ShouldBeFalse();
x.Update.ShouldBeFalse();
});
}
[Test]
public void UniqueShouldntBeOverwritten()
{
Mapping(x => x.Unique());
Convention(x => x.Not.Unique());
VerifyModel(x => x.Columns.First().Unique.ShouldBeTrue());
}
[Test]
public void UniqueKeyShouldntBeOverwritten()
{
Mapping(x => x.UniqueKey("key"));
Convention(x => x.UniqueKey("xxx"));
VerifyModel(x => x.Columns.First().UniqueKey.ShouldEqual("key"));
}
[Test]
public void UpdateShouldntBeOverwritten()
{
Mapping(x => x.Update());
Convention(x => x.Not.Update());
VerifyModel(x => x.Update.ShouldBeTrue());
}
[Test]
public void ForeignKeyShouldntBeOverwritten()
{
Mapping(x => x.ForeignKey("key"));
Convention(x => x.ForeignKey("xxx"));
VerifyModel(x => x.ForeignKey.ShouldEqual("key"));
}
[Test]
public void FormulaShouldntBeOverwritten()
{
Mapping(x => x.Formula("form"));
Convention(x => x.Formula("xxx"));
VerifyModel(x => x.Formula.ShouldEqual("form"));
}
#region Helpers
private void Convention(Action<IManyToOneInstance> convention)
{
model.Conventions.Add(new ReferenceConventionBuilder().Always(convention));
}
private void Mapping(Action<ManyToOnePart<ExampleParentClass>> mappingDefinition)
{
var classMap = new ClassMap<ExampleClass>();
classMap.Id(x => x.Id);
var map = classMap.References(x => x.Parent);
mappingDefinition(map);
mapping = classMap;
mappingType = typeof(ExampleClass);
}
private void VerifyModel(Action<ManyToOneMapping> modelVerification)
{
model.Add(mapping);
var generatedModels = model.BuildMappings();
var modelInstance = generatedModels
.First(x => x.Classes.FirstOrDefault(c => c.Type == mappingType) != null)
.Classes.First()
.References.First();
modelVerification(modelInstance);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Kiko.Web.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// 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 Rodrigo B. de Oliveira 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.
#endregion
using System;
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.TypeSystem;
namespace Boo.Lang.Compiler.Steps
{
//TODO: constant propagation (which allows precise unreachable branch detection)
public class ConstantFolding : AbstractTransformerCompilerStep
{
public const string FoldedExpression = "foldedExpression";
override public void Run()
{
if (Errors.Count > 0)
return;
Visit(CompileUnit);
}
override public void OnModule(Module node)
{
Visit(node.Members);
}
object GetLiteralValue(Expression node)
{
switch (node.NodeType)
{
case NodeType.CastExpression:
return GetLiteralValue(((CastExpression) node).Target);
case NodeType.BoolLiteralExpression:
return ((BoolLiteralExpression) node).Value;
case NodeType.IntegerLiteralExpression:
return ((IntegerLiteralExpression) node).Value;
case NodeType.DoubleLiteralExpression:
return ((DoubleLiteralExpression) node).Value;
case NodeType.MemberReferenceExpression:
{
IField field = node.Entity as IField;
if (null != field && field.IsLiteral)
{
if (field.Type.IsEnum)
{
object o = field.StaticValue;
if (null != o && o != Error.Default)
return o;
}
else
{
Expression e = field.StaticValue as Expression;
return (null != e)
? GetLiteralValue(e)
: field.StaticValue;
}
}
break;
}
}
return null;
}
override public void LeaveEnumMember(EnumMember node)
{
if (node.Initializer.NodeType == NodeType.IntegerLiteralExpression)
return;
IType type = node.Initializer.ExpressionType;
if (null != type && (TypeSystemServices.IsIntegerNumber(type) || type.IsEnum))
{
object val = GetLiteralValue(node.Initializer);
if (null != val && val != Error.Default)
node.Initializer = new IntegerLiteralExpression(Convert.ToInt64(val));
}
return;
}
override public void LeaveBinaryExpression(BinaryExpression node)
{
if (AstUtil.GetBinaryOperatorKind(node.Operator) == BinaryOperatorKind.Assignment
|| node.Operator == BinaryOperatorType.ReferenceEquality
|| node.Operator == BinaryOperatorType.ReferenceInequality)
return;
if (null == node.Left.ExpressionType || null == node.Right.ExpressionType)
return;
object lhs = GetLiteralValue(node.Left);
object rhs = GetLiteralValue(node.Right);
if (null == lhs || null == rhs)
return;
Expression folded = null;
IType lhsType = GetExpressionType(node.Left);
IType rhsType = GetExpressionType(node.Right);
if (TypeSystemServices.BoolType == lhsType && TypeSystemServices.BoolType == rhsType)
{
folded = GetFoldedBoolLiteral(node.Operator, Convert.ToBoolean(lhs), Convert.ToBoolean(rhs));
}
else if (TypeSystemServices.IsFloatingPointNumber(lhsType) || TypeSystemServices.IsFloatingPointNumber(rhsType))
{
folded = GetFoldedDoubleLiteral(node.Operator, Convert.ToDouble(lhs), Convert.ToDouble(rhs));
}
else if (TypeSystemServices.IsIntegerNumber(lhsType) || lhsType.IsEnum)
{
bool lhsSigned = TypeSystemServices.IsSignedNumber(lhsType);
bool rhsSigned = TypeSystemServices.IsSignedNumber(rhsType);
if (lhsSigned == rhsSigned) //mixed signed/unsigned not supported for folding
{
folded = lhsSigned
? GetFoldedIntegerLiteral(node.Operator, Convert.ToInt64(lhs), Convert.ToInt64(rhs))
: GetFoldedIntegerLiteral(node.Operator, Convert.ToUInt64(lhs), Convert.ToUInt64(rhs));
}
}
else if (node.Operator == BinaryOperatorType.TypeTest && lhsType.IsValueType)
{
folded = GetFoldedValueTypeTest(node, lhsType, (IType) node.Right.Entity);
}
if (null != folded)
{
folded.LexicalInfo = node.LexicalInfo;
folded.ExpressionType = GetExpressionType(node);
folded.Annotate(FoldedExpression, node);
ReplaceCurrentNode(folded);
}
}
private BoolLiteralExpression GetFoldedValueTypeTest(Expression node, IType leftType, IType rightType)
{
Context.Warnings.Add(CompilerWarningFactory.ConstantExpression(node));
return CodeBuilder.CreateBoolLiteral(rightType.IsAssignableFrom(leftType));
}
override public void LeaveUnaryExpression(UnaryExpression node)
{
if (node.Operator == UnaryOperatorType.Explode
|| node.Operator == UnaryOperatorType.AddressOf
|| node.Operator == UnaryOperatorType.Indirection
|| node.Operator == UnaryOperatorType.LogicalNot)
return;
if (null == node.Operand.ExpressionType)
return;
object operand = GetLiteralValue(node.Operand);
if (null == operand)
return;
Expression folded = null;
IType operandType = GetExpressionType(node.Operand);
if (TypeSystemServices.IsFloatingPointNumber(operandType))
{
folded = GetFoldedDoubleLiteral(node.Operator, Convert.ToDouble(operand));
}
else if (TypeSystemServices.IsIntegerNumber(operandType) || operandType.IsEnum)
{
folded = GetFoldedIntegerLiteral(node.Operator, Convert.ToInt64(operand));
}
if (null != folded)
{
folded.LexicalInfo = node.LexicalInfo;
folded.ExpressionType = GetExpressionType(node);
ReplaceCurrentNode(folded);
}
}
public override void LeaveTryCastExpression(TryCastExpression node)
{
base.LeaveTryCastExpression(node);
var target = GetExpressionType(node.Target);
if (target.IsValueType)
{
var toType = GetType(node.Type);
ReplaceCurrentNode(toType.IsAssignableFrom(target)
? CodeBuilder.CreateCast(toType, node.Target)
: CodeBuilder.CreateNullLiteral());
}
}
static BoolLiteralExpression GetFoldedBoolLiteral(BinaryOperatorType @operator, bool lhs, bool rhs)
{
bool result;
switch (@operator)
{
//comparison
case BinaryOperatorType.Equality:
result = (lhs == rhs);
break;
case BinaryOperatorType.Inequality:
result = (lhs != rhs);
break;
//bitwise
case BinaryOperatorType.BitwiseOr:
result = lhs | rhs;
break;
case BinaryOperatorType.BitwiseAnd:
result = lhs & rhs;
break;
case BinaryOperatorType.ExclusiveOr:
result = lhs ^ rhs;
break;
//logical
case BinaryOperatorType.And:
result = lhs && rhs;
break;
case BinaryOperatorType.Or:
result = lhs || rhs;
break;
default:
return null; //not supported
}
return new BoolLiteralExpression(result);
}
static LiteralExpression GetFoldedIntegerLiteral(BinaryOperatorType @operator, long lhs, long rhs)
{
long result;
switch (@operator)
{
//arithmetic
case BinaryOperatorType.Addition:
result = lhs + rhs;
break;
case BinaryOperatorType.Subtraction:
result = lhs - rhs;
break;
case BinaryOperatorType.Multiply:
result = lhs * rhs;
break;
case BinaryOperatorType.Division:
result = lhs / rhs;
break;
case BinaryOperatorType.Modulus:
result = lhs % rhs;
break;
case BinaryOperatorType.Exponentiation:
result = (long) Math.Pow(lhs, rhs);
break;
//bitwise
case BinaryOperatorType.BitwiseOr:
result = lhs | rhs;
break;
case BinaryOperatorType.BitwiseAnd:
result = lhs & rhs;
break;
case BinaryOperatorType.ExclusiveOr:
result = lhs ^ rhs;
break;
case BinaryOperatorType.ShiftLeft:
result = lhs << (int) rhs;
break;
case BinaryOperatorType.ShiftRight:
result = lhs >> (int) rhs;
break;
//comparison
case BinaryOperatorType.LessThan:
return new BoolLiteralExpression(lhs < rhs);
case BinaryOperatorType.LessThanOrEqual:
return new BoolLiteralExpression(lhs <= rhs);
case BinaryOperatorType.GreaterThan:
return new BoolLiteralExpression(lhs > rhs);
case BinaryOperatorType.GreaterThanOrEqual:
return new BoolLiteralExpression(lhs >= rhs);
case BinaryOperatorType.Equality:
return new BoolLiteralExpression(lhs == rhs);
case BinaryOperatorType.Inequality:
return new BoolLiteralExpression(lhs != rhs);
default:
return null; //not supported
}
return new IntegerLiteralExpression(result);
}
static LiteralExpression GetFoldedIntegerLiteral(BinaryOperatorType @operator, ulong lhs, ulong rhs)
{
ulong result;
switch (@operator)
{
//arithmetic
case BinaryOperatorType.Addition:
result = lhs + rhs;
break;
case BinaryOperatorType.Subtraction:
result = lhs - rhs;
break;
case BinaryOperatorType.Multiply:
result = lhs * rhs;
break;
case BinaryOperatorType.Division:
result = lhs / rhs;
break;
case BinaryOperatorType.Modulus:
result = lhs % rhs;
break;
case BinaryOperatorType.Exponentiation:
result = (ulong) Math.Pow(lhs, rhs);
break;
//bitwise
case BinaryOperatorType.BitwiseOr:
result = lhs | rhs;
break;
case BinaryOperatorType.BitwiseAnd:
result = lhs & rhs;
break;
case BinaryOperatorType.ExclusiveOr:
result = lhs ^ rhs;
break;
case BinaryOperatorType.ShiftLeft:
result = lhs << (int) rhs;
break;
case BinaryOperatorType.ShiftRight:
result = lhs >> (int) rhs;
break;
//comparison
case BinaryOperatorType.LessThan:
return new BoolLiteralExpression(lhs < rhs);
case BinaryOperatorType.LessThanOrEqual:
return new BoolLiteralExpression(lhs <= rhs);
case BinaryOperatorType.GreaterThan:
return new BoolLiteralExpression(lhs > rhs);
case BinaryOperatorType.GreaterThanOrEqual:
return new BoolLiteralExpression(lhs >= rhs);
case BinaryOperatorType.Equality:
return new BoolLiteralExpression(lhs == rhs);
case BinaryOperatorType.Inequality:
return new BoolLiteralExpression(lhs != rhs);
default:
return null; //not supported
}
return new IntegerLiteralExpression((long) result);
}
static LiteralExpression GetFoldedDoubleLiteral(BinaryOperatorType @operator, double lhs, double rhs)
{
double result;
switch (@operator)
{
//arithmetic
case BinaryOperatorType.Addition:
result = lhs + rhs;
break;
case BinaryOperatorType.Subtraction:
result = lhs - rhs;
break;
case BinaryOperatorType.Multiply:
result = lhs * rhs;
break;
case BinaryOperatorType.Division:
result = lhs / rhs;
break;
case BinaryOperatorType.Modulus:
result = lhs % rhs;
break;
case BinaryOperatorType.Exponentiation:
result = Math.Pow(lhs, rhs);
break;
//comparison
case BinaryOperatorType.LessThan:
return new BoolLiteralExpression(lhs < rhs);
case BinaryOperatorType.LessThanOrEqual:
return new BoolLiteralExpression(lhs <= rhs);
case BinaryOperatorType.GreaterThan:
return new BoolLiteralExpression(lhs > rhs);
case BinaryOperatorType.GreaterThanOrEqual:
return new BoolLiteralExpression(lhs >= rhs);
case BinaryOperatorType.Equality:
return new BoolLiteralExpression(lhs == rhs);
case BinaryOperatorType.Inequality:
return new BoolLiteralExpression(lhs != rhs);
default:
return null; //not supported
}
return new DoubleLiteralExpression(result);
}
static LiteralExpression GetFoldedIntegerLiteral(UnaryOperatorType @operator, long operand)
{
long result;
switch (@operator)
{
case UnaryOperatorType.UnaryNegation:
result = -operand;
break;
case UnaryOperatorType.OnesComplement:
result = ~operand;
break;
default:
return null; //not supported
}
return new IntegerLiteralExpression(result);
}
static LiteralExpression GetFoldedDoubleLiteral(UnaryOperatorType @operator, double operand)
{
double result;
switch (@operator)
{
case UnaryOperatorType.UnaryNegation:
result = -operand;
break;
default:
return null; //not supported
}
return new DoubleLiteralExpression(result);
}
}
}
| |
using FluentFTP.Rules;
using FluentFTP.Servers;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.CompilerServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
#if (CORE || NETFX)
using System.Threading;
#endif
#if (CORE || NET45)
using System.Threading.Tasks;
#endif
namespace FluentFTP {
/// <summary>
/// Interface for the FtpClient class.
/// For detailed documentation of the methods, please see the FtpClient class or check the Wiki on the FluentFTP Github project.
/// </summary>
public interface IFtpClient : IDisposable {
// PROPERTIES (From FtpClient_Properties)
bool IsDisposed { get;}
FtpIpVersion InternetProtocolVersions { get; set; }
int SocketPollInterval { get; set; }
bool StaleDataCheck { get; set; }
bool IsConnected { get; }
bool EnableThreadSafeDataConnections { get; set; }
int NoopInterval { get; set; }
bool CheckCapabilities { get; set; }
Encoding Encoding { get; set; }
string Host { get; set; }
int Port { get; set; }
NetworkCredential Credentials { get; set; }
int MaximumDereferenceCount { get; set; }
X509CertificateCollection ClientCertificates { get; }
Func<string> AddressResolver { get; set; }
IEnumerable<int> ActivePorts { get; set; }
FtpDataConnectionType DataConnectionType { get; set; }
bool UngracefullDisconnection { get; set; }
int ConnectTimeout { get; set; }
int ReadTimeout { get; set; }
int DataConnectionConnectTimeout { get; set; }
int DataConnectionReadTimeout { get; set; }
bool SocketKeepAlive { get; set; }
List<FtpCapability> Capabilities { get; }
FtpHashAlgorithm HashAlgorithms { get; }
FtpEncryptionMode EncryptionMode { get; set; }
bool DataConnectionEncryption { get; set; }
#if !CORE
bool PlainTextEncryption { get; set; }
#endif
SslProtocols SslProtocols { get; set; }
FtpsBuffering SslBuffering { get; set; }
event FtpSslValidation ValidateCertificate;
bool ValidateAnyCertificate { get; set; }
bool ValidateCertificateRevocation { get; set; }
string SystemType { get; }
FtpServer ServerType { get; }
FtpBaseServer ServerHandler { get; set; }
FtpOperatingSystem ServerOS { get; }
string ConnectionType { get; }
FtpReply LastReply { get; }
FtpDataType ListingDataType { get; set; }
FtpParser ListingParser { get; set; }
CultureInfo ListingCulture { get; set; }
bool RecursiveList { get; set; }
double TimeZone { get; set; }
#if CORE
double LocalTimeZone { get; set; }
#endif
FtpDate TimeConversion { get; set; }
bool BulkListing { get; set; }
int BulkListingLength { get; set; }
int TransferChunkSize { get; set; }
int LocalFileBufferSize { get; set; }
int RetryAttempts { get; set; }
uint UploadRateLimit { get; set; }
uint DownloadRateLimit { get; set; }
bool DownloadZeroByteFiles { get; set; }
FtpDataType UploadDataType { get; set; }
FtpDataType DownloadDataType { get; set; }
bool UploadDirectoryDeleteExcluded { get; set; }
bool DownloadDirectoryDeleteExcluded { get; set; }
FtpDataType FXPDataType { get; set; }
int FXPProgressInterval { get; set; }
bool SendHost { get; set; }
string SendHostDomain { get; set; }
// METHODS
FtpReply Execute(string command);
FtpReply GetReply();
void Connect();
void Connect(FtpProfile profile);
List<FtpProfile> AutoDetect(bool firstOnly = true, bool cloneConnection = true);
FtpProfile AutoConnect();
void Disconnect();
bool HasFeature(FtpCapability cap);
void DisableUTF8();
#if ASYNC
Task<FtpReply> ExecuteAsync(string command, CancellationToken token = default(CancellationToken));
Task<FtpReply> GetReplyAsync(CancellationToken token = default(CancellationToken));
Task ConnectAsync(CancellationToken token = default(CancellationToken));
Task ConnectAsync(FtpProfile profile, CancellationToken token = default(CancellationToken));
Task<List<FtpProfile>> AutoDetectAsync(bool firstOnly = true, bool cloneConnection = true, CancellationToken token = default(CancellationToken));
Task<FtpProfile> AutoConnectAsync(CancellationToken token = default(CancellationToken));
Task DisconnectAsync(CancellationToken token = default(CancellationToken));
#endif
// MANAGEMENT
void DeleteFile(string path);
void DeleteDirectory(string path);
void DeleteDirectory(string path, FtpListOption options);
bool DirectoryExists(string path);
bool FileExists(string path);
bool CreateDirectory(string path);
bool CreateDirectory(string path, bool force);
void Rename(string path, string dest);
bool MoveFile(string path, string dest, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite);
bool MoveDirectory(string path, string dest, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite);
void SetFilePermissions(string path, int permissions);
void Chmod(string path, int permissions);
void SetFilePermissions(string path, FtpPermission owner, FtpPermission group, FtpPermission other);
void Chmod(string path, FtpPermission owner, FtpPermission group, FtpPermission other);
FtpListItem GetFilePermissions(string path);
int GetChmod(string path);
FtpListItem DereferenceLink(FtpListItem item);
FtpListItem DereferenceLink(FtpListItem item, int recMax);
void SetWorkingDirectory(string path);
string GetWorkingDirectory();
long GetFileSize(string path, long defaultValue = -1);
DateTime GetModifiedTime(string path);
void SetModifiedTime(string path, DateTime date);
#if ASYNC
Task DeleteFileAsync(string path, CancellationToken token = default(CancellationToken));
Task DeleteDirectoryAsync(string path, CancellationToken token = default(CancellationToken));
Task DeleteDirectoryAsync(string path, FtpListOption options, CancellationToken token = default(CancellationToken));
Task<bool> DirectoryExistsAsync(string path, CancellationToken token = default(CancellationToken));
Task<bool> FileExistsAsync(string path, CancellationToken token = default(CancellationToken));
Task<bool> CreateDirectoryAsync(string path, bool force, CancellationToken token = default(CancellationToken));
Task<bool> CreateDirectoryAsync(string path, CancellationToken token = default(CancellationToken));
Task RenameAsync(string path, string dest, CancellationToken token = default(CancellationToken));
Task<bool> MoveFileAsync(string path, string dest, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, CancellationToken token = default(CancellationToken));
Task<bool> MoveDirectoryAsync(string path, string dest, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, CancellationToken token = default(CancellationToken));
Task SetFilePermissionsAsync(string path, int permissions, CancellationToken token = default(CancellationToken));
Task ChmodAsync(string path, int permissions, CancellationToken token = default(CancellationToken));
Task SetFilePermissionsAsync(string path, FtpPermission owner, FtpPermission group, FtpPermission other, CancellationToken token = default(CancellationToken));
Task ChmodAsync(string path, FtpPermission owner, FtpPermission group, FtpPermission other, CancellationToken token = default(CancellationToken));
Task<FtpListItem> GetFilePermissionsAsync(string path, CancellationToken token = default(CancellationToken));
Task<int> GetChmodAsync(string path, CancellationToken token = default(CancellationToken));
Task<FtpListItem> DereferenceLinkAsync(FtpListItem item, int recMax, CancellationToken token = default(CancellationToken));
Task<FtpListItem> DereferenceLinkAsync(FtpListItem item, CancellationToken token = default(CancellationToken));
Task SetWorkingDirectoryAsync(string path, CancellationToken token = default(CancellationToken));
Task<string> GetWorkingDirectoryAsync(CancellationToken token = default(CancellationToken));
Task<long> GetFileSizeAsync(string path, long defaultValue = -1, CancellationToken token = default(CancellationToken));
Task<DateTime> GetModifiedTimeAsync(string path, CancellationToken token = default(CancellationToken));
Task SetModifiedTimeAsync(string path, DateTime date, CancellationToken token = default(CancellationToken));
#endif
// LISTING
FtpListItem GetObjectInfo(string path, bool dateModified = false);
FtpListItem[] GetListing();
FtpListItem[] GetListing(string path);
FtpListItem[] GetListing(string path, FtpListOption options);
string[] GetNameListing();
string[] GetNameListing(string path);
#if ASYNC
Task<FtpListItem> GetObjectInfoAsync(string path, bool dateModified = false, CancellationToken token = default(CancellationToken));
Task<FtpListItem[]> GetListingAsync(string path, FtpListOption options, CancellationToken token = default(CancellationToken));
Task<FtpListItem[]> GetListingAsync(string path, CancellationToken token = default(CancellationToken));
Task<FtpListItem[]> GetListingAsync(CancellationToken token = default(CancellationToken));
Task<string[]> GetNameListingAsync(string path, CancellationToken token = default(CancellationToken));
Task<string[]> GetNameListingAsync(CancellationToken token = default(CancellationToken));
#endif
#if ASYNCPLUS
IAsyncEnumerable<FtpListItem> GetListingAsyncEnumerable(string path, FtpListOption options, CancellationToken token = default(CancellationToken), CancellationToken enumToken = default(CancellationToken));
IAsyncEnumerable<FtpListItem> GetListingAsyncEnumerable(string path, CancellationToken token = default(CancellationToken), CancellationToken enumToken = default(CancellationToken));
IAsyncEnumerable<FtpListItem> GetListingAsyncEnumerable(CancellationToken token = default(CancellationToken), CancellationToken enumToken = default(CancellationToken));
#endif
// LOW LEVEL
Stream OpenRead(string path, FtpDataType type = FtpDataType.Binary, long restart = 0, bool checkIfFileExists = true);
Stream OpenRead(string path, FtpDataType type, long restart, long fileLen);
Stream OpenWrite(string path, FtpDataType type = FtpDataType.Binary, bool checkIfFileExists = true);
Stream OpenWrite(string path, FtpDataType type, long fileLen);
Stream OpenAppend(string path, FtpDataType type = FtpDataType.Binary, bool checkIfFileExists = true);
Stream OpenAppend(string path, FtpDataType type, long fileLen);
#if ASYNC
Task<Stream> OpenReadAsync(string path, FtpDataType type = FtpDataType.Binary, long restart = 0, bool checkIfFileExists = true, CancellationToken token = default(CancellationToken));
Task<Stream> OpenReadAsync(string path, FtpDataType type, long restart, long fileLen, CancellationToken token = default(CancellationToken));
Task<Stream> OpenWriteAsync(string path, FtpDataType type = FtpDataType.Binary, bool checkIfFileExists = true, CancellationToken token = default(CancellationToken));
Task<Stream> OpenWriteAsync(string path, FtpDataType type, long fileLen, CancellationToken token = default(CancellationToken));
Task<Stream> OpenAppendAsync(string path, FtpDataType type = FtpDataType.Binary, bool checkIfFileExists = true, CancellationToken token = default(CancellationToken));
Task<Stream> OpenAppendAsync(string path, FtpDataType type, long fileLen, CancellationToken token = default(CancellationToken));
#endif
// HIGH LEVEL
int UploadFiles(IEnumerable<string> localPaths, string remoteDir, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, bool createRemoteDir = true, FtpVerify verifyOptions = FtpVerify.None, FtpError errorHandling = FtpError.None, Action<FtpProgress> progress = null);
int UploadFiles(IEnumerable<FileInfo> localFiles, string remoteDir, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, bool createRemoteDir = true, FtpVerify verifyOptions = FtpVerify.None, FtpError errorHandling = FtpError.None, Action<FtpProgress> progress = null);
int DownloadFiles(string localDir, IEnumerable<string> remotePaths, FtpLocalExists existsMode = FtpLocalExists.Overwrite, FtpVerify verifyOptions = FtpVerify.None, FtpError errorHandling = FtpError.None, Action<FtpProgress> progress = null);
FtpStatus UploadFile(string localPath, string remotePath, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, bool createRemoteDir = false, FtpVerify verifyOptions = FtpVerify.None, Action<FtpProgress> progress = null);
FtpStatus Upload(Stream fileStream, string remotePath, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, bool createRemoteDir = false, Action<FtpProgress> progress = null);
FtpStatus Upload(byte[] fileData, string remotePath, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, bool createRemoteDir = false, Action<FtpProgress> progress = null);
FtpStatus DownloadFile(string localPath, string remotePath, FtpLocalExists existsMode = FtpLocalExists.Overwrite, FtpVerify verifyOptions = FtpVerify.None, Action<FtpProgress> progress = null);
bool Download(Stream outStream, string remotePath, long restartPosition = 0, Action<FtpProgress> progress = null);
bool Download(out byte[] outBytes, string remotePath, long restartPosition = 0, Action<FtpProgress> progress = null);
List<FtpResult> DownloadDirectory(string localFolder, string remoteFolder, FtpFolderSyncMode mode = FtpFolderSyncMode.Update, FtpLocalExists existsMode = FtpLocalExists.Skip, FtpVerify verifyOptions = FtpVerify.None, List<FtpRule> rules = null, Action<FtpProgress> progress = null);
List<FtpResult> UploadDirectory(string localFolder, string remoteFolder, FtpFolderSyncMode mode = FtpFolderSyncMode.Update, FtpRemoteExists existsMode = FtpRemoteExists.Skip, FtpVerify verifyOptions = FtpVerify.None, List<FtpRule> rules = null, Action<FtpProgress> progress = null);
#if ASYNC
Task<int> UploadFilesAsync(IEnumerable<string> localPaths, string remoteDir, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, bool createRemoteDir = true, FtpVerify verifyOptions = FtpVerify.None, FtpError errorHandling = FtpError.None, CancellationToken token = default(CancellationToken), IProgress<FtpProgress> progress = null);
Task<int> DownloadFilesAsync(string localDir, IEnumerable<string> remotePaths, FtpLocalExists existsMode = FtpLocalExists.Overwrite, FtpVerify verifyOptions = FtpVerify.None, FtpError errorHandling = FtpError.None, CancellationToken token = default(CancellationToken), IProgress<FtpProgress> progress = null);
Task<FtpStatus> UploadFileAsync(string localPath, string remotePath, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, bool createRemoteDir = false, FtpVerify verifyOptions = FtpVerify.None, IProgress<FtpProgress> progress = null, CancellationToken token = default(CancellationToken));
Task<FtpStatus> UploadAsync(Stream fileStream, string remotePath, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, bool createRemoteDir = false, IProgress<FtpProgress> progress = null, CancellationToken token = default(CancellationToken));
Task<FtpStatus> UploadAsync(byte[] fileData, string remotePath, FtpRemoteExists existsMode = FtpRemoteExists.Overwrite, bool createRemoteDir = false, IProgress<FtpProgress> progress = null, CancellationToken token = default(CancellationToken));
Task<FtpStatus> DownloadFileAsync(string localPath, string remotePath, FtpLocalExists existsMode = FtpLocalExists.Overwrite, FtpVerify verifyOptions = FtpVerify.None, IProgress<FtpProgress> progress = null, CancellationToken token = default(CancellationToken));
Task<bool> DownloadAsync(Stream outStream, string remotePath, long restartPosition = 0, IProgress<FtpProgress> progress = null, CancellationToken token = default(CancellationToken));
Task<byte[]> DownloadAsync(string remotePath, long restartPosition = 0, IProgress<FtpProgress> progress = null, CancellationToken token = default(CancellationToken));
Task<List<FtpResult>> DownloadDirectoryAsync(string localFolder, string remoteFolder, FtpFolderSyncMode mode = FtpFolderSyncMode.Update, FtpLocalExists existsMode = FtpLocalExists.Skip, FtpVerify verifyOptions = FtpVerify.None, List<FtpRule> rules = null, IProgress<FtpProgress> progress = null, CancellationToken token = default(CancellationToken));
Task<List<FtpResult>> UploadDirectoryAsync(string localFolder, string remoteFolder, FtpFolderSyncMode mode = FtpFolderSyncMode.Update, FtpRemoteExists existsMode = FtpRemoteExists.Skip, FtpVerify verifyOptions = FtpVerify.None, List<FtpRule> rules = null, IProgress<FtpProgress> progress = null, CancellationToken token = default(CancellationToken));
#endif
// HASH
FtpHash GetChecksum(string path, FtpHashAlgorithm algorithm = FtpHashAlgorithm.NONE);
#if ASYNC
Task<FtpHash> GetChecksumAsync(string path, FtpHashAlgorithm algorithm = FtpHashAlgorithm.NONE, CancellationToken token = default(CancellationToken));
#endif
}
}
| |
using SFML.Graphics;
using SFML.System;
using SFML.Window;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Iris
{
public class Menu : Gamestate
{
int stage = 0;
private static RenderStates shader;
public string usernameField = "Username";
public string ipField = "giga.krash.net";
public bool composingUsername = false;
public bool composingIP = false;
public float trainPosX = -250;
public StringBuilder activeField = new StringBuilder("");
private RectangleShape rectConnect;
private RectangleShape rectIP;
private RectangleShape rectUsername;
private bool submitted;
private Texture currentCursor, defaultCursor, hoverCursor;
private int submitTimer = 0;
Animation char1, char2;
public Menu()
: base()
{
hoverCursor = Content.GetTexture("cursorHover.png");
defaultCursor = Content.GetTexture("cursorPointer.png");
currentCursor = defaultCursor;
char1 = new Animation(Content.GetTexture("idle.png"), 4, 0, 0, true);
char2 = new Animation(Content.GetTexture("char2_idle.png"), 4, 0, 0, true);
shader = new RenderStates(new Shader(null, "Content/bgPrlx.frag"));
rectConnect = new RectangleShape()
{
Size = new Vector2f(150, 30),
Position = new Vector2f(-25, 70)
};
rectIP = new RectangleShape()
{
Size = new Vector2f(150, 20),
Position = new Vector2f(-25, 40)
};
rectUsername = new RectangleShape()
{
Size = new Vector2f(150, 20),
Position = new Vector2f(-25, 10)
};
MainGame.window.TextEntered += TextEnteredEvent;
}
public void TextEnteredEvent(Object sender, TextEventArgs e)
{
if (Keyboard.IsKeyPressed(Keyboard.Key.BackSpace))
{
if (activeField.Length > 0)
{
activeField = activeField.Remove(activeField.Length - 1, 1);
MainGame.soundInstances.Add(new SoundInstance(Content.GetSound("dryFireSfx.wav"), 1, 0, 1));
}
}
else if (Keyboard.IsKeyPressed(Keyboard.Key.Return))
{
}
else if (Keyboard.IsKeyPressed(Keyboard.Key.LControl))
{
}
else if (Keyboard.IsKeyPressed(Keyboard.Key.Escape))
{
}
else if (Keyboard.IsKeyPressed(Keyboard.Key.Tab))
{
}
else
{
if (activeField.Length < 20)
{
activeField.Append(e.Unicode);
MainGame.soundInstances.Add(new SoundInstance(Content.GetSound("dryFireSfx.wav"), 1, 0, 1));
}
}
}
public override void Update()
{
//move the train
//Reset cursor
currentCursor = defaultCursor;
trainPosX += .7f;
if (trainPosX > 400)
trainPosX = -250f;
if (!submitted)
{
UpdateMenuGui();
}
else if (MainGame.dm.Mailman.FullyConnected)
{
MainGame.window.TextEntered -= TextEnteredEvent;
MainGame.dm.player.Name = usernameField;
MainGame.gamestate = MainGame.dm;
}
}
private void UpdateMenuGui()
{
if (stage == 0)
{
//handle paste
if (Clipboard.ContainsText())
{
if (Input.isKeyDown(Keyboard.Key.LControl) && Input.isKeyTap(Keyboard.Key.V))
{
activeField.Append(Clipboard.GetText());
}
}
//max length for any active field
if (activeField.Length > 20)
{
activeField.Remove(20, activeField.Length - 20);
}
//tab switching
if (Input.isKeyTap(Keyboard.Key.Tab))
{
if (composingUsername)
{
MainGame.soundInstances.Add(new SoundInstance(Content.GetSound("click.wav"), 1, 0, 5));
composingUsername = false;
composingIP = true;
}
else if (composingIP)
{
MainGame.soundInstances.Add(new SoundInstance(Content.GetSound("click.wav"), 1, 0, 5));
composingUsername = false;
composingIP = false;
}
activeField.Clear();
}
//update the textboxes display
if (composingIP)
ipField = activeField.ToString();
if (composingUsername)
usernameField = activeField.ToString();
if (rectUsername.GetGlobalBounds().Contains(MainGame.worldMousePos.X, MainGame.worldMousePos.Y))
{
currentCursor = hoverCursor;
}
if (rectIP.GetGlobalBounds().Contains(MainGame.worldMousePos.X, MainGame.worldMousePos.Y))
{
currentCursor = hoverCursor;
}
if (rectConnect.GetGlobalBounds().Contains(MainGame.worldMousePos.X, MainGame.worldMousePos.Y))
{
currentCursor = hoverCursor;
}
//reset click
if (Input.isMouseButtonTap(Mouse.Button.Left))
{
composingUsername = false;
composingIP = false;
if (usernameField.Trim().Equals(""))
usernameField = "Username";
if (ipField.Trim().Equals(""))
ipField = "Server IP";
activeField.Clear();
MainGame.soundInstances.Add(new SoundInstance(Content.GetSound("click.wav"), 1, 0, 5));
//click to activate username textbox
if (rectUsername.GetGlobalBounds().Contains(MainGame.worldMousePos.X, MainGame.worldMousePos.Y))
{
currentCursor = hoverCursor;
composingUsername = true;
if (usernameField.Equals("Username"))
{
usernameField = "";
}
}
//else, click to activate ip textbox
else if (rectIP.GetGlobalBounds().Contains(MainGame.worldMousePos.X, MainGame.worldMousePos.Y))
{
composingIP = true;
if (ipField.Equals("Server IP"))
{
ipField = "";
}
}
//else, click to activate connect button
else if (rectConnect.GetGlobalBounds().Contains(MainGame.worldMousePos.X, MainGame.worldMousePos.Y))
{
if (BoxesValid)
{
stage = 1;
}
}
}
//Hit enter to connect as well
if (Input.isKeyDown(SFML.Window.Keyboard.Key.Return))
{
if (BoxesValid)
{
stage = 1;
MainGame.soundInstances.Add(new SoundInstance(Content.GetSound("click.wav"), 1, 0, 5));
}
}
//if (Input.isKeyTap(Keyboard.Key.Q))
//{
// ipField = "giga.krash.net";
// usernameField = "Quick Draw McGraw";
// Submit();
//}
}
}
public override void Draw()
{
//blue sky
MainGame.window.SetView(MainGame.window.DefaultView);
shader.Shader.SetParameter("offsetY", MainGame.Camera.Center.Y);
RectangleShape rs = new RectangleShape
{
Size = new Vector2f(800, 600)
};
MainGame.window.Draw(rs, shader);
MainGame.window.SetView(MainGame.Camera);
//background
Render.Draw(Content.GetTexture("background1Far.png"), new Vector2f(-200, -100), Color.White, new Vector2f(0, 0), 1, 0f);
Render.Draw(Content.GetTexture("background1Far.png"), new Vector2f(145, -100), Color.White, new Vector2f(0, 0), 1, 0f);
Render.Draw(Content.GetTexture("background1.png"), new Vector2f(-200, -150), Color.White, new Vector2f(0, 0), 1, 0f);
//tracks
RectangleShape tracks = new RectangleShape(new Vector2f(800, .5f));
tracks.Position = new Vector2f(-400, -49);
tracks.FillColor = new Color(10, 10, 10, 50);
tracks.Draw(MainGame.window, RenderStates.Default);
//train
Render.Draw(Content.GetTexture("mapDecor.png"), new Vector2f(trainPosX, -55), new Color(255, 255, 255, 200), new Vector2f(0, 0), 1, 0f, .03f);
//title
Render.Draw(Content.GetTexture("title.png"), new Vector2f(-50, -190), new Color(255, 255, 255, 240), new Vector2f(0, 0), 1, 0f, .4f);
if (stage == 0)
{
//menubox
RectangleShape rectBG = new RectangleShape(new Vector2f(200, 110));
rectBG.Position = new Vector2f(-50, 0);
rectBG.FillColor = new Color(10, 10, 10, 100);
rectBG.Draw(MainGame.window, RenderStates.Default);
if (!submitted)
{
//menu username
rectUsername.FillColor = new Color(10, 10, 10, (byte)(composingUsername ? 150 : 50));
rectUsername.Draw(MainGame.window, RenderStates.Default);
//menu ip
rectIP.FillColor = new Color(10, 10, 10, (byte)(composingIP ? 150 : 50));
rectIP.Draw(MainGame.window, RenderStates.Default);
//menu connect button
rectConnect.FillColor = new Color(10, 255, 10,
(byte)(rectConnect.GetGlobalBounds().Contains(
(int)MainGame.worldMousePos.X, (int)MainGame.worldMousePos.Y) ? 150 : 70));
rectConnect.Draw(MainGame.window, RenderStates.Default);
//text: username, ip, connect button
Render.DrawString(Content.GetFont("OldNewspaperTypes.ttf"), usernameField, new Vector2f(50, 15), Color.White, .3f, true, 1);
Render.DrawString(Content.GetFont("OldNewspaperTypes.ttf"), ipField, new Vector2f(50, 45), Color.White, .3f, true, 1);
Render.DrawString(Content.GetFont("OldNewspaperTypes.ttf"), "Connect", new Vector2f(50, 77), Color.White, .4f, true, 1);
}
else
{
Render.DrawString(Content.GetFont("OldNewspaperTypes.ttf"), "Connecting...", new Vector2f(50, 15), Color.White, .3f, true, 1);
submitTimer++;
if (submitTimer > 300)
{
submitted = false;
submitTimer = 0;
ipField = "Failed to Connect";
}
}
}
if (stage == 1)
{
RectangleShape rectBG = new RectangleShape(new Vector2f(200, 110));
rectBG.Position = new Vector2f(-50, 0);
rectBG.FillColor = new Color(10, 10, 10, 100);
rectBG.Draw(MainGame.window, RenderStates.Default);
//char1.Update();
//char2.Update();
Render.DrawAnimation(char1.Texture, new Vector2f(-0, 5), Color.White, new Vector2f(0, 0), 1, char1.Count, char1.Frame);
Render.DrawAnimation(char2.Texture, new Vector2f(100, 5), Color.White, new Vector2f(0, 0), -1, char2.Count, char2.Frame);
//Render.Draw(Content.GetTexture("gibHead.png"), new Vector2f(40, 10), Color.White, new Vector2f(0, 0), 1, 0, 2);
//Render.Draw(Content.GetTexture("char2_gibHead.png"), new Vector2f(0, 10), Color.White, new Vector2f(0, 0), 1, 0, 2);
FloatRect leftRect = new FloatRect(new Vector2f(0, 5), new Vector2f(20, 55));
FloatRect rightRect = new FloatRect(new Vector2f(75, 5), new Vector2f(20, 55));
if (leftRect.Contains(MainGame.worldMousePos.X, MainGame.worldMousePos.Y))
{
currentCursor = hoverCursor;
if (Input.isMouseButtonTap(Mouse.Button.Left))
{
stage = 2;
MainGame.dm.player.model = MainGame.Char1Model;
MainGame.dm.player.UpdateToCurrentModel();
return;
}
}
if (rightRect.Contains(MainGame.worldMousePos.X, MainGame.worldMousePos.Y))
{
currentCursor = hoverCursor;
if (Input.isMouseButtonTap(Mouse.Button.Left))
{
stage = 2;
MainGame.dm.player.model = MainGame.Char2Model;
MainGame.dm.player.UpdateToCurrentModel();
return;
}
}
rectConnect.Draw(MainGame.window, RenderStates.Default);
Render.DrawString(Content.GetFont("OldNewspaperTypes.ttf"), "Select Character", new Vector2f(50, 77), Color.White, .4f, true, 1);
}
if (stage == 2)
{
RectangleShape rectBG = new RectangleShape(new Vector2f(200, 110));
rectBG.Position = new Vector2f(-50, 0);
rectBG.FillColor = new Color(10, 10, 10, 100);
rectBG.Draw(MainGame.window, RenderStates.Default);
Render.Draw(Content.GetTexture("generatorStand.png"), new Vector2f(-10, 5), Color.White, new Vector2f(0, 0), 1, 0f);
Render.Draw(Content.GetTexture("genBlue.png"), new Vector2f(-10, 5), Color.White, new Vector2f(0, 0), 1, 0f);
Render.DrawString(Content.GetFont("PixelSix.ttf"), " Shield\nGenerator", new Vector2f(0, 45), Color.White, .3f, true, 1);
Render.Draw(Content.GetTexture("mine.png"), new Vector2f(40, 30), Color.White, new Vector2f(0, 0), 1, 0f);
Render.Draw(Content.GetTexture("mine.png"), new Vector2f(40, 30), Color.White, new Vector2f(0, 0), 1, 0f);
Render.DrawString(Content.GetFont("PixelSix.ttf"), "Land\nMine", new Vector2f(50, 45), Color.White, .3f, true, 1);
Render.Draw(Content.GetTexture("generatorStand.png"), new Vector2f(90, 5), Color.White, new Vector2f(0, 0), 1, 0f);
Render.Draw(Content.GetTexture("genGreen.png"), new Vector2f(90, 5), Color.White, new Vector2f(0, 0), 1, 0f);
Render.DrawString(Content.GetFont("PixelSix.ttf"), " Health\nGenerator", new Vector2f(100, 45), Color.White, .3f, true, 1);
FloatRect genShieldRect = new FloatRect(new Vector2f(-10, 5), new Vector2f(20, 55));
FloatRect genHealthRect = new FloatRect(new Vector2f(90, 5), new Vector2f(20, 55));
FloatRect MineRect = new FloatRect(new Vector2f(40, 5), new Vector2f(20, 55));
if (genShieldRect.Contains(MainGame.worldMousePos.X, MainGame.worldMousePos.Y))
{
currentCursor = hoverCursor;
if (Input.isMouseButtonTap(Mouse.Button.Left))
{
MainGame.dm.player.ItemType = 3; // Shield Generator
Submit();
}
}
if (genHealthRect.Contains(MainGame.worldMousePos.X, MainGame.worldMousePos.Y))
{
currentCursor = hoverCursor;
if (Input.isMouseButtonTap(Mouse.Button.Left))
{
MainGame.dm.player.ItemType = 2; // Health Generator
Submit();
}
}
if (MineRect.Contains(MainGame.worldMousePos.X, MainGame.worldMousePos.Y))
{
currentCursor = hoverCursor;
if (Input.isMouseButtonTap(Mouse.Button.Left))
{
MainGame.dm.player.ItemType = 1; // Land Mines
Submit();
}
}
rectConnect.Draw(MainGame.window, RenderStates.Default);
Render.DrawString(Content.GetFont("OldNewspaperTypes.ttf"), "Select Item", new Vector2f(50, 77), Color.White, .4f, true, 1);
}
//cursor
Render.Draw(currentCursor, MainGame.worldMousePos, Color.White, new Vector2f(0, 0), 1, 0f);
}
public bool BoxesValid
{
get
{
return ipField.Trim() != "Server IP" && usernameField.Trim() != "Username" && !MainGame.containsProfanity(usernameField);
}
}
public void Submit()
{
ClientMailman.ip = ipField;
stage = 0;
if (MainGame.dm.Mailman.Connect())
{
submitted = true;
}
else
{
MainGame.soundInstances.Add(new SoundInstance(Content.GetSound("error.wav"), 1, 0, 10));
ipField = "Failed to Connect";
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Internal;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.CommandLineUtils;
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk;
using static Templates.Test.Helpers.ProcessLock;
namespace Templates.Test.Helpers
{
[DebuggerDisplay("{ToString(),nq}")]
public class Project : IDisposable
{
private const string _urls = "http://127.0.0.1:0;https://127.0.0.1:0";
public static string ArtifactsLogDir
{
get
{
var testLogFolder = typeof(Project).Assembly.GetCustomAttribute<TestFrameworkFileLoggerAttribute>()?.BaseDirectory;
if (!string.IsNullOrEmpty(testLogFolder))
{
return testLogFolder;
}
var helixWorkItemUploadRoot = Environment.GetEnvironmentVariable("HELIX_WORKITEM_UPLOAD_ROOT");
return string.IsNullOrEmpty(helixWorkItemUploadRoot) ? GetAssemblyMetadata("ArtifactsLogDir") : helixWorkItemUploadRoot;
}
}
public static string DotNetEfFullPath => (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DotNetEfFullPath")))
? typeof(ProjectFactoryFixture).Assembly.GetCustomAttributes<AssemblyMetadataAttribute>()
.First(attribute => attribute.Key == "DotNetEfFullPath")
.Value
: Environment.GetEnvironmentVariable("DotNetEfFullPath");
public string ProjectName { get; set; }
public string ProjectArguments { get; set; }
public string ProjectGuid { get; set; }
public string TemplateOutputDir { get; set; }
public string TargetFramework { get; set; } = GetAssemblyMetadata("Test.DefaultTargetFramework");
public string RuntimeIdentifier { get; set; } = string.Empty;
public static DevelopmentCertificate DevCert { get; } = DevelopmentCertificate.Create(AppContext.BaseDirectory);
public string TemplateBuildDir => Path.Combine(TemplateOutputDir, "bin", "Debug", TargetFramework, RuntimeIdentifier);
public string TemplatePublishDir => Path.Combine(TemplateOutputDir, "bin", "Release", TargetFramework, RuntimeIdentifier, "publish");
public ITestOutputHelper Output { get; set; }
public IMessageSink DiagnosticsMessageSink { get; set; }
internal async Task<ProcessResult> RunDotNetNewAsync(
string templateName,
string auth = null,
string language = null,
bool useLocalDB = false,
bool noHttps = false,
bool errorOnRestoreError = true,
string[] args = null,
// Used to set special options in MSBuild
IDictionary<string, string> environmentVariables = null)
{
var hiveArg = $" --debug:disable-sdk-templates --debug:custom-hive \"{TemplatePackageInstaller.CustomHivePath}\"";
var argString = $"new {templateName} {hiveArg}";
environmentVariables ??= new Dictionary<string, string>();
if (!string.IsNullOrEmpty(auth))
{
argString += $" --auth {auth}";
}
if (!string.IsNullOrEmpty(language))
{
argString += $" -lang {language}";
}
if (useLocalDB)
{
argString += $" --use-local-db";
}
if (noHttps)
{
argString += $" --no-https";
}
if (args != null)
{
foreach (var arg in args)
{
argString += " " + arg;
}
}
// Save a copy of the arguments used for better diagnostic error messages later.
// We omit the hive argument and the template output dir as they are not relevant and add noise.
ProjectArguments = argString.Replace(hiveArg, "");
argString += $" -o {TemplateOutputDir}";
// Only run one instance of 'dotnet new' at once, as a workaround for
// https://github.com/aspnet/templating/issues/63
await DotNetNewLock.WaitAsync();
try
{
Output.WriteLine("Acquired DotNetNewLock");
if (Directory.Exists(TemplateOutputDir))
{
Output.WriteLine($"Template directory already exists, deleting contents of {TemplateOutputDir}");
Directory.Delete(TemplateOutputDir, recursive: true);
}
using var execution = ProcessEx.Run(Output, AppContext.BaseDirectory, DotNetMuxer.MuxerPathOrDefault(), argString, environmentVariables);
await execution.Exited;
var result = new ProcessResult(execution);
// Because dotnet new automatically restores but silently ignores restore errors, need to handle restore errors explicitly
if (errorOnRestoreError && (execution.Output.Contains("Restore failed.") || execution.Error.Contains("Restore failed.")))
{
result.ExitCode = -1;
}
return result;
}
finally
{
DotNetNewLock.Release();
Output.WriteLine("Released DotNetNewLock");
}
}
internal async Task<ProcessResult> RunDotNetPublishAsync(IDictionary<string, string> packageOptions = null, string additionalArgs = null, bool noRestore = true)
{
Output.WriteLine("Publishing ASP.NET Core application...");
// Avoid restoring as part of build or publish. These projects should have already restored as part of running dotnet new. Explicitly disabling restore
// should avoid any global contention and we can execute a build or publish in a lock-free way
var restoreArgs = noRestore ? "--no-restore" : null;
using var result = ProcessEx.Run(Output, TemplateOutputDir, DotNetMuxer.MuxerPathOrDefault(), $"publish {restoreArgs} -c Release /bl {additionalArgs}", packageOptions);
await result.Exited;
CaptureBinLogOnFailure(result);
return new ProcessResult(result);
}
internal async Task<ProcessResult> RunDotNetBuildAsync(IDictionary<string, string> packageOptions = null, string additionalArgs = null)
{
Output.WriteLine("Building ASP.NET Core application...");
// Avoid restoring as part of build or publish. These projects should have already restored as part of running dotnet new. Explicitly disabling restore
// should avoid any global contention and we can execute a build or publish in a lock-free way
using var result = ProcessEx.Run(Output, TemplateOutputDir, DotNetMuxer.MuxerPathOrDefault(), $"build --no-restore -c Debug /bl {additionalArgs}", packageOptions);
await result.Exited;
CaptureBinLogOnFailure(result);
return new ProcessResult(result);
}
internal AspNetProcess StartBuiltProjectAsync(bool hasListeningUri = true, ILogger logger = null)
{
var environment = new Dictionary<string, string>
{
["ASPNETCORE_URLS"] = _urls,
["ASPNETCORE_ENVIRONMENT"] = "Development",
["ASPNETCORE_Logging__Console__LogLevel__Default"] = "Debug",
["ASPNETCORE_Logging__Console__LogLevel__System"] = "Debug",
["ASPNETCORE_Logging__Console__LogLevel__Microsoft"] = "Debug",
["ASPNETCORE_Logging__Console__FormatterOptions__IncludeScopes"] = "true",
};
var projectDll = Path.Combine(TemplateBuildDir, $"{ProjectName}.dll");
return new AspNetProcess(DevCert, Output, TemplateOutputDir, projectDll, environment, published: false, hasListeningUri: hasListeningUri, logger: logger);
}
internal AspNetProcess StartPublishedProjectAsync(bool hasListeningUri = true, bool usePublishedAppHost = false)
{
var environment = new Dictionary<string, string>
{
["ASPNETCORE_URLS"] = _urls,
["ASPNETCORE_Logging__Console__LogLevel__Default"] = "Debug",
["ASPNETCORE_Logging__Console__LogLevel__System"] = "Debug",
["ASPNETCORE_Logging__Console__LogLevel__Microsoft"] = "Debug",
["ASPNETCORE_Logging__Console__FormatterOptions__IncludeScopes"] = "true",
};
var projectDll = Path.Combine(TemplatePublishDir, $"{ProjectName}.dll");
return new AspNetProcess(DevCert, Output, TemplatePublishDir, projectDll, environment, published: true, hasListeningUri: hasListeningUri, usePublishedAppHost: usePublishedAppHost);
}
internal async Task<ProcessResult> RunDotNetEfCreateMigrationAsync(string migrationName)
{
var args = $"--verbose --no-build migrations add {migrationName}";
// Only run one instance of 'dotnet new' at once, as a workaround for
// https://github.com/aspnet/templating/issues/63
await DotNetNewLock.WaitAsync();
try
{
Output.WriteLine("Acquired DotNetNewLock");
var command = DotNetMuxer.MuxerPathOrDefault();
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DotNetEfFullPath")))
{
args = $"\"{DotNetEfFullPath}\" " + args;
}
else
{
command = "dotnet-ef";
}
using var result = ProcessEx.Run(Output, TemplateOutputDir, command, args);
await result.Exited;
return new ProcessResult(result);
}
finally
{
DotNetNewLock.Release();
Output.WriteLine("Released DotNetNewLock");
}
}
internal async Task<ProcessResult> RunDotNetEfUpdateDatabaseAsync()
{
var assembly = typeof(ProjectFactoryFixture).Assembly;
var args = "--verbose --no-build database update";
// Only run one instance of 'dotnet new' at once, as a workaround for
// https://github.com/aspnet/templating/issues/63
await DotNetNewLock.WaitAsync();
try
{
Output.WriteLine("Acquired DotNetNewLock");
var command = DotNetMuxer.MuxerPathOrDefault();
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DotNetEfFullPath")))
{
args = $"\"{DotNetEfFullPath}\" " + args;
}
else
{
command = "dotnet-ef";
}
using var result = ProcessEx.Run(Output, TemplateOutputDir, command, args);
await result.Exited;
return new ProcessResult(result);
}
finally
{
DotNetNewLock.Release();
Output.WriteLine("Released DotNetNewLock");
}
}
// If this fails, you should generate new migrations via migrations/updateMigrations.cmd
public void AssertEmptyMigration(string migration)
{
var fullPath = Path.Combine(TemplateOutputDir, "Data/Migrations");
var file = Directory.EnumerateFiles(fullPath).Where(f => f.EndsWith($"{migration}.cs", StringComparison.Ordinal)).FirstOrDefault();
Assert.NotNull(file);
var contents = File.ReadAllText(file);
var emptyMigration = @"protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}";
// This comparison can break depending on how GIT checked out newlines on different files.
Assert.Contains(RemoveNewLines(emptyMigration), RemoveNewLines(contents));
static string RemoveNewLines(string str)
{
return str.Replace("\n", string.Empty).Replace("\r", string.Empty);
}
}
public void AssertFileExists(string path, bool shouldExist)
{
var fullPath = Path.Combine(TemplateOutputDir, path);
var doesExist = File.Exists(fullPath);
if (shouldExist)
{
Assert.True(doesExist, "Expected file to exist, but it doesn't: " + path);
}
else
{
Assert.False(doesExist, "Expected file not to exist, but it does: " + path);
}
}
public string ReadFile(string path)
{
AssertFileExists(path, shouldExist: true);
return File.ReadAllText(Path.Combine(TemplateOutputDir, path));
}
internal async Task<ProcessEx> RunDotNetNewRawAsync(string arguments)
{
await DotNetNewLock.WaitAsync();
try
{
Output.WriteLine("Acquired DotNetNewLock");
var result = ProcessEx.Run(
Output,
AppContext.BaseDirectory,
DotNetMuxer.MuxerPathOrDefault(),
arguments +
$" --debug:disable-sdk-templates --debug:custom-hive \"{TemplatePackageInstaller.CustomHivePath}\"" +
$" -o {TemplateOutputDir}");
await result.Exited;
return result;
}
finally
{
DotNetNewLock.Release();
Output.WriteLine("Released DotNetNewLock");
}
}
public void Dispose()
{
DeleteOutputDirectory();
}
public void DeleteOutputDirectory()
{
const int NumAttempts = 10;
for (var numAttemptsRemaining = NumAttempts; numAttemptsRemaining > 0; numAttemptsRemaining--)
{
try
{
Directory.Delete(TemplateOutputDir, true);
return;
}
catch (Exception ex)
{
if (numAttemptsRemaining > 1)
{
DiagnosticsMessageSink.OnMessage(new DiagnosticMessage($"Failed to delete directory {TemplateOutputDir} because of error {ex.Message}. Will try again {numAttemptsRemaining - 1} more time(s)."));
Thread.Sleep(3000);
}
else
{
DiagnosticsMessageSink.OnMessage(new DiagnosticMessage($"Giving up trying to delete directory {TemplateOutputDir} after {NumAttempts} attempts. Most recent error was: {ex.StackTrace}"));
}
}
}
}
private class OrderedLock
{
private bool _nodeLockTaken;
private bool _dotNetLockTaken;
public OrderedLock(ProcessLock nodeLock, ProcessLock dotnetLock)
{
NodeLock = nodeLock;
DotnetLock = dotnetLock;
}
public ProcessLock NodeLock { get; }
public ProcessLock DotnetLock { get; }
public async Task WaitAsync()
{
if (NodeLock == null)
{
await DotnetLock.WaitAsync();
_dotNetLockTaken = true;
return;
}
try
{
// We want to take the NPM lock first as is going to be the busiest one, and we want other threads to be
// able to run dotnet new while we are waiting for another thread to finish running NPM.
await NodeLock.WaitAsync();
_nodeLockTaken = true;
await DotnetLock.WaitAsync();
_dotNetLockTaken = true;
}
catch
{
if (_nodeLockTaken)
{
NodeLock.Release();
_nodeLockTaken = false;
}
throw;
}
}
public void Release()
{
try
{
if (_dotNetLockTaken)
{
DotnetLock.Release();
_dotNetLockTaken = false;
}
}
finally
{
if (_nodeLockTaken)
{
NodeLock.Release();
_nodeLockTaken = false;
}
}
}
}
private void CaptureBinLogOnFailure(ProcessEx result)
{
if (result.ExitCode != 0 && !string.IsNullOrEmpty(ArtifactsLogDir))
{
var sourceFile = Path.Combine(TemplateOutputDir, "msbuild.binlog");
Assert.True(File.Exists(sourceFile), $"Log for '{ProjectName}' not found in '{sourceFile}'.");
var destination = Path.Combine(ArtifactsLogDir, ProjectName + ".binlog");
File.Move(sourceFile, destination, overwrite: true); // binlog will exist on retries
}
}
public override string ToString() => $"{ProjectName}: {TemplateOutputDir}";
private static string GetAssemblyMetadata(string key)
{
var attribute = typeof(Project).Assembly.GetCustomAttributes<AssemblyMetadataAttribute>()
.FirstOrDefault(a => a.Key == key);
if (attribute is null)
{
throw new ArgumentException($"AssemblyMetadataAttribute with key {key} was not found.");
}
return attribute.Value;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.SiteRecovery;
using Microsoft.WindowsAzure.Management.SiteRecovery.Models;
namespace Microsoft.WindowsAzure.Management.SiteRecovery
{
public static partial class JobOperationsExtensions
{
/// <summary>
/// Cancel the job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Required. Job ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Cancel(this IJobOperations operations, string jobId, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).CancelAsync(jobId, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Cancel the job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Required. Job ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> CancelAsync(this IJobOperations operations, string jobId, CustomRequestHeaders customRequestHeaders)
{
return operations.CancelAsync(jobId, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Get the job details.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Required. Job ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static JobResponse Get(this IJobOperations operations, string jobId, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).GetAsync(jobId, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the job details.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Required. Job ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static Task<JobResponse> GetAsync(this IJobOperations operations, string jobId, CustomRequestHeaders customRequestHeaders)
{
return operations.GetAsync(jobId, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Get the list of all jobs.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Optional. Job query parameter.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the list Jobs operation.
/// </returns>
public static JobListResponse List(this IJobOperations operations, JobQueryParameter parameters, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).ListAsync(parameters, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the list of all jobs.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Optional. Job query parameter.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the list Jobs operation.
/// </returns>
public static Task<JobListResponse> ListAsync(this IJobOperations operations, JobQueryParameter parameters, CustomRequestHeaders customRequestHeaders)
{
return operations.ListAsync(parameters, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Restart the job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Required. Job ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static JobResponse Restart(this IJobOperations operations, string jobId, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).RestartAsync(jobId, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Restart the job.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Required. Job ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static Task<JobResponse> RestartAsync(this IJobOperations operations, string jobId, CustomRequestHeaders customRequestHeaders)
{
return operations.RestartAsync(jobId, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Resume the job .
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Required. Job ID.
/// </param>
/// <param name='resumeJobParameters'>
/// Optional. Resume job parameters.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static JobResponse Resume(this IJobOperations operations, string jobId, ResumeJobParams resumeJobParameters, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).ResumeAsync(jobId, resumeJobParameters, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Resume the job .
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.SiteRecovery.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Required. Job ID.
/// </param>
/// <param name='resumeJobParameters'>
/// Optional. Resume job parameters.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// The response model for the Job details object.
/// </returns>
public static Task<JobResponse> ResumeAsync(this IJobOperations operations, string jobId, ResumeJobParams resumeJobParameters, CustomRequestHeaders customRequestHeaders)
{
return operations.ResumeAsync(jobId, resumeJobParameters, customRequestHeaders, CancellationToken.None);
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace IO.Swagger.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public class UserVariableRelationship : IEquatable<UserVariableRelationship>
{
/// <summary>
/// Initializes a new instance of the <see cref="UserVariableRelationship" /> class.
/// </summary>
public UserVariableRelationship()
{
}
/// <summary>
/// id
/// </summary>
/// <value>id</value>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; set; }
/// <summary>
/// Our confidence that a consistent predictive relationship exists based on the amount of evidence, reproducibility, and other factors
/// </summary>
/// <value>Our confidence that a consistent predictive relationship exists based on the amount of evidence, reproducibility, and other factors</value>
[DataMember(Name="confidence_level", EmitDefaultValue=false)]
public string ConfidenceLevel { get; set; }
/// <summary>
/// A quantitative representation of our confidence that a consistent predictive relationship exists based on the amount of evidence, reproducibility, and other factors
/// </summary>
/// <value>A quantitative representation of our confidence that a consistent predictive relationship exists based on the amount of evidence, reproducibility, and other factors</value>
[DataMember(Name="confidence_score", EmitDefaultValue=false)]
public float? ConfidenceScore { get; set; }
/// <summary>
/// Direction is positive if higher predictor values generally precede higher outcome values. Direction is negative if higher predictor values generally precede lower outcome values.
/// </summary>
/// <value>Direction is positive if higher predictor values generally precede higher outcome values. Direction is negative if higher predictor values generally precede lower outcome values.</value>
[DataMember(Name="direction", EmitDefaultValue=false)]
public string Direction { get; set; }
/// <summary>
/// Number of seconds over which the predictor variable event is expected to produce a perceivable effect following the onset delay
/// </summary>
/// <value>Number of seconds over which the predictor variable event is expected to produce a perceivable effect following the onset delay</value>
[DataMember(Name="duration_of_action", EmitDefaultValue=false)]
public int? DurationOfAction { get; set; }
/// <summary>
/// error_message
/// </summary>
/// <value>error_message</value>
[DataMember(Name="error_message", EmitDefaultValue=false)]
public string ErrorMessage { get; set; }
/// <summary>
/// User estimated (or default number of seconds) after cause measurement before a perceivable effect is observed
/// </summary>
/// <value>User estimated (or default number of seconds) after cause measurement before a perceivable effect is observed</value>
[DataMember(Name="onset_delay", EmitDefaultValue=false)]
public int? OnsetDelay { get; set; }
/// <summary>
/// Variable ID for the outcome variable
/// </summary>
/// <value>Variable ID for the outcome variable</value>
[DataMember(Name="outcome_variable_id", EmitDefaultValue=false)]
public int? OutcomeVariableId { get; set; }
/// <summary>
/// Variable ID for the predictor variable
/// </summary>
/// <value>Variable ID for the predictor variable</value>
[DataMember(Name="predictor_variable_id", EmitDefaultValue=false)]
public int? PredictorVariableId { get; set; }
/// <summary>
/// ID for default unit of the predictor variable
/// </summary>
/// <value>ID for default unit of the predictor variable</value>
[DataMember(Name="predictor_unit_id", EmitDefaultValue=false)]
public int? PredictorUnitId { get; set; }
/// <summary>
/// A value representative of the relevance of this predictor relative to other predictors of this outcome. Usually used for relevancy sorting.
/// </summary>
/// <value>A value representative of the relevance of this predictor relative to other predictors of this outcome. Usually used for relevancy sorting.</value>
[DataMember(Name="sinn_rank", EmitDefaultValue=false)]
public float? SinnRank { get; set; }
/// <summary>
/// Can be weak, medium, or strong based on the size of the effect which the predictor appears to have on the outcome relative to other variable relationship strength scores.
/// </summary>
/// <value>Can be weak, medium, or strong based on the size of the effect which the predictor appears to have on the outcome relative to other variable relationship strength scores.</value>
[DataMember(Name="strength_level", EmitDefaultValue=false)]
public string StrengthLevel { get; set; }
/// <summary>
/// A value represented to the size of the effect which the predictor appears to have on the outcome.
/// </summary>
/// <value>A value represented to the size of the effect which the predictor appears to have on the outcome.</value>
[DataMember(Name="strength_score", EmitDefaultValue=false)]
public float? StrengthScore { get; set; }
/// <summary>
/// user_id
/// </summary>
/// <value>user_id</value>
[DataMember(Name="user_id", EmitDefaultValue=false)]
public int? UserId { get; set; }
/// <summary>
/// vote
/// </summary>
/// <value>vote</value>
[DataMember(Name="vote", EmitDefaultValue=false)]
public string Vote { get; set; }
/// <summary>
/// Value for the predictor variable (in it's default unit) which typically precedes an above average outcome value
/// </summary>
/// <value>Value for the predictor variable (in it's default unit) which typically precedes an above average outcome value</value>
[DataMember(Name="value_predicting_high_outcome", EmitDefaultValue=false)]
public float? ValuePredictingHighOutcome { get; set; }
/// <summary>
/// Value for the predictor variable (in it's default unit) which typically precedes a below average outcome value
/// </summary>
/// <value>Value for the predictor variable (in it's default unit) which typically precedes a below average outcome value</value>
[DataMember(Name="value_predicting_low_outcome", EmitDefaultValue=false)]
public float? ValuePredictingLowOutcome { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class UserVariableRelationship {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" ConfidenceLevel: ").Append(ConfidenceLevel).Append("\n");
sb.Append(" ConfidenceScore: ").Append(ConfidenceScore).Append("\n");
sb.Append(" Direction: ").Append(Direction).Append("\n");
sb.Append(" DurationOfAction: ").Append(DurationOfAction).Append("\n");
sb.Append(" ErrorMessage: ").Append(ErrorMessage).Append("\n");
sb.Append(" OnsetDelay: ").Append(OnsetDelay).Append("\n");
sb.Append(" OutcomeVariableId: ").Append(OutcomeVariableId).Append("\n");
sb.Append(" PredictorVariableId: ").Append(PredictorVariableId).Append("\n");
sb.Append(" PredictorUnitId: ").Append(PredictorUnitId).Append("\n");
sb.Append(" SinnRank: ").Append(SinnRank).Append("\n");
sb.Append(" StrengthLevel: ").Append(StrengthLevel).Append("\n");
sb.Append(" StrengthScore: ").Append(StrengthScore).Append("\n");
sb.Append(" UserId: ").Append(UserId).Append("\n");
sb.Append(" Vote: ").Append(Vote).Append("\n");
sb.Append(" ValuePredictingHighOutcome: ").Append(ValuePredictingHighOutcome).Append("\n");
sb.Append(" ValuePredictingLowOutcome: ").Append(ValuePredictingLowOutcome).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as UserVariableRelationship);
}
/// <summary>
/// Returns true if UserVariableRelationship instances are equal
/// </summary>
/// <param name="obj">Instance of UserVariableRelationship to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(UserVariableRelationship other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.ConfidenceLevel == other.ConfidenceLevel ||
this.ConfidenceLevel != null &&
this.ConfidenceLevel.Equals(other.ConfidenceLevel)
) &&
(
this.ConfidenceScore == other.ConfidenceScore ||
this.ConfidenceScore != null &&
this.ConfidenceScore.Equals(other.ConfidenceScore)
) &&
(
this.Direction == other.Direction ||
this.Direction != null &&
this.Direction.Equals(other.Direction)
) &&
(
this.DurationOfAction == other.DurationOfAction ||
this.DurationOfAction != null &&
this.DurationOfAction.Equals(other.DurationOfAction)
) &&
(
this.ErrorMessage == other.ErrorMessage ||
this.ErrorMessage != null &&
this.ErrorMessage.Equals(other.ErrorMessage)
) &&
(
this.OnsetDelay == other.OnsetDelay ||
this.OnsetDelay != null &&
this.OnsetDelay.Equals(other.OnsetDelay)
) &&
(
this.OutcomeVariableId == other.OutcomeVariableId ||
this.OutcomeVariableId != null &&
this.OutcomeVariableId.Equals(other.OutcomeVariableId)
) &&
(
this.PredictorVariableId == other.PredictorVariableId ||
this.PredictorVariableId != null &&
this.PredictorVariableId.Equals(other.PredictorVariableId)
) &&
(
this.PredictorUnitId == other.PredictorUnitId ||
this.PredictorUnitId != null &&
this.PredictorUnitId.Equals(other.PredictorUnitId)
) &&
(
this.SinnRank == other.SinnRank ||
this.SinnRank != null &&
this.SinnRank.Equals(other.SinnRank)
) &&
(
this.StrengthLevel == other.StrengthLevel ||
this.StrengthLevel != null &&
this.StrengthLevel.Equals(other.StrengthLevel)
) &&
(
this.StrengthScore == other.StrengthScore ||
this.StrengthScore != null &&
this.StrengthScore.Equals(other.StrengthScore)
) &&
(
this.UserId == other.UserId ||
this.UserId != null &&
this.UserId.Equals(other.UserId)
) &&
(
this.Vote == other.Vote ||
this.Vote != null &&
this.Vote.Equals(other.Vote)
) &&
(
this.ValuePredictingHighOutcome == other.ValuePredictingHighOutcome ||
this.ValuePredictingHighOutcome != null &&
this.ValuePredictingHighOutcome.Equals(other.ValuePredictingHighOutcome)
) &&
(
this.ValuePredictingLowOutcome == other.ValuePredictingLowOutcome ||
this.ValuePredictingLowOutcome != null &&
this.ValuePredictingLowOutcome.Equals(other.ValuePredictingLowOutcome)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 57 + this.Id.GetHashCode();
if (this.ConfidenceLevel != null)
hash = hash * 57 + this.ConfidenceLevel.GetHashCode();
if (this.ConfidenceScore != null)
hash = hash * 57 + this.ConfidenceScore.GetHashCode();
if (this.Direction != null)
hash = hash * 57 + this.Direction.GetHashCode();
if (this.DurationOfAction != null)
hash = hash * 57 + this.DurationOfAction.GetHashCode();
if (this.ErrorMessage != null)
hash = hash * 57 + this.ErrorMessage.GetHashCode();
if (this.OnsetDelay != null)
hash = hash * 57 + this.OnsetDelay.GetHashCode();
if (this.OutcomeVariableId != null)
hash = hash * 57 + this.OutcomeVariableId.GetHashCode();
if (this.PredictorVariableId != null)
hash = hash * 57 + this.PredictorVariableId.GetHashCode();
if (this.PredictorUnitId != null)
hash = hash * 57 + this.PredictorUnitId.GetHashCode();
if (this.SinnRank != null)
hash = hash * 57 + this.SinnRank.GetHashCode();
if (this.StrengthLevel != null)
hash = hash * 57 + this.StrengthLevel.GetHashCode();
if (this.StrengthScore != null)
hash = hash * 57 + this.StrengthScore.GetHashCode();
if (this.UserId != null)
hash = hash * 57 + this.UserId.GetHashCode();
if (this.Vote != null)
hash = hash * 57 + this.Vote.GetHashCode();
if (this.ValuePredictingHighOutcome != null)
hash = hash * 57 + this.ValuePredictingHighOutcome.GetHashCode();
if (this.ValuePredictingLowOutcome != null)
hash = hash * 57 + this.ValuePredictingLowOutcome.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Backpack.Api.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);
}
}
}
}
| |
using J2N.Numerics;
using YAF.Lucene.Net.Support;
using System;
using System.Diagnostics;
namespace YAF.Lucene.Net.Util
{
/*
* 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 DocIdSet = YAF.Lucene.Net.Search.DocIdSet;
using DocIdSetIterator = YAF.Lucene.Net.Search.DocIdSetIterator;
using MonotonicAppendingInt64Buffer = YAF.Lucene.Net.Util.Packed.MonotonicAppendingInt64Buffer;
using PackedInt32s = YAF.Lucene.Net.Util.Packed.PackedInt32s;
/// <summary>
/// <see cref="DocIdSet"/> implementation based on pfor-delta encoding.
/// <para>This implementation is inspired from LinkedIn's Kamikaze
/// (http://data.linkedin.com/opensource/kamikaze) and Daniel Lemire's JavaFastPFOR
/// (https://github.com/lemire/JavaFastPFOR).</para>
/// <para>On the contrary to the original PFOR paper, exceptions are encoded with
/// FOR instead of Simple16.</para>
/// </summary>
public sealed class PForDeltaDocIdSet : DocIdSet
{
internal const int BLOCK_SIZE = 128;
internal const int MAX_EXCEPTIONS = 24; // no more than 24 exceptions per block
internal static readonly PackedInt32s.IDecoder[] DECODERS = new PackedInt32s.IDecoder[32];
internal static readonly int[] ITERATIONS = new int[32];
internal static readonly int[] BYTE_BLOCK_COUNTS = new int[32];
internal static readonly int MAX_BYTE_BLOCK_COUNT;
internal static readonly MonotonicAppendingInt64Buffer SINGLE_ZERO_BUFFER = new MonotonicAppendingInt64Buffer(0, 64, PackedInt32s.COMPACT);
internal static readonly PForDeltaDocIdSet EMPTY = new PForDeltaDocIdSet(null, 0, int.MaxValue, SINGLE_ZERO_BUFFER, SINGLE_ZERO_BUFFER);
internal static readonly int LAST_BLOCK = 1 << 5; // flag to indicate the last block
internal static readonly int HAS_EXCEPTIONS = 1 << 6;
internal static readonly int UNARY = 1 << 7;
static PForDeltaDocIdSet()
{
SINGLE_ZERO_BUFFER.Add(0);
SINGLE_ZERO_BUFFER.Freeze();
int maxByteBLockCount = 0;
for (int i = 1; i < ITERATIONS.Length; ++i)
{
DECODERS[i] = PackedInt32s.GetDecoder(PackedInt32s.Format.PACKED, PackedInt32s.VERSION_CURRENT, i);
Debug.Assert(BLOCK_SIZE % DECODERS[i].ByteValueCount == 0);
ITERATIONS[i] = BLOCK_SIZE / DECODERS[i].ByteValueCount;
BYTE_BLOCK_COUNTS[i] = ITERATIONS[i] * DECODERS[i].ByteBlockCount;
maxByteBLockCount = Math.Max(maxByteBLockCount, DECODERS[i].ByteBlockCount);
}
MAX_BYTE_BLOCK_COUNT = maxByteBLockCount;
}
/// <summary>
/// A builder for <see cref="PForDeltaDocIdSet"/>. </summary>
public class Builder
{
internal readonly GrowableByteArrayDataOutput data;
internal readonly int[] buffer = new int[BLOCK_SIZE];
internal readonly int[] exceptionIndices = new int[BLOCK_SIZE];
internal readonly int[] exceptions = new int[BLOCK_SIZE];
internal int bufferSize;
internal int previousDoc;
internal int cardinality;
internal int indexInterval;
internal int numBlocks;
// temporary variables used when compressing blocks
internal readonly int[] freqs = new int[32];
internal int bitsPerValue;
internal int numExceptions;
internal int bitsPerException;
/// <summary>
/// Sole constructor. </summary>
public Builder()
{
data = new GrowableByteArrayDataOutput(128);
bufferSize = 0;
previousDoc = -1;
indexInterval = 2;
cardinality = 0;
numBlocks = 0;
}
/// <summary>
/// Set the index interval. Every <paramref name="indexInterval"/>-th block will
/// be stored in the index. Set to <see cref="int.MaxValue"/> to disable indexing.
/// </summary>
public virtual Builder SetIndexInterval(int indexInterval)
{
if (indexInterval < 1)
{
throw new System.ArgumentException("indexInterval must be >= 1");
}
this.indexInterval = indexInterval;
return this;
}
/// <summary>
/// Add a document to this builder. Documents must be added in order. </summary>
public virtual Builder Add(int doc)
{
if (doc <= previousDoc)
{
throw new System.ArgumentException("Doc IDs must be provided in order, but previousDoc=" + previousDoc + " and doc=" + doc);
}
buffer[bufferSize++] = doc - previousDoc - 1;
if (bufferSize == BLOCK_SIZE)
{
EncodeBlock();
bufferSize = 0;
}
previousDoc = doc;
++cardinality;
return this;
}
/// <summary>
/// Convenience method to add the content of a <see cref="DocIdSetIterator"/> to this builder. </summary>
public virtual Builder Add(DocIdSetIterator it)
{
for (int doc = it.NextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = it.NextDoc())
{
Add(doc);
}
return this;
}
internal virtual void ComputeFreqs()
{
Arrays.Fill(freqs, 0);
for (int i = 0; i < bufferSize; ++i)
{
++freqs[32 - buffer[i].LeadingZeroCount()];
}
}
internal virtual int PforBlockSize(int bitsPerValue, int numExceptions, int bitsPerException)
{
PackedInt32s.Format format = PackedInt32s.Format.PACKED;
long blockSize = 1 + format.ByteCount(PackedInt32s.VERSION_CURRENT, BLOCK_SIZE, bitsPerValue); // header: number of bits per value
if (numExceptions > 0)
{
blockSize += 2 + numExceptions + format.ByteCount(PackedInt32s.VERSION_CURRENT, numExceptions, bitsPerException); // indices of the exceptions - 2 additional bytes in case of exceptions: numExceptions and bitsPerException
}
if (bufferSize < BLOCK_SIZE)
{
blockSize += 1; // length of the block
}
return (int)blockSize;
}
internal virtual int UnaryBlockSize()
{
int deltaSum = 0;
for (int i = 0; i < BLOCK_SIZE; ++i)
{
deltaSum += 1 + buffer[i];
}
int blockSize = (int)((uint)(deltaSum + 0x07) >> 3); // round to the next byte
++blockSize; // header
if (bufferSize < BLOCK_SIZE)
{
blockSize += 1; // length of the block
}
return blockSize;
}
internal virtual int ComputeOptimalNumberOfBits()
{
ComputeFreqs();
bitsPerValue = 31;
numExceptions = 0;
while (bitsPerValue > 0 && freqs[bitsPerValue] == 0)
{
--bitsPerValue;
}
int actualBitsPerValue = bitsPerValue;
int blockSize = PforBlockSize(bitsPerValue, numExceptions, bitsPerException);
// Now try different values for bitsPerValue and pick the best one
for (int bitsPerValue = this.bitsPerValue - 1, numExceptions = freqs[this.bitsPerValue]; bitsPerValue >= 0 && numExceptions <= MAX_EXCEPTIONS; numExceptions += freqs[bitsPerValue--])
{
int newBlockSize = PforBlockSize(bitsPerValue, numExceptions, actualBitsPerValue - bitsPerValue);
if (newBlockSize < blockSize)
{
this.bitsPerValue = bitsPerValue;
this.numExceptions = numExceptions;
blockSize = newBlockSize;
}
}
this.bitsPerException = actualBitsPerValue - bitsPerValue;
Debug.Assert(bufferSize < BLOCK_SIZE || numExceptions < bufferSize);
return blockSize;
}
internal virtual void PforEncode()
{
if (numExceptions > 0)
{
int mask = (1 << bitsPerValue) - 1;
int ex = 0;
for (int i = 0; i < bufferSize; ++i)
{
if (buffer[i] > mask)
{
exceptionIndices[ex] = i;
exceptions[ex++] = (int)((uint)buffer[i] >> bitsPerValue);
buffer[i] &= mask;
}
}
Debug.Assert(ex == numExceptions);
Arrays.Fill(exceptions, numExceptions, BLOCK_SIZE, 0);
}
if (bitsPerValue > 0)
{
PackedInt32s.IEncoder encoder = PackedInt32s.GetEncoder(PackedInt32s.Format.PACKED, PackedInt32s.VERSION_CURRENT, bitsPerValue);
int numIterations = ITERATIONS[bitsPerValue];
encoder.Encode(buffer, 0, data.Bytes, data.Length, numIterations);
data.Length += encoder.ByteBlockCount * numIterations;
}
if (numExceptions > 0)
{
Debug.Assert(bitsPerException > 0);
data.WriteByte((byte)(sbyte)numExceptions);
data.WriteByte((byte)(sbyte)bitsPerException);
PackedInt32s.IEncoder encoder = PackedInt32s.GetEncoder(PackedInt32s.Format.PACKED, PackedInt32s.VERSION_CURRENT, bitsPerException);
int numIterations = (numExceptions + encoder.ByteValueCount - 1) / encoder.ByteValueCount;
encoder.Encode(exceptions, 0, data.Bytes, data.Length, numIterations);
data.Length += (int)PackedInt32s.Format.PACKED.ByteCount(PackedInt32s.VERSION_CURRENT, numExceptions, bitsPerException);
for (int i = 0; i < numExceptions; ++i)
{
data.WriteByte((byte)(sbyte)exceptionIndices[i]);
}
}
}
internal virtual void UnaryEncode()
{
int current = 0;
for (int i = 0, doc = -1; i < BLOCK_SIZE; ++i)
{
doc += 1 + buffer[i];
while (doc >= 8)
{
data.WriteByte((byte)(sbyte)current);
current = 0;
doc -= 8;
}
current |= 1 << doc;
}
if (current != 0)
{
data.WriteByte((byte)(sbyte)current);
}
}
internal virtual void EncodeBlock()
{
int originalLength = data.Length;
Arrays.Fill(buffer, bufferSize, BLOCK_SIZE, 0);
int unaryBlockSize = UnaryBlockSize();
int pforBlockSize = ComputeOptimalNumberOfBits();
int blockSize;
if (pforBlockSize <= unaryBlockSize)
{
// use pfor
blockSize = pforBlockSize;
data.Bytes = ArrayUtil.Grow(data.Bytes, data.Length + blockSize + MAX_BYTE_BLOCK_COUNT);
int token = bufferSize < BLOCK_SIZE ? LAST_BLOCK : 0;
token |= bitsPerValue;
if (numExceptions > 0)
{
token |= HAS_EXCEPTIONS;
}
data.WriteByte((byte)(sbyte)token);
PforEncode();
}
else
{
// use unary
blockSize = unaryBlockSize;
int token = UNARY | (bufferSize < BLOCK_SIZE ? LAST_BLOCK : 0);
data.WriteByte((byte)(sbyte)token);
UnaryEncode();
}
if (bufferSize < BLOCK_SIZE)
{
data.WriteByte((byte)(sbyte)bufferSize);
}
++numBlocks;
Debug.Assert(data.Length - originalLength == blockSize, (data.Length - originalLength) + " <> " + blockSize);
}
/// <summary>
/// Build the <see cref="PForDeltaDocIdSet"/> instance. </summary>
public virtual PForDeltaDocIdSet Build()
{
Debug.Assert(bufferSize < BLOCK_SIZE);
if (cardinality == 0)
{
Debug.Assert(previousDoc == -1);
return EMPTY;
}
EncodeBlock();
var dataArr = Arrays.CopyOf(data.Bytes, data.Length + MAX_BYTE_BLOCK_COUNT);
int indexSize = (numBlocks - 1) / indexInterval + 1;
MonotonicAppendingInt64Buffer docIDs, offsets;
if (indexSize <= 1)
{
docIDs = offsets = SINGLE_ZERO_BUFFER;
}
else
{
const int pageSize = 128;
int initialPageCount = (indexSize + pageSize - 1) / pageSize;
docIDs = new MonotonicAppendingInt64Buffer(initialPageCount, pageSize, PackedInt32s.COMPACT);
offsets = new MonotonicAppendingInt64Buffer(initialPageCount, pageSize, PackedInt32s.COMPACT);
// Now build the index
Iterator it = new Iterator(dataArr, cardinality, int.MaxValue, SINGLE_ZERO_BUFFER, SINGLE_ZERO_BUFFER);
for (int k = 0; k < indexSize; ++k)
{
docIDs.Add(it.DocID + 1);
offsets.Add(it.offset);
for (int i = 0; i < indexInterval; ++i)
{
it.SkipBlock();
if (it.DocID == DocIdSetIterator.NO_MORE_DOCS)
{
goto indexBreak;
}
}
//indexContinue: ;
}
indexBreak:
docIDs.Freeze();
offsets.Freeze();
}
return new PForDeltaDocIdSet(dataArr, cardinality, indexInterval, docIDs, offsets);
}
}
internal readonly byte[] data;
internal readonly MonotonicAppendingInt64Buffer docIDs, offsets; // for the index
internal readonly int cardinality, indexInterval;
internal PForDeltaDocIdSet(byte[] data, int cardinality, int indexInterval, MonotonicAppendingInt64Buffer docIDs, MonotonicAppendingInt64Buffer offsets)
{
this.data = data;
this.cardinality = cardinality;
this.indexInterval = indexInterval;
this.docIDs = docIDs;
this.offsets = offsets;
}
public override bool IsCacheable
{
get
{
return true;
}
}
public override DocIdSetIterator GetIterator()
{
if (data == null)
{
return null;
}
else
{
return new Iterator(data, cardinality, indexInterval, docIDs, offsets);
}
}
internal class Iterator : DocIdSetIterator
{
// index
internal readonly int indexInterval;
internal readonly MonotonicAppendingInt64Buffer docIDs, offsets;
internal readonly int cardinality;
internal readonly byte[] data;
internal int offset; // offset in data
internal readonly int[] nextDocs;
internal int i; // index in nextDeltas
internal readonly int[] nextExceptions;
internal int blockIdx;
internal int docID;
internal Iterator(byte[] data, int cardinality, int indexInterval, MonotonicAppendingInt64Buffer docIDs, MonotonicAppendingInt64Buffer offsets)
{
this.data = data;
this.cardinality = cardinality;
this.indexInterval = indexInterval;
this.docIDs = docIDs;
this.offsets = offsets;
offset = 0;
nextDocs = new int[BLOCK_SIZE];
Arrays.Fill(nextDocs, -1);
i = BLOCK_SIZE;
nextExceptions = new int[BLOCK_SIZE];
blockIdx = -1;
docID = -1;
}
public override int DocID
{
get { return docID; }
}
internal virtual void PforDecompress(byte token)
{
int bitsPerValue = token & 0x1F;
if (bitsPerValue == 0)
{
Arrays.Fill(nextDocs, 0);
}
else
{
DECODERS[bitsPerValue].Decode(data, offset, nextDocs, 0, ITERATIONS[bitsPerValue]);
offset += BYTE_BLOCK_COUNTS[bitsPerValue];
}
if ((token & HAS_EXCEPTIONS) != 0)
{
// there are exceptions
int numExceptions = data[offset++];
int bitsPerException = data[offset++];
int numIterations = (numExceptions + DECODERS[bitsPerException].ByteValueCount - 1) / DECODERS[bitsPerException].ByteValueCount;
DECODERS[bitsPerException].Decode(data, offset, nextExceptions, 0, numIterations);
offset += (int)PackedInt32s.Format.PACKED.ByteCount(PackedInt32s.VERSION_CURRENT, numExceptions, bitsPerException);
for (int i = 0; i < numExceptions; ++i)
{
nextDocs[data[offset++]] |= nextExceptions[i] << bitsPerValue;
}
}
for (int previousDoc = docID, i = 0; i < BLOCK_SIZE; ++i)
{
int doc = previousDoc + 1 + nextDocs[i];
previousDoc = nextDocs[i] = doc;
}
}
internal virtual void UnaryDecompress(byte token)
{
Debug.Assert((token & HAS_EXCEPTIONS) == 0);
int docID = this.docID;
for (int i = 0; i < BLOCK_SIZE; )
{
var b = data[offset++];
for (int bitList = BitUtil.BitList(b); bitList != 0; ++i, bitList = (int)((uint)bitList >> 4))
{
nextDocs[i] = docID + (bitList & 0x0F);
}
docID += 8;
}
}
internal virtual void DecompressBlock()
{
var token = data[offset++];
if ((token & UNARY) != 0)
{
UnaryDecompress(token);
}
else
{
PforDecompress(token);
}
if ((token & LAST_BLOCK) != 0)
{
int blockSize = data[offset++];
Arrays.Fill(nextDocs, blockSize, BLOCK_SIZE, NO_MORE_DOCS);
}
++blockIdx;
}
internal virtual void SkipBlock()
{
Debug.Assert(i == BLOCK_SIZE);
DecompressBlock();
docID = nextDocs[BLOCK_SIZE - 1];
}
public override int NextDoc()
{
if (i == BLOCK_SIZE)
{
DecompressBlock();
i = 0;
}
return docID = nextDocs[i++];
}
internal virtual int ForwardBinarySearch(int target)
{
// advance forward and double the window at each step
int indexSize = (int)docIDs.Count;
int lo = Math.Max(blockIdx / indexInterval, 0), hi = lo + 1;
Debug.Assert(blockIdx == -1 || docIDs.Get(lo) <= docID);
Debug.Assert(lo + 1 == docIDs.Count || docIDs.Get(lo + 1) > docID);
while (true)
{
if (hi >= indexSize)
{
hi = indexSize - 1;
break;
}
else if (docIDs.Get(hi) >= target)
{
break;
}
int newLo = hi;
hi += (hi - lo) << 1;
lo = newLo;
}
// we found a window containing our target, let's binary search now
while (lo <= hi)
{
int mid = (int)((uint)(lo + hi) >> 1);
int midDocID = (int)docIDs.Get(mid);
if (midDocID <= target)
{
lo = mid + 1;
}
else
{
hi = mid - 1;
}
}
Debug.Assert(docIDs.Get(hi) <= target);
Debug.Assert(hi + 1 == docIDs.Count || docIDs.Get(hi + 1) > target);
return hi;
}
public override int Advance(int target)
{
Debug.Assert(target > docID);
if (nextDocs[BLOCK_SIZE - 1] < target)
{
// not in the next block, now use the index
int index = ForwardBinarySearch(target);
int offset = (int)offsets.Get(index);
if (offset > this.offset)
{
this.offset = offset;
docID = (int)docIDs.Get(index) - 1;
blockIdx = index * indexInterval - 1;
while (true)
{
DecompressBlock();
if (nextDocs[BLOCK_SIZE - 1] >= target)
{
break;
}
docID = nextDocs[BLOCK_SIZE - 1];
}
i = 0;
}
}
return SlowAdvance(target);
}
public override long GetCost()
{
return cardinality;
}
}
/// <summary>
/// Return the number of documents in this <see cref="DocIdSet"/> in constant time. </summary>
public int Cardinality()
{
return cardinality;
}
/// <summary>
/// Return the memory usage of this instance. </summary>
public long RamBytesUsed()
{
return RamUsageEstimator.AlignObjectSize(3 * RamUsageEstimator.NUM_BYTES_OBJECT_REF) + docIDs.RamBytesUsed() + offsets.RamBytesUsed();
}
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using System.Collections;
using System.IO;
using System.Text;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
namespace Org.BouncyCastle.Asn1.Utilities
{
public sealed class Asn1Dump
{
private static readonly string NewLine = Platform.NewLine;
private Asn1Dump()
{
}
private const string Tab = " ";
private const int SampleSize = 32;
/**
* dump a Der object as a formatted string with indentation
*
* @param obj the Asn1Object to be dumped out.
*/
private static void AsString(
string indent,
bool verbose,
Asn1Object obj,
StringBuilder buf)
{
if (obj is Asn1Sequence)
{
string tab = indent + Tab;
buf.Append(indent);
if (obj is BerSequence)
{
buf.Append("BER Sequence");
}
else if (obj is DerSequence)
{
buf.Append("DER Sequence");
}
else
{
buf.Append("Sequence");
}
buf.Append(NewLine);
foreach (Asn1Encodable o in ((Asn1Sequence)obj))
{
if (o == null || o is Asn1Null)
{
buf.Append(tab);
buf.Append("NULL");
buf.Append(NewLine);
}
else
{
AsString(tab, verbose, o.ToAsn1Object(), buf);
}
}
}
else if (obj is DerTaggedObject)
{
string tab = indent + Tab;
buf.Append(indent);
if (obj is BerTaggedObject)
{
buf.Append("BER Tagged [");
}
else
{
buf.Append("Tagged [");
}
DerTaggedObject o = (DerTaggedObject)obj;
buf.Append(((int)o.TagNo).ToString());
buf.Append(']');
if (!o.IsExplicit())
{
buf.Append(" IMPLICIT ");
}
buf.Append(NewLine);
if (o.IsEmpty())
{
buf.Append(tab);
buf.Append("EMPTY");
buf.Append(NewLine);
}
else
{
AsString(tab, verbose, o.GetObject(), buf);
}
}
else if (obj is BerSet)
{
string tab = indent + Tab;
buf.Append(indent);
buf.Append("BER Set");
buf.Append(NewLine);
foreach (Asn1Encodable o in ((Asn1Set)obj))
{
if (o == null)
{
buf.Append(tab);
buf.Append("NULL");
buf.Append(NewLine);
}
else
{
AsString(tab, verbose, o.ToAsn1Object(), buf);
}
}
}
else if (obj is DerSet)
{
string tab = indent + Tab;
buf.Append(indent);
buf.Append("DER Set");
buf.Append(NewLine);
foreach (Asn1Encodable o in ((Asn1Set)obj))
{
if (o == null)
{
buf.Append(tab);
buf.Append("NULL");
buf.Append(NewLine);
}
else
{
AsString(tab, verbose, o.ToAsn1Object(), buf);
}
}
}
else if (obj is DerObjectIdentifier)
{
buf.Append(indent + "ObjectIdentifier(" + ((DerObjectIdentifier)obj).Id + ")" + NewLine);
}
else if (obj is DerBoolean)
{
buf.Append(indent + "Boolean(" + ((DerBoolean)obj).IsTrue + ")" + NewLine);
}
else if (obj is DerInteger)
{
buf.Append(indent + "Integer(" + ((DerInteger)obj).Value + ")" + NewLine);
}
else if (obj is BerOctetString)
{
byte[] octets = ((Asn1OctetString)obj).GetOctets();
string extra = verbose ? dumpBinaryDataAsString(indent, octets) : "";
buf.Append(indent + "BER Octet String" + "[" + octets.Length + "] " + extra + NewLine);
}
else if (obj is DerOctetString)
{
byte[] octets = ((Asn1OctetString)obj).GetOctets();
string extra = verbose ? dumpBinaryDataAsString(indent, octets) : "";
buf.Append(indent + "DER Octet String" + "[" + octets.Length + "] " + extra + NewLine);
}
else if (obj is DerBitString)
{
DerBitString bt = (DerBitString)obj;
byte[] bytes = bt.GetBytes();
string extra = verbose ? dumpBinaryDataAsString(indent, bytes) : "";
buf.Append(indent + "DER Bit String" + "[" + bytes.Length + ", " + bt.PadBits + "] " + extra + NewLine);
}
else if (obj is DerIA5String)
{
buf.Append(indent + "IA5String(" + ((DerIA5String)obj).GetString() + ") " + NewLine);
}
else if (obj is DerUtf8String)
{
buf.Append(indent + "UTF8String(" + ((DerUtf8String)obj).GetString() + ") " + NewLine);
}
else if (obj is DerPrintableString)
{
buf.Append(indent + "PrintableString(" + ((DerPrintableString)obj).GetString() + ") " + NewLine);
}
else if (obj is DerVisibleString)
{
buf.Append(indent + "VisibleString(" + ((DerVisibleString)obj).GetString() + ") " + NewLine);
}
else if (obj is DerBmpString)
{
buf.Append(indent + "BMPString(" + ((DerBmpString)obj).GetString() + ") " + NewLine);
}
else if (obj is DerT61String)
{
buf.Append(indent + "T61String(" + ((DerT61String)obj).GetString() + ") " + NewLine);
}
else if (obj is DerUtcTime)
{
buf.Append(indent + "UTCTime(" + ((DerUtcTime)obj).TimeString + ") " + NewLine);
}
else if (obj is DerGeneralizedTime)
{
buf.Append(indent + "GeneralizedTime(" + ((DerGeneralizedTime)obj).GetTime() + ") " + NewLine);
}
else if (obj is BerApplicationSpecific)
{
buf.Append(outputApplicationSpecific("BER", indent, verbose, (BerApplicationSpecific)obj));
}
else if (obj is DerApplicationSpecific)
{
buf.Append(outputApplicationSpecific("DER", indent, verbose, (DerApplicationSpecific)obj));
}
else if (obj is DerEnumerated)
{
DerEnumerated en = (DerEnumerated)obj;
buf.Append(indent + "DER Enumerated(" + en.Value + ")" + NewLine);
}
else if (obj is DerExternal)
{
DerExternal ext = (DerExternal)obj;
buf.Append(indent + "External " + NewLine);
string tab = indent + Tab;
if (ext.DirectReference != null)
{
buf.Append(tab + "Direct Reference: " + ext.DirectReference.Id + NewLine);
}
if (ext.IndirectReference != null)
{
buf.Append(tab + "Indirect Reference: " + ext.IndirectReference.ToString() + NewLine);
}
if (ext.DataValueDescriptor != null)
{
AsString(tab, verbose, ext.DataValueDescriptor, buf);
}
buf.Append(tab + "Encoding: " + ext.Encoding + NewLine);
AsString(tab, verbose, ext.ExternalContent, buf);
}
else
{
buf.Append(indent + obj.ToString() + NewLine);
}
}
private static string outputApplicationSpecific(
string type,
string indent,
bool verbose,
DerApplicationSpecific app)
{
StringBuilder buf = new StringBuilder();
if (app.IsConstructed())
{
try
{
Asn1Sequence s = Asn1Sequence.GetInstance(app.GetObject(Asn1Tags.Sequence));
buf.Append(indent + type + " ApplicationSpecific[" + app.ApplicationTag + "]" + NewLine);
foreach (Asn1Encodable ae in s)
{
AsString(indent + Tab, verbose, ae.ToAsn1Object(), buf);
}
}
catch (IOException e)
{
buf.Append(e);
}
return buf.ToString();
}
return indent + type + " ApplicationSpecific[" + app.ApplicationTag + "] ("
+ Hex.ToHexString(app.GetContents()) + ")" + NewLine;
}
[Obsolete("Use version accepting Asn1Encodable")]
public static string DumpAsString(
object obj)
{
if (obj is Asn1Encodable)
{
StringBuilder buf = new StringBuilder();
AsString("", false, ((Asn1Encodable)obj).ToAsn1Object(), buf);
return buf.ToString();
}
return "unknown object type " + obj.ToString();
}
/**
* dump out a DER object as a formatted string, in non-verbose mode
*
* @param obj the Asn1Encodable to be dumped out.
* @return the resulting string.
*/
public static string DumpAsString(
Asn1Encodable obj)
{
return DumpAsString(obj, false);
}
/**
* Dump out the object as a string
*
* @param obj the Asn1Encodable to be dumped out.
* @param verbose if true, dump out the contents of octet and bit strings.
* @return the resulting string.
*/
public static string DumpAsString(
Asn1Encodable obj,
bool verbose)
{
StringBuilder buf = new StringBuilder();
AsString("", verbose, obj.ToAsn1Object(), buf);
return buf.ToString();
}
private static string dumpBinaryDataAsString(string indent, byte[] bytes)
{
indent += Tab;
StringBuilder buf = new StringBuilder(NewLine);
for (int i = 0; i < bytes.Length; i += SampleSize)
{
if (bytes.Length - i > SampleSize)
{
buf.Append(indent);
buf.Append(Hex.ToHexString(bytes, i, SampleSize));
buf.Append(Tab);
buf.Append(calculateAscString(bytes, i, SampleSize));
buf.Append(NewLine);
}
else
{
buf.Append(indent);
buf.Append(Hex.ToHexString(bytes, i, bytes.Length - i));
for (int j = bytes.Length - i; j != SampleSize; j++)
{
buf.Append(" ");
}
buf.Append(Tab);
buf.Append(calculateAscString(bytes, i, bytes.Length - i));
buf.Append(NewLine);
}
}
return buf.ToString();
}
private static string calculateAscString(
byte[] bytes,
int off,
int len)
{
StringBuilder buf = new StringBuilder();
for (int i = off; i != off + len; i++)
{
char c = (char)bytes[i];
if (c >= ' ' && c <= '~')
{
buf.Append(c);
}
}
return buf.ToString();
}
}
}
#endif
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using Microsoft.Llilum.Lwip;
using System;
using System.Net;
namespace Microsoft.Zelig.Test
{
public class WebExceptionTests : TestBase, ITestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
try
{
NetworkInterface[] nis = NetworkInterface.GetAllNetworkInterfaces();
}
catch
{
return InitializeResult.Skip;
}
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests.");
// TODO: Add your clean up steps here.
}
public override TestResult Run( string[] args )
{
return TestResult.Pass;
}
//--//
//--//
//--//
#region Helper methods
private TestResult VerifyStream(HttpWebResponse response, HttpServer server)
{
TestResult result = TestResult.Pass;
using (System.IO.Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
string page = HttpTests.ReadStream("Client", responseStream);
if (page != server.ResponseString)
{
Log.Exception("Expect " + server.ResponseString + " but get " + responseStream.ToString());
result = TestResult.Fail;
}
}
else
{
result = TestResult.Fail;
Log.Exception("[Client] Expected stream, but got null");
}
}
return result;
}
#endregion Helper methods
#region Test
[TestMethod]
public TestResult TestWebExceptionHTTP1_1_ConnectionClosed()
{
TestResult result = TestResult.Pass;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/ConnClose.html"); //expect ConnectionClosed
wr.UserAgent = ".Net Micro Framwork Device/4.0";
wr.Method = "HEAD";
Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1
Log.Comment("Set Version 1.1");
wr.ProtocolVersion = new Version(1, 1);
HttpServer server = new HttpServer("http", ref result)
{
RequestUri = wr.RequestUri,
RequestHeaders = wr.Headers,
ResponseString = ""
};
try
{
// Setup server
server.StartServer();
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Log.Comment("Expect ConnectionClosed");
VerifyStream(response, server);
response.Close();
}
catch (Exception ex)
{
Log.Exception("Exception caught: ", ex);
}
finally
{
//Stop server
server.StopServer();
}
return result;
}
[TestMethod]
public TestResult TestWebExceptionHTTP1_1_KeepAliveFailure()
{
TestResult result = TestResult.Pass;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/KeepAliveFailure.html"); //expect KeepAliveFailure
wr.UserAgent = ".Net Micro Framwork Device/4.0";
wr.Method = "HEAD";
Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1
Log.Comment("Set Version 1.1");
wr.ProtocolVersion = new Version(1, 1);
HttpServer server = new HttpServer("http", ref result)
{
RequestUri = wr.RequestUri,
RequestHeaders = wr.Headers,
ResponseString = ""
};
try
{
// Setup server
server.StartServer();
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Log.Comment("Expect KeepAliveFailure");
VerifyStream(response, server);
response.Close();
}
catch (Exception ex)
{
Log.Exception("Exception caught: ", ex);
}
finally
{
//Stop server
server.StopServer();
}
return result;
}
[TestMethod]
public TestResult TestWebExceptionHTTP1_1_Pending()
{
TestResult result = TestResult.Pass;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/Pending.html"); //expect Pending
wr.UserAgent = ".Net Micro Framwork Device/4.0";
wr.Method = "HEAD";
Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1
Log.Comment("Set Version 1.1");
wr.ProtocolVersion = new Version(1, 1);
HttpServer server = new HttpServer("http", ref result)
{
RequestUri = wr.RequestUri,
RequestHeaders = wr.Headers,
ResponseString = ""
};
try
{
// Setup server
server.StartServer();
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Log.Comment("Expect Pending");
VerifyStream(response, server);
response.Close();
}
catch (Exception ex)
{
Log.Exception("Exception caught: ", ex);
}
finally
{
//Stop server
server.StopServer();
}
return result;
}
[TestMethod]
public TestResult TestWebExceptionHTTP1_1_PipelineFailure()
{
TestResult result = TestResult.Pass;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/PipelineFailure.html"); //expect PipelineFailure
wr.UserAgent = ".Net Micro Framwork Device/4.0";
wr.Method = "HEAD";
Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1
Log.Comment("Set Version 1.1");
wr.ProtocolVersion = new Version(1, 1);
HttpServer server = new HttpServer("http", ref result)
{
RequestUri = wr.RequestUri,
RequestHeaders = wr.Headers,
ResponseString = ""
};
try
{
// Setup server
server.StartServer();
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Log.Comment("Expect PipelineFailure");
VerifyStream(response, server);
response.Close();
}
catch (Exception ex)
{
Log.Exception("Exception caught: ", ex);
}
finally
{
//Stop server
server.StopServer();
}
return result;
}
[TestMethod]
public TestResult TestWebExceptionHTTP1_1_ProxyNameResolutionFailure()
{
TestResult result = TestResult.Pass;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/ProxyNameResolutionFailure.html"); //expect ProxyNameResolutionFailure
wr.UserAgent = ".Net Micro Framwork Device/4.0";
wr.Method = "HEAD";
Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1
Log.Comment("Set Version 1.1");
wr.ProtocolVersion = new Version(1, 1);
HttpServer server = new HttpServer("http", ref result)
{
RequestUri = wr.RequestUri,
RequestHeaders = wr.Headers,
ResponseString = ""
};
try
{
// Setup server
server.StartServer();
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Log.Comment("Expect ProxyNameResolutionFailure");
VerifyStream(response, server);
response.Close();
}
catch (Exception ex)
{
Log.Exception("Exception caught: ", ex);
}
finally
{
//Stop server
server.StopServer();
}
return result;
}
[TestMethod]
public TestResult TestWebExceptionHTTP1_1_ReceiveFailure()
{
TestResult result = TestResult.Pass;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/ReceiveFailure.html"); //expect ReceiveFailure
wr.UserAgent = ".Net Micro Framwork Device/4.0";
wr.Method = "HEAD";
Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1
Log.Comment("Set Version 1.1");
wr.ProtocolVersion = new Version(1, 1);
HttpServer server = new HttpServer("http", ref result)
{
RequestUri = wr.RequestUri,
RequestHeaders = wr.Headers,
ResponseString = ""
};
try
{
// Setup server
server.StartServer();
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Log.Comment("Expect ReceiveFailure");
VerifyStream(response, server);
response.Close();
}
catch (Exception ex)
{
Log.Exception("Exception caught: ", ex);
}
finally
{
//Stop server
server.StopServer();
}
return result;
}
[TestMethod]
public TestResult TestWebExceptionHTTP1_1_RequestCanceled()
{
TestResult result = TestResult.Pass;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/RequestCanceled.html"); //expect RequestCanceled
wr.UserAgent = ".Net Micro Framwork Device/4.0";
wr.Method = "HEAD";
Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1
Log.Comment("Set Version 1.1");
wr.ProtocolVersion = new Version(1, 1);
HttpServer server = new HttpServer("http", ref result)
{
RequestUri = wr.RequestUri,
RequestHeaders = wr.Headers,
ResponseString = ""
};
try
{
// Setup server
server.StartServer();
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Log.Comment("Expect RequestCanceled");
VerifyStream(response, server);
response.Close();
}
catch (Exception ex)
{
Log.Exception("Exception caught: ", ex);
}
finally
{
//Stop server
server.StopServer();
}
return result;
}
[TestMethod]
public TestResult TestWebExceptionHTTP1_1_SecureChannelFailure()
{
TestResult result = TestResult.Pass;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/SecureChannelFailure.html"); //expect SecureChannelFailure
wr.UserAgent = ".Net Micro Framwork Device/4.0";
wr.Method = "HEAD";
Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1
Log.Comment("Set Version 1.1");
wr.ProtocolVersion = new Version(1, 1);
HttpServer server = new HttpServer("http", ref result)
{
RequestUri = wr.RequestUri,
RequestHeaders = wr.Headers,
ResponseString = ""
};
try
{
// Setup server
server.StartServer();
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Log.Comment("Expect SecureChannelFailure");
VerifyStream(response, server);
response.Close();
}
catch (Exception ex)
{
Log.Exception("Exception caught: ", ex);
}
finally
{
//Stop server
server.StopServer();
}
return result;
}
[TestMethod]
public TestResult TestWebExceptionHTTP1_1_SendFailure()
{
TestResult result = TestResult.Pass;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/SendFailure.html"); //expect SendFailure
wr.UserAgent = ".Net Micro Framwork Device/4.0";
wr.Method = "HEAD";
Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1
Log.Comment("Set Version 1.1");
wr.ProtocolVersion = new Version(1, 1);
HttpServer server = new HttpServer("http", ref result)
{
RequestUri = wr.RequestUri,
RequestHeaders = wr.Headers,
ResponseString = ""
};
try
{
// Setup server
server.StartServer();
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Log.Comment("Expect SendFailure");
VerifyStream(response, server);
response.Close();
}
catch (Exception ex)
{
Log.Exception("Exception caught: ", ex);
}
finally
{
//Stop server
server.StopServer();
}
return result;
}
[TestMethod]
public TestResult TestWebExceptionHTTP1_1_Success()
{
TestResult result = TestResult.Pass;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/Success.html"); //expect Success
wr.UserAgent = ".Net Micro Framwork Device/4.0";
wr.Method = "HEAD";
Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1
Log.Comment("Set Version 1.1");
wr.ProtocolVersion = new Version(1, 1);
HttpServer server = new HttpServer("http", ref result)
{
RequestUri = wr.RequestUri,
RequestHeaders = wr.Headers,
ResponseString = ""
};
try
{
// Setup server
server.StartServer();
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Log.Comment("Expect Success");
VerifyStream(response, server);
response.Close();
}
catch (Exception ex)
{
Log.Exception("Exception caught: ", ex);
}
finally
{
//Stop server
server.StopServer();
}
return result;
}
[TestMethod]
public TestResult TestWebExceptionHTTP1_1_Timeout()
{
TestResult result = TestResult.Pass;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/Timeout.html"); //expect Timeout
wr.UserAgent = ".Net Micro Framwork Device/4.0";
wr.Method = "HEAD";
Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1
Log.Comment("Set Version 1.1");
wr.ProtocolVersion = new Version(1, 1);
HttpServer server = new HttpServer("http", ref result)
{
RequestUri = wr.RequestUri,
RequestHeaders = wr.Headers,
ResponseString = ""
};
try
{
// Setup server
server.StartServer();
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Log.Comment("Expect Timeout");
VerifyStream(response, server);
response.Close();
}
catch (Exception ex)
{
Log.Exception("Exception caught: ", ex);
}
finally
{
//Stop server
server.StopServer();
}
return result;
}
[TestMethod]
public TestResult TestWebExceptionHTTP1_1_TrustFailure()
{
TestResult result = TestResult.Pass;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/TrustFailure.html"); //expect TrustFailure
wr.UserAgent = ".Net Micro Framwork Device/4.0";
wr.Method = "HEAD";
Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1
Log.Comment("Set Version 1.1");
wr.ProtocolVersion = new Version(1, 1);
HttpServer server = new HttpServer("http", ref result)
{
RequestUri = wr.RequestUri,
RequestHeaders = wr.Headers,
ResponseString = ""
};
try
{
// Setup server
server.StartServer();
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Log.Comment("Expect TrustFailure");
VerifyStream(response, server);
response.Close();
}
catch (Exception ex)
{
Log.Exception("Exception caught: ", ex);
}
finally
{
//Stop server
server.StopServer();
}
return result;
}
[TestMethod]
public TestResult TestWebExceptionHTTP1_1_ConnectFailure()
{
TestResult result = TestResult.Pass;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/ConnectFailure.html"); //expect ConnectFailure
wr.UserAgent = ".Net Micro Framwork Device/4.0";
wr.Method = "HEAD";
Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1
Log.Comment("Set Version 1.1");
wr.ProtocolVersion = new Version(1, 1);
HttpServer server = new HttpServer("http", ref result)
{
RequestUri = wr.RequestUri,
RequestHeaders = wr.Headers,
ResponseString = ""
};
try
{
// Setup server
server.StartServer();
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Log.Comment("Expect ConnectFailure");
VerifyStream(response, server);
response.Close();
}
catch (Exception ex)
{
Log.Exception("Exception caught: ", ex);
}
finally
{
//Stop server
server.StopServer();
}
return result;
}
[TestMethod]
public TestResult TestWebExceptionHTTP1_1_NameResolutionFailure()
{
TestResult result = TestResult.Pass;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/NameResolutionFailure.html"); //expect NameResolutionFailure
wr.UserAgent = ".Net Micro Framwork Device/4.0";
wr.Method = "HEAD";
Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1
Log.Comment("Set Version 1.1");
wr.ProtocolVersion = new Version(1, 1);
HttpServer server = new HttpServer("http", ref result)
{
RequestUri = wr.RequestUri,
RequestHeaders = wr.Headers,
ResponseString = ""
};
try
{
// Setup server
server.StartServer();
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Log.Comment("Expect NameResolutionFailure");
VerifyStream(response, server);
response.Close();
}
catch (Exception ex)
{
Log.Exception("Exception caught: ", ex);
}
finally
{
//Stop server
server.StopServer();
}
return result;
}
[TestMethod]
public TestResult TestWebExceptionHTTP1_1_ProtocolError()
{
TestResult result = TestResult.Pass;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/ProtocolError.html"); //expect ProtocolError
wr.UserAgent = ".Net Micro Framwork Device/4.0";
wr.Method = "HEAD";
Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1
Log.Comment("Set Version 1.1");
wr.ProtocolVersion = new Version(1, 1);
HttpServer server = new HttpServer("http", ref result)
{
RequestUri = wr.RequestUri,
RequestHeaders = wr.Headers,
ResponseString = ""
};
try
{
// Setup server
server.StartServer();
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Log.Comment("Expect ProtocolError");
VerifyStream(response, server);
response.Close();
}
catch (Exception ex)
{
Log.Exception("Exception caught: ", ex);
}
finally
{
//Stop server
server.StopServer();
}
return result;
}
[TestMethod]
public TestResult TestWebExceptionHTTP1_1_ServerProtocolViolation()
{
TestResult result = TestResult.Pass;
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/webexception/ServerProtocolViolation.html"); //expect ServerProtocolViolation
wr.UserAgent = ".Net Micro Framwork Device/4.0";
wr.Method = "HEAD";
Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1
Log.Comment("Set Version 1.1");
wr.ProtocolVersion = new Version(1, 1);
HttpServer server = new HttpServer("http", ref result)
{
RequestUri = wr.RequestUri,
RequestHeaders = wr.Headers,
ResponseString = ""
};
try
{
// Setup server
server.StartServer();
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Log.Comment("Expect ServerProtocolViolation");
VerifyStream(response, server);
response.Close();
}
catch (Exception ex)
{
Log.Exception("Exception caught: ", ex);
}
finally
{
//Stop server
server.StopServer();
}
return result;
}
#endregion Test
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Net;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Photos;
using Google.GData.Extensions.MediaRss;
using System.Collections.Generic;
using Google.GData.Extensions.Location;
using System.ComponentModel;
namespace Google.Picasa
{
/// <summary>
/// as all picasa entries are "similiar" we have this abstract baseclass here as
/// well, although it is not clear yet how this will benefit
/// </summary>
/// <returns></returns>
public abstract class PicasaEntity : Entry
{
/// <summary>
/// readonly accessor for the AlbumEntry that is underneath this object.
/// </summary>
/// <returns></returns>
public PicasaEntry PicasaEntry
{
get
{
EnsureInnerObject();
return this.AtomEntry as PicasaEntry;
}
}
}
public class Album : PicasaEntity
{
/// <summary>
/// needs to be subclassed to ensure the creation of the corrent AtomEntry based
/// object
/// </summary>
protected override void EnsureInnerObject()
{
if (this.AtomEntry == null)
{
this.AtomEntry = new AlbumEntry();
}
}
/// <summary>
/// The album's access level. In this document, access level is also
/// referred to as "visibility." Valid values are public or private.
/// </summary>
[Category("Meta Album Data"),
Description("Specifies the access for the album.")]
public string Access
{
get
{
return this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.Access);
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.Access, value);
}
}
/// <summary>
/// The nickname of the author
/// </summary>
[Category("Base Album Data"),
Description("Specifies the author's nickname")]
public string AlbumAuthorNickname
{
get
{
return this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.Nickname);
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.Nickname, value);
}
}
/// <summary>
/// The number of bytes of storage that this album uses.
/// </summary>
[Category("Meta Album Data"),
Description("Specifies the bytes used for the album.")]
[CLSCompliant(false)]
public uint BytesUsed
{
get
{
return Convert.ToUInt32(this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.BytesUsed));
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.BytesUsed, Convert.ToString(value));
}
}
/// <summary>
/// The user-specified location associated with the album
/// </summary>
[Category("Location Data"),
Description("Specifies the location for the album.")]
public string Location
{
get
{
return this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.Location);
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.Location, value);
}
}
/// <summary>
/// the Longitude of the photo
/// </summary>
[Category("Location Data"),
Description("The longitude of the photo.")]
public double Longitude
{
get
{
GeoRssWhere w = this.PicasaEntry.FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
if (w != null)
{
return w.Longitude;
}
return -1;
}
set
{
GeoRssWhere w = this.PicasaEntry.FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
if (w == null)
{
w = this.PicasaEntry.CreateExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
this.PicasaEntry.ExtensionElements.Add(w);
}
w.Longitude = value;
}
}
/// <summary>
/// the Longitude of the photo
/// </summary>
[Category("Location Data"),
Description("The Latitude of the photo.")]
public double Latitude
{
get
{
GeoRssWhere w = this.PicasaEntry.FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
if (w != null)
{
return w.Latitude;
}
return -1;
}
set
{
GeoRssWhere w = this.PicasaEntry.FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
if (w == null)
{
w = this.PicasaEntry.CreateExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
this.PicasaEntry.ExtensionElements.Add(w);
}
w.Latitude = value;
}
}
/// <summary>
/// The number of photos in the album.
/// </summary>
///
[Category("Meta Album Data"),
Description("Specifies the number of photos in the album.")]
[CLSCompliant(false)]
public uint NumPhotos
{
get
{
return Convert.ToUInt32(this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.NumPhotos));
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.NumPhotos, Convert.ToString(value));
}
}
/// <summary>
/// The number of remaining photo uploads allowed in this album.
/// This is equivalent to the user's maximum number of photos per
/// album (gphoto:maxPhotosPerAlbum) minus the number of photos
/// currently in the album (gphoto:numphotos).
/// </summary>
[Category("Meta Album Data"),
Description("Specifies the number of remaining photo uploads for the album.")]
[CLSCompliant(false)]
public uint NumPhotosRemaining
{
get
{
return Convert.ToUInt32(this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.NumPhotosRemaining));
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.NumPhotosRemaining, Convert.ToString(value));
}
}
/// <summary>
/// the number of comments on an album
/// </summary>
[Category("Commenting"),
Description("Specifies the number of comments for the album.")]
[CLSCompliant(false)]
public uint CommentCount
{
get
{
return Convert.ToUInt32(this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.CommentCount));
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.CommentCount, Convert.ToString(value));
}
}
/// <summary>
/// is commenting enabled on an album
/// </summary>
[Category("Commenting"),
Description("Comments enabled?")]
public bool CommentingEnabled
{
get
{
return Convert.ToBoolean(this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.CommentingEnabled));
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.CommentingEnabled, Utilities.ConvertBooleanToXSDString(value));
}
}
/// <summary>
/// the id of the album
/// </summary>
[Category("Base Album Data"),
Description("Specifies the id for the album.")]
public string Id
{
get
{
return this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.Id);
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.Id, value);
}
}
}
/// <summary>
/// The Tag is just a base PicasaEntity, beside the category it is not different
/// from a standard atom entry
/// </summary>
/// <returns></returns>
public class Tag : PicasaEntity
{
/// <summary>
/// needs to be subclassed to ensure the creation of the corrent AtomEntry based
/// object
/// </summary>
protected override void EnsureInnerObject()
{
if (this.AtomEntry == null)
{
this.AtomEntry = new TagEntry();
}
}
}
/// <summary>
/// a comment object for a picasa photo
/// </summary>
/// <returns></returns>
public class Comment : PicasaEntity
{
/// <summary>
/// needs to be subclassed to ensure the creation of the corrent AtomEntry based
/// object
/// </summary>
protected override void EnsureInnerObject()
{
if (this.AtomEntry == null)
{
this.AtomEntry = new CommentEntry();
}
}
/// <summary>
/// The ID of the photo associated with the current comment.
/// </summary>
[Category("Base Comment Data"),
Description("The ID of the photo associated with the current comment.")]
public string PhotoId
{
get
{
return this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.Photoid);
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.Photoid, value);
}
}
/// <summary>
/// The albums ID
/// </summary>
[Category("Base Comment Data"),
Description("The ID of the album associated with the current comment.")]
public string AlbumId
{
get
{
return this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.AlbumId);
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.AlbumId, value);
}
}
/// <summary>
/// the id of the comment
/// </summary>
[Category("Base Comment Data"),
Description("The ID of the comment itself.")]
public string CommentId
{
get
{
return this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.Id);
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.Id, value);
}
}
}
/// <summary>
/// represents a photo based on a PicasaEntry object
/// </summary>
public class Photo : PicasaEntity
{
/// <summary>
/// creates the inner contact object when needed
/// </summary>
/// <returns></returns>
protected override void EnsureInnerObject()
{
if (this.AtomEntry == null)
{
this.AtomEntry = new PhotoEntry();
}
}
/// <summary>
/// tries to construct an URI on the Url attribute in media.content
/// </summary>
/// <returns>a Uri object or null</returns>
[Category("Base Photo Data"),
Description("Returns the URL to the photo media.")]
public Uri PhotoUri
{
get
{
EnsureInnerObject();
if (this.PicasaEntry.Media != null &&
this.PicasaEntry.Media.Content != null)
{
return new Uri(this.PicasaEntry.Media.Content.Attributes["url"] as string);
}
return null;
}
set
{
EnsureMediaContent();
this.PicasaEntry.Media.Content.Attributes["url"] = value.AbsoluteUri;
}
}
/// <summary>
/// The checksum on the photo. This optional field can be used by
/// uploaders to associate a checksum with a photo to ease duplicate detection
/// </summary>
[Category("Meta Photo Data"),
Description("The checksum on the photo.")]
public string Checksum
{
get
{
return this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.Checksum);
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.Checksum, value);
}
}
/// <summary>
/// The height of the photo in pixels
/// </summary>
[Category("Basic Photo Data"),
Description("The height of the photo in pixels.")]
public int Height
{
get
{
return Convert.ToInt32(this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.Height));
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.Height, Convert.ToString(value));
}
}
/// <summary>
/// The width of the photo in pixels
/// </summary>
[Category("Basic Photo Data"),
Description("The width of the photo in pixels.")]
public int Width
{
get
{
return Convert.ToInt32(this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.Width));
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.Width, Convert.ToString(value));
}
}
/// <summary>
/// The rotation of the photo in degrees, used to change the rotation of the photo. Will only be shown if
/// the rotation has not already been applied to the requested images.
/// </summary>
[Category("Basic Photo Data"),
Description("The rotation of the photo in degrees.")]
public int Rotation
{
get
{
return Convert.ToInt32(this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.Rotation));
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.Rotation, Convert.ToString(value));
}
}
/// <summary>
/// The size of the photo in bytes
/// </summary>
[Category("Basic Photo Data"),
Description("The size of the photo in bytes.")]
public long Size
{
get
{
return Convert.ToInt32(this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.Size));
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.Size, Convert.ToString(value));
}
}
/// <summary>
/// The photo's timestamp, represented as the number of milliseconds since
/// January 1st, 1970. Contains the date of the photo either set externally
/// or retrieved from the Exif data.
/// </summary>
[Category("Meta Photo Data"),
Description("The photo's timestamp")]
[CLSCompliant(false)]
public ulong Timestamp
{
get
{
return Convert.ToUInt64(this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.Timestamp));
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.Timestamp, Convert.ToString(value));
}
}
/// <summary>
/// The albums ID
/// </summary>
[Category("Meta Photo Data"),
Description("The albums ID.")]
public string AlbumId
{
get
{
return this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.AlbumId);
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.AlbumId, value);
}
}
/// <summary>
/// the number of comments on a photo
/// </summary>
[Category("Commenting"),
Description("the number of comments on a photo.")]
[CLSCompliant(false)]
public uint CommentCount
{
get
{
return Convert.ToUInt32(this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.CommentCount));
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.CommentCount, Convert.ToString(value));
}
}
/// <summary>
/// is commenting enabled on a photo
/// </summary>
[Category("Commenting"),
Description("is commenting enabled on a photo.")]
public bool CommentingEnabled
{
get
{
return Convert.ToBoolean(this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.CommentingEnabled));
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.CommentingEnabled, Utilities.ConvertBooleanToXSDString(value));
}
}
/// <summary>
/// the id of the photo
/// </summary>
[Category("Meta Photo Data"),
Description("the id of the photo.")]
public string Id
{
get
{
return this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.Id);
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.Id, value);
}
}
/// <summary>
/// the Longitude of the photo
/// </summary>
[Category("Location Photo Data"),
Description("The longitude of the photo.")]
public double Longitude
{
get
{
GeoRssWhere where = this.PicasaEntry.FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
if (where != null)
{
return where.Longitude;
}
return -1;
}
set
{
GeoRssWhere where = this.PicasaEntry.FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
if (where == null)
{
where = this.PicasaEntry.CreateExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
this.PicasaEntry.ExtensionElements.Add(where);
}
where.Longitude = value;
}
}
/// <summary>
/// the Longitude of the photo
/// </summary>
[Category("Location Photo Data"),
Description("The Latitude of the photo.")]
public double Latitude
{
get
{
GeoRssWhere where = this.PicasaEntry.FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
if (where != null)
{
return where.Latitude;
}
return -1;
}
set
{
GeoRssWhere where = this.PicasaEntry.FindExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
if (where == null)
{
where = this.PicasaEntry.CreateExtension(GeoNametable.GeoRssWhereElement, GeoNametable.NSGeoRss) as GeoRssWhere;
this.PicasaEntry.ExtensionElements.Add(where);
}
where.Latitude = value;
}
}
/// <summary>
/// Description of the album this photo is in.
/// </summary>
[Category("Base Photo Data"),
Description("Description of the album this photo is in.")]
public string AlbumDescription
{
get
{
return this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.AlbumDesc);
}
set
{
this.PicasaEntry.SetPhotoExtensionValue(GPhotoNameTable.AlbumDesc, value);
}
}
/// <summary>
/// Snippet that matches the search text.
/// </summary>
[Category("Search Photo Data"),
Description("Snippet that matches the search text.")]
public string Snippet
{
get
{
return this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.Snippet);
}
}
/// <summary>
/// Describes where the match with the search query was found, and thus where
/// the snippet is from: the photo caption, the photo tags, the album title,
/// the album description, or the album location.
/// Possible values are PHOTO_DESCRIPTION, PHOTO_TAGS, ALBUM_TITLE,
/// ALBUM_DESCRIPTION, or ALBUM_LOCATION.
/// </summary>
[Category("Search Photo Data"),
Description("Describes where the match with the search query was found.")]
public string SnippetType
{
get
{
return this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.SnippetType);
}
}
/// <summary>
/// Indicates whether search results are truncated or not.
/// Possible values are 1 (results are truncated) or 0 (results are not truncated).
/// </summary>
[Category("Search Photo Data"),
Description("Indicates whether search results are truncated or not.")]
public string Truncated
{
get
{
return this.PicasaEntry.GetPhotoExtensionValue(GPhotoNameTable.Truncated);
}
}
private void EnsureMediaContent()
{
EnsureInnerObject();
if (this.PicasaEntry.Media == null)
{
this.PicasaEntry.Media = new MediaGroup();
}
if (this.PicasaEntry.Media.Content == null)
{
this.PicasaEntry.Media.Content = new MediaContent();
}
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>
/// The Picasa Web Albums Data API allows client applications to view and
/// update albums, photos, and comments in the form of Google Data API feeds.
/// Your client application can use the Picasa Web Albums Data API to create
/// new albums, upload photos, add comments, edit or delete existing albums,
/// photos, and comments, and query for items that match particular criteria.
/// </summary>
/// <example>
/// The following code illustrates a possible use of
/// the <c>PicasaRequest</c> object:
/// <code>
/// RequestSettings settings = new RequestSettings("yourApp");
/// settings.PageSize = 50;
/// settings.AutoPaging = true;
/// PicasaRequest pr = new PicasaRequest(settings);
/// Feed<Photo> feed = c.GetPhotos();
///
/// foreach (Photo p in feed.Entries)
/// {
/// Console.WriteLine(d.Title);
/// }
/// </code>
/// </example>
//////////////////////////////////////////////////////////////////////
public class PicasaRequest : FeedRequest<PicasaService>
{
/// <summary>
/// default constructor for a PicasaRequest
/// </summary>
/// <param name="settings"></param>
public PicasaRequest(RequestSettings settings) : base(settings)
{
this.Service = new PicasaService(settings.Application);
PrepareService();
}
/// <summary>
/// returns the list of Albums for the default user
/// </summary>
public Feed<Album> GetAlbums()
{
AlbumQuery q = PrepareQuery<AlbumQuery>(PicasaQuery.CreatePicasaUri(Utilities.DefaultUser));
return PrepareFeed<Album>(q);
}
/// <summary>
/// returns a Feed of all photos for the authorized user
/// </summary>
/// <returns>a feed of everyting</returns>
public Feed<Photo> GetPhotos()
{
PhotoQuery q = PrepareQuery<PhotoQuery>(PicasaQuery.CreatePicasaUri(Utilities.DefaultUser));
return PrepareFeed<Photo>(q);
}
/// <summary>
/// returns a feed of photos in that particular album for the default user
/// </summary>
/// <param name="albumId"></param>
/// <returns></returns>
public Feed<Photo> GetPhotosInAlbum(string albumId)
{
PhotoQuery q = PrepareQuery<PhotoQuery>(PicasaQuery.CreatePicasaUri(Utilities.DefaultUser, albumId));
return PrepareFeed<Photo>(q);
}
/// <summary>
/// Returns the comments a single photo based on
/// the default user, the albumid and the photoid
/// </summary>
/// <param name="albumId">The Id of the Album</param>
/// <param name="photoId">The id of the photo</param>
/// <returns></returns>
public Feed<Comment> GetComments(string albumId, string photoId)
{
CommentsQuery q = PrepareQuery<CommentsQuery>(PicasaQuery.CreatePicasaUri(Utilities.DefaultUser, albumId, photoId));
return PrepareFeed<Comment>(q);
}
/// <summary>
/// Get all Tags for the default user
/// </summary>
/// <returns></returns>
public Feed<Tag> GetTags()
{
TagQuery q = PrepareQuery<TagQuery>(PicasaQuery.CreatePicasaUri(Utilities.DefaultUser));
return PrepareFeed<Tag>(q);
}
/// <summary>
/// downloads a photo.
/// </summary>
/// <param name="photo">The photo to download.
/// <returns>either a stream to the photo, or NULL if the photo has no media URL set</returns>
public Stream Download(Photo photo)
{
Service s = this.Service;
Uri target = photo.PhotoUri;
if (target != null)
{
return s.Query(target);
}
return null;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace Lucene.Net.Search
{
/// <summary> Stores information about how to sort documents by terms in an individual
/// field. Fields must be indexed in order to sort by them.
/// </summary>
/// <since> lucene 1.4
/// </since>
/// <version> $Id: SortField.java 598296 2007-11-26 14:52:01Z mikemccand $
/// </version>
/// <seealso cref="Sort">
/// </seealso>
[Serializable]
public class SortField
{
/// <summary>Sort by document score (relevancy). Sort values are Float and higher
/// values are at the front.
/// </summary>
public const int SCORE = 0;
/// <summary>Sort by document number (index order). Sort values are Integer and lower
/// values are at the front.
/// </summary>
public const int DOC = 1;
/// <summary>Guess type of sort based on field contents. A regular expression is used
/// to look at the first term indexed for the field and determine if it
/// represents an integer number, a floating point number, or just arbitrary
/// string characters.
/// </summary>
public const int AUTO = 2;
/// <summary>Sort using term values as Strings. Sort values are String and lower
/// values are at the front.
/// </summary>
public const int STRING = 3;
/// <summary>Sort using term values as encoded Integers. Sort values are Integer and
/// lower values are at the front.
/// </summary>
public const int INT = 4;
/// <summary>Sort using term values as encoded Floats. Sort values are Float and
/// lower values are at the front.
/// </summary>
public const int FLOAT = 5;
/// <summary>Sort using term values as encoded Longs. Sort values are Long and
/// lower values are at the front.
/// </summary>
public const int LONG = 6;
/// <summary>Sort using term values as encoded Doubles. Sort values are Double and
/// lower values are at the front.
/// </summary>
public const int DOUBLE = 7;
/// <summary>
/// Sort using term values as encoded shorts.
/// Sort values are shorts and lower values are at the front.
/// </summary>
public const int SHORT = 8;
/// <summary>Sort using a custom Comparator. Sort values are any Comparable and
/// sorting is done according to natural order.
/// </summary>
public const int CUSTOM = 9;
/// <summary>
/// Sort using term values as encoded bytes.
/// Sort values are bytes and lower values are at the front.
/// </summary>
public const int BYTE = 10;
// IMPLEMENTATION NOTE: the FieldCache.STRING_INDEX is in the same "namespace"
// as the above static int values. Any new values must not have the same value
// as FieldCache.STRING_INDEX.
/// <summary>Represents sorting by document score (relevancy). </summary>
public static readonly SortField FIELD_SCORE = new SortField(null, SCORE);
/// <summary>Represents sorting by document number (index order). </summary>
public static readonly SortField FIELD_DOC = new SortField(null, DOC);
private System.String field;
private int type = AUTO; // defaults to determining type dynamically
private System.Globalization.CultureInfo locale; // defaults to "natural order" (no Locale)
internal bool reverse = false; // defaults to natural order
private SortComparatorSource factory;
/// <summary>Creates a sort by terms in the given field where the type of term value
/// is determined dynamically ({@link #AUTO AUTO}).
/// </summary>
/// <param name="field">Name of field to sort by, cannot be <code>null</code>.
/// </param>
public SortField(System.String field)
{
this.field = String.Intern(field);
}
/// <summary>Creates a sort, possibly in reverse, by terms in the given field where
/// the type of term value is determined dynamically ({@link #AUTO AUTO}).
/// </summary>
/// <param name="field">Name of field to sort by, cannot be <code>null</code>.
/// </param>
/// <param name="reverse">True if natural order should be reversed.
/// </param>
public SortField(System.String field, bool reverse)
{
this.field = String.Intern(field);
this.reverse = reverse;
}
/// <summary>Creates a sort by terms in the given field with the type of term
/// values explicitly given.
/// </summary>
/// <param name="field"> Name of field to sort by. Can be <code>null</code> if
/// <code>type</code> is SCORE or DOC.
/// </param>
/// <param name="type"> Type of values in the terms.
/// </param>
public SortField(System.String field, int type)
{
this.field = (field != null) ? String.Intern(field) : field;
this.type = type;
}
/// <summary>Creates a sort, possibly in reverse, by terms in the given field with the
/// type of term values explicitly given.
/// </summary>
/// <param name="field"> Name of field to sort by. Can be <code>null</code> if
/// <code>type</code> is SCORE or DOC.
/// </param>
/// <param name="type"> Type of values in the terms.
/// </param>
/// <param name="reverse">True if natural order should be reversed.
/// </param>
public SortField(System.String field, int type, bool reverse)
{
this.field = (field != null) ? String.Intern(field) : field;
this.type = type;
this.reverse = reverse;
}
/// <summary>Creates a sort by terms in the given field sorted
/// according to the given locale.
/// </summary>
/// <param name="field"> Name of field to sort by, cannot be <code>null</code>.
/// </param>
/// <param name="locale">Locale of values in the field.
/// </param>
public SortField(System.String field, System.Globalization.CultureInfo locale)
{
this.field = String.Intern(field);
this.type = STRING;
this.locale = locale;
}
/// <summary>Creates a sort, possibly in reverse, by terms in the given field sorted
/// according to the given locale.
/// </summary>
/// <param name="field"> Name of field to sort by, cannot be <code>null</code>.
/// </param>
/// <param name="locale">Locale of values in the field.
/// </param>
public SortField(System.String field, System.Globalization.CultureInfo locale, bool reverse)
{
this.field = String.Intern(field);
this.type = STRING;
this.locale = locale;
this.reverse = reverse;
}
/// <summary>Creates a sort with a custom comparison function.</summary>
/// <param name="field">Name of field to sort by; cannot be <code>null</code>.
/// </param>
/// <param name="comparator">Returns a comparator for sorting hits.
/// </param>
public SortField(System.String field, SortComparatorSource comparator)
{
this.field = (field != null) ? String.Intern(field) : field;
this.type = CUSTOM;
this.factory = comparator;
}
/// <summary>Creates a sort, possibly in reverse, with a custom comparison function.</summary>
/// <param name="field">Name of field to sort by; cannot be <code>null</code>.
/// </param>
/// <param name="comparator">Returns a comparator for sorting hits.
/// </param>
/// <param name="reverse">True if natural order should be reversed.
/// </param>
public SortField(System.String field, SortComparatorSource comparator, bool reverse)
{
this.field = (field != null) ? String.Intern(field) : field;
this.type = CUSTOM;
this.reverse = reverse;
this.factory = comparator;
}
/// <summary>Returns the name of the field. Could return <code>null</code>
/// if the sort is by SCORE or DOC.
/// </summary>
/// <returns> Name of field, possibly <code>null</code>.
/// </returns>
public virtual System.String GetField()
{
return field;
}
/// <summary>Returns the type of contents in the field.</summary>
/// <returns> One of the constants SCORE, DOC, AUTO, STRING, INT or FLOAT.
/// </returns>
public new virtual int GetType()
{
return type;
}
/// <summary>Returns the Locale by which term values are interpreted.
/// May return <code>null</code> if no Locale was specified.
/// </summary>
/// <returns> Locale, or <code>null</code>.
/// </returns>
public virtual System.Globalization.CultureInfo GetLocale()
{
return locale;
}
/// <summary>Returns whether the sort should be reversed.</summary>
/// <returns> True if natural order should be reversed.
/// </returns>
public virtual bool GetReverse()
{
return reverse;
}
public virtual SortComparatorSource GetFactory()
{
return factory;
}
public override System.String ToString()
{
System.Text.StringBuilder buffer = new System.Text.StringBuilder();
switch (type)
{
case SCORE: buffer.Append("<score>");
break;
case DOC: buffer.Append("<doc>");
break;
case CUSTOM:
buffer.Append("<custom:\"").Append(field).Append("\": ").Append(factory).Append('>');
break;
default:
buffer.Append('\"').Append(field).Append('\"');
break;
}
if (locale != null)
buffer.Append('(').Append(locale).Append(')');
if (reverse)
buffer.Append('!');
return buffer.ToString();
}
}
}
| |
//#define DEBUG
using System;
using System.Collections.Generic;
using System.Text;
namespace ICSimulator
{
class EpochWireAlloc // one per direction
{
ulong[,] epochDue; // indexed by parity,epoch: cycle when epoch will be freed
int[] currentEpoch; // indexed by parity: epoch# currently filling (0 or 1)
int[] currentWire; // indexed by parity: current wire in epoch
public EpochWireAlloc()
{
epochDue = new ulong[2,2];
currentEpoch = new int[2];
currentWire = new int[2];
}
void checkEpoch(int parity)
{
if (currentWire[parity] >= Config.nack_nr / 2) // check if we ran out of wires.
{
// check if other epoch is expired.
if (epochDue[parity, 1 - currentEpoch[parity]] <= Simulator.CurrentRound)
{
// other epoch is expired: flip over to it.
currentEpoch[parity] = 1 - currentEpoch[parity];
epochDue[parity, currentEpoch[parity]] = 0;
currentWire[parity] = 0;
}
}
}
public int allocateNack(ulong due)
{
int parity = (int)(Simulator.CurrentRound & 1);
checkEpoch(parity);
// if no wires remaining, fail.
if (currentWire[parity] >= Config.nack_nr / 2)
return -1;
// allocate wire
if (epochDue[parity, currentEpoch[parity]] < due)
epochDue[parity, currentEpoch[parity]] = due;
return (currentEpoch[parity] * Config.nack_nr / 2) +
currentWire[parity]++;
}
public bool nackAvailable()
{
int parity = (int)(Simulator.CurrentRound & 1);
checkEpoch(parity);
return currentWire[parity] < Config.nack_nr / 2;
}
}
public class Router_SCARAB : Router
{
//Router_Flit_RXBuf m_rxbuf;
//bool m_real_rxbuf;
Flit m_injectSlot;
int[] nackRouting; // indexed by parity, output port; -1 for unallocated, -2 for local
// batch-based NACK wire allocation
// EpochWireAlloc[] allocator;
public Link[] nackOut = new Link[4*Config.nack_nr];
public Link[] nackIn = new Link[4*Config.nack_nr];
private double[] avgOutPriority = new double[4];
//private Dictionary<Packet, ulong> nack_due = new Dictionary<Packet, ulong>();
int[] wormRouting; // indexed by input port; -1 for no worm, -2 for dropping
public int parity()
{
return (int)(Simulator.CurrentRound & 1);
}
public int nackNr(int dir, int nackWireNr)
{
return dir * Config.nack_nr + nackWireNr;
}
public int nackWireNr(int nackNr)
{
return nackNr % Config.nack_nr;
}
public int nackDir(int nackNr)
{
return nackNr / Config.nack_nr;
}
public Router_SCARAB(Coord myCoord)
: base(myCoord)
{
m_injectSlot = null;
nackRouting = new int[Config.nack_nr * 4];
wormRouting = new int[5]; // fifth direction for local port
for (int i = 0; i < Config.nack_nr * 4; i++)
nackRouting[i] = -1;
for (int i = 0; i < 5; i++)
wormRouting[i] = -1;
/*
allocator = new EpochWireAlloc[4];
for (int i = 0; i < 4; i++)
allocator[i] = new EpochWireAlloc();
*/
}
private ulong ejectingPacket = ulong.MaxValue;
bool ejectLocal()
{
#if DEBUG
if (ID == 0) Console.WriteLine("------");
#endif
bool noneEjected = true;
for (int dir = 0; dir < 4; dir++)
if (linkIn[dir] != null && linkIn[dir].Out != null)
{
#if DEBUG
Console.WriteLine("flit at {0}: {1}", coord, linkIn[dir].Out);
#endif
if (linkIn[dir].Out.dest.ID == ID)
{
Flit f = linkIn[dir].Out;
f.inDir = dir;
#if DEBUG
Console.WriteLine("candidate ejection {0} at {1}", f, coord);
#endif
if (f.packet.ID == ejectingPacket || (f.isHeadFlit && noneEjected && ejectingPacket == ulong.MaxValue) || Config.router.ejectMultipleCheat)
{
#if DEBUG
Console.WriteLine("ejecting at {0}: flit {1}", coord, f);
#endif
statsEjectFlit(f);
m_n.receiveFlit(f);
#if DEBUG
Console.WriteLine("ejecting flit {0} of packet {1} ({2}/{3} arrived)", f.flitNr, f.packet.ID, f.packet.nrOfArrivedFlits, f.packet.nrOfFlits);
#endif
if (f.packet.nrOfArrivedFlits != f.flitNr+1)
throw new Exception("Out of order ejection!");
if (f.isHeadFlit)
{
sendTeardown(f);
ejectingPacket = f.packet.ID;
#if DEBUG
Console.WriteLine("ejecting packet {0}",f.packet.ID);
#endif
}
if (f.isTailFlit)
{
ejectingPacket = ulong.MaxValue;
#if DEBUG
Console.WriteLine("no longer ejecting packet {0}", f.packet.ID);
#endif
}
noneEjected = false;
}
else
if (f.isHeadFlit)
{
#if DEBUG
Console.WriteLine("SECONDARY EJECTION DROPPED at proc {0} with dir {1}", ID, dir);
#endif
sendNack(f);
wormRouting[dir] = -2;
Simulator.stats.drop.Add();
Simulator.stats.drop_by_src[ID].Add();
}
linkIn[dir].Out = null;
}
}
return noneEjected;
}
Flit[] input = new Flit[4]; // keep this as a member var so we don't
// have to allocate on every step (why can't
// we have arrays on the stack like in C?)
int RR = 0;
int getRR() { RR++; if (RR > 3) RR = 0; return RR; }
protected override void _doStep()
{
stepNacks();
/* bool ejectedThisCycle = */ ejectLocal();
for (int i = 0; i < 4; i++) input[i] = null;
// first, propagate the non-head flits along their worm paths
// (no truncation, so this is very simple)
for (int dir = 0; dir < 4; dir++)
{
if (linkIn[dir] != null && linkIn[dir].Out != null &&
!linkIn[dir].Out.isHeadFlit)
{
#if DEBUG
Console.WriteLine("non-head flit: {0}", linkIn[dir].Out);
#endif
Flit f = linkIn[dir].Out; // grab the input flit from the link
linkIn[dir].Out = null;
if (wormRouting[dir] == -1)
{
// AGH: worm not routed
throw new Exception("SHOULDN'T HAPPEN!");
}
if (wormRouting[dir] != -2) // if not dropping, propagate the flit
linkOut[wormRouting[dir]].In = f;
if (f.isTailFlit) // if last flit, close the wormhole
wormRouting[dir] = -1;
}
}
if (m_injectSlot != null && !m_injectSlot.isHeadFlit)
{
linkOut[wormRouting[4]].In = m_injectSlot;
if (m_injectSlot.isTailFlit)
wormRouting[4] = -1;
m_injectSlot = null;
}
// grab inputs into a local array
int c = 0;
for (int dir = 0; dir < 4; dir++)
if (linkIn[dir] != null && linkIn[dir].Out != null)
{
linkIn[dir].Out.inDir = dir; // record this for below
input[c++] = linkIn[dir].Out;
linkIn[dir].Out = null;
}
// step 1: get possible-output vectors for each input
bool[,] possible = new bool[4,4]; // (input,direction)
int[] possible_count = new int[4];
for (int i = 0; i < 4 && input[i] != null; i++)
{
PreferredDirection pd = determineDirection(input[i].dest);
if (pd.xDir != Simulator.DIR_NONE &&
linkOut[pd.xDir].In == null)
{
if (nackAvailable(pd.xDir))
possible[i,pd.xDir] = true;
else
{
Simulator.stats.nack_unavail.Add();
Simulator.stats.nack_unavail_by_src[ID].Add();
}
}
if (pd.yDir != Simulator.DIR_NONE &&
linkOut[pd.yDir].In == null)
{
if (nackAvailable(pd.yDir))
possible[i,pd.yDir] = true;
else
{
Simulator.stats.nack_unavail.Add();
Simulator.stats.nack_unavail_by_src[ID].Add();
}
}
}
// step 2: count possible requests per output
for (int i = 0; i < 4; i++)
for (int dir = 0; dir < 4; dir++)
if (possible[i,dir]) possible_count[dir]++;
// step 3: if more than one possible for a given request, pick one with least
// requests; if tie, break randomly
for (int i = 0; i < 4; i++)
{
int min_req = 10, min_req_j = -1;
for (int j = 0; j < 4; j++)
if (possible[i,j])
if (possible_count[j] < min_req)
{
min_req_j = j;
min_req = possible_count[j];
}
for (int j = 0; j < 4; j++) possible[i,j] = false;
if (min_req_j != -1)
possible[i, min_req_j] = true;
}
// step 4,5: compute maximum priority requesting each output; set everyone
// below this prio to false
for (int dir = 0; dir < 4; dir++)
{
int max_prio = -1;
for (int i = 0; i < 4; i++)
if (possible[i,dir])
if (input[i].packet.scarab_retransmit_count > max_prio)
max_prio = input[i].packet.scarab_retransmit_count;
for (int i = 0; i < 4; i++)
if (possible[i,dir] && input[i].packet.scarab_retransmit_count < max_prio)
possible[i,dir] = false;
}
// step 6: select a winner in round-robin fashion
int offset = getRR();
int[] assignments = new int[4];
for (int i = 0; i < 4; i++) assignments[i] = -1;
for (int i_ = 0; i_ < 4; i_++)
{
int i = (i_ + offset) % 4;
for (int dir = 0; dir < 4; dir++)
if (possible[i,dir])
{
assignments[i] = dir;
for (int j = 0; j < 4; j++)
possible[j,dir] = false;
}
}
//Flit oppBufferable = null;
// assign outputs, choose a flit to opp. buffer if appropriate
for (int i = 0; i < 4 && input[i] != null; i++)
{
int dir = assignments[i];
if (dir == -1)
{
// drop!
sendNack(input[i]);
wormRouting[input[i].inDir] = -2;
Simulator.stats.drop.Add();
Simulator.stats.drop_by_src[ID].Add();
}
else
{
double decay = 0.875; //TODO parameterize
avgOutPriority[dir] = avgOutPriority[dir] * (1 - decay) + input[i].packet.scarab_retransmit_count * decay;
/*
if (Config.opp_buffering
&& !ejectedThisCycle
&& input[i].packet.nrOfFlits == 1
&& myProcessor.msh.hasOppBufferSpace()
&& input[i].packet.scarab_retransmit_count < avgOutPriority[dir]
)
{
// buffer opportunistically! (choose highest priority packet)
if (oppBufferable == null || input[i].packet.scarab_retransmit_count > oppBufferable.packet.scarab_retransmit_count)
oppBufferable = input[i];
}
*/
}
}
for (int i = 0; i < 4 && input[i] != null; i++)
{
int dir = assignments[i];
if (dir == -1) continue;
int nackWire;
ulong due = Simulator.CurrentRound + 4 * (1 + Simulator.distance(coord, input[i].dest));
//nack_due[input[i].packet] = due;
/*
if (input[i] == oppBufferable)
{
Console.WriteLine("Opp Buffering flit!");
sendTeardown(oppBufferable);
myProcessor.ejectFlit(oppBufferable);
nackWire = allocateNack(dir, -2, due);
}
else
*/
nackWire = allocateNack(dir, nackNr(input[i].inDir, input[i].nackWire), due);
if (nackWire == -1)
throw new Exception("shouldn't happen");
input[i].nackWire = nackWire;
linkOut[dir].In = input[i];
wormRouting[input[i].inDir] = dir;
}
// now try to inject
if (m_injectSlot != null)
{
PreferredDirection pd = determineDirection(m_injectSlot.dest);
ulong due = Simulator.CurrentRound + 4 * (1 + Simulator.distance(coord, m_injectSlot.dest));
//nack_due[m_injectSlot.packet] = due;
if (pd.xDir != Simulator.DIR_NONE && linkOut[pd.xDir].In == null)
{
int nackWire = allocateNack(pd.xDir, -2, due);
if (nackWire != -1)
{
linkOut[pd.xDir].In = m_injectSlot;
m_injectSlot.nackWire = nackWire;
m_injectSlot = null;
wormRouting[4] = pd.xDir;
}
}
if (m_injectSlot != null && // check this again: only try y if x didn't work
pd.yDir != Simulator.DIR_NONE && linkOut[pd.yDir].In == null)
{
int nackWire = allocateNack(pd.yDir, -2, due);
if (nackWire != -1)
{
linkOut[pd.yDir].In = m_injectSlot;
m_injectSlot.nackWire = nackWire;
m_injectSlot = null;
wormRouting[4] = pd.yDir;
}
}
}
}
void stepNacks()
{
// int p = parity();
for (int i = 0; i < Config.nack_nr * 4; i++)
{
if (nackIn[i] != null && nackIn[i].Out != null)
{
if (nackRouting[i] == -2) // local?
{
/*
if (Config.nack_epoch)
{
if (nack_due[nackIn[i].Out.packet.scarab_retransmit] < Simulator.CurrentRound)
{
#if DEBUG
Console.WriteLine("late nack: due {0}, t = {1} (ID = {2})",
nack_due[nackIn[i].Out.packet.scarab_retransmit], Simulator.CurrentRound,
nackIn[i].Out.packet.scarab_retransmit.ID);
#endif
}
}
*/
if (nackIn[i].Out.packet.scarab_is_nack)
{
Packet p = nackIn[i].Out.packet.scarab_retransmit;
p.nrOfArrivedFlits = 0;
m_n.queuePacket(p);
}
//else if (nackIn[i].Out.packet.scarab_is_teardown)
// myProcessor.deliverTeardown(nackIn[i].Out.packet);
}
else
{
#if DEBUG
Console.WriteLine("Proc {2} nack routing from in {0} to out {1}", i, nackRouting[i], ID);
#endif
nackOut[nackRouting[i]].In = nackIn[i].Out;
}
// now we tear it down (a NACK or TEARDOWN only comes once in a circuit)
nackRouting[i] = -1;
}
}
}
bool nackAvailable(int outDir)
{
// int p = parity();
// if (Config.nack_epoch)
// return allocator[outDir].nackAvailable();
// else
// {
for (int wireNr = 0; wireNr < Config.nack_nr; wireNr++)
{
int nNr = nackNr(outDir, wireNr);
if (nackOut[nNr] != null && nackRouting[nNr] == -1)
return true;
}
return false;
// }
}
int allocateNack(int outDir, int inNr, ulong due)
{
// int p = parity();
if (!nackAvailable(outDir))
return -1;
// if (Config.nack_epoch)
// {
// int nNr = allocator[outDir].allocateNack(due);
// int outNr = nackNr(outDir, nNr);
// if (nackRouting[outNr] != -1) throw new Exception("re-allocated wire!");
// nackRouting[outNr] = inNr;
// return nNr;
// }
// else
// {
int wireNr;
for (wireNr = 0; wireNr < Config.nack_nr; wireNr++)
{
int nNr = nackNr(outDir, wireNr);
if (nackOut[nNr] != null && nackRouting[nNr] == -1)
break;
}
int outNr = nackNr(outDir, wireNr);
nackRouting[outNr] = inNr;
return wireNr; // return wire#, not global nack#
// }
}
void sendNack(Flit f)
{
int nNr = nackNr(f.inDir, f.nackWire);
// Console.WriteLine("\tProc {4}:sendNack for ID {0}: inDir = {1}, nackWire = {2}, nNr = {3}",
// f.packet.ID, f.inDir, f.nackWire, nNr, ID);
Packet p = new Packet(f.packet.request, 0, 1, coord, f.packet.src);
p.scarab_retransmit = f.packet;
f.packet.scarab_retransmit_count++;
p.scarab_is_nack = true;
nackOut[nNr].In = p.flits[0];
}
void sendTeardown(Flit f)
{
// Console.WriteLine("\tProc {3}:Teardown for ID {0}: inDir = {1}, nackWire = {2} (packet src {4}, dest {5})",
// f.packet.ID, f.inDir, f.nackWire, ID, f.packet.source.ID, f.packet.dest.ID);
int nNr = nackNr(f.inDir, f.nackWire);
Packet p = new Packet(f.packet.request, 0, 1, coord, f.packet.src);
p.scarab_retransmit = f.packet; // don't actually retransmit, but keep this for debugging
p.scarab_is_teardown = true;
/*
// these two pieces of data are recorded to let a processor receiveing
// a teardown whether it should look for an opp buffering slot to be cleared
p.ID = f.packet.ID;
p.source = f.packet.source;
*/
nackOut[nNr].In = p.flits[0];
}
public override bool canInjectFlit(Flit f)
{
#if DEBUG
Console.WriteLine("canInjectFlit at {0}: answer is {1}", coord, m_injectSlot == null);
#endif
return m_injectSlot == null;
}
public override void InjectFlit(Flit f)
{
if (m_injectSlot != null)
throw new Exception("Trying to inject twice in one cycle");
#if DEBUG
Console.WriteLine("injectFlit at {0}: {1}", coord, f);
#endif
statsInjectFlit(f);
m_injectSlot = f;
}
}
}
//#endif
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Media;
using Windows.Media.DialProtocol;
using ScreenCasting.Data.Azure;
using System.Collections.Generic;
using ScreenCasting.Data.Common;
using Windows.Devices.Enumeration;
using System.Threading.Tasks;
using Windows.Media.Casting;
using ScreenCasting.Controls;
using ScreenCasting.Util;
using Windows.UI;
using Windows.UI.ViewManagement;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
namespace ScreenCasting
{
public sealed partial class Scenario2 : Page
{
private const int MAX_RESULTS = 10;
private MainPage rootPage;
private DevicePicker picker = null;
private DeviceInformation activeDevice = null;
private object activeCastConnectionHandler = null;
private VideoMetaData video = null;
int thisViewId;
public Scenario2()
{
this.InitializeComponent();
rootPage = MainPage.Current;
// Get the list of available Azure videos.
AzureDataProvider dataProvider = new AzureDataProvider();
List<VideoMetaData> videos = dataProvider.GetAll(MAX_RESULTS);
Random indexRandomizer = new Random();
// Pick a random video
video = videos[indexRandomizer.Next(0, videos.Count - 1)];
//Subscribe to player events
player.MediaOpened += Player_MediaOpened;
player.MediaFailed += Player_MediaFailed;
player.CurrentStateChanged += Player_CurrentStateChanged;
//Set the look and feel of the TransportControls
player.TransportControls.IsCompact = true;
//Set the source on the player
rootPage.NotifyUser(string.Format("Opening '{0}'", video.Title), NotifyType.StatusMessage);
player.Source = video.VideoLink;
//Configure the DIAL launch arguments for the current video
this.dial_launch_args_textbox.Text = string.Format("v={0}&t=0&pairingCode=E4A8136D-BCD3-45F4-8E49-AE01E9A46B5F", video.Id);
//Subscribe for the clicked event on the custom cast button
((MediaTransportControlsWithCustomCastButton)this.player.TransportControls).CastButtonClicked += TransportControls_CastButtonClicked;
// Instantiate the Device Picker
picker = new DevicePicker();
//Hook up device selected event
picker.DeviceSelected += Picker_DeviceSelected;
//Hook up device disconnected event
picker.DisconnectButtonClicked += Picker_DisconnectButtonClicked;
//Hook up device disconnected event
picker.DevicePickerDismissed += Picker_DevicePickerDismissed;
////Set the Appearence of the picker
//picker.Appearance.BackgroundColor = Colors.Black;
//picker.Appearance.ForegroundColor = Colors.White;
//picker.Appearance.SelectedAccentColor = Colors.LightGray;
//picker.Appearance.SelectedForegroundColor = Colors.White;
//picker.Appearance.AccentColor = Colors.White;
//picker.Appearance.SelectedAccentColor = Colors.White;
pvb.ProjectionStopping += Pvb_ProjectionStopping;
}
ProjectionViewBroker pvb = new ProjectionViewBroker();
private async void TransportControls_CastButtonClicked(object sender, EventArgs e)
{
//Pause Current Playback
player.Pause();
rootPage.NotifyUser("Show Device Picker Button Clicked", NotifyType.StatusMessage);
//Get the custom transport controls
MediaTransportControlsWithCustomCastButton mtc = (MediaTransportControlsWithCustomCastButton)this.player.TransportControls;
//Retrieve the location of the casting button
GeneralTransform transform = mtc.CastButton.TransformToVisual(Window.Current.Content as UIElement);
Point pt = transform.TransformPoint(new Point(0, 0));
//Add the DIAL Filter, so that the application only shows DIAL devices that have the application installed or advertise that they can install them.
picker.Filter.SupportedDeviceSelectors.Add(DialDevice.GetDeviceSelector(this.dial_appname_textbox.Text));
System.Diagnostics.Debug.WriteLine(DialDevice.GetDeviceSelector(this.dial_appname_textbox.Text));
//Add the CAST API Filter, so that the application only shows Miracast, Bluetooth, DLNA devices that can render the video
//picker.Filter.SupportedDeviceSelectors.Add(await CastingDevice.GetDeviceSelectorFromCastingSourceAsync(player.GetAsCastingSource()));
//picker.Filter.SupportedDeviceSelectors.Add(CastingDevice.GetDeviceSelector(CastingPlaybackTypes.Video));
//picker.Filter.SupportedDeviceSelectors.Add("System.Devices.InterfaceClassGuid:=\"{D0875FB4-2196-4c7a-A63D-E416ADDD60A1}\"" + " AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True");
//Add projection manager filter
//picker.Filter.SupportedDeviceSelectors.Add(ProjectionManager.GetDeviceSelector());
//if (activeDevice != null)
// //Update the display status for the previously selected device.
// picker.SetDisplayStatus(activeDevice, "Connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton);
//Show the picker above our Show Device Picker button
picker.Show(new Rect(pt.X, pt.Y, mtc.CastButton.ActualWidth, mtc.CastButton.ActualHeight), Windows.UI.Popups.Placement.Above);
}
#region ProjectionManager APIs
private async Task<bool> TryProjectionManagerCastAsync(DeviceInformation device)
{
bool projectionManagerCastAsyncSucceeded = false;
if ((activeDevice ==null && ProjectionManager.ProjectionDisplayAvailable && device == null) || device != null)
{
thisViewId = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Id;
// If projection is already in progress, then it could be shown on the monitor again
// Otherwise, we need to create a new view to show the presentation
if (rootPage.ProjectionViewPageControl == null)
{
// First, create a new, blank view
var thisDispatcher = Window.Current.Dispatcher;
await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// ViewLifetimeControl is a wrapper to make sure the view is closed only
// when the app is done with it
rootPage.ProjectionViewPageControl = ViewLifetimeControl.CreateForCurrentView();
// Assemble some data necessary for the new page
pvb.MainPageDispatcher = thisDispatcher;
pvb.ProjectionViewPageControl = rootPage.ProjectionViewPageControl;
pvb.MainViewId = thisViewId;
// Display the page in the view. Note that the view will not become visible
// until "StartProjectingAsync" is called
var rootFrame = new Frame();
rootFrame.Navigate(typeof(ProjectionViewPage), pvb);
Window.Current.Content = rootFrame;
Window.Current.Activate();
});
}
try
{
// Start/StopViewInUse are used to signal that the app is interacting with the
// view, so it shouldn't be closed yet, even if the user loses access to it
rootPage.ProjectionViewPageControl.StartViewInUse();
try
{
//if (ProjectionManager.ProjectionDisplayAvailable)
//{
// // Show the view on a second display (if available) or on the primary display
// await ProjectionManager.StartProjectingAsync(rootPage.ProjectionViewPageControl.Id, thisViewId);
//}
//else
//{
await ProjectionManager.StartProjectingAsync(rootPage.ProjectionViewPageControl.Id, thisViewId, device);
//}
}
catch (Exception ex)
{
if (!ProjectionManager.ProjectionDisplayAvailable)
throw ex;
}
if (pvb.ProjectedPage != null)
{
this.player.Pause();
await pvb.ProjectedPage.SetMediaSource(this.player.Source, this.player.Position);
}
if (device != null)
{
activeDevice = device;
activeCastConnectionHandler = pvb;
}
projectionManagerCastAsyncSucceeded = true;
}
catch (Exception)
{
rootPage.NotifyUser("The projection view is being disposed", NotifyType.ErrorMessage);
}
ApplicationView.GetForCurrentView().ExitFullScreenMode();
}
return projectionManagerCastAsyncSucceeded;
}
private bool TryStopProjectionManagerAsync(ProjectionViewBroker broker)
{
broker.ProjectedPage.StopProjecting();
return true;
}
private async void Pvb_ProjectionStarted(object sender, EventArgs e)
{
//await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
//{
// //rootPage.NotifyUser("Moving Media Element to the second screen", NotifyType.StatusMessage);
// //ProjectionViewBroker broker = sender as ProjectionViewBroker;
//});
}
private async void Pvb_ProjectionStopping(object sender, EventArgs e)
{
ProjectionViewBroker broker = sender as ProjectionViewBroker;
TimeSpan position = broker.ProjectedPage.Player.Position;
Uri source = broker.ProjectedPage.Player.Source;
await rootPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Moving Media Element back to the first screen", NotifyType.StatusMessage);
this.player.Position = position;
this.player.Source = source;
this.player.Play();
});
}
#endregion
#region Windows.Devices.Enumeration.DevicePicker Methods
private async void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
{
string deviceId = args.SelectedDevice.Id;
//Casting must occur from the UI thread. This dispatches the casting calls to the UI thread.
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
//Update the display status for the selected device to connecting.
picker.SetDisplayStatus(args.SelectedDevice, "Connecting", DevicePickerDisplayStatusOptions.ShowProgress);
// BUG: In order to support debugging it is best to retreive the device from the local app instead
// of continuing to use the DeviceInformation instance that is proxied from the picker.
DeviceInformation device = null;
try { if (deviceId.IndexOf("dial", StringComparison.OrdinalIgnoreCase) == -1) device = await DeviceInformation.CreateFromIdAsync(deviceId, RequiredDeviceProperties.Props, DeviceInformationKind.DeviceContainer); } catch { }
try { if (device == null) device = await DeviceInformation.CreateFromIdAsync(deviceId, RequiredDeviceProperties.Props, DeviceInformationKind.AssociationEndpoint); } catch { }
// In case the workaround did not work
if (device == null) device = args.SelectedDevice;
//Try casting using DIAL first
bool castSucceeded = false;
// The dial AssociationEndpoint ID will have 'dial' in the string. If it doesn't try the ProjectionManager API.
if (deviceId.IndexOf("dial", StringComparison.OrdinalIgnoreCase) == -1)
castSucceeded = await TryProjectionManagerCastAsync(device);
// If the ProjectionManager API did not work and the device id will have 'dial' in it.
if (!castSucceeded && deviceId.IndexOf("dial", StringComparison.OrdinalIgnoreCase) > -1)
castSucceeded = await TryLaunchDialAppAsync(device);
//If DIAL did not work for the selected device, try the CAST API
if (!castSucceeded)
{
castSucceeded = await TryCastMediaElementAsync(device);
}
if (castSucceeded)
{
//Update the display status for the selected device. Try Catch in case the picker is not visible anymore.
try { picker.SetDisplayStatus(device, "Connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton); } catch { }
// Hide the picker now that all the work is completed. Try Catch in case the picker is not visible anymore.
try { picker.Hide(); } catch { }
}
else
{
//Show a retry button when connecting to the selected device failed.
try { picker.SetDisplayStatus(device, "Connecting failed", DevicePickerDisplayStatusOptions.ShowRetryButton); } catch { }
}
});
}
private async void Picker_DevicePickerDismissed(DevicePicker sender, object args)
{
//Casting must occur from the UI thread. This dispatches the casting calls to the UI thread.
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
if (activeDevice == null)
{
player.Play();
}
});
}
private async void Picker_DisconnectButtonClicked(DevicePicker sender, DeviceDisconnectButtonClickedEventArgs args)
{
//Casting must occur from the UI thread. This dispatches the casting calls to the UI thread.
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
rootPage.NotifyUser("Disconnect Button clicked", NotifyType.StatusMessage);
//Update the display status for the selected device.
sender.SetDisplayStatus(args.Device, "Disconnecting", DevicePickerDisplayStatusOptions.ShowProgress);
bool disconnected = false;
if (this.activeCastConnectionHandler is ProjectionViewBroker)
disconnected = TryStopProjectionManagerAsync((ProjectionViewBroker)activeCastConnectionHandler);
if (this.activeCastConnectionHandler is DialApp)
disconnected = await TryStopDialAppAsync((DialApp)activeCastConnectionHandler);
if (this.activeCastConnectionHandler is CastingConnection)
disconnected = await TryDisconnectCastingSessionAsync((CastingConnection)activeCastConnectionHandler);
if (disconnected)
{
//Update the display status for the selected device.
try { sender.SetDisplayStatus(args.Device, "Disconnected", DevicePickerDisplayStatusOptions.None); } catch { }
// Set the active device variables to null
activeDevice = null;
activeCastConnectionHandler = null;
//Hide the picker
sender.Hide();
}
else
{
//Update the display status for the selected device.
sender.SetDisplayStatus(args.Device, "Disconnect failed", DevicePickerDisplayStatusOptions.ShowDisconnectButton);
}
});
}
#endregion
#region Media Element Methods
private void Player_CurrentStateChanged(object sender, RoutedEventArgs e)
{
// Update status
rootPage.NotifyUser(string.Format("{0} '{1}'", this.player.CurrentState, video.Title), NotifyType.StatusMessage);
}
private void Player_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
rootPage.NotifyUser(string.Format("Failed to load '{0}'", video.Title), NotifyType.ErrorMessage);
}
private void Player_MediaOpened(object sender, RoutedEventArgs e)
{
rootPage.NotifyUser(string.Format("Openend '{0}'", video.Title), NotifyType.StatusMessage);
player.Play();
}
#endregion
#region Windows.Media.Casting APIs
private async Task<bool> TryCastMediaElementAsync(DeviceInformation device)
{
bool castMediaElementSucceeded = false;
//Verify whether the selected device supports DLNA, Bluetooth, or Miracast.
rootPage.NotifyUser(string.Format("Checking to see if device {0} supports Miracast, Bluetooth, or DLNA", device.Name), NotifyType.StatusMessage);
//BUG: Takes too long. Workaround, just try to create the CastingDevice
//if (await CastingDevice.DeviceInfoSupportsCastingAsync(device))
//{
CastingConnection connection = null;
//Check to see whether we are casting to the same device
if (activeDevice != null && device.Id == activeDevice.Id)
connection = activeCastConnectionHandler as CastingConnection;
else // if not casting to the same device reset the active device related variables.
{
activeDevice = null;
activeCastConnectionHandler = null;
}
// If we can re-use the existing connection
if (connection == null || connection.State == CastingConnectionState.Disconnected || connection.State == CastingConnectionState.Disconnecting)
{
CastingDevice castDevice = null;
activeDevice = null;
//Try to create a CastingDevice instannce. If it doesn't succeed, the selected device does not support playback of the video source.
rootPage.NotifyUser(string.Format("Attempting to resolve casting device for '{0}'", device.Name), NotifyType.StatusMessage);
try { castDevice = await CastingDevice.FromIdAsync(device.Id); } catch { }
if (castDevice == null)
{
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("'{0}' does not support playback of this media", device.Name), NotifyType.StatusMessage);
}
else
{
//Create a casting conneciton from our selected casting device
rootPage.NotifyUser(string.Format("Creating connection for '{0}'", device.Name), NotifyType.StatusMessage);
connection = castDevice.CreateCastingConnection();
//Hook up the casting events
connection.ErrorOccurred += Connection_ErrorOccurred;
connection.StateChanged += Connection_StateChanged;
}
//Cast the content loaded in the media element to the selected casting device
rootPage.NotifyUser(string.Format("Casting to '{0}'", device.Name), NotifyType.StatusMessage);
CastingSource source = null;
// Get the casting source
try { source = player.GetAsCastingSource(); } catch { }
if (source == null)
{
rootPage.NotifyUser(string.Format("Failed to get casting source for video '{0}'", video.Title), NotifyType.ErrorMessage);
}
else
{
CastingConnectionErrorStatus status = await connection.RequestStartCastingAsync(source);
if (status == CastingConnectionErrorStatus.Succeeded)
{
//Remember the device to which casting succeeded
activeDevice = device;
//Remember the current active connection.
activeCastConnectionHandler = connection;
castMediaElementSucceeded = true;
player.Play();
}
else
{
rootPage.NotifyUser(string.Format("Failed to cast to '{0}'", device.Name), NotifyType.ErrorMessage);
}
}
//}
}
return castMediaElementSucceeded;
}
private async void Connection_StateChanged(CastingConnection sender, object args)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Casting Connection State Changed: " + sender.State, NotifyType.StatusMessage);
});
}
private async void Connection_ErrorOccurred(CastingConnection sender, CastingConnectionErrorOccurredEventArgs args)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Casting Error Occured: " + args.Message, NotifyType.ErrorMessage);
activeDevice = null;
activeCastConnectionHandler = null;
});
}
private async Task<bool> TryDisconnectCastingSessionAsync(CastingConnection connection)
{
bool disconnected = false;
//Disconnect the casting session
CastingConnectionErrorStatus status = await connection.DisconnectAsync();
if (status == CastingConnectionErrorStatus.Succeeded)
{
rootPage.NotifyUser("Connection disconnected successfully.", NotifyType.StatusMessage);
disconnected = true;
}
else
{
rootPage.NotifyUser(string.Format("Failed to disconnect connection with reason {0}.", status.ToString()), NotifyType.ErrorMessage);
}
return disconnected;
}
#endregion
#region Windows.Media.DialProtocol APIs
private async Task<bool> TryLaunchDialAppAsync(DeviceInformation device)
{
bool dialAppLaunchSucceeded = false;
if (device.Id.IndexOf("dial", StringComparison.OrdinalIgnoreCase) > -1)
{
//Update the launch arguments to include the Position
this.dial_launch_args_textbox.Text = string.Format("v={0}&t={1}&pairingCode=E4A8136D-BCD3-45F4-8E49-AE01E9A46B5F", video.Id, player.Position.Ticks);
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("Checking to see if device {0} supports DIAL", device.Name), NotifyType.StatusMessage);
//BUG: Takes too long. Workaround, just try to create the DialDevice
//if (await DialDevice.DeviceInfoSupportsDialAsync(device))
//{
DialDevice dialDevice = null;
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("Attempting to resolve DIAL device for '{0}'", device.Name), NotifyType.StatusMessage);
try { dialDevice = await DialDevice.FromIdAsync(device.Id); } catch { }
if (dialDevice == null)
{
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("'{0}' does not support DIAL", device.Name), NotifyType.StatusMessage);
}
else
{
//Get the DialApp object for the specific application on the selected device
DialApp app = dialDevice.GetDialApp(this.dial_appname_textbox.Text);
if (app == null)
{
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("'{0}' cannot find app with ID '{1}'", device.Name, this.dial_appname_textbox.Text), NotifyType.StatusMessage);
}
else
{
//Get the current application state
DialAppStateDetails stateDetails = await app.GetAppStateAsync();
if (stateDetails.State == DialAppState.NetworkFailure)
{
// In case getting the application state failed because of a network failure
rootPage.NotifyUser("Network Failure while getting application state", NotifyType.ErrorMessage);
}
else
{
rootPage.NotifyUser(string.Format("Attempting to launch '{0}'", app.AppName), NotifyType.StatusMessage);
//Launch the application on the 1st screen device
DialAppLaunchResult result = await app.RequestLaunchAsync(this.dial_launch_args_textbox.Text);
//Verify to see whether the application was launched
if (result == DialAppLaunchResult.Launched)
{
//Remember the device to which casting succeeded
activeDevice = device;
//DIAL is sessionsless but the DIAL app allows us to get the state and "disconnect".
//Disconnect in the case of DIAL is equivalenet to stopping the app.
activeCastConnectionHandler = app;
rootPage.NotifyUser(string.Format("Launched '{0}'", app.AppName), NotifyType.StatusMessage);
//This is where you will need to add you application specific communication between your 1st and 2nd screen applications
//...
dialAppLaunchSucceeded = true;
}
}
}
}
//}
//else
//{
// rootPage.NotifyUser(string.Format("'{0}' does not support DIAL", device.Name), NotifyType.StatusMessage);
//}
}
else
{
rootPage.NotifyUser(string.Format("'{0}' does not support DIAL", device.Name), NotifyType.StatusMessage);
}
return dialAppLaunchSucceeded;
}
private async Task<bool> TryStopDialAppAsync(DialApp app)
{
bool stopped = false;
//Get the current application state
DialAppStateDetails stateDetails = await app.GetAppStateAsync();
switch (stateDetails.State)
{
case DialAppState.NetworkFailure:
{
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser("Network Failure while getting application state", NotifyType.ErrorMessage);
break;
}
case DialAppState.Stopped:
{
stopped = true;
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser("Application was already stopped.", NotifyType.StatusMessage);
break;
}
default:
{
DialAppStopResult result = await app.StopAsync();
if (result == DialAppStopResult.Stopped)
{
stopped = true;
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser("Application stopped successfully.", NotifyType.StatusMessage);
}
else
{
if (result == DialAppStopResult.StopFailed || result == DialAppStopResult.NetworkFailure)
{
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser(string.Format("Error occured trying to stop application. Status: '{0}'", result.ToString()), NotifyType.StatusMessage);
}
else //in case of DialAppStopResult.OperationNotSupported, there is not much more you can do. You could implement your own
// mechanism to stop the application on that device.
{
stopped = true;
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser(string.Format("Stop is not supported by device: '{0}'", activeDevice.Name), NotifyType.ErrorMessage);
}
}
break;
}
}
return stopped;
}
#endregion
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
}
}
}
| |
// DirectXTK MakeSpriteFont tool
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
namespace MakeSpriteFont
{
// Writes the output spritefont binary file.
public static class SpriteFontWriter
{
const string spriteFontMagic = "DXTKfont";
const int DXGI_FORMAT_R8G8B8A8_UNORM = 28;
const int DXGI_FORMAT_B4G4R4A4_UNORM = 115;
const int DXGI_FORMAT_BC2_UNORM = 74;
public static void WriteSpriteFont(CommandLineOptions options, Glyph[] glyphs, float lineSpacing, Bitmap bitmap)
{
using (FileStream file = File.OpenWrite(options.OutputFile))
using (BinaryWriter writer = new BinaryWriter(file))
{
WriteMagic(writer);
WriteGlyphs(writer, glyphs);
writer.Write(lineSpacing);
writer.Write(options.DefaultCharacter);
WriteBitmap(writer, options, bitmap);
}
}
static void WriteMagic(BinaryWriter writer)
{
foreach (char magic in spriteFontMagic)
{
writer.Write((byte)magic);
}
}
static void WriteGlyphs(BinaryWriter writer, Glyph[] glyphs)
{
writer.Write(glyphs.Length);
foreach (Glyph glyph in glyphs)
{
writer.Write((int)glyph.Character);
writer.Write(glyph.Subrect.Left);
writer.Write(glyph.Subrect.Top);
writer.Write(glyph.Subrect.Right);
writer.Write(glyph.Subrect.Bottom);
writer.Write(glyph.XOffset);
writer.Write(glyph.YOffset);
writer.Write(glyph.XAdvance);
}
}
static void WriteBitmap(BinaryWriter writer, CommandLineOptions options, Bitmap bitmap)
{
writer.Write(bitmap.Width);
writer.Write(bitmap.Height);
switch (options.TextureFormat)
{
case TextureFormat.Rgba32:
WriteRgba32(writer, bitmap);
break;
case TextureFormat.Bgra4444:
WriteBgra4444(writer, bitmap);
break;
case TextureFormat.CompressedMono:
WriteCompressedMono(writer, bitmap, options);
break;
default:
throw new NotSupportedException();
}
}
// Writes an uncompressed 32 bit font texture.
static void WriteRgba32(BinaryWriter writer, Bitmap bitmap)
{
writer.Write(DXGI_FORMAT_R8G8B8A8_UNORM);
writer.Write(bitmap.Width * 4);
writer.Write(bitmap.Height);
using (var bitmapData = new BitmapUtils.PixelAccessor(bitmap, ImageLockMode.ReadOnly))
{
for (int y = 0; y < bitmap.Height; y++)
{
for (int x = 0; x < bitmap.Width; x++)
{
Color color = bitmapData[x, y];
writer.Write(color.R);
writer.Write(color.G);
writer.Write(color.B);
writer.Write(color.A);
}
}
}
}
// Writes a 16 bit font texture.
static void WriteBgra4444(BinaryWriter writer, Bitmap bitmap)
{
writer.Write(DXGI_FORMAT_B4G4R4A4_UNORM);
writer.Write(bitmap.Width * sizeof(ushort));
writer.Write(bitmap.Height);
using (var bitmapData = new BitmapUtils.PixelAccessor(bitmap, ImageLockMode.ReadOnly))
{
for (int y = 0; y < bitmap.Height; y++)
{
for (int x = 0; x < bitmap.Width; x++)
{
Color color = bitmapData[x, y];
int r = color.R >> 4;
int g = color.G >> 4;
int b = color.B >> 4;
int a = color.A >> 4;
int packed = b | (g << 4) | (r << 8) | (a << 12);
writer.Write((ushort)packed);
}
}
}
}
// Writes a block compressed monochromatic font texture.
static void WriteCompressedMono(BinaryWriter writer, Bitmap bitmap, CommandLineOptions options)
{
if ((bitmap.Width & 3) != 0 ||
(bitmap.Height & 3) != 0)
{
throw new ArgumentException("Block compression requires texture size to be a multiple of 4.");
}
writer.Write(DXGI_FORMAT_BC2_UNORM);
writer.Write(bitmap.Width * 4);
writer.Write(bitmap.Height / 4);
using (var bitmapData = new BitmapUtils.PixelAccessor(bitmap, ImageLockMode.ReadOnly))
{
for (int y = 0; y < bitmap.Height; y += 4)
{
for (int x = 0; x < bitmap.Width; x += 4)
{
CompressBlock(writer, bitmapData, x, y, options);
}
}
}
}
// We want to compress our font textures, because, like, smaller is better,
// right? But a standard DXT compressor doesn't do a great job with fonts that
// are in premultiplied alpha format. Our font data is greyscale, so all of the
// RGBA channels have the same value. If one channel is compressed differently
// to another, this causes an ugly variation in brightness of the rendered text.
// Also, fonts are mostly either black or white, with grey values only used for
// antialiasing along their edges. It is very important that the black and white
// areas be accurately represented, while the precise value of grey is less
// important.
//
// Trouble is, your average DXT compressor knows nothing about these
// requirements. It will optimize to minimize a generic error metric such as
// RMS, but this will often sacrifice crisp black and white in exchange for
// needless accuracy of the antialiasing pixels, or encode RGB differently to
// alpha. UGLY!
//
// Fortunately, encoding monochrome fonts turns out to be trivial. Using DXT3,
// we can fix the end colors as black and white, which gives guaranteed exact
// encoding of the font inside and outside, plus two fractional values for edge
// antialiasing. Also, these RGB values (0, 1/3, 2/3, 1) map exactly to four of
// the possible 16 alpha values available in DXT3, so we can ensure the RGB and
// alpha channels always exactly match.
static void CompressBlock(BinaryWriter writer, BitmapUtils.PixelAccessor bitmapData, int blockX, int blockY, CommandLineOptions options)
{
long alphaBits = 0;
int rgbBits = 0;
int pixelCount = 0;
for (int y = 0; y < 4; y++)
{
for (int x = 0; x < 4; x++)
{
long alpha;
int rgb;
int value = bitmapData[blockX + x, blockY + y].A;
if (options.NoPremultiply)
{
// If we are not premultiplied, RGB is always white and we have 4 bit alpha.
alpha = value >> 4;
rgb = 0;
}
else
{
// For premultiplied encoding, quantize the source value to 2 bit precision.
if (value < 256 / 6)
{
alpha = 0;
rgb = 1;
}
else if (value < 256 / 2)
{
alpha = 5;
rgb = 3;
}
else if (value < 256 * 5 / 6)
{
alpha = 10;
rgb = 2;
}
else
{
alpha = 15;
rgb = 0;
}
}
// Add this pixel to the alpha and RGB bit masks.
alphaBits |= alpha << (pixelCount * 4);
rgbBits |= rgb << (pixelCount * 2);
pixelCount++;
}
}
// Output the alpha bit mask.
writer.Write(alphaBits);
// Output the two endpoint colors (black and white in 5.6.5 format).
writer.Write((ushort)0xFFFF);
writer.Write((ushort)0);
// Output the RGB bit mask.
writer.Write(rgbBits);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Azure.Data.Tables.Queryable;
using NUnit.Framework;
namespace Azure.Data.Tables.Tests
{
/// <summary>
/// The suite of tests for the <see cref="TableServiceClient"/> class.
/// </summary>
/// <remarks>
/// These tests have a dependency on live Azure services and may incur costs for the associated
/// Azure subscription.
/// </remarks>
public class TableClientQueryableLiveTests : TableServiceLiveTestsBase
{
public TableClientQueryableLiveTests(bool isAsync, TableEndpointType endpointType) : base(isAsync, endpointType /* To record tests, add this argument, RecordedTestMode.Record */)
{ }
[RecordedTest]
public async Task TableQueryableExecuteQueryDictionary()
{
var entitiesToCreate = CreateTableEntities(PartitionKeyValue, 1);
entitiesToCreate.AddRange(CreateTableEntities(PartitionKeyValue2, 1));
// Create the new entities.
await CreateTestEntities(entitiesToCreate).ConfigureAwait(false);
var results = await client.QueryAsync<TableEntity>(x => x.PartitionKey == PartitionKeyValue, select: default).ToEnumerableAsync().ConfigureAwait(false);
foreach (var entity in results)
{
Assert.That(entity["PartitionKey"], Is.EqualTo(PartitionKeyValue));
}
}
[RecordedTest]
public async Task TableQueryableExecuteQueryGeneric()
{
var entitiesToCreate = CreateComplexTableEntities(PartitionKeyValue, 1);
entitiesToCreate.AddRange(CreateComplexTableEntities(PartitionKeyValue2, 1));
// Create the new entities.
await CreateTestEntities(entitiesToCreate).ConfigureAwait(false);
var results = await client.QueryAsync<ComplexEntity>(x => x.PartitionKey == PartitionKeyValue, select: default).ToEnumerableAsync().ConfigureAwait(false);
foreach (var entity in results)
{
Assert.That(entity.PartitionKey, Is.EqualTo(PartitionKeyValue));
}
}
[RecordedTest]
public async Task TableQueryableFilterPredicate()
{
var entitiesToCreate = CreateComplexTableEntities(PartitionKeyValue, 4);
// Create the new entities.
await CreateTestEntities(entitiesToCreate).ConfigureAwait(false);
// Filter before key predicate.
var results = await client.QueryAsync<ComplexEntity>(ent => ent.RowKey != "0004" && ent.PartitionKey == PartitionKeyValue).ToEnumerableAsync().ConfigureAwait(false);
foreach (ComplexEntity ent in results)
{
Assert.That(ent.PartitionKey, Is.EqualTo(PartitionKeyValue));
Assert.That(ent.RowKey, Is.Not.EqualTo("0004"));
}
Assert.That(results.Count, Is.EqualTo(entitiesToCreate.Count - 1));
// Key predicate before filter.
results = await client.QueryAsync<ComplexEntity>(ent => ent.PartitionKey == PartitionKeyValue && ent.RowKey != "0004").ToEnumerableAsync().ConfigureAwait(false);
foreach (ComplexEntity ent in results)
{
Assert.That(ent.PartitionKey, Is.EqualTo(PartitionKeyValue));
Assert.That(ent.RowKey, Is.Not.EqualTo("0004"));
}
Assert.That(results.Count, Is.EqualTo(entitiesToCreate.Count - 1));
}
[RecordedTest]
public async Task TableQueryableComplexFilter()
{
var entitiesToCreate = CreateComplexTableEntities(PartitionKeyValue, 4);
// Create the new entities.
await CreateTestEntities(entitiesToCreate).ConfigureAwait(false);
var results = await client.QueryAsync<ComplexEntity>(ent => (ent.RowKey == "0004" && ent.Int32 == 4) || ((ent.Int32 == 2) && (ent.String == "wrong string" || ent.Bool == true)) || (ent.LongPrimitiveN == (long)int.MaxValue + 50)).ToEnumerableAsync().ConfigureAwait(false);
foreach (ComplexEntity ent in results)
{
Assert.IsTrue(ent.Int32 == 4 || ent.Int32 == 2);
}
Assert.That(results.Count, Is.EqualTo(2));
}
[RecordedTest]
public async Task TableQueryableComplexFilterWithCreateFilter()
{
var entitiesToCreate = CreateComplexTableEntities(PartitionKeyValue, 4);
// Create the new entities.
await CreateTestEntities(entitiesToCreate).ConfigureAwait(false);
var filter = TableClient.CreateQueryFilter<ComplexEntity>(ent => (ent.RowKey == "0004" && ent.Int32 == 4) || ((ent.Int32 == 2) && (ent.String == "wrong string" || ent.Bool == true)) || (ent.LongPrimitiveN == (long)int.MaxValue + 50));
var results = await client.QueryAsync<ComplexEntity>(filter).ToEnumerableAsync().ConfigureAwait(false);
foreach (ComplexEntity ent in results)
{
Assert.IsTrue(ent.Int32 == 4 || ent.Int32 == 2);
}
Assert.That(results.Count, Is.EqualTo(2));
}
[RecordedTest]
public async Task TableQueryableNestedParanthesis()
{
var entitiesToCreate = CreateComplexTableEntities(PartitionKeyValue, 4);
// Create the new entities.
await CreateTestEntities(entitiesToCreate).ConfigureAwait(false);
// Complex nested query to return entity 2 and 4.
var results = await client.QueryAsync<ComplexEntity>(ent => (ent.RowKey == "0004" && ent.Int32 == 4) ||
((ent.Int32 == 2) && (ent.String == "wrong string" || ent.Bool == true) && !(ent.IntegerPrimitive == 1 && ent.LongPrimitive == (long)int.MaxValue + 1)) ||
(ent.LongPrimitiveN == (long)int.MaxValue + 50)).ToEnumerableAsync().ConfigureAwait(false);
foreach (ComplexEntity ent in results)
{
Assert.IsTrue(ent.Int32 == 4 || ent.Int32 == 2);
}
Assert.That(results.Count, Is.EqualTo(2));
}
[RecordedTest]
public async Task TableQueryableUnary()
{
var entitiesToCreate = CreateComplexTableEntities(PartitionKeyValue, 4);
// Create the new entities.
await CreateTestEntities(entitiesToCreate).ConfigureAwait(false);
// Unary Not.
var results = await client.QueryAsync<ComplexEntity>(x => x.PartitionKey == PartitionKeyValue && !(x.RowKey == entitiesToCreate[0].RowKey)).ToEnumerableAsync().ConfigureAwait(false);
// Assert that all but one were returned
Assert.That(results.Count, Is.EqualTo(entitiesToCreate.Count - 1));
foreach (var ent in results)
{
Assert.That(ent.RowKey, Is.Not.EqualTo(entitiesToCreate[0].RowKey));
}
// Unary +.
results = await client.QueryAsync<ComplexEntity>(x => x.PartitionKey == PartitionKeyValue && +x.Int32 < +5).ToEnumerableAsync().ConfigureAwait(false);
// Assert that all were returned
Assert.That(results.Count, Is.EqualTo(entitiesToCreate.Count));
// Unary -.
results = await client.QueryAsync<ComplexEntity>(x => x.PartitionKey == PartitionKeyValue && x.Int32 > -1).ToEnumerableAsync().ConfigureAwait(false);
// Assert that all were returned
Assert.That(results.Count, Is.EqualTo(entitiesToCreate.Count));
}
[RecordedTest]
public async Task TableTakeWithContinuationTask()
{
var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 20);
// Create the new entities.
await CreateTestEntities(entitiesToCreate).ConfigureAwait(false);
// Query the entities with a Take count to limit the number of responses
var pagedResult = client.QueryAsync<TestEntity>(e => e.PartitionKey == PartitionKeyValue, maxPerPage: 10);
await foreach (Page<TestEntity> page in pagedResult.AsPages())
{
Assert.That(page.Values.Count, Is.EqualTo(10), "The entity paged result count should be 10");
}
}
[RecordedTest]
public async Task TableQueryableMultipleTake()
{
var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 10);
// Create the new entities.
await CreateTestEntities(entitiesToCreate).ConfigureAwait(false);
// Query the entities with a Take count to limit the number of responses. The lower of the Take values is what takes effect.
var pagedResult = client.QueryAsync<TestEntity>(e => e.PartitionKey == PartitionKeyValue, maxPerPage: 5);
await foreach (Page<TestEntity> page in pagedResult.AsPages())
{
Assert.That(page.Values.Count, Is.EqualTo(5), "The entity paged result count should be 5");
}
}
[RecordedTest]
public async Task TableQueryableDictionaryTableEntityQuery()
{
var entitiesToCreate = CreateComplexTableEntities(PartitionKeyValue, 2);
// Create the new entities.
await CreateTestEntities(entitiesToCreate).ConfigureAwait(false);
Func<string, string> identityFunc = (s) => s;
var results = await client.QueryAsync<ComplexEntity>(x => x.PartitionKey == PartitionKeyValue && x.RowKey == identityFunc(entitiesToCreate[1].RowKey)).ToEnumerableAsync().ConfigureAwait(false);
var entity = results.SingleOrDefault();
Assert.That(entity, Is.Not.Null);
Assert.That(entity.PartitionKey, Is.EqualTo(PartitionKeyValue));
Assert.That(entity.RowKey, Is.EqualTo(entitiesToCreate[1].RowKey));
}
[RecordedTest]
public async Task TableQueryableMultipleWhere()
{
var entitiesToCreate = CreateComplexTableEntities(PartitionKeyValue, 2);
// Create the new entities.
await CreateTestEntities(entitiesToCreate).ConfigureAwait(false);
var results = await client.QueryAsync<ComplexEntity>(x => x.PartitionKey == PartitionKeyValue && x.RowKey == entitiesToCreate[1].RowKey).ToEnumerableAsync().ConfigureAwait(false);
var entity = results.SingleOrDefault();
Assert.That(entity, Is.Not.Null);
Assert.That(entity.PartitionKey, Is.EqualTo(PartitionKeyValue));
Assert.That(entity.RowKey, Is.EqualTo(entitiesToCreate[1].RowKey));
}
[RecordedTest]
public async Task TableQueryableEnumerateTwice()
{
var entitiesToCreate = CreateComplexTableEntities(PartitionKeyValue, 2);
// Create the new entities.
await CreateTestEntities(entitiesToCreate).ConfigureAwait(false);
var results = await client.QueryAsync<ComplexEntity>(x => true).ToEnumerableAsync().ConfigureAwait(false);
List<ComplexEntity> firstIteration = new List<ComplexEntity>();
List<ComplexEntity> secondIteration = new List<ComplexEntity>();
foreach (ComplexEntity ent in results)
{
Assert.That(ent.PartitionKey, Is.EqualTo(PartitionKeyValue));
firstIteration.Add(ent);
}
foreach (ComplexEntity ent in results)
{
Assert.That(ent.PartitionKey, Is.EqualTo(PartitionKeyValue));
secondIteration.Add(ent);
}
Assert.That(firstIteration.Count, Is.EqualTo(secondIteration.Count));
for (int m = 0; m < firstIteration.Count; m++)
{
ComplexEntity.AssertEquality(firstIteration[m], secondIteration[m]);
}
}
[RecordedTest]
public async Task TableQueryableOnSupportedTypes()
{
var entitiesToCreate = CreateComplexTableEntities(PartitionKeyValue, 4);
ComplexEntity thirdEntity = entitiesToCreate[2];
// Create the new entities.
foreach (var entity in entitiesToCreate)
{
await client.AddEntityAsync(entity).ConfigureAwait(false);
}
// 1. Filter on String
var results = await client.QueryAsync<ComplexEntity>(ent => ent.String.CompareTo(thirdEntity.String) >= 0).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
// 2. Filter on Guid
results = await client.QueryAsync<ComplexEntity>(ent => ent.Guid == thirdEntity.Guid).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(1));
// 3. Filter on Long
results = await client.QueryAsync<ComplexEntity>(ent => ent.Int64 >= thirdEntity.Int64).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
results = await client.QueryAsync<ComplexEntity>(ent => ent.LongPrimitive >= thirdEntity.LongPrimitive).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
results = await client.QueryAsync<ComplexEntity>(ent => ent.LongPrimitiveN >= thirdEntity.LongPrimitiveN).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
// 4. Filter on Double
results = await client.QueryAsync<ComplexEntity>(ent => ent.Double >= thirdEntity.Double).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
results = await client.QueryAsync<ComplexEntity>(ent => ent.DoublePrimitive >= thirdEntity.DoublePrimitive).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
// 5. Filter on Integer
results = await client.QueryAsync<ComplexEntity>(ent => ent.Int32 >= thirdEntity.Int32).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
results = await client.QueryAsync<ComplexEntity>(ent => ent.Int32N >= thirdEntity.Int32N).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
// 6. Filter on Date
results = await client.QueryAsync<ComplexEntity>(ent => ent.DateTimeOffset >= thirdEntity.DateTimeOffset).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
results = await client.QueryAsync<ComplexEntity>(ent => ent.DateTimeOffset < thirdEntity.DateTimeOffset).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
// 7. Filter on Boolean
results = await client.QueryAsync<ComplexEntity>(ent => ent.Bool == thirdEntity.Bool).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
results = await client.QueryAsync<ComplexEntity>(ent => ent.BoolPrimitive == thirdEntity.BoolPrimitive).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
// 8. Filter on Binary
results = await client.QueryAsync<ComplexEntity>(ent => ent.Binary == thirdEntity.Binary).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(1));
results = await client.QueryAsync<ComplexEntity>(ent => ent.BinaryPrimitive == thirdEntity.BinaryPrimitive).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(1));
// 10. Complex Filter on Binary GTE
results = await client.QueryAsync<ComplexEntity>(ent => ent.PartitionKey == thirdEntity.PartitionKey &&
ent.String.CompareTo(thirdEntity.String) >= 0 &&
ent.Int64 >= thirdEntity.Int64 &&
ent.LongPrimitive >= thirdEntity.LongPrimitive &&
ent.LongPrimitiveN >= thirdEntity.LongPrimitiveN &&
ent.Int32 >= thirdEntity.Int32 &&
ent.Int32N >= thirdEntity.Int32N &&
ent.DateTimeOffset >= thirdEntity.DateTimeOffset).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
}
[RecordedTest]
public async Task TableQueryableWithDictionaryTypeOnSupportedTypes()
{
var entitiesToCreate = CreateComplexTableEntities(PartitionKeyValue, 4);
ComplexEntity thirdEntity = entitiesToCreate[2];
// Create the new entities.
foreach (var entity in entitiesToCreate)
{
await client.AddEntityAsync(entity).ConfigureAwait(false);
}
// 1. Filter on String
var results = await client.QueryAsync<TableEntity>(ent => ent.GetString("String").CompareTo(thirdEntity.String) >= 0).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
// 2. Filter on Guid
results = await client.QueryAsync<TableEntity>(ent => ent.GetGuid("Guid") == thirdEntity.Guid).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(1));
// 3. Filter on Long
results = await client.QueryAsync<TableEntity>(ent => ent.GetInt64("Int64") >= thirdEntity.Int64).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
results = await client.QueryAsync<TableEntity>(ent => ent.GetInt64("LongPrimitive") >= thirdEntity.LongPrimitive).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
results = await client.QueryAsync<TableEntity>(ent => ent.GetInt64("LongPrimitiveN") >= thirdEntity.LongPrimitiveN).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
// 4. Filter on Double
results = await client.QueryAsync<TableEntity>(ent => ent.GetDouble("Double") >= thirdEntity.Double).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
results = await client.QueryAsync<TableEntity>(ent => ent.GetDouble("DoublePrimitive") >= thirdEntity.DoublePrimitive).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
// 5. Filter on Integer
results = await client.QueryAsync<TableEntity>(ent => ent.GetInt32("Int32") >= thirdEntity.Int32).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
results = await client.QueryAsync<TableEntity>(ent => ent.GetInt32("Int32N") >= thirdEntity.Int32N).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
// 6. Filter on Date
results = await client.QueryAsync<TableEntity>(ent => (DateTimeOffset)ent["DateTimeOffset"] >= thirdEntity.DateTimeOffset).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
results = await client.QueryAsync<TableEntity>(ent => (DateTimeOffset)ent["DateTimeOffset"] < thirdEntity.DateTimeOffset).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
// 7. Filter on Boolean
results = await client.QueryAsync<TableEntity>(ent => ent.GetBoolean("Bool") == thirdEntity.Bool).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
results = await client.QueryAsync<TableEntity>(ent => ent.GetBoolean("BoolPrimitive") == thirdEntity.BoolPrimitive).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
// 8. Filter on Binary
results = await client.QueryAsync<TableEntity>(ent => ent.GetBinaryData("Binary") == thirdEntity.Binary).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(1));
results = await client.QueryAsync<TableEntity>(ent => ent.GetBinary("BinaryPrimitive") == thirdEntity.BinaryPrimitive).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(1));
// 9. Filter using indexer.
results = await client.QueryAsync<TableEntity>(ent => (ent["String"] as string).CompareTo(thirdEntity.String) >= 0).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
// 10. Complex Filter on Binary GTE
results = await client.QueryAsync<TableEntity>(ent => ent.PartitionKey == thirdEntity.PartitionKey &&
ent.GetString("String").CompareTo(thirdEntity.String) >= 0 &&
ent.GetInt64("Int64") >= thirdEntity.Int64 &&
ent.GetInt64("LongPrimitive") >= thirdEntity.LongPrimitive &&
ent.GetInt64("LongPrimitiveN") >= thirdEntity.LongPrimitiveN &&
ent.GetInt32("Int32") >= thirdEntity.Int32 &&
ent.GetInt32("Int32N") >= thirdEntity.Int32N &&
(DateTimeOffset)ent["DateTimeOffset"] >= thirdEntity.DateTimeOffset).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.EqualTo(2));
}
[RecordedTest]
public async Task TableQueryableWithInvalidQuery()
{
var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 1);
entitiesToCreate.AddRange(CreateCustomTableEntities(PartitionKeyValue2, 1));
// Create the new entities.
await CreateTestEntities(entitiesToCreate).ConfigureAwait(false);
var results = await client.QueryAsync<ComplexEntity>(ent => ent.PartitionKey == PartitionKeyValue && ent.PartitionKey == PartitionKeyValue2).ToEnumerableAsync().ConfigureAwait(false);
Assert.That(results.Count, Is.Zero);
}
}
}
| |
#if SILVERLIGHT
using Window = DevExpress.Xpf.Core.DXWindow;
using Microsoft.Silverlight.Testing;
#else
using NUnit.Framework;
#endif
using DevExpress.Mvvm.Tests;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using DevExpress.Mvvm.Native;
using DevExpress.Mvvm.UI.Interactivity;
using DevExpress.Mvvm.POCO;
using DevExpress.Mvvm.UI.Native;
namespace DevExpress.Mvvm.UI.Tests {
[TestFixture]
public class IWindowSurrogateTests {
[Test]
public void WindowProxyTest() {
Window w = new Window();
var ws1 = WindowProxy.GetWindowSurrogate(w);
var ws2 = WindowProxy.GetWindowSurrogate(w);
Assert.AreSame(ws1, ws2);
}
}
[TestFixture]
public class WindowedDocumentUIServiceTests : BaseWpfFixture {
public class View1 : FrameworkElement { }
public class View2 : FrameworkElement { }
public class EmptyView : FrameworkElement { }
#if !SILVERLIGHT
protected class TestStyleSelector : StyleSelector {
public Style Style { get; set; }
public override Style SelectStyle(object item, DependencyObject container) { return Style; }
}
#endif
protected class ViewModelWithNullTitle : IDocumentContent {
public IDocumentOwner DocumentOwner { get; set; }
void IDocumentContent.OnClose(CancelEventArgs e) { }
object IDocumentContent.Title { get { return null; } }
void IDocumentContent.OnDestroy() { }
}
protected override void SetUpCore() {
base.SetUpCore();
ViewLocator.Default = new TestViewLocator(this);
}
protected override void TearDownCore() {
Interaction.GetBehaviors(Window).Clear();
ViewLocator.Default = null;
base.TearDownCore();
}
[Test, Asynchronous]
public void WindowStyle() {
EnqueueShowWindow();
IDocument document = null;
EnqueueCallback(() => {
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
service.WindowType = typeof(Window);
Style windowStyle = new Style(typeof(Window));
windowStyle.Setters.Add(new Setter(FrameworkElement.TagProperty, "Style Tag"));
service.WindowStyle = windowStyle;
document = service.CreateDocument("EmptyView", new object());
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
var windowDocument = (WindowedDocumentUIService.WindowDocument)document;
Assert.AreEqual("Style Tag", windowDocument.Window.RealWindow.Tag);
});
EnqueueTestComplete();
}
public class UITestViewModel {
public virtual string Title { get; set; }
public virtual int Parameter { get; set; }
}
[Test, Asynchronous]
public void ActivateWhenDocumentShow() {
EnqueueShowWindow();
IDocument document = null;
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
EnqueueCallback(() => {
document = iService.CreateDocument("View1",
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title1", Parameter = 1 }));
document.Show();
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
Assert.AreEqual(iService.ActiveDocument, document);
Assert.IsNotNull(document.Content);
Assert.AreEqual(document.Content, ViewHelper.GetViewModelFromView(service.ActiveView));
document.Close();
});
EnqueueTestComplete();
}
[Test, Asynchronous]
public void UnActiveDocumentClose() {
EnqueueShowWindow();
IDocument document1 = null;
IDocument document2 = null;
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
int counter = 0;
EnqueueCallback(() => {
iService.ActiveDocumentChanged += (s, e) => counter++;
document1 = iService.CreateDocument("View1",
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title1", Parameter = 1 }));
document2 = iService.CreateDocument("View2",
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title2", Parameter = 2 }));
document1.Show();
Assert.AreEqual(1, counter);
document2.Show();
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
Assert.AreEqual(iService.ActiveDocument, document2);
Assert.IsNotNull(document2.Content);
Assert.AreEqual(document2.Content, ViewHelper.GetViewModelFromView(service.ActiveView));
document1.Close();
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
Assert.AreEqual(iService.ActiveDocument, document2);
Assert.IsNotNull(document2.Content);
Assert.AreEqual(document2.Content, ViewHelper.GetViewModelFromView(service.ActiveView));
#if !SILVERLIGHT
Assert.AreEqual(3, counter);
#else
Assert.AreEqual(2, counter);
#endif
document2.Close();
});
EnqueueTestComplete();
}
[Test, Asynchronous]
public void SettingActiveDocument() {
EnqueueShowWindow();
IDocument document1 = null;
IDocument document2 = null;
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
int counter = 0;
EnqueueCallback(() => {
iService.ActiveDocumentChanged += (s, e) => counter++;
document1 = iService.CreateDocument("View1",
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title1", Parameter = 1 }));
document2 = iService.CreateDocument("View2",
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title2", Parameter = 2 }));
document1.Show();
document2.Show();
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
#if !SILVERLIGHT
Assert.AreEqual(3, counter);
#else
Assert.AreEqual(2, counter);
#endif
iService.ActiveDocument = document1;
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
Assert.AreEqual(iService.ActiveDocument, document1);
#if !SILVERLIGHT
Assert.AreEqual(4, counter);
#else
Assert.AreEqual(3, counter);
#endif
document1.Close();
document2.Close();
});
EnqueueTestComplete();
}
#if !SILVERLIGHT
[Test, Asynchronous]
public void ActivateDocumentsWhenClosed() {
EnqueueShowWindow();
List<IDocument> documents = new List<IDocument>();
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
int counter = 0;
EnqueueCallback(() => {
service.ActiveDocumentChanged += (s, e) => counter++;
for(int i = 0; i < 4; i++) {
documents.Add(iService.CreateDocument("View" + i,
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title" + i, Parameter = i })));
documents[i].Show();
}
iService.ActiveDocument = documents[1];
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
counter = 0;
documents[1].Close();
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
Assert.AreEqual(2, counter);
Assert.AreEqual(iService.ActiveDocument, documents[3]);
iService.ActiveDocument = documents[3];
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
counter = 0;
documents[3].Close();
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
Assert.AreEqual(iService.ActiveDocument, documents[2]);
Assert.AreEqual(2, counter);
documents[0].Close();
documents[2].Close();
});
EnqueueTestComplete();
}
public class BindingTestClass : DependencyObject {
public static readonly DependencyProperty ActiveDocumentProperty =
DependencyProperty.Register("ActiveDocument", typeof(IDocument), typeof(BindingTestClass), new PropertyMetadata(null));
public IDocument ActiveDocument {
get { return (IDocument)GetValue(ActiveDocumentProperty); }
set { SetValue(ActiveDocumentProperty, value); }
}
static readonly DependencyPropertyKey ReadonlyActiveDocumentPropertyKey
= DependencyProperty.RegisterReadOnly("ReadonlyActiveDocument", typeof(IDocument), typeof(BindingTestClass), new PropertyMetadata(null));
public static readonly DependencyProperty ReadonlyActiveDocumentProperty = ReadonlyActiveDocumentPropertyKey.DependencyProperty;
public IDocument ReadonlyActiveDocument {
get { return (IDocument)GetValue(ReadonlyActiveDocumentProperty); }
private set { SetValue(ReadonlyActiveDocumentPropertyKey, value); }
}
}
[Test, Asynchronous]
public void TwoWayBinding() {
EnqueueShowWindow();
BindingTestClass testClass = new BindingTestClass();
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
IDocument document1 = null;
IDocument document2 = null;
BindingOperations.SetBinding(service, WindowedDocumentUIService.ActiveDocumentProperty,
new Binding() { Path = new PropertyPath(BindingTestClass.ActiveDocumentProperty), Source = testClass, Mode = BindingMode.Default });
EnqueueCallback(delegate {
document1 = iService.CreateDocument("View1", ViewModelSource.Create(() => new UITestViewModel() { Title = "Title1", Parameter = 1 }));
document1.Show();
DispatcherHelper.DoEvents();
document2 = iService.CreateDocument("View2", ViewModelSource.Create(() => new UITestViewModel() { Title = "Title2", Parameter = 2 }));
document2.Show();
DispatcherHelper.DoEvents();
});
EnqueueWindowUpdateLayout();
EnqueueCallback(delegate {
Assert.AreSame(document2, service.ActiveDocument);
Assert.AreSame(document2, testClass.ActiveDocument);
testClass.ActiveDocument = document1;
DispatcherHelper.DoEvents();
Assert.AreSame(document1, service.ActiveDocument);
});
EnqueueWindowUpdateLayout();
EnqueueTestComplete();
}
class TestDocumentContent : IDocumentContent {
public Action onClose = null;
public IDocumentOwner DocumentOwner { get; set; }
public void OnClose(CancelEventArgs e) {
onClose();
}
public void OnDestroy() {
}
public object Title {
get { return ""; }
}
}
[Test, Asynchronous]
public void ClosingDocumentOnWindowClosingShouldntThrow() {
EnqueueShowWindow();
BindingTestClass testClass = new BindingTestClass();
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
IDocument document = null;
WindowedDocumentUIService.WindowDocument typedDocument = null;
var content = new TestDocumentContent();
EnqueueCallback(delegate {
document = iService.CreateDocument("View1", content);
typedDocument = (WindowedDocumentUIService.WindowDocument)document;
document.Show();
DispatcherHelper.DoEvents();
});
EnqueueWindowUpdateLayout();
EnqueueCallback(delegate {
Window window = typedDocument.Window.RealWindow;
content.onClose = () => document.Close();
window.Close();
});
EnqueueWindowUpdateLayout();
EnqueueTestComplete();
}
[Test, ExpectedException(typeof(InvalidOperationException))]
public void TwoWayBindingReadonlyProperty() {
BindingTestClass testClass = new BindingTestClass();
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
BindingOperations.SetBinding(service, WindowedDocumentUIService.ActiveDocumentProperty,
new Binding() { Path = new PropertyPath(BindingTestClass.ReadonlyActiveDocumentProperty), Source = testClass, Mode = BindingMode.Default });
}
#endif
#if !SILVERLIGHT
[Test]
public void WindowStyleSelector() {
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
service.WindowType = typeof(Window);
Style windowStyle = new Style(typeof(Window));
windowStyle.Setters.Add(new Setter(System.Windows.Window.TagProperty, "Style Selector Tag"));
service.WindowStyleSelector = new TestStyleSelector() { Style = windowStyle };
IDocument document = service.CreateDocument("EmptyView", new object());
var windowDocument = (WindowedDocumentUIService.WindowDocument)document;
Assert.AreEqual("Style Selector Tag", windowDocument.Window.RealWindow.Tag);
}
#endif
protected virtual WindowedDocumentUIService CreateService() {
return new WindowedDocumentUIService();
}
}
#if !FREE && !SILVERLIGHT
[TestFixture]
public class WindowedDocumentUIServiceTests_DXWindow : WindowedDocumentUIServiceTests {
protected override WindowedDocumentUIService CreateService() {
return new WindowedDocumentUIService() { WindowType = typeof(DXWindow) };
}
#if !FREE && !SILVERLIGHT
[Test]
public void UseDXWindowWithNullTitle() {
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
IDocument document = service.CreateDocument("EmptyView", new ViewModelWithNullTitle());
Assert.AreEqual(string.Empty, document.Title);
}
#endif
}
[TestFixture]
public class WindowedDocumentUIServiceTests_DXDialogWindow : WindowedDocumentUIServiceTests_DXWindow {
protected override WindowedDocumentUIService CreateService() {
return new WindowedDocumentUIService() { WindowType = typeof(DXDialogWindow) };
}
}
#endif
[TestFixture]
public class WindowedDocumentUIServiceIDocumentContentCloseTests : BaseWpfFixture {
public class EmptyView : FrameworkElement { }
class TestDocumentContent : IDocumentContent {
Func<bool> close;
Action onDestroy;
public TestDocumentContent(Func<bool> close, Action onDestroy = null) {
this.close = close;
this.onDestroy = onDestroy;
}
public IDocumentOwner DocumentOwner { get; set; }
public void OnClose(CancelEventArgs e) { e.Cancel = !close(); }
public object Title { get { return null; } }
void IDocumentContent.OnDestroy() {
if(onDestroy != null)
onDestroy();
}
}
protected override void SetUpCore() {
base.SetUpCore();
ViewLocator.Default = new TestViewLocator(this);
}
protected override void TearDownCore() {
Interaction.GetBehaviors(Window).Clear();
ViewLocator.Default = null;
base.TearDownCore();
}
protected virtual WindowedDocumentUIService CreateService() {
return new WindowedDocumentUIService();
}
void DoCloseTest(bool allowClose, bool destroyOnClose, bool destroyed, Action<IDocument> closeMethod) {
DoCloseTest((bool?)allowClose, destroyOnClose, destroyed, (d, b) => closeMethod(d));
}
void DoCloseTest(bool? allowClose, bool destroyOnClose, bool destroyed, Action<IDocument, bool> closeMethod) {
EnqueueShowWindow();
IDocumentManagerService service = null;
bool closeChecked = false;
bool destroyCalled = false;
IDocument document = null;
EnqueueCallback(() => {
WindowedDocumentUIService windowedDocumentUIService = CreateService();
Interaction.GetBehaviors(Window).Add(windowedDocumentUIService);
service = windowedDocumentUIService;
TestDocumentContent viewModel = new TestDocumentContent(() => {
closeChecked = true;
return allowClose != null && allowClose.Value;
}, () => {
destroyCalled = true;
});
document = service.CreateDocument("EmptyView", viewModel);
document.Show();
});
EnqueueWindowUpdateLayout();
EnqueueCallback(() => {
document.DestroyOnClose = destroyOnClose;
closeMethod(document, allowClose == null);
Assert.AreEqual(allowClose != null, closeChecked);
Assert.AreEqual(destroyed, destroyCalled);
Assert.AreEqual(!destroyed, service.Documents.Contains(document));
});
EnqueueTestComplete();
}
void CloseDocument(IDocument document, bool force) {
document.Close(force);
}
void CloseDocumentWithDocumentOwner(IDocument document, bool force) {
IDocumentContent documentContent = (IDocumentContent)document.Content;
documentContent.DocumentOwner.Close(documentContent, force);
}
void CloseDocumentWithClosingWindow(IDocument document) {
Window window = ((WindowedDocumentUIService.WindowDocument)document).Window.RealWindow;
window.Close();
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest1() {
DoCloseTest(allowClose: false, destroyOnClose: false, destroyed: false, closeMethod: CloseDocument);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest2() {
DoCloseTest(allowClose: false, destroyOnClose: false, destroyed: false, closeMethod: CloseDocumentWithDocumentOwner);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest12() {
DoCloseTest(allowClose: false, destroyOnClose: false, destroyed: false, closeMethod: CloseDocumentWithClosingWindow);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest3() {
DoCloseTest(allowClose: false, destroyOnClose: true, destroyed: false, closeMethod: CloseDocument);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest4() {
DoCloseTest(allowClose: false, destroyOnClose: true, destroyed: false, closeMethod: CloseDocumentWithDocumentOwner);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest14() {
DoCloseTest(allowClose: false, destroyOnClose: true, destroyed: false, closeMethod: CloseDocumentWithClosingWindow);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest5() {
DoCloseTest(allowClose: true, destroyOnClose: false, destroyed: false, closeMethod: CloseDocument);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest6() {
DoCloseTest(allowClose: true, destroyOnClose: false, destroyed: false, closeMethod: CloseDocumentWithDocumentOwner);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest16() {
DoCloseTest(allowClose: true, destroyOnClose: false, destroyed: false, closeMethod: CloseDocumentWithClosingWindow);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest7() {
DoCloseTest(allowClose: true, destroyOnClose: true, destroyed: true, closeMethod: CloseDocument);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest8() {
DoCloseTest(allowClose: true, destroyOnClose: true, destroyed: true, closeMethod: CloseDocumentWithDocumentOwner);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest18() {
DoCloseTest(allowClose: true, destroyOnClose: true, destroyed: true, closeMethod: CloseDocumentWithClosingWindow);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest9() {
DoCloseTest(allowClose: null, destroyOnClose: false, destroyed: false, closeMethod: CloseDocument);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest10() {
DoCloseTest(allowClose: null, destroyOnClose: false, destroyed: false, closeMethod: CloseDocumentWithDocumentOwner);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest11() {
DoCloseTest(allowClose: null, destroyOnClose: true, destroyed: true, closeMethod: CloseDocument);
}
[Test, Asynchronous]
public void IDocumentViewModelCloseTest13() {
DoCloseTest(allowClose: null, destroyOnClose: true, destroyed: true, closeMethod: CloseDocumentWithDocumentOwner);
}
}
public class TestViewLocator : IViewLocator {
Dictionary<string, Type> types;
IViewLocator innerViewLocator;
public TestViewLocator(object ownerTypeInstance, IViewLocator innerViewLocator = null) : this(ownerTypeInstance.GetType(), innerViewLocator) { }
public TestViewLocator(Type ownerType, IViewLocator innerViewLocator = null) {
this.innerViewLocator = innerViewLocator;
types = GetBaseTypes(ownerType).SelectMany(x => x.GetNestedTypes(BindingFlags.Public)).ToDictionary(t => t.Name, t => t);
}
object IViewLocator.ResolveView(string name) {
Type type;
return types.TryGetValue(name, out type) ? Activator.CreateInstance(type) : innerViewLocator.With(i => i.ResolveView(name));
}
Type IViewLocator.ResolveViewType(string name) {
throw new NotImplementedException();
}
IEnumerable<Type> GetBaseTypes(Type type) {
for(var baseType = type; baseType != null; baseType = baseType.BaseType)
yield return baseType;
}
}
}
| |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org.
// ****************************************************************
using System;
using System.IO;
using System.Threading;
using System.Collections;
using System.Collections.Specialized;
using NUnit.Core.Filters;
using System.Reflection;
namespace NUnit.Core
{
/// <summary>
/// SimpleTestRunner is the simplest direct-running TestRunner. It
/// passes the event listener interface that is provided on to the tests
/// to use directly and does nothing to redirect text output. Both
/// Run and BeginRun are actually synchronous, although the client
/// can usually ignore this. BeginRun + EndRun operates as expected.
/// </summary>
public class SimpleTestRunner : MarshalByRefObject, TestRunner
{
static Logger log = InternalTrace.GetLogger(typeof(SimpleTestRunner));
#region Instance Variables
/// <summary>
/// Identifier for this runner. Must be unique among all
/// active runners in order to locate tests. Default
/// value of 0 is adequate in applications with a single
/// runner or a non-branching chain of runners.
/// </summary>
private int runnerID = 0;
/// <summary>
/// The loaded test suite
/// </summary>
private Test test;
/// <summary>
/// The builder we use to load tests, created for each load
/// </summary>
private TestSuiteBuilder builder;
/// <summary>
/// Results from the last test run
/// </summary>
private TestResult testResult;
/// <summary>
/// The thread on which Run was called. Set to the
/// current thread while a run is in process.
/// </summary>
private Thread runThread;
#endregion
#region Constructor
public SimpleTestRunner() : this( 0 ) { }
public SimpleTestRunner( int runnerID )
{
this.runnerID = runnerID;
}
#endregion
#region Properties
public virtual int ID
{
get { return runnerID; }
}
public IList AssemblyInfo
{
get { return builder.AssemblyInfo; }
}
public ITest Test
{
get { return test == null ? null : new TestNode( test ); }
}
/// <summary>
/// Results from the last test run
/// </summary>
public TestResult TestResult
{
get { return testResult; }
}
public virtual bool Running
{
get { return runThread != null && runThread.IsAlive; }
}
#endregion
#region Methods for Loading Tests
/// <summary>
/// Load a TestPackage
/// </summary>
/// <param name="package">The package to be loaded</param>
/// <returns>True on success, false on failure</returns>
public bool Load( TestPackage package )
{
log.Debug("Loading package " + package.Name);
this.builder = new TestSuiteBuilder();
this.test = builder.Build( package );
if ( test == null ) return false;
test.SetRunnerID( this.runnerID, true );
TestExecutionContext.CurrentContext.TestPackage = package;
return true;
}
/// <summary>
/// Unload all tests previously loaded
/// </summary>
public void Unload()
{
log.Debug("Unloading");
this.test = null; // All for now
}
#endregion
#region CountTestCases
public int CountTestCases( ITestFilter filter )
{
return test.CountTestCases( filter );
}
#endregion
#region Methods for Running Tests
public virtual TestResult Run( EventListener listener, ITestFilter filter, bool tracing, LoggingThreshold logLevel )
{
try
{
log.Debug("Starting test run");
// Take note of the fact that we are running
this.runThread = Thread.CurrentThread;
listener.RunStarted( this.Test.TestName.FullName, test.CountTestCases( filter ) );
testResult = test.Run( listener, filter );
// Signal that we are done
listener.RunFinished( testResult );
log.Debug("Test run complete");
// Return result array
return testResult;
}
catch( Exception exception )
{
// Signal that we finished with an exception
listener.RunFinished( exception );
// Rethrow - should we do this?
throw;
}
finally
{
runThread = null;
}
}
public void BeginRun(EventListener listener, ITestFilter filter, bool tracing, LoggingThreshold logLevel)
{
testResult = this.Run(listener, filter, tracing, logLevel);
}
public virtual TestResult EndRun()
{
return TestResult;
}
/// <summary>
/// Wait is a NOP for SimpleTestRunner
/// </summary>
public virtual void Wait()
{
}
public virtual void CancelRun()
{
if (this.runThread != null)
{
// Cancel Synchronous run only if on another thread
if ( this.runThread == Thread.CurrentThread )
throw new InvalidOperationException( "May not CancelRun on same thread that is running the test" );
ThreadUtility.Kill(this.runThread);
}
}
#endregion
#region InitializeLifetimeService Override
public override object InitializeLifetimeService()
{
return null;
}
#endregion
#region IDisposable Members
public void Dispose()
{
Unload();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Modules;
using IronPython.Runtime.Types;
using System.Numerics;
using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute;
namespace IronPython.Runtime.Operations {
public static partial class Int32Ops {
private static object FastNew(CodeContext/*!*/ context, object o) {
Extensible<BigInteger> el;
if (o is string) return __new__(null, (string)o, 10);
if (o is double) return DoubleOps.__int__((double)o);
if (o is int) return o;
if (o is bool) return ((bool)o) ? 1 : 0;
if (o is BigInteger) {
int res;
if (((BigInteger)o).AsInt32(out res)) {
return ScriptingRuntimeHelpers.Int32ToObject(res);
}
return o;
}
if ((el = o as Extensible<BigInteger>) != null) {
int res;
if (el.Value.AsInt32(out res)) {
return ScriptingRuntimeHelpers.Int32ToObject(res);
}
return el.Value;
}
if (o is float) return DoubleOps.__int__((double)(float)o);
if (o is Complex) throw PythonOps.TypeError("can't convert complex to int; use int(abs(z))");
if (o is Int64) {
Int64 val = (Int64)o;
if (Int32.MinValue <= val && val <= Int32.MaxValue) {
return (Int32)val;
} else {
return (BigInteger)val;
}
} else if (o is UInt32) {
UInt32 val = (UInt32)o;
if (val <= Int32.MaxValue) {
return (Int32)val;
} else {
return (BigInteger)val;
}
} else if (o is UInt64) {
UInt64 val = (UInt64)o;
if (val <= Int32.MaxValue) {
return (Int32)val;
} else {
return (BigInteger)val;
}
} else if (o is Decimal) {
Decimal val = (Decimal)o;
if (Int32.MinValue <= val && val <= Int32.MaxValue) {
return (Int32)val;
} else {
return (BigInteger)val;
}
} else if (o is Enum) {
return ((IConvertible)o).ToInt32(null);
}
if (o is Extensible<string> es) {
// __int__ takes precedence, call it if it's available...
object value;
if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, es, "__int__", out value)) {
return value;
}
// otherwise call __new__ on the string value
return __new__(null, es.Value, 10);
}
object result;
int intRes;
BigInteger bigintRes;
if (PythonTypeOps.TryInvokeUnaryOperator(context, o, "__int__", out result) &&
!Object.ReferenceEquals(result, NotImplementedType.Value)) {
if (result is int || result is BigInteger ||
result is Extensible<int> || result is Extensible<BigInteger>) {
return result;
} else {
throw PythonOps.TypeError("__int__ returned non-Integral (type {0})", PythonTypeOps.GetOldName(result));
}
} else if (PythonOps.TryGetBoundAttr(context, o, "__trunc__", out result)) {
result = PythonOps.CallWithContext(context, result);
if (result is int || result is BigInteger ||
result is Extensible<int> || result is Extensible<BigInteger>) {
return result;
} else if (Converter.TryConvertToInt32(result, out intRes)) {
return intRes;
} else if (Converter.TryConvertToBigInteger(result, out bigintRes)) {
return bigintRes;
} else {
throw PythonOps.TypeError("__trunc__ returned non-Integral (type {0})", PythonTypeOps.GetOldName(result));
}
}
if (o is OldInstance) {
throw PythonOps.AttributeError("{0} instance has no attribute '__trunc__'", PythonTypeOps.GetOldName((OldInstance)o));
} else {
throw PythonOps.TypeError("int() argument must be a string or a number, not '{0}'", PythonTypeOps.GetName(o));
}
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, object o) {
return __new__(context, TypeCache.Int32, o);
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType cls, Extensible<double> o) {
object value;
// always succeeds as float defines __int__
PythonTypeOps.TryInvokeUnaryOperator(context, o, "__int__", out value);
if (cls == TypeCache.Int32) {
return (int)value;
} else {
return cls.CreateInstance(context, value);
}
}
private static void ValidateType(PythonType cls) {
if (cls == TypeCache.Boolean)
throw PythonOps.TypeError("int.__new__(bool) is not safe, use bool.__new__()");
}
[StaticExtensionMethod]
public static object __new__(PythonType cls, string s, int @base) {
ValidateType(cls);
// radix 16/8/2 allows a 0x/0o/0b preceding it... We either need a whole new
// integer parser, or special case it here.
int start = 0;
if (@base == 16 || @base == 8 || @base == 2) {
start = s.Length - TrimRadix(s, @base).Length;
}
return LiteralParser.ParseIntegerSign(s, @base, start);
}
[StaticExtensionMethod]
public static object __new__(CodeContext/*!*/ context, PythonType cls, IList<byte> s) {
object value;
IPythonObject po = s as IPythonObject;
if (po == null ||
!PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, po, "__int__", out value)) {
value = FastNew(context, s.MakeString());
}
if (cls == TypeCache.Int32) {
return value;
} else {
ValidateType(cls);
// derived int creation...
return cls.CreateInstance(context, value);
}
}
internal static string TrimRadix(string s, int radix) {
for (int i = 0; i < s.Length; i++) {
if (Char.IsWhiteSpace(s[i])) continue;
if (s[i] == '0' && i < s.Length - 1) {
switch(radix) {
case 16:
if (s[i + 1] == 'x' || s[i + 1] == 'X') {
s = s.Substring(i + 2);
}
break;
case 8:
if (s[i + 1] == 'o' || s[i + 1] == 'O') {
s = s.Substring(i + 2);
}
break;
case 2:
if (s[i + 1] == 'b' || s[i + 1] == 'B') {
s = s.Substring(i + 2);
}
break;
default:
break;
}
}
break;
}
return s;
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType cls, object x) {
object value = FastNew(context, x);
if (cls == TypeCache.Int32) {
return value;
} else {
ValidateType(cls);
// derived int creation...
return cls.CreateInstance(context, value);
}
}
// "int()" calls ReflectedType.Call(), which calls "Activator.CreateInstance" and return directly.
// this is for derived int creation or direct calls to __new__...
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType cls) {
if (cls == TypeCache.Int32) return 0;
return cls.CreateInstance(context);
}
#region Binary Operators
[SpecialName]
public static object FloorDivide(int x, int y) {
if (y == -1 && x == Int32.MinValue) {
return -(BigInteger)Int32.MinValue;
}
return ScriptingRuntimeHelpers.Int32ToObject(MathUtils.FloorDivideUnchecked(x, y));
}
[SpecialName]
public static int Mod(int x, int y) {
return MathUtils.FloorRemainder(x, y);
}
[SpecialName]
public static object Power(int x, BigInteger power, BigInteger qmod) {
return BigIntegerOps.Power((BigInteger)x, power, qmod);
}
[SpecialName]
public static object Power(int x, double power, double qmod) {
return NotImplementedType.Value;
}
[SpecialName]
public static object Power(int x, int power, int? qmod) {
if (qmod == null) return Power(x, power);
int mod = (int)qmod;
if (power < 0) throw PythonOps.TypeError("power", power, "power must be >= 0");
if (mod == 0) {
throw PythonOps.ZeroDivisionError();
}
// This is "exponentiation by squaring" (described in Applied Cryptography; a log-time algorithm)
long result = 1 % mod; // Handle special case of power=0, mod=1
long factor = x;
while (power != 0) {
if ((power & 1) != 0) result = (result * factor) % mod;
factor = (factor * factor) % mod;
power >>= 1;
}
// fix the sign for negative moduli or negative mantissas
if ((mod < 0 && result > 0) || (mod > 0 && result < 0)) {
result += mod;
}
return (int)result;
}
[SpecialName]
public static object Power(int x, int power) {
if (power == 0) return 1;
if (power < 0) {
if (x == 0)
throw PythonOps.ZeroDivisionError("0.0 cannot be raised to a negative power");
return DoubleOps.Power(x, power);
}
int factor = x;
int result = 1;
int savePower = power;
try {
checked {
while (power != 0) {
if ((power & 1) != 0) result = result * factor;
if (power == 1) break; // prevent overflow
factor = factor * factor;
power >>= 1;
}
return result;
}
} catch (OverflowException) {
return BigIntegerOps.Power((BigInteger)x, savePower);
}
}
[SpecialName]
public static object LeftShift(int x, int y) {
if (y < 0) {
throw PythonOps.ValueError("negative shift count");
}
if (y > 31 ||
(x > 0 && x > (Int32.MaxValue >> y)) ||
(x < 0 && x < (Int32.MinValue >> y))) {
return Int64Ops.LeftShift((long)x, y);
}
return ScriptingRuntimeHelpers.Int32ToObject(x << y);
}
[SpecialName]
public static int RightShift(int x, int y) {
if (y < 0) {
throw PythonOps.ValueError("negative shift count");
}
if (y > 31) {
return x >= 0 ? 0 : -1;
}
int q;
if (x >= 0) {
q = x >> y;
} else {
q = (x + ((1 << y) - 1)) >> y;
int r = x - (q << y);
if (r != 0) q--;
}
return q;
}
#endregion
public static PythonTuple __divmod__(int x, int y) {
return PythonTuple.MakeTuple(Divide(x, y), Mod(x, y));
}
[return: MaybeNotImplemented]
public static object __divmod__(int x, object y) {
return NotImplementedType.Value;
}
#region Unary Operators
public static string __oct__(int x) {
if (x == 0) {
return "0";
} else if (x > 0) {
return "0" + ((BigInteger)x).ToString(8);
} else {
return "-0" + ((BigInteger)(-x)).ToString(8);
}
}
public static string __hex__(int x) {
if (x < 0) {
return "-0x" + (-x).ToString("x");
} else {
return "0x" + x.ToString("x");
}
}
#endregion
public static object __getnewargs__(CodeContext context, int self) {
return PythonTuple.MakeTuple(Int32Ops.__new__(context, TypeCache.Int32, self));
}
public static object __rdivmod__(int x, int y) {
return __divmod__(y, x);
}
public static int __int__(int self) {
return self;
}
public static BigInteger __long__(int self) {
return (BigInteger)self;
}
public static double __float__(int self) {
return (double)self;
}
public static int __abs__(int self) {
return Math.Abs(self);
}
public static object __coerce__(CodeContext context, int x, object o) {
// called via builtin.coerce()
if (o is int) {
return PythonTuple.MakeTuple(ScriptingRuntimeHelpers.Int32ToObject(x), o);
}
return NotImplementedType.Value;
}
public static string __format__(CodeContext/*!*/ context, int self, [NotNull]string/*!*/ formatSpec) {
StringFormatSpec spec = StringFormatSpec.FromString(formatSpec);
if (spec.Precision != null) {
throw PythonOps.ValueError("Precision not allowed in integer format specifier");
}
string digits;
int width = 0;
switch (spec.Type) {
case 'n':
CultureInfo culture = context.LanguageContext.NumericCulture;
if (culture == CultureInfo.InvariantCulture) {
// invariant culture maps to CPython's C culture, which doesn't
// include any formatting info.
goto case 'd';
}
width = spec.Width ?? 0;
// If we're padding with leading zeros and we might be inserting
// culture sensitive number group separators. (i.e. commas)
// So use FormattingHelper.ToCultureString for that support.
if (spec.Fill.HasValue && spec.Fill.Value == '0' && width > 1) {
digits = FormattingHelper.ToCultureString(self, culture.NumberFormat, spec);
}
else {
digits = self.ToString("N0", culture);
}
break;
case null:
case 'd':
if (spec.ThousandsComma) {
width = spec.Width ?? 0;
// If we're inserting commas, and we're padding with leading zeros.
// AlignNumericText won't know where to place the commas,
// so use FormattingHelper.ToCultureString for that support.
if (spec.Fill.HasValue && spec.Fill.Value == '0' && width > 1) {
digits = FormattingHelper.ToCultureString(self, FormattingHelper.InvariantCommaNumberInfo, spec);
}
else {
digits = self.ToString("#,0", CultureInfo.InvariantCulture);
}
} else {
digits = self.ToString("D", CultureInfo.InvariantCulture);
}
break;
case '%':
if (spec.ThousandsComma) {
digits = self.ToString("#,0.000000%", CultureInfo.InvariantCulture);
} else {
digits = self.ToString("0.000000%", CultureInfo.InvariantCulture);
}
break;
case 'e':
if (spec.ThousandsComma) {
digits = self.ToString("#,0.000000e+00", CultureInfo.InvariantCulture);
} else {
digits = self.ToString("0.000000e+00", CultureInfo.InvariantCulture);
}
break;
case 'E':
if (spec.ThousandsComma) {
digits = self.ToString("#,0.000000E+00", CultureInfo.InvariantCulture);
} else {
digits = self.ToString("0.000000E+00", CultureInfo.InvariantCulture);
}
break;
case 'f':
case 'F':
if (spec.ThousandsComma) {
digits = self.ToString("#,########0.000000", CultureInfo.InvariantCulture);
} else {
digits = self.ToString("#########0.000000", CultureInfo.InvariantCulture);
}
break;
case 'g':
if (self >= 1000000 || self <= -1000000) {
digits = self.ToString("0.#####e+00", CultureInfo.InvariantCulture);
} else if (spec.ThousandsComma) {
// Handle the common case in 'd'.
goto case 'd';
} else {
digits = self.ToString(CultureInfo.InvariantCulture);
}
break;
case 'G':
if (self >= 1000000 || self <= -1000000) {
digits = self.ToString("0.#####E+00", CultureInfo.InvariantCulture);
} else if (spec.ThousandsComma) {
// Handle the common case in 'd'.
goto case 'd';
}
else {
digits = self.ToString(CultureInfo.InvariantCulture);
}
break;
case 'X':
digits = ToHex(self, false);
break;
case 'x':
digits = ToHex(self, true);
break;
case 'o': // octal
digits = ToOctal(self, true);
break;
case 'b': // binary
digits = ToBinary(self, false);
break;
case 'c': // single char
if (spec.Sign != null) {
throw PythonOps.ValueError("Sign not allowed with integer format specifier 'c'");
}
if (self < 0 || self > 0xFF) {
throw PythonOps.OverflowError("%c arg not in range(0x10000)");
}
digits = ScriptingRuntimeHelpers.CharToString((char)self);
break;
default:
throw PythonOps.ValueError("Unknown format code '{0}'", spec.Type.ToString());
}
if (self < 0 && digits[0] == '-') {
digits = digits.Substring(1);
}
return spec.AlignNumericText(digits, self == 0, self > 0);
}
private static string ToHex(int self, bool lowercase) {
string digits;
if (self != Int32.MinValue) {
int val = self;
if (self < 0) {
val = -self;
}
digits = val.ToString(lowercase ? "x" : "X", CultureInfo.InvariantCulture);
} else {
digits = "80000000";
}
return digits;
}
private static string ToOctal(int self, bool lowercase) {
string digits;
if (self == 0) {
digits = "0";
} else if (self != Int32.MinValue) {
int val = self;
if (self < 0) {
val = -self;
}
StringBuilder sbo = new StringBuilder();
for (int i = 30; i >= 0; i -= 3) {
char value = (char)('0' + (val >> i & 0x07));
if (value != '0' || sbo.Length > 0) {
sbo.Append(value);
}
}
digits = sbo.ToString();
} else {
digits = "20000000000";
}
return digits;
}
internal static string ToBinary(int self) {
if (self == Int32.MinValue) {
return "-0b10000000000000000000000000000000";
}
string res = ToBinary(self, true);
if (self < 0) {
res = "-" + res;
}
return res;
}
private static string ToBinary(int self, bool includeType) {
string digits;
if (self == 0) {
digits = "0";
} else if (self != Int32.MinValue) {
StringBuilder sbb = new StringBuilder();
int val = self;
if (self < 0) {
val = -self;
}
for (int i = 31; i >= 0; i--) {
if ((val & (1 << i)) != 0) {
sbb.Append('1');
} else if (sbb.Length != 0) {
sbb.Append('0');
}
}
digits = sbb.ToString();
} else {
digits = "10000000000000000000000000000000";
}
if (includeType) {
digits = "0b" + digits;
}
return digits;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace SDammann.WebApi.Versioning.TestApi.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);
}
}
}
}
| |
using System;
using System.Collections;
namespace GrillScript
{
/// <summary>
/// Summary description for AbsSynTree.
/// </summary>
public class LispLexer
{
private string str;
private int pos;
private int max;
public LispLexer(string src)
{ str = src.TrimStart(); pos = 0; max = str.Length; }
public char LookAhead()
{
if(pos < max) return str[pos];
else { Console.WriteLine("AUTO ADD )"); return ')'; }
}
public void eatWhite()
{while(pos < max && Char.IsWhiteSpace(str[pos])) pos++;}
public void ConsumeLook()
{
pos++;
eatWhite();
}
public void ConsumeLook2()
{
pos++;
}
public bool IsPartStr(char x)
{
if(x == '(') return false;
if(x == ')') return false;
return ! Char.IsWhiteSpace(x);
}
public string ReadString()
{
string rez = "";
while(pos < max && IsPartStr(str[pos]) )
{
rez += str[pos];
pos++;
}
eatWhite();
return rez;
}
public bool Good(char x)
{
if(pos >= max) return false;
return (str[pos] != x);
}
public bool GoodE2(char x, char y)
{
if(pos >= max) return false;
return (str[pos] == x || str[pos] == y);
}
public string ReadConstString()
{
string rez = "";
while(Good('\"'))
{
rez += str[pos];
if(str[pos]=='\\')
{
pos++;
rez += "" + str[pos];
}
pos++;
}
pos++;
eatWhite();
return rez;
}
public string ReadConstString2()
{
string rez = "";
while(Good('\''))
{
rez += str[pos];
if(str[pos]=='\\')
{
pos++;
rez += "" + str[pos];
}
pos++;
}
pos++;
eatWhite();
return rez;
}
public string ReadRegex()
{
string rez = "/";
while(Good('/'))
{
rez += str[pos];
if(str[pos]=='\\')
{
pos++;
rez += "" + str[pos];
}
pos++;
}
pos++;
rez += "/";
while(GoodE2('i','g'))
{
rez += str[pos];
pos++;
}
eatWhite();
return rez;
}
/*
public char LookAhead()
{
if(str.Length == 0)
{
Console.WriteLine("STRANGE!!");
return ')';
}
return str[0];
}
public void ConsumeLook()
{ str = str.Substring(1).TrimStart(); }
public void ConsumeLook2()
{ str = str.Substring(1); }
public string ReadString()
{
int k = str.IndexOf(" ");
string res = str.Substring(0,k);
str = str.Substring(k+1).TrimStart();
return res;
}
public string ReadUpTo(int k)
{
string res = str.Substring(0,k);
str = str.Substring(k+1).TrimStart();
return res;
}
public string ReadConstString()
{
for(int k = 0; k < str.Length; k++)
{
if(str[k]=='\\')
{
k++;
}
else
{
if(str[k].Equals('\"')) return ReadUpTo(k);
}
}
return str;
}
public string ReadConstString2()
{
for(int k = 0; k < str.Length; k++)
{
if(str[k]=='\\')
{
k++;
}
else
{
if(str[k].Equals('\'')) return ReadUpTo(k);
}
}
return str;
}
*/
}
public class LispNode
{
public string node;
public LispNode[] children;
public bool visit;
public void clearV()
{
visit = false;
if(children != null)
{
foreach(LispNode N in children) N.clearV();
}
}
public LispNode(string N, ArrayList C)
{
visit = false;
// Console.WriteLine("Node: " + N);
node = N;
children = null;
if(C == null) return;
children = new LispNode[C.Count];
int idx = 0;
foreach(LispNode c in C)
{
children[idx] = c;
idx++;
}
}
public string str() // output
{
if(children == null)
return "\"" + node + "\" ";
string res = "(" + node + " ";
foreach(LispNode LN in children)
res += LN.str();
return res + ")";
}
public bool Eq(LispNode LN)
{
if(LN.node.Equals(this.node))
{
if(LN.children == null && this.children == null) return true;
if(LN.children != null && this.children != null)
{
if(LN.children.Length == this.children.Length)
{
for(int k = 0; k < this.children.Length; k++)
{
if(! LN.children[k].Eq(this.children[k]))
return false;
}
return true;
}
}
}
return false;
}
public static LispNode Parse(LispLexer Lex)
{
char lookahead = Lex.LookAhead();
if(lookahead == '\"' || lookahead == '\'' || lookahead == '/')
{
Lex.ConsumeLook2();
string X;
if(lookahead=='"') X = Lex.ReadConstString();
else if(lookahead=='\'') X = Lex.ReadConstString2();
else X = Lex.ReadRegex();
return new LispNode(X, null);
}
if(lookahead == '(')
{
// get the name (<node>' ')
Lex.ConsumeLook();
string Name = Lex.ReadString();
// get the children
ArrayList Children = new ArrayList();
while(Lex.LookAhead() != ')')
{
Children.Add(Parse(Lex));
}
if(Children.Count == 0) Children = null;
Lex.ConsumeLook();
return new LispNode(Name, Children);
}
else
{
return new LispNode(Lex.ReadString(),null);
}
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Encog.Util.CSV;
using System.IO;
using System.Globalization;
namespace Encog.ML.Data.Market.Loader
{
public partial class CSVFormLoader : Form
{
string chosenfile = "";
public string Chosenfile
{
get { return chosenfile; }
set { chosenfile = value; }
}
public CSVFormLoader()
{
InitializeComponent();
GetCSVFormats();
this.ShowDialog();
}
CSVFormat currentFormat;
public Encog.Util.CSV.CSVFormat CurrentFormat
{
get { return currentFormat; }
set { currentFormat = value; }
}
Dictionary<string, CSVFormat> FormatDictionary = new Dictionary<string, CSVFormat>();
Dictionary<string, MarketDataType> MarketDataTypesToUse = new Dictionary<string, MarketDataType>();
string[] MarketDataTypesValues;
public void GetCSVFormats()
{
FormatDictionary.Add("Decimal Point", CSVFormat.DecimalPoint);
FormatDictionary.Add("Decimal Comma", CSVFormat.DecimalComma);
FormatDictionary.Add("English Format", CSVFormat.English);
FormatDictionary.Add("EG Format", CSVFormat.EgFormat);
Array a = Enum.GetNames(typeof(MarketDataType));
MarketDataTypesValues = new string[a.Length];
int i = 0;
foreach (string item in a)
{
MarketDataTypesValues[i] = item;
i++;
}
return;
}
public CSVFormat format { get; set; }
public List<MarketDataType> TypesLoaded = new List<MarketDataType>();
public List<MarketDataType> MarketTypesUsed
{
get { return TypesLoaded; }
set { TypesLoaded = value; }
}
OpenFileDialog openFileDialog1;
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = ("c:\\");
openFileDialog1.Filter = ("txt files (*.csv)|*.csv|All files (*.*)|*.*");
openFileDialog1.FilterIndex = (2);
openFileDialog1.RestoreDirectory = (true);
this.Visible = false;
DialogResult result = this.openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
Chosenfile = file;
format = FormatDictionary[CSVFormatsCombo.Text];
foreach (string item in MarketDataTypesListBox.SelectedItems)
{
TypesLoaded.Add((MarketDataType) Enum.Parse(typeof(MarketDataType),item));
}
ReadCSV csv = new ReadCSV(Chosenfile, true, format);
var ColQuery =
from Names in csv.ColumnNames
select new {Names};
//ComboBox comboxTypes = new ComboBox();
// comboxTypes.Items.Add("DateTime");
// comboxTypes.Items.Add("Double");
// comboxTypes.Items.Add("Skip");
// comboxTypes.SelectedIndex = 0;
// DataGridViewRow dr = new DataGridViewRow();
// DataGridViewComboBoxCell CellGrids = new DataGridViewComboBoxCell();
// foreach (string item in comboxTypes.Items)
// {
// CellGrids.Items.Add(item);
// }
// dr.Cells.Add(CellGrids);
// //newColumnsSetup.dataGridView1.Rows.Add(dr);
// DataGridViewColumn cols = new DataGridViewColumn(CellGrids);
// cols.Name = "Combo";
// newColumnsSetup.dataGridView1.Columns.Add(cols);
//DataGridViewColumn aCol = new DataGridViewColumn();
//foreach (DataGridViewRow item in newColumnsSetup.dataGridView1.Rows)
//{
// DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)(item.Cells[0]);
//}
}
catch (Exception ex)
{
toolStripStatusLabel1.Text = "Error Loading the CSV:" + ex.Message;
}
}
}
private void CSVFormLoader_Load(object sender, EventArgs e)
{
foreach (string item in FormatDictionary.Keys)
{
CSVFormatsCombo.Items.Add(item);
}
foreach (string item in MarketDataTypesValues)
{
MarketDataTypesListBox.Items.Add(item);
}
CSVFormatsCombo.SelectedIndex = 2;
}
private void button2_Click(object sender, EventArgs e)
{
Chosenfile = openFileDialog1.FileName;
toolStripStatusLabel1.Text = " File:" + openFileDialog1.FileName + " has been successfully loaded";
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using Hydra.Framework.ImageProcessing.Analysis.Maths;
namespace Hydra.Framework.ImageProcessing.Analysis.Filters
{
//
//**********************************************************************
/// <summary>
/// ChannelFiltering
/// </summary>
//**********************************************************************
//
public class ChannelFiltering
: IFilter
{
#region Private Member Variables
//
//**********************************************************************
/// <summary>
/// Colour Range Red
/// </summary>
//**********************************************************************
//
private Range red_m = new Range(0, 255);
//
//**********************************************************************
/// <summary>
/// Colour Range Green
/// </summary>
//**********************************************************************
//
private Range green_m = new Range(0, 255);
//
//**********************************************************************
/// <summary>
/// Colour Range Blue
/// </summary>
//**********************************************************************
//
private Range blue_m = new Range(0, 255);
//
//**********************************************************************
/// <summary>
/// Fill Red Flag
/// </summary>
//**********************************************************************
//
private byte fillR_m = 0;
//
//**********************************************************************
/// <summary>
/// Fill Green Flag
/// </summary>
//**********************************************************************
//
private byte fillG_m = 0;
//
//**********************************************************************
/// <summary>
/// Fill Blue Flag
/// </summary>
//**********************************************************************
//
private byte fillB_m = 0;
//
//**********************************************************************
/// <summary>
/// FillOutside Range Red
/// </summary>
//**********************************************************************
//
private bool redFillOutsideRange_m = true;
//
//**********************************************************************
/// <summary>
/// FillOutside Range Green
/// </summary>
//**********************************************************************
//
private bool greenFillOutsideRange_m = true;
//
//**********************************************************************
/// <summary>
/// FillOutside Range Blue
/// </summary>
//**********************************************************************
//
private bool blueFillOutsideRange_m = true;
//
//**********************************************************************
/// <summary>
/// Map Colour Red Array
/// </summary>
//**********************************************************************
//
private byte[] mapRed_m = new byte[256];
//
//**********************************************************************
/// <summary>
/// Map Colour Green Array
/// </summary>
//**********************************************************************
//
private byte[] mapGreen_m = new byte[256];
//
//**********************************************************************
/// <summary>
/// Map Colour Blue Array
/// </summary>
//**********************************************************************
//
private byte[] mapBlue_m = new byte[256];
#endregion
#region Properties
//
//**********************************************************************
/// <summary>
/// Gets or sets the red property.
/// </summary>
/// <value>The red.</value>
//**********************************************************************
//
public Range Red
{
get
{
return red_m;
}
set
{
red_m = value;
CalculateMap(red_m, fillR_m, redFillOutsideRange_m, mapRed_m);
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the fill red property.
/// </summary>
/// <value>The fill red.</value>
//**********************************************************************
//
public byte FillRed
{
get
{
return fillR_m;
}
set
{
fillR_m = value;
CalculateMap(red_m, fillR_m, redFillOutsideRange_m, mapRed_m);
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the green property.
/// </summary>
/// <value>The green.</value>
//**********************************************************************
//
public Range Green
{
get
{
return green_m;
}
set
{
green_m = value;
CalculateMap(green_m, fillG_m, greenFillOutsideRange_m, mapGreen_m);
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the fill green property.
/// </summary>
/// <value>The fill green.</value>
//**********************************************************************
//
public byte FillGreen
{
get
{
return fillG_m;
}
set
{
fillG_m = value;
CalculateMap(green_m, fillG_m, greenFillOutsideRange_m, mapGreen_m);
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the blue property.
/// </summary>
/// <value>The blue.</value>
//**********************************************************************
//
public Range Blue
{
get
{
return blue_m;
}
set
{
blue_m = value;
CalculateMap(blue_m, fillB_m, blueFillOutsideRange_m, mapBlue_m);
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the fill blue property.
/// </summary>
/// <value>The fill blue.</value>
//**********************************************************************
//
public byte FillBlue
{
get
{
return fillB_m;
}
set
{
fillB_m = value;
CalculateMap(blue_m, fillB_m, blueFillOutsideRange_m, mapBlue_m);
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets a value indicating whether [red fill outside range] property.
/// </summary>
/// <value>
/// <c>true</c> if [red fill outside range]; otherwise, <c>false</c>.
/// </value>
//**********************************************************************
//
public bool RedFillOutsideRange
{
get
{
return redFillOutsideRange_m;
}
set
{
redFillOutsideRange_m = value;
CalculateMap(red_m, fillR_m, redFillOutsideRange_m, mapRed_m);
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets a value indicating whether [green fill outside range] property.
/// </summary>
/// <value>
/// <c>true</c> if [green fill outside range]; otherwise, <c>false</c>.
/// </value>
//**********************************************************************
//
public bool GreenFillOutsideRange
{
get
{
return greenFillOutsideRange_m;
}
set
{
greenFillOutsideRange_m = value;
CalculateMap(green_m, fillG_m, greenFillOutsideRange_m, mapGreen_m);
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets a value indicating whether [blue fill outside range] property.
/// </summary>
/// <value>
/// <c>true</c> if [blue fill outside range]; otherwise, <c>false</c>.
/// </value>
//**********************************************************************
//
public bool BlueFillOutsideRange
{
get
{
return blueFillOutsideRange_m;
}
set
{
blueFillOutsideRange_m = value;
CalculateMap(blue_m, fillB_m, blueFillOutsideRange_m, mapBlue_m);
}
}
#endregion
#region Constructors
//
//**********************************************************************
/// <summary>
/// Initialises a new instance of the <see cref="T:ChannelFiltering"/> class.
/// </summary>
//**********************************************************************
//
public ChannelFiltering()
{
CalculateMap(red_m, fillR_m, redFillOutsideRange_m, mapRed_m);
CalculateMap(green_m, fillG_m, greenFillOutsideRange_m, mapGreen_m);
CalculateMap(blue_m, fillB_m, blueFillOutsideRange_m, mapBlue_m);
}
//
//**********************************************************************
/// <summary>
/// Initialises a new instance of the <see cref="T:ChannelFiltering"/> class.
/// </summary>
/// <param name="red">The red.</param>
/// <param name="green">The green.</param>
/// <param name="blue">The blue.</param>
//**********************************************************************
//
public ChannelFiltering(Range red, Range green, Range blue)
{
Red = red;
Green = green;
Blue = blue;
}
#endregion
#region Private Methods
//
//**********************************************************************
/// <summary>
/// Calculates the map.
/// </summary>
/// <param name="range">The range.</param>
/// <param name="fill">The fill.</param>
/// <param name="fillOutsideRange">if set to <c>true</c> [fill outside range].</param>
/// <param name="map">The map.</param>
//**********************************************************************
//
private void CalculateMap (Range range, byte fill, bool fillOutsideRange, byte[] map)
{
for (int i = 0; i < 256; i++)
{
if ((i >= range.Min) && (i <= range.Max))
{
map[i] = (fillOutsideRange) ? (byte)i : fill;
}
else
{
map[i] = (fillOutsideRange) ? fill : (byte)i;
}
}
}
#endregion
#region Public Methods
//
//**********************************************************************
/// <summary>
/// Apply filter
/// </summary>
/// <param name="srcImg">The SRC img.</param>
/// <returns></returns>
//**********************************************************************
//
public Bitmap Apply(Bitmap srcImg)
{
if (srcImg.PixelFormat != PixelFormat.Format24bppRgb)
throw new ArgumentException();
//
// get source image size
//
int width = srcImg.Width;
int height = srcImg.Height;
//
// lock source bitmap data
//
BitmapData srcData = srcImg.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
//
// create new image
//
Bitmap dstImg = new Bitmap(width, height, PixelFormat.Format24bppRgb);
//
// lock destination bitmap data
//
BitmapData dstData = dstImg.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
int offset = srcData.Stride - width * 3;
//
// do the job (Warning Unsafe Code)
//
unsafe
{
byte * src = (byte *) srcData.Scan0.ToPointer();
byte * dst = (byte *) dstData.Scan0.ToPointer();
//
// for each row
//
for (int y = 0; y < height; y++)
{
//
// for each pixel
//
for (int x = 0; x < width; x++, src += 3, dst += 3)
{
//
// red
//
dst[RGB.R] = mapRed_m[src[RGB.R]];
// green
dst[RGB.G] = mapGreen_m[src[RGB.G]];
//
// blue
//
dst[RGB.B] = mapBlue_m[src[RGB.B]];
}
src += offset;
dst += offset;
}
}
//
// unlock both images
//
dstImg.UnlockBits(dstData);
srcImg.UnlockBits(srcData);
return dstImg;
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="RandomBundlingTests.cs" company="Microsoft">
// (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
#if GDI_DEBUG_VIEWER
using Microsoft.Msagl.GraphViewerGdi;
#endif
using Microsoft.Msagl.Core;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Core.Routing;
using Microsoft.Msagl.DebugHelpers.Persistence;
using Microsoft.Msagl.Layout.Incremental;
using Microsoft.Msagl.Layout.Initial;
using Microsoft.Msagl.Routing;
using Microsoft.Msagl.Routing.Rectilinear;
using Microsoft.Msagl.Routing.Spline.Bundling;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Msagl.Layout.Layered;
using Microsoft.Msagl.Layout.MDS;
namespace Microsoft.Msagl.UnitTests {
/// <summary>
/// Test class for methods inside EdgeRouterHelper
/// </summary>
[TestClass]
[DeploymentItem(@"Resources\MSAGLGeometryGraphs")]
public class RandomBundlingTests : MsaglTestBase {
[TestMethod]
[Description("Random small tree")]
public void RouteEdges_SmallTree() {
//DisplayGeometryGraph.SetShowFunctions();
Random random = new Random(1);
int ntest = 100;
for (int i = 0; i < ntest; i++) {
GeometryGraph graph = GraphGenerator.GenerateTree(10 + random.Next(10), random);
AddRootCluster(graph);
SetRandomNodeShapes(graph, random);
Layout(graph, random);
//DisplayGeometryGraph.ShowGraph(graph);
RouteEdges(graph, 5 * random.NextDouble());
//DisplayGeometryGraph.ShowGraph(graph);
}
}
[TestMethod]
[Description("Random large tree")]
public void RouteEdges_LargeTree() {
//DisplayGeometryGraph.SetShowFunctions();
Random random = new Random(1);
int ntest = 10;
for (int i = 0; i < ntest; i++) {
GeometryGraph graph = GraphGenerator.GenerateTree(50 + random.Next(100));
AddRootCluster(graph);
SetRandomNodeShapes(graph, random);
Layout(graph, random);
//DisplayGeometryGraph.ShowGraph(graph);
RouteEdges(graph, 5 * random.NextDouble());
//DisplayGeometryGraph.ShowGraph(graph);
}
}
[TestMethod]
[Description("Random small grid graph")]
public void RouteEdges_SmallGrid() {
//DisplayGeometryGraph.SetShowFunctions();
Random random = new Random(1);
int ntest = 20;
for (int i = 0; i < ntest; i++) {
GeometryGraph graph = GraphGenerator.GenerateSquareLattice(20 + random.Next(20));
AddRootCluster(graph);
SetRandomNodeShapes(graph, random);
int additionalEdges = random.Next(20);
for (int j = 0; j < additionalEdges; j++) {
Node source = graph.Nodes[random.Next(graph.Nodes.Count)];
Node target = graph.Nodes[random.Next(graph.Nodes.Count)];
Edge edge = GraphGenerator.CreateEdge(source, target);
graph.Edges.Add(edge);
}
Layout(graph, random);
//DisplayGeometryGraph.ShowGraph(graph);
RouteEdges(graph, 5 * random.NextDouble());
//DisplayGeometryGraph.ShowGraph(graph);
}
}
[TestMethod]
[Description("Random graph with small subgraphs")]
public void RouteEdges_Subgraphs() {
//DisplayGeometryGraph.SetShowFunctions();
Random random = new Random(1);
int ntest = 20;
for (int i = 0; i < ntest; i++) {
int numberOfSubgraphs = 2 + random.Next(10);
int numberOfNodesInSubgraphs = 2 + random.Next(10);
GeometryGraph graph = GraphGenerator.GenerateGraphWithSameSubgraphs(numberOfSubgraphs, numberOfNodesInSubgraphs);
AddRootCluster(graph);
SetRandomNodeShapes(graph, random);
int additionalEdges = random.Next(10);
for (int j = 0; j < additionalEdges; j++) {
Node source = graph.Nodes[random.Next(graph.Nodes.Count)];
Node target = graph.Nodes[random.Next(graph.Nodes.Count)];
Edge edge = GraphGenerator.CreateEdge(source, target);
graph.Edges.Add(edge);
}
Layout(graph, random);
//DisplayGeometryGraph.ShowGraph(graph);
RouteEdges(graph, 5 * random.NextDouble());
//DisplayGeometryGraph.ShowGraph(graph);
}
}
[TestMethod]
[Description("Random small graph")]
public void RouteEdges_RandomGraph() {
//DisplayGeometryGraph.SetShowFunctions();
Random random = new Random(1);
int ntest = 100;
for (int i = 0; i < ntest; i++) {
int nodeCount = 5 + random.Next(10);
int edgeCount = 10 + random.Next(20);
GeometryGraph graph = GraphGenerator.GenerateRandomGraph(nodeCount, edgeCount, random);
AddRootCluster(graph);
SetRandomNodeShapes(graph, random);
Layout(graph, random);
//DisplayGeometryGraph.ShowGraph(graph);
RouteEdges(graph, 5 * random.NextDouble());
//DisplayGeometryGraph.ShowGraph(graph);
}
}
[Timeout(TestTimeout.Infinite)]
[TestMethod]
[Description("Random graph with groups")]
public void RouteEdges_SmallGroups()
{
RsmContent();
}
[Timeout(TestTimeout.Infinite)]
[TestMethod]
[Description("Random graph with groups")]
[DeploymentItem(@"Resources\MSAGLGeometryGraphs\graph0.msagl.geom")]
public void RouteEdges_SmallGroupsFromDisc() {
RsmContentFromDisc();
}
public static void RsmContentFromDisc() {
int ntest = 10000;
int iStart = 1; // 470;
#if DEBUG && TEST_MSAGL
DisplayGeometryGraph.SetShowFunctions();
#endif
var graph = GeometryGraphReader.CreateFromFile(@"c:\tmp\graph0.msagl.geom");
for (int i = iStart; i < ntest; i++) {
Random random = new Random(i);
double edgeSeparation = 5*random.NextDouble();
Console.WriteLine("i={0} es={1}", i, edgeSeparation);
RouteEdges(graph, edgeSeparation);
// DisplayGeometryGraph.ShowGraph(graph);
//TODO: try to move it
}
}
public static void RsmContent()
{
const int ntest = 7000;
int iStart = 1;
for (int multiplier = 1; multiplier < 12; multiplier++)
{
Console.WriteLine("multiplier " + multiplier);
#if DEBUG && TEST_MSAGL
DisplayGeometryGraph.SetShowFunctions();
#endif
for (int i = iStart; i < ntest; i++) {
Random random = new Random(i);
GeometryGraph graph = GenerateGraphWithGroups(random, multiplier);
SetRandomNodeShapes(graph, random);
Layout(graph, random);
// DisplayGeometryGraph.ShowGraph(graph);
double edgeSeparation = 5 * random.NextDouble();
Console.WriteLine("i={0} es={1}", i, edgeSeparation);
GeometryGraphWriter.Write(graph, "c:\\tmp\\graph");
RouteEdges(graph, edgeSeparation);
//DisplayGeometryGraph.ShowGraph(graph);
//TODO: try to move it
}
}
}
static GeometryGraph GenerateGraphWithGroups(Random random, int multiplier)
{
int clusterCount = (2 + random.Next(5))*multiplier;
int nodeCount = (clusterCount + random.Next(20))*multiplier;
int edgeCount = (10 + random.Next(20))*multiplier;
//tree of clusters
var parent = GenerateClusterTree(clusterCount, random);
GeometryGraph graph = new GeometryGraph();
//create nodes
for (int i = 0; i < nodeCount; i++) {
Node node = GraphGenerator.CreateNode(i);
graph.Nodes.Add(node);
}
//create clusters
var clusters = new Cluster[clusterCount];
for (int i = 0; i < clusterCount; i++) {
clusters[i] = new Cluster();
clusters[i].BoundaryCurve = CurveFactory.CreateRectangle(30, 30, new Point(15, 15));
clusters[i].RectangularBoundary = new RectangularClusterBoundary { LeftMargin = 5, RightMargin = 5, BottomMargin = 5, TopMargin = 5 };
}
//set cluster hiearchy
graph.RootCluster = clusters[0];
for (int i = 1; i < clusterCount; i++) {
clusters[parent[i]].AddChild(clusters[i]);
}
//put nodes to clusters
for (int i = 0; i < nodeCount; i++) {
clusters[random.Next(clusterCount)].AddChild(graph.Nodes[i]);
}
for (int i = 0; i < clusterCount; i++) {
if (clusters[i].Nodes.Count() == 0 && clusters[i].Clusters.Count() == 0) {
Node node = GraphGenerator.CreateNode(i);
graph.Nodes.Add(node);
clusters[i].AddChild(node);
nodeCount++;
}
}
//adding edges
for (int i = 0; i < edgeCount; i++) {
int s = random.Next(nodeCount + clusterCount - 1);
Node snode = (s < nodeCount ? graph.Nodes[s] : clusters[s - nodeCount + 1]);
int t = random.Next(nodeCount + clusterCount - 1);
Node tnode = (t < nodeCount ? graph.Nodes[t] : clusters[t - nodeCount + 1]);
if (EdgeIsValid(snode, tnode)) {
var edge = new Edge(snode, tnode);
edge.LineWidth = 0.5 + 3 * random.NextDouble();
graph.Edges.Add(edge);
}
else
i--;
}
SetupPorts(graph);
return graph;
}
static void FixHookPorts(GeometryGraph geometryGraph)
{
foreach (var edge in geometryGraph.Edges)
{
var s = edge.Source;
var t = edge.Target;
var sc = s as Cluster;
if (sc != null && Ancestor(sc, t))
{
edge.SourcePort = new HookUpAnywhereFromInsidePort(() => s.BoundaryCurve);
}
else
{
var tc = t as Cluster;
if (tc != null && Ancestor(tc, s))
{
edge.TargetPort = new HookUpAnywhereFromInsidePort(() => t.BoundaryCurve);
}
}
}
}
static bool Ancestor(Cluster root, Node node)
{
if (node.ClusterParents.Contains(root))
return true;
var parents = new Queue<Cluster>(node.ClusterParents);
while (parents.Count > 0)
{
Cluster parent = parents.Dequeue();
if (root.Clusters.Contains(parent))
return true;
foreach (Cluster grandParent in parent.ClusterParents)
parents.Enqueue(grandParent);
}
return false;
}
static bool EdgeIsValid(Node snode, Node tnode)
{
if (snode == tnode) return false;
if (snode.ClusterParents.First() == tnode.ClusterParents.First())
return true;
/*if (!(snode is Cluster) && snode.AllClusterAncestors.Contains(tnode))
return true;
if (!(tnode is Cluster) && tnode.AllClusterAncestors.Contains(snode))
return true;*/
return false;
}
static int[] GenerateClusterTree(int nc, Random random)
{
int[] parents = new int[nc];
for (int i = 1; i < nc; i++) {
parents[i] = random.Next(i);
}
return parents;
}
static void RouteEdges(GeometryGraph graph, double edgeSeparation)
{
var bs = new BundlingSettings();
bs.EdgeSeparation = edgeSeparation;
var br = new SplineRouter(graph, 0.25, 10, Math.PI / 6, bs);
br.Run();
}
static void Layout(GeometryGraph graph, Random rnd)
{
if (rnd.Next() % 5 < 3){
var settings = new SugiyamaLayoutSettings();
var layout = new InitialLayoutByCluster(graph, settings) {RunInParallel = false};
layout.Run();
}
else {
var settings = new FastIncrementalLayoutSettings { AvoidOverlaps = true };
var layout = new InitialLayoutByCluster(graph, settings);
layout.Run();
}
}
void AddRootCluster(GeometryGraph graph) {
var c = new Cluster(graph.Nodes);
graph.RootCluster = c;
}
/// <summary>
/// Update node shape with randomly selected boundary curve
/// </summary>
static void SetRandomNodeShapes(GeometryGraph graph, Random random) {
if (graph == null) {
return;
}
foreach (Node node in graph.Nodes) {
node.BoundaryCurve = GetRandomShape(random);
}
}
static ICurve GetRandomShape(Random random)
{
//we support rectangle, roundedRectangle, circle, ellipse, diamond, Octagon, triangle, star
int index = random.Next(3);
var center = new Microsoft.Msagl.Core.Geometry.Point();
switch (index) {
case 0:
return CurveFactory.CreateRectangle(20 + random.Next(10), 10 + random.Next(10), center);
case 1:
return CurveFactory.CreateRectangleWithRoundedCorners(30 + random.Next(10), 20 + random.Next(10), 1 + random.Next(8), 1 + random.Next(8), center);
case 2:
return CurveFactory.CreateEllipse(26, 18, center);
}
return null;
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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.Linq;
using System.Net;
using OpenMetaverse;
using Aurora.Framework;
using Aurora.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
namespace OpenSim.Services.CapsService
{
public class PerClientBasedCapsService : IClientCapsService
{
protected ICapsService m_CapsService;
protected Dictionary<ulong, IRegionClientCapsService> m_RegionCapsServices =
new Dictionary<ulong, IRegionClientCapsService>();
protected UserAccount m_account;
protected UUID m_agentID;
protected bool m_callbackHasCome;
protected IPEndPoint m_clientEndPoint;
protected bool m_inTeleport;
protected bool m_requestToCancelTeleport;
#region IClientCapsService Members
public UUID AgentID
{
get { return m_agentID; }
}
public IPEndPoint ClientEndPoint
{
get { return m_clientEndPoint; }
}
public UserAccount AccountInfo
{
get { return m_account; }
}
public bool InTeleport
{
get { return m_inTeleport; }
set { m_inTeleport = value; }
}
public bool RequestToCancelTeleport
{
get { return m_requestToCancelTeleport; }
set { m_requestToCancelTeleport = value; }
}
public bool CallbackHasCome
{
get { return m_callbackHasCome; }
set { m_callbackHasCome = value; }
}
public IHttpServer Server
{
get { return m_CapsService.Server; }
}
public IRegistryCore Registry
{
get { return m_CapsService.Registry; }
}
public String HostUri
{
get { return m_CapsService.HostUri; }
}
public void Initialise(ICapsService server, UUID agentID)
{
m_CapsService = server;
m_agentID = agentID;
m_account = Registry.RequestModuleInterface<IUserAccountService>().GetUserAccount(UUID.Zero, agentID);
}
/// <summary>
/// Close out all of the CAPS for this user
/// </summary>
public void Close()
{
List<ulong> handles = new List<ulong>(m_RegionCapsServices.Keys);
foreach (ulong regionHandle in handles)
{
RemoveCAPS(regionHandle);
}
m_RegionCapsServices.Clear();
}
/// <summary>
/// Attempt to find the CapsService for the given user/region
/// </summary>
/// <param name = "regionID"></param>
/// <param name = "agentID"></param>
/// <returns></returns>
public IRegionClientCapsService GetCapsService(ulong regionID)
{
if (m_RegionCapsServices.ContainsKey(regionID))
return m_RegionCapsServices[regionID];
return null;
}
/// <summary>
/// Attempt to find the CapsService for the root user/region
/// </summary>
/// <param name = "regionID"></param>
/// <param name = "agentID"></param>
/// <returns></returns>
public IRegionClientCapsService GetRootCapsService()
{
#if (!ISWIN)
foreach (IRegionClientCapsService clientCaps in m_RegionCapsServices.Values)
{
if (clientCaps.RootAgent) return clientCaps;
}
return null;
#else
return m_RegionCapsServices.Values.FirstOrDefault(clientCaps => clientCaps.RootAgent);
#endif
}
public List<IRegionClientCapsService> GetCapsServices()
{
return new List<IRegionClientCapsService>(m_RegionCapsServices.Values);
}
/// <summary>
/// Find, or create if one does not exist, a Caps Service for the given region
/// </summary>
/// <param name = "regionID"></param>
/// <returns></returns>
public IRegionClientCapsService GetOrCreateCapsService(ulong regionID, string CAPSBase,
AgentCircuitData circuitData, uint port)
{
//If one already exists, don't add a new one
if (m_RegionCapsServices.ContainsKey(regionID))
{
if (port == 0 || m_RegionCapsServices[regionID].Server.Port == port)
{
m_RegionCapsServices[regionID].InformModulesOfRequest();
return m_RegionCapsServices[regionID];
}
else
RemoveCAPS(regionID);
}
//Create a new one, and then call Get to find it
AddCapsServiceForRegion(regionID, CAPSBase, circuitData, port);
return GetCapsService(regionID);
}
/// <summary>
/// Remove the CAPS for the given user in the given region
/// </summary>
/// <param name = "AgentID"></param>
/// <param name = "regionHandle"></param>
public void RemoveCAPS(ulong regionHandle)
{
if (!m_RegionCapsServices.ContainsKey(regionHandle))
return;
//Remove the agent from the region caps
IRegionCapsService regionCaps = m_CapsService.GetCapsForRegion(regionHandle);
if (regionCaps != null)
regionCaps.RemoveClientFromRegion(m_RegionCapsServices[regionHandle]);
//Remove all the CAPS handlers
m_RegionCapsServices[regionHandle].Close();
m_RegionCapsServices.Remove(regionHandle);
}
#endregion
/// <summary>
/// Add a new Caps Service for the given region if one does not already exist
/// </summary>
/// <param name = "regionHandle"></param>
protected void AddCapsServiceForRegion(ulong regionHandle, string CAPSBase, AgentCircuitData circuitData,
uint port)
{
if (m_clientEndPoint == null && circuitData.ClientIPEndPoint != null)
m_clientEndPoint = circuitData.ClientIPEndPoint;
if (m_clientEndPoint == null)
{
///Should only happen in grid HG/OpenSim situtations
IPAddress test = null;
if (IPAddress.TryParse(circuitData.IPAddress, out test))
m_clientEndPoint = new IPEndPoint(test, 0); //Dunno the port, so leave it alone
}
if (!m_RegionCapsServices.ContainsKey(regionHandle))
{
//Now add this client to the region caps
//Create if needed
m_CapsService.AddCapsForRegion(regionHandle);
IRegionCapsService regionCaps = m_CapsService.GetCapsForRegion(regionHandle);
PerRegionClientCapsService regionClient = new PerRegionClientCapsService();
regionClient.Initialise(this, regionCaps, CAPSBase, circuitData, port);
m_RegionCapsServices[regionHandle] = regionClient;
//Now get and add them
regionCaps.AddClientToRegion(regionClient);
}
}
}
}
| |
/*
* Copyright 2013 ThirdMotion, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @class strange.extensions.dispatcher.eventdispatcher.impl.EventDispatcher
*
* A Dispatcher that uses IEvent to send messages.
*
* Whenever the Dispatcher executes a `Dispatch()`, observers will be
* notified of any event (Key) for which they have registered.
*
* EventDispatcher dispatches TmEvent : IEvent.
*
* The EventDispatcher is the only Dispatcher currently released with Strange
* (though by separating EventDispatcher from Dispatcher I'm obviously
* signalling that I don't think it's the only possible one).
*
* EventDispatcher is both an ITriggerProvider and an ITriggerable.
*
* @see strange.extensions.dispatcher.eventdispatcher.api.IEvent
* @see strange.extensions.dispatcher.api.ITriggerProvider
* @see strange.extensions.dispatcher.api.ITriggerable
*/
using System;
using System.Collections.Generic;
using strange.framework.api;
using strange.framework.impl;
using strange.extensions.dispatcher.api;
using strange.extensions.dispatcher.eventdispatcher.api;
using strange.extensions.pool.api;
using strange.extensions.pool.impl;
namespace strange.extensions.dispatcher.eventdispatcher.impl
{
public class EventDispatcher : Binder, IEventDispatcher, ITriggerProvider, ITriggerable
{
/// The list of clients that will be triggered as a consequence of an Event firing.
protected HashSet<ITriggerable> triggerClients;
protected HashSet<ITriggerable> triggerClientRemovals;
protected bool isTriggeringClients;
/// The eventPool is shared across all EventDispatchers for efficiency
public static IPool<TmEvent> eventPool;
public EventDispatcher ()
{
if (eventPool == null)
{
eventPool = new Pool<TmEvent> ();
eventPool.instanceProvider = new EventInstanceProvider ();
}
}
override public IBinding GetRawBinding()
{
return new EventBinding (resolver);
}
new public IEventBinding Bind(object key)
{
return base.Bind (key) as IEventBinding;
}
public void Dispatch (object eventType)
{
Dispatch (eventType, null);
}
public void Dispatch (object eventType, object data)
{
//Scrub the data to make eventType and data conform if possible
IEvent evt = conformDataToEvent (eventType, data);
if (evt is IPoolable)
{
(evt as IPoolable).Retain ();
}
bool continueDispatch = true;
if (triggerClients != null)
{
isTriggeringClients = true;
foreach (ITriggerable trigger in triggerClients)
{
try
{
if (!trigger.Trigger(evt.type, evt))
{
continueDispatch = false;
break;
}
}
catch (Exception ex) //If trigger throws, we still want to cleanup!
{
internalReleaseEvent(evt);
throw;
}
}
if (triggerClientRemovals != null)
{
flushRemovals();
}
isTriggeringClients = false;
}
if (!continueDispatch)
{
internalReleaseEvent (evt);
return;
}
IEventBinding binding = GetBinding (evt.type) as IEventBinding;
if (binding == null)
{
internalReleaseEvent (evt);
return;
}
object[] callbacks = (binding.value as object[]).Clone() as object[];
if (callbacks == null)
{
internalReleaseEvent (evt);
return;
}
for(int a = 0; a < callbacks.Length; a++)
{
object callback = callbacks[a];
if(callback == null)
continue;
callbacks[a] = null;
object[] currentCallbacks = binding.value as object[];
if(Array.IndexOf(currentCallbacks, callback) == -1)
continue;
if (callback is EventCallback)
{
invokeEventCallback (evt, callback as EventCallback);
}
else if (callback is EmptyCallback)
{
(callback as EmptyCallback)();
}
}
internalReleaseEvent (evt);
}
virtual protected IEvent conformDataToEvent(object eventType, object data)
{
IEvent retv = null;
if (eventType == null)
{
throw new EventDispatcherException("Attempt to Dispatch to null.\ndata: " + data, EventDispatcherExceptionType.EVENT_KEY_NULL);
}
else if (eventType is IEvent)
{
//Client provided a full-formed event
retv = (IEvent)eventType;
}
else if (data == null)
{
//Client provided just an event ID. Create an event for injection
retv = createEvent (eventType, null);
}
else if (data is IEvent)
{
//Client provided both an evertType and a full-formed IEvent
retv = (IEvent)data;
}
else
{
//Client provided an eventType and some data which is not a IEvent.
retv = createEvent (eventType, data);
}
return retv;
}
virtual protected IEvent createEvent(object eventType, object data)
{
IEvent retv = eventPool.GetInstance();
retv.type = eventType;
retv.target = this;
retv.data = data;
return retv;
}
virtual protected void invokeEventCallback(object data, EventCallback callback)
{
try
{
callback (data as IEvent);
}
catch(InvalidCastException)
{
object tgt = callback.Target;
string methodName = (callback as Delegate).Method.Name;
string message = "An EventCallback is attempting an illegal cast. One possible reason is not typing the payload to IEvent in your callback. Another is illegal casting of the data.\nTarget class: " + tgt + " method: " + methodName;
throw new EventDispatcherException (message, EventDispatcherExceptionType.TARGET_INVOCATION);
}
}
public void AddListener(object evt, EventCallback callback)
{
IBinding binding = GetBinding (evt);
if (binding == null)
{
Bind (evt).To (callback);
}
else
{
binding.To (callback);
}
}
public void AddListener(object evt, EmptyCallback callback)
{
IBinding binding = GetBinding (evt);
if (binding == null)
{
Bind (evt).To (callback);
}
else
{
binding.To (callback);
}
}
public void RemoveListener(object evt, EventCallback callback)
{
IBinding binding = GetBinding (evt);
RemoveValue (binding, callback);
}
public void RemoveListener(object evt, EmptyCallback callback)
{
IBinding binding = GetBinding (evt);
RemoveValue (binding, callback);
}
public bool HasListener(object evt, EventCallback callback)
{
IEventBinding binding = GetBinding (evt) as IEventBinding;
if (binding == null)
{
return false;
}
return binding.TypeForCallback (callback) != EventCallbackType.NOT_FOUND;
}
public bool HasListener(object evt, EmptyCallback callback)
{
IEventBinding binding = GetBinding (evt) as IEventBinding;
if (binding == null)
{
return false;
}
return binding.TypeForCallback (callback) != EventCallbackType.NOT_FOUND;
}
public void UpdateListener(bool toAdd, object evt, EventCallback callback)
{
if (toAdd)
{
AddListener (evt, callback);
}
else
{
RemoveListener (evt, callback);
}
}
public void UpdateListener(bool toAdd, object evt, EmptyCallback callback)
{
if (toAdd)
{
AddListener (evt, callback);
}
else
{
RemoveListener (evt, callback);
}
}
public void AddTriggerable(ITriggerable target)
{
if (triggerClients == null)
{
triggerClients = new HashSet<ITriggerable>();
}
triggerClients.Add(target);
}
public void RemoveTriggerable(ITriggerable target)
{
if (triggerClients.Contains(target))
{
if (triggerClientRemovals == null)
{
triggerClientRemovals = new HashSet<ITriggerable>();
}
triggerClientRemovals.Add (target);
if (!isTriggeringClients)
{
flushRemovals();
}
}
}
public int Triggerables
{
get
{
if (triggerClients == null)
return 0;
return triggerClients.Count;
}
}
protected void flushRemovals()
{
if (triggerClientRemovals == null)
{
return;
}
foreach(ITriggerable target in triggerClientRemovals)
{
if (triggerClients.Contains(target))
{
triggerClients.Remove(target);
}
}
triggerClientRemovals = null;
}
public bool Trigger<T>(object data)
{
return Trigger (typeof(T), data);
}
public bool Trigger(object key, object data)
{
bool allow = ((data is IEvent && System.Object.ReferenceEquals((data as IEvent).target, this) == false) ||
(key is IEvent && System.Object.ReferenceEquals((data as IEvent).target, this) == false));
if (allow)
Dispatch(key, data);
return true;
}
protected void internalReleaseEvent(IEvent evt)
{
if (evt is IPoolable)
{
(evt as IPoolable).Release ();
}
}
public void ReleaseEvent(IEvent evt)
{
if ((evt as IPoolable).retain == false)
{
cleanEvent (evt);
eventPool.ReturnInstance (evt);
}
}
protected void cleanEvent(IEvent evt)
{
evt.target = null;
evt.data = null;
evt.type = null;
}
}
class EventInstanceProvider : IInstanceProvider
{
public T GetInstance<T>()
{
object instance = new TmEvent ();
T retv = (T) instance;
return retv;
}
public object GetInstance(Type key)
{
return new TmEvent ();
}
}
}
| |
using System;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Orleans;
using Orleans.AzureUtils;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Tester;
using TestExtensions;
using Xunit;
using Xunit.Abstractions;
namespace UnitTests.StorageTests
{
internal static class SiloInstanceTableTestConstants
{
internal static readonly TimeSpan Timeout = TimeSpan.FromMinutes(1);
internal static readonly bool DeleteEntriesAfterTest = true; // false; // Set to false for Debug mode
internal static readonly string INSTANCE_STATUS_CREATED = SiloStatus.Created.ToString(); //"Created";
internal static readonly string INSTANCE_STATUS_ACTIVE = SiloStatus.Active.ToString(); //"Active";
internal static readonly string INSTANCE_STATUS_DEAD = SiloStatus.Dead.ToString(); //"Dead";
}
/// <summary>
/// Tests for operation of Orleans SiloInstanceManager using AzureStore - Requires access to external Azure storage
/// </summary>
public class SiloInstanceTableManagerTests : IClassFixture<SiloInstanceTableManagerTests.Fixture>, IDisposable
{
public class Fixture
{
public Fixture()
{
LogManager.Initialize(new NodeConfiguration());
TestUtils.CheckForAzureStorage();
}
}
private string deploymentId;
private int generation;
private SiloAddress siloAddress;
private SiloInstanceTableEntry myEntry;
private OrleansSiloInstanceManager manager;
private readonly Logger logger;
private readonly ITestOutputHelper output;
public SiloInstanceTableManagerTests(ITestOutputHelper output)
{
this.output = output;
logger = LogManager.GetLogger("SiloInstanceTableManagerTests", LoggerType.Application);
deploymentId = "test-" + Guid.NewGuid();
generation = SiloAddress.AllocateNewGeneration();
siloAddress = SiloAddress.NewLocalAddress(generation);
logger.Info("DeploymentId={0} Generation={1}", deploymentId, generation);
logger.Info("Initializing SiloInstanceManager");
manager = OrleansSiloInstanceManager.GetManager(deploymentId, TestDefaultConfiguration.DataConnectionString)
.WaitForResultWithThrow(SiloInstanceTableTestConstants.Timeout);
}
// Use TestCleanup to run code after each test has run
public void Dispose()
{
if(manager != null && SiloInstanceTableTestConstants.DeleteEntriesAfterTest)
{
TimeSpan timeout = SiloInstanceTableTestConstants.Timeout;
logger.Info("TestCleanup Timeout={0}", timeout);
manager.DeleteTableEntries(deploymentId).WaitWithThrow(timeout);
logger.Info("TestCleanup - Finished");
manager = null;
}
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public void SiloInstanceTable_Op_RegisterSiloInstance()
{
RegisterSiloInstance();
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public void SiloInstanceTable_Op_ActivateSiloInstance()
{
RegisterSiloInstance();
manager.ActivateSiloInstance(myEntry);
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public void SiloInstanceTable_Op_UnregisterSiloInstance()
{
RegisterSiloInstance();
manager.UnregisterSiloInstance(myEntry);
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public async Task SiloInstanceTable_Op_CreateSiloEntryConditionally()
{
bool didInsert = await manager.TryCreateTableVersionEntryAsync()
.WithTimeout(AzureTableDefaultPolicies.TableOperationTimeout);
Assert.True(didInsert, "Did insert");
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public async Task SiloInstanceTable_Register_CheckData()
{
const string testName = "SiloInstanceTable_Register_CheckData";
logger.Info("Start {0}", testName);
RegisterSiloInstance();
var data = await FindSiloEntry(siloAddress);
SiloInstanceTableEntry siloEntry = data.Item1;
string eTag = data.Item2;
Assert.NotNull(eTag); // ETag should not be null
Assert.NotNull(siloEntry); // SiloInstanceTableEntry should not be null
Assert.Equal(SiloInstanceTableTestConstants.INSTANCE_STATUS_CREATED, siloEntry.Status);
CheckSiloInstanceTableEntry(myEntry, siloEntry);
logger.Info("End {0}", testName);
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public async Task SiloInstanceTable_Activate_CheckData()
{
RegisterSiloInstance();
manager.ActivateSiloInstance(myEntry);
var data = await FindSiloEntry(siloAddress);
Assert.NotNull(data); // Data returned should not be null
SiloInstanceTableEntry siloEntry = data.Item1;
string eTag = data.Item2;
Assert.NotNull(eTag); // ETag should not be null
Assert.NotNull(siloEntry); // SiloInstanceTableEntry should not be null
Assert.Equal(SiloInstanceTableTestConstants.INSTANCE_STATUS_ACTIVE, siloEntry.Status);
CheckSiloInstanceTableEntry(myEntry, siloEntry);
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public async Task SiloInstanceTable_Unregister_CheckData()
{
RegisterSiloInstance();
manager.UnregisterSiloInstance(myEntry);
var data = await FindSiloEntry(siloAddress);
SiloInstanceTableEntry siloEntry = data.Item1;
string eTag = data.Item2;
Assert.NotNull(eTag); // ETag should not be null
Assert.NotNull(siloEntry); // SiloInstanceTableEntry should not be null
Assert.Equal(SiloInstanceTableTestConstants.INSTANCE_STATUS_DEAD, siloEntry.Status);
CheckSiloInstanceTableEntry(myEntry, siloEntry);
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public void SiloInstanceTable_FindAllGatewayProxyEndpoints()
{
RegisterSiloInstance();
var gateways = manager.FindAllGatewayProxyEndpoints().GetResult();
Assert.Equal(0, gateways.Count); // "Number of gateways before Silo.Activate"
manager.ActivateSiloInstance(myEntry);
gateways = manager.FindAllGatewayProxyEndpoints().GetResult();
Assert.Equal(1, gateways.Count); // "Number of gateways after Silo.Activate"
Uri myGateway = gateways.First();
Assert.Equal(myEntry.Address, myGateway.Host.ToString()); // "Gateway address"
Assert.Equal(myEntry.ProxyPort, myGateway.Port.ToString(CultureInfo.InvariantCulture)); // "Gateway port"
}
[Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")]
public void SiloAddress_ToFrom_RowKey()
{
string ipAddress = "1.2.3.4";
int port = 5555;
int generation = 6666;
IPAddress address = IPAddress.Parse(ipAddress);
IPEndPoint endpoint = new IPEndPoint(address, port);
SiloAddress siloAddress = SiloAddress.New(endpoint, generation);
string MembershipRowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddress);
output.WriteLine("SiloAddress = {0} Row Key string = {1}", siloAddress, MembershipRowKey);
SiloAddress fromRowKey = SiloInstanceTableEntry.UnpackRowKey(MembershipRowKey);
output.WriteLine("SiloAddress result = {0} From Row Key string = {1}", fromRowKey, MembershipRowKey);
Assert.Equal(siloAddress, fromRowKey);
Assert.Equal(SiloInstanceTableEntry.ConstructRowKey(siloAddress), SiloInstanceTableEntry.ConstructRowKey(fromRowKey));
}
private void RegisterSiloInstance()
{
string partitionKey = deploymentId;
string rowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddress);
IPEndPoint myEndpoint = siloAddress.Endpoint;
myEntry = new SiloInstanceTableEntry
{
PartitionKey = partitionKey,
RowKey = rowKey,
DeploymentId = deploymentId,
Address = myEndpoint.Address.ToString(),
Port = myEndpoint.Port.ToString(CultureInfo.InvariantCulture),
Generation = generation.ToString(CultureInfo.InvariantCulture),
HostName = myEndpoint.Address.ToString(),
ProxyPort = "30000",
RoleName = "MyRole",
SiloName = "MyInstance",
UpdateZone = "0",
FaultZone = "0",
StartTime = LogFormatter.PrintDate(DateTime.UtcNow),
};
logger.Info("MyEntry={0}", myEntry);
manager.RegisterSiloInstance(myEntry);
}
private async Task<Tuple<SiloInstanceTableEntry, string>> FindSiloEntry(SiloAddress siloAddr)
{
string partitionKey = deploymentId;
string rowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddr);
logger.Info("FindSiloEntry for SiloAddress={0} PartitionKey={1} RowKey={2}", siloAddr, partitionKey, rowKey);
Tuple<SiloInstanceTableEntry, string> data = await manager.ReadSingleTableEntryAsync(partitionKey, rowKey);
logger.Info("FindSiloEntry returning Data={0}", data);
return data;
}
private void CheckSiloInstanceTableEntry(SiloInstanceTableEntry referenceEntry, SiloInstanceTableEntry entry)
{
Assert.Equal(referenceEntry.DeploymentId, entry.DeploymentId);
Assert.Equal(referenceEntry.Address, entry.Address);
Assert.Equal(referenceEntry.Port, entry.Port);
Assert.Equal(referenceEntry.Generation, entry.Generation);
Assert.Equal(referenceEntry.HostName, entry.HostName);
//Assert.Equal(referenceEntry.Status, entry.Status);
Assert.Equal(referenceEntry.ProxyPort, entry.ProxyPort);
Assert.Equal(referenceEntry.RoleName, entry.RoleName);
Assert.Equal(referenceEntry.SiloName, entry.SiloName);
Assert.Equal(referenceEntry.UpdateZone, entry.UpdateZone);
Assert.Equal(referenceEntry.FaultZone, entry.FaultZone);
Assert.Equal(referenceEntry.StartTime, entry.StartTime);
Assert.Equal(referenceEntry.IAmAliveTime, entry.IAmAliveTime);
Assert.Equal(referenceEntry.MembershipVersion, entry.MembershipVersion);
Assert.Equal(referenceEntry.SuspectingTimes, entry.SuspectingTimes);
Assert.Equal(referenceEntry.SuspectingSilos, entry.SuspectingSilos);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Purpose: Resource annotation rules.
**
===========================================================*/
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.Win32;
using System.Diagnostics.Contracts;
namespace System.Runtime.Versioning
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
[Conditional("RESOURCE_ANNOTATION_WORK")]
public sealed class ResourceConsumptionAttribute : Attribute
{
private ResourceScope _consumptionScope;
private ResourceScope _resourceScope;
public ResourceConsumptionAttribute(ResourceScope resourceScope)
{
_resourceScope = resourceScope;
_consumptionScope = _resourceScope;
}
public ResourceConsumptionAttribute(ResourceScope resourceScope, ResourceScope consumptionScope)
{
_resourceScope = resourceScope;
_consumptionScope = consumptionScope;
}
public ResourceScope ResourceScope {
get { return _resourceScope; }
}
public ResourceScope ConsumptionScope {
get { return _consumptionScope; }
}
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
[Conditional("RESOURCE_ANNOTATION_WORK")]
public sealed class ResourceExposureAttribute : Attribute
{
private ResourceScope _resourceExposureLevel;
public ResourceExposureAttribute(ResourceScope exposureLevel)
{
_resourceExposureLevel = exposureLevel;
}
public ResourceScope ResourceExposureLevel {
get { return _resourceExposureLevel; }
}
}
// Default visibility is Public, which isn't specified in this enum.
// Public == the lack of Private or Assembly
// Does this actually work? Need to investigate that.
[Flags]
public enum ResourceScope
{
None = 0,
// Resource type
Machine = 0x1,
Process = 0x2,
AppDomain = 0x4,
Library = 0x8,
// Visibility
Private = 0x10, // Private to this one class.
Assembly = 0x20, // Assembly-level, like C#'s "internal"
}
[Flags]
internal enum SxSRequirements
{
None = 0,
AppDomainID = 0x1,
ProcessID = 0x2,
CLRInstanceID = 0x4, // for multiple CLR's within the process
AssemblyName = 0x8,
TypeName = 0x10
}
public static class VersioningHelper
{
// These depend on the exact values given to members of the ResourceScope enum.
private const ResourceScope ResTypeMask = ResourceScope.Machine | ResourceScope.Process | ResourceScope.AppDomain | ResourceScope.Library;
private const ResourceScope VisibilityMask = ResourceScope.Private | ResourceScope.Assembly;
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Process)]
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern int GetRuntimeId();
public static String MakeVersionSafeName(String name, ResourceScope from, ResourceScope to)
{
return MakeVersionSafeName(name, from, to, null);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
public static String MakeVersionSafeName(String name, ResourceScope from, ResourceScope to, Type type)
{
ResourceScope fromResType = from & ResTypeMask;
ResourceScope toResType = to & ResTypeMask;
if (fromResType > toResType)
throw new ArgumentException(Environment.GetResourceString("Argument_ResourceScopeWrongDirection", fromResType, toResType), "from");
SxSRequirements requires = GetRequirements(to, from);
if ((requires & (SxSRequirements.AssemblyName | SxSRequirements.TypeName)) != 0 && type == null)
throw new ArgumentNullException("type", Environment.GetResourceString("ArgumentNull_TypeRequiredByResourceScope"));
// Add in process ID, CLR base address, and appdomain ID's. Also, use a character identifier
// to ensure that these can never accidentally overlap (ie, you create enough appdomains and your
// appdomain ID might equal your process ID).
StringBuilder safeName = new StringBuilder(name);
char separator = '_';
if ((requires & SxSRequirements.ProcessID) != 0) {
safeName.Append(separator);
safeName.Append('p');
#if MONO
safeName.Append (NativeMethods.GetCurrentProcessId ());
#else
safeName.Append(Win32Native.GetCurrentProcessId());
#endif
}
if ((requires & SxSRequirements.CLRInstanceID) != 0) {
String clrID = GetCLRInstanceString();
safeName.Append(separator);
safeName.Append('r');
safeName.Append(clrID);
}
if ((requires & SxSRequirements.AppDomainID) != 0) {
safeName.Append(separator);
safeName.Append("ad");
safeName.Append(AppDomain.CurrentDomain.Id);
}
if ((requires & SxSRequirements.TypeName) != 0) {
safeName.Append(separator);
safeName.Append(type.Name);
}
if ((requires & SxSRequirements.AssemblyName) != 0) {
safeName.Append(separator);
safeName.Append(type.Assembly.FullName);
}
return safeName.ToString();
}
private static String GetCLRInstanceString()
{
int id = GetRuntimeId();
return id.ToString(CultureInfo.InvariantCulture);
}
private static SxSRequirements GetRequirements(ResourceScope consumeAsScope, ResourceScope calleeScope)
{
SxSRequirements requires = SxSRequirements.None;
switch(calleeScope & ResTypeMask) {
case ResourceScope.Machine:
switch(consumeAsScope & ResTypeMask) {
case ResourceScope.Machine:
// No work
break;
case ResourceScope.Process:
requires |= SxSRequirements.ProcessID;
break;
case ResourceScope.AppDomain:
requires |= SxSRequirements.AppDomainID | SxSRequirements.CLRInstanceID | SxSRequirements.ProcessID;
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeTypeBits", consumeAsScope), "consumeAsScope");
}
break;
case ResourceScope.Process:
if ((consumeAsScope & ResourceScope.AppDomain) != 0)
requires |= SxSRequirements.AppDomainID | SxSRequirements.CLRInstanceID;
break;
case ResourceScope.AppDomain:
// No work
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeTypeBits", calleeScope), "calleeScope");
}
switch(calleeScope & VisibilityMask) {
case ResourceScope.None: // Public - implied
switch(consumeAsScope & VisibilityMask) {
case ResourceScope.None: // Public - implied
// No work
break;
case ResourceScope.Assembly:
requires |= SxSRequirements.AssemblyName;
break;
case ResourceScope.Private:
requires |= SxSRequirements.TypeName | SxSRequirements.AssemblyName;
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeVisibilityBits", consumeAsScope), "consumeAsScope");
}
break;
case ResourceScope.Assembly:
if ((consumeAsScope & ResourceScope.Private) != 0)
requires |= SxSRequirements.TypeName;
break;
case ResourceScope.Private:
// No work
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeVisibilityBits", calleeScope), "calleeScope");
}
if (consumeAsScope == calleeScope) {
Contract.Assert(requires == SxSRequirements.None, "Computed a strange set of required resource scoping. It's probably wrong.");
}
return requires;
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: BreakRecordTable manages cached informaion bout pages and
// break records of FlowDocument contnet.
//
// History:
// 01/24/2004 : [....] - Created
//
//---------------------------------------------------------------------------
using System; // WeakReference, ...
using System.Collections.Generic; // List<T>
using System.Collections.ObjectModel; // ReadOnlyCollection<T>
using System.Windows.Documents; // FlowDocument, TextPointer
using MS.Internal.Documents; // TextDocumentView
namespace MS.Internal.PtsHost
{
/// <summary>
/// BreakRecordTable manages cached informaion bout pages and break
/// records of FlowDocument contnet.
/// </summary>
internal sealed class BreakRecordTable
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
/// <param name="owner">Ownder of the BreakRecordTable.</param>
internal BreakRecordTable(FlowDocumentPaginator owner)
{
_owner = owner;
_breakRecords = new List<BreakRecordTableEntry>();
}
#endregion Constructors
//-------------------------------------------------------------------
//
// Internal Methods
//
//-------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// Retrieves input BreakRecord for given PageNumber.
/// </summary>
/// <param name="pageNumber">
/// Page index indicating which input BreakRecord should be retrieved.</param>
/// <returns>Input BreakRecord for given PageNumber.</returns>
internal PageBreakRecord GetPageBreakRecord(int pageNumber)
{
PageBreakRecord breakRecord = null;
Invariant.Assert(pageNumber >= 0 && pageNumber <= _breakRecords.Count, "Invalid PageNumber.");
// Input BreakRecord for the first page is always NULL.
// For the rest of pages, go to the entry preceding requested index and
// return the output BreakRecord.
if (pageNumber > 0)
{
Invariant.Assert(_breakRecords[pageNumber - 1] != null, "Invalid BreakRecordTable entry.");
breakRecord = _breakRecords[pageNumber - 1].BreakRecord;
Invariant.Assert(breakRecord != null, "BreakRecord can be null only for the first page.");
}
return breakRecord;
}
/// <summary>
/// Retrieves cached DocumentPage for given PageNumber.
/// </summary>
/// <param name="pageNumber">
/// Page index indicating which cached DocumentPage should be retrieved.
/// </param>
/// <returns>Cached DocumentPage for given PageNumber.</returns>
internal FlowDocumentPage GetCachedDocumentPage(int pageNumber)
{
WeakReference pageRef;
FlowDocumentPage documentPage = null;
if (pageNumber < _breakRecords.Count)
{
Invariant.Assert(_breakRecords[pageNumber] != null, "Invalid BreakRecordTable entry.");
pageRef = _breakRecords[pageNumber].DocumentPage;
if (pageRef != null)
{
documentPage = pageRef.Target as FlowDocumentPage;
if (documentPage != null && documentPage.IsDisposed)
{
documentPage = null;
}
}
}
return documentPage;
}
/// <summary>
/// Retrieves PageNumber for specified ContentPosition.
/// </summary>
/// <param name="contentPosition">
/// Represents content position for which PageNumber is requested.</param>
/// <param name="pageNumber">Starting index for search process.</param>
/// <returns>
/// Returns true, if successfull. 'pageNumber' is updated with actual
/// page number that contains specified ContentPosition.
/// Returns false, if BreakRecordTable is missing information about
/// page that contains specified ContentPosition. 'pageNumber'
/// is updated with the last investigated page number.
/// </returns>
internal bool GetPageNumberForContentPosition(TextPointer contentPosition, ref int pageNumber)
{
bool foundPageNumber = false;
ReadOnlyCollection<TextSegment> textSegments;
Invariant.Assert(pageNumber >= 0 && pageNumber <= _breakRecords.Count, "Invalid PageNumber.");
// Iterate through entries in the BreakRecordTable (starting from specified index)
// and look for page that contains specified ContentPosition.
// NOTE: For each cached page collection of TextSegments is stored to
// optimize this search.
while (pageNumber < _breakRecords.Count)
{
Invariant.Assert(_breakRecords[pageNumber] != null, "Invalid BreakRecordTable entry.");
textSegments = _breakRecords[pageNumber].TextSegments;
if (textSegments != null)
{
if (TextDocumentView.Contains(contentPosition, textSegments))
{
foundPageNumber = true;
break;
}
}
else
{
// There is no information about this page.
break;
}
++pageNumber;
}
return foundPageNumber;
}
/// <summary>
/// Layout of entire content has been affected.
/// </summary>
internal void OnInvalidateLayout()
{
if (_breakRecords.Count > 0)
{
// Destroy all affected BreakRecords.
InvalidateBreakRecords(0, _breakRecords.Count);
// Initiate the next async operation.
_owner.InitiateNextAsyncOperation();
// Raise PagesChanged event. Start with the first page and set
// count to Int.Max/2, because somebody might want to display a page
// that wasn't available before, but will be right now.
_owner.OnPagesChanged(0, int.MaxValue/2);
}
}
/// <summary>
/// Layout for specified range has been affected.
/// </summary>
/// <param name="start">Start of the affected content range.</param>
/// <param name="end">End of the affected content range.</param>
internal void OnInvalidateLayout(ITextPointer start, ITextPointer end)
{
int pageStart, pageCount;
if (_breakRecords.Count > 0)
{
// Get range of affected pages and dispose them
GetAffectedPages(start, end, out pageStart, out pageCount);
// Currently there is no possibility to do partial invalidation
// of BreakRecordTable, so always extend pageCount to the end
// of BreakRecordTable.
pageCount = _breakRecords.Count - pageStart;
if (pageCount > 0)
{
// Destroy all affected BreakRecords.
InvalidateBreakRecords(pageStart, pageCount);
// Initiate the next async operation.
_owner.InitiateNextAsyncOperation();
// Raise PagesChanged event. Start with the first affected page and set
// count to Int.Max/2, because somebody might want to display a page
// that wasn't available before, but will be right now.
_owner.OnPagesChanged(pageStart, int.MaxValue/2);
}
}
}
/// <summary>
/// Rendering of entire content has been affected.
/// </summary>
internal void OnInvalidateRender()
{
if (_breakRecords.Count > 0)
{
// Dispose all existing pages.
DisposePages(0, _breakRecords.Count);
// Raise PagesChanged event. Start with the first page and set
// count to this.Count (number of pages have not been changed).
_owner.OnPagesChanged(0, _breakRecords.Count);
}
}
/// <summary>
/// Rendering for specified range has been affected.
/// </summary>
/// <param name="start">Start of the affected content range.</param>
/// <param name="end">End of the affected content range.</param>
internal void OnInvalidateRender(ITextPointer start, ITextPointer end)
{
int pageStart, pageCount;
if (_breakRecords.Count > 0)
{
// Get range of affected pages and dispose them.
GetAffectedPages(start, end, out pageStart, out pageCount);
if (pageCount > 0)
{
// Dispose all affected pages.
DisposePages(pageStart, pageCount);
// Raise PagesChanged event.
_owner.OnPagesChanged(pageStart, pageCount);
}
}
}
/// <summary>
/// Updates entry of BreakRecordTable with new data.
/// </summary>
/// <param name="pageNumber">Index of the entry to update.</param>
/// <param name="page">DocumentPage object that has been just created.</param>
/// <param name="brOut">Output BreakRecord for created page.</param>
/// <param name="dependentMax">Last content position that can affect the output break record.</param>
internal void UpdateEntry(int pageNumber, FlowDocumentPage page, PageBreakRecord brOut, TextPointer dependentMax)
{
ITextView textView;
BreakRecordTableEntry entry;
bool isClean;
Invariant.Assert(pageNumber >= 0 && pageNumber <= _breakRecords.Count, "The previous BreakRecord does not exist.");
Invariant.Assert(page != null && page != DocumentPage.Missing, "Cannot update BRT with an invalid document page.");
// Get TextView for DocumentPage. This TextView is used to access list of
// content ranges. Those serve as optimalization in finding affeceted pages.
textView = (ITextView)((IServiceProvider)page).GetService(typeof(ITextView));
Invariant.Assert(textView != null, "Cannot access ITextView for FlowDocumentPage.");
// Get current state of BreakRecordTable
isClean = this.IsClean;
// Add new entry into BreakRecordTable
entry = new BreakRecordTableEntry();
entry.BreakRecord = brOut;
entry.DocumentPage = new WeakReference(page);
entry.TextSegments = textView.TextSegments;
entry.DependentMax = dependentMax;
if (pageNumber == _breakRecords.Count)
{
_breakRecords.Add(entry);
// Raise PaginationProgress event only if we did not have valid
// entry for specified page number.
_owner.OnPaginationProgress(pageNumber, 1);
}
else
{
// If old Page and/or BreakRecord are not changing, do not dispose them.
if (_breakRecords[pageNumber].BreakRecord != null &&
_breakRecords[pageNumber].BreakRecord != entry.BreakRecord)
{
_breakRecords[pageNumber].BreakRecord.Dispose();
}
if (_breakRecords[pageNumber].DocumentPage != null &&
_breakRecords[pageNumber].DocumentPage.Target != null &&
_breakRecords[pageNumber].DocumentPage.Target != entry.DocumentPage.Target)
{
((FlowDocumentPage)_breakRecords[pageNumber].DocumentPage.Target).Dispose();
}
_breakRecords[pageNumber] = entry;
}
// Raise PaginationCompleted event only if the BreakRecordTable just
// become clean.
if (!isClean && this.IsClean)
{
_owner.OnPaginationCompleted();
}
}
/// <summary>
/// Determines whenever input BreakRecord for given page number exists.
/// </summary>
/// <param name="pageNumber">Page index.</param>
/// <returns>true, if BreakRecord for given page number exists.</returns>
internal bool HasPageBreakRecord(int pageNumber)
{
Invariant.Assert(pageNumber >= 0, "Page number cannot be negative.");
// For the first page, the input break record is always NULL.
// For the rest of pages, it exists if the preceding entry has
// non-NULL output BreakRecord.
if (pageNumber == 0)
return true;
if (pageNumber > _breakRecords.Count)
return false;
Invariant.Assert(_breakRecords[pageNumber - 1] != null, "Invalid BreakRecordTable entry.");
return (_breakRecords[pageNumber - 1].BreakRecord != null);
}
#endregion Internal Methods
//-------------------------------------------------------------------
//
// Internal Properties
//
//-------------------------------------------------------------------
#region Internal Properties
/// <summary>
/// Current count reflecting number of known pages.
/// </summary>
internal int Count
{
get { return _breakRecords.Count; }
}
/// <summary>
/// Whether BreakRecordTable is clean.
/// </summary>
internal bool IsClean
{
get
{
if (_breakRecords.Count == 0)
return false;
Invariant.Assert(_breakRecords[_breakRecords.Count - 1] != null, "Invalid BreakRecordTable entry.");
return (_breakRecords[_breakRecords.Count - 1].BreakRecord == null);
}
}
#endregion Internal Properties
//-------------------------------------------------------------------
//
// Private Methods
//
//-------------------------------------------------------------------
#region Private Methods
/// <summary>
/// Dispose all alive pages for specified range.
/// </summary>
/// <param name="start">Index of the first page to dispose.</param>
/// <param name="count">Number of pages to dispose.</param>
private void DisposePages(int start, int count)
{
WeakReference pageRef;
int index = start + count - 1; // Start from the end of BreakRecordTable
Invariant.Assert(start >= 0 && start < _breakRecords.Count, "Invalid starting index for BreakRecordTable invalidation.");
Invariant.Assert(start + count <= _breakRecords.Count, "Partial invalidation of BreakRecordTable is not allowed.");
while (index >= start)
{
Invariant.Assert(_breakRecords[index] != null, "Invalid BreakRecordTable entry.");
pageRef = _breakRecords[index].DocumentPage;
if (pageRef != null && pageRef.Target != null)
{
((FlowDocumentPage)pageRef.Target).Dispose();
}
_breakRecords[index].DocumentPage = null;
index--;
}
}
/// <summary>
/// Destroy BreakRecordsTable entries for specified range.
/// </summary>
/// <param name="start">Index of the first entry to destroy.</param>
/// <param name="count">Nmber of entries to destroy.</param>
private void InvalidateBreakRecords(int start, int count)
{
WeakReference pageRef;
int index = start + count - 1; // Start from the end of BreakRecordTable
Invariant.Assert(start >= 0 && start < _breakRecords.Count, "Invalid starting index for BreakRecordTable invalidation.");
Invariant.Assert(start + count == _breakRecords.Count, "Partial invalidation of BreakRecordTable is not allowed.");
while (index >= start)
{
Invariant.Assert(_breakRecords[index] != null, "Invalid BreakRecordTable entry.");
// Dispose Page and BreakRecord before removing the entry.
pageRef = _breakRecords[index].DocumentPage;
if (pageRef != null && pageRef.Target != null)
{
((FlowDocumentPage)pageRef.Target).Dispose();
}
if (_breakRecords[index].BreakRecord != null)
{
_breakRecords[index].BreakRecord.Dispose();
}
// Remov the entry.
_breakRecords.RemoveAt(index);
index--;
}
}
/// <summary>
/// Retrieves indices of affected pages by specified content range.
/// </summary>
/// <param name="start">Content change start position.</param>
/// <param name="end">Content change end position.</param>
/// <param name="pageStart">The first affected page.</param>
/// <param name="pageCount">Number of affected pages.</param>
private void GetAffectedPages(ITextPointer start, ITextPointer end, out int pageStart, out int pageCount)
{
bool affects;
ReadOnlyCollection<TextSegment> textSegments;
TextPointer dependentMax;
// Find the first affected page.
pageStart = 0;
while (pageStart < _breakRecords.Count)
{
Invariant.Assert(_breakRecords[pageStart] != null, "Invalid BreakRecordTable entry.");
// If the start position is before last position affecting the output break record,
// this page is affected.
dependentMax = _breakRecords[pageStart].DependentMax;
if (dependentMax != null)
{
if (start.CompareTo(dependentMax) <= 0)
break;
}
textSegments = _breakRecords[pageStart].TextSegments;
if (textSegments != null)
{
affects = false;
foreach (TextSegment textSegment in textSegments)
{
if (start.CompareTo(textSegment.End) <= 0)
{
affects = true;
break;
}
}
if (affects)
break;
}
else
{
// There is no information about this page, so assume that it is
// affected.
break;
}
++pageStart;
}
// Find the last affected page
// For now assume that all following pages are affected.
pageCount = _breakRecords.Count - pageStart;
}
#endregion Private Methods
//-------------------------------------------------------------------
//
// Private Fields
//
//-------------------------------------------------------------------
#region Private Fields
/// <summary>
/// Owner of the BreakRecordTable.
/// </summary>
private FlowDocumentPaginator _owner;
/// <summary>
/// Array of entries in the BreakRecordTable.
/// </summary>
private List<BreakRecordTableEntry> _breakRecords;
/// <summary>
/// BreakRecordTableEntry
/// </summary>
private class BreakRecordTableEntry
{
public PageBreakRecord BreakRecord;
public ReadOnlyCollection<TextSegment> TextSegments;
public WeakReference DocumentPage;
public TextPointer DependentMax;
}
#endregion Private Fields
}
}
| |
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 PnEvaluadore class.
/// </summary>
[Serializable]
public partial class PnEvaluadoreCollection : ActiveList<PnEvaluadore, PnEvaluadoreCollection>
{
public PnEvaluadoreCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnEvaluadoreCollection</returns>
public PnEvaluadoreCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnEvaluadore 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_evaluadores table.
/// </summary>
[Serializable]
public partial class PnEvaluadore : ActiveRecord<PnEvaluadore>, IActiveRecord
{
#region .ctors and Default Settings
public PnEvaluadore()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnEvaluadore(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnEvaluadore(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnEvaluadore(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_evaluadores", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdEvaluador = new TableSchema.TableColumn(schema);
colvarIdEvaluador.ColumnName = "id_evaluador";
colvarIdEvaluador.DataType = DbType.Int32;
colvarIdEvaluador.MaxLength = 0;
colvarIdEvaluador.AutoIncrement = true;
colvarIdEvaluador.IsNullable = false;
colvarIdEvaluador.IsPrimaryKey = true;
colvarIdEvaluador.IsForeignKey = false;
colvarIdEvaluador.IsReadOnly = false;
colvarIdEvaluador.DefaultSetting = @"";
colvarIdEvaluador.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdEvaluador);
TableSchema.TableColumn colvarIdUsuario = new TableSchema.TableColumn(schema);
colvarIdUsuario.ColumnName = "id_usuario";
colvarIdUsuario.DataType = DbType.Int32;
colvarIdUsuario.MaxLength = 0;
colvarIdUsuario.AutoIncrement = false;
colvarIdUsuario.IsNullable = true;
colvarIdUsuario.IsPrimaryKey = false;
colvarIdUsuario.IsForeignKey = false;
colvarIdUsuario.IsReadOnly = false;
colvarIdUsuario.DefaultSetting = @"";
colvarIdUsuario.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdUsuario);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_evaluadores",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdEvaluador")]
[Bindable(true)]
public int IdEvaluador
{
get { return GetColumnValue<int>(Columns.IdEvaluador); }
set { SetColumnValue(Columns.IdEvaluador, value); }
}
[XmlAttribute("IdUsuario")]
[Bindable(true)]
public int? IdUsuario
{
get { return GetColumnValue<int?>(Columns.IdUsuario); }
set { SetColumnValue(Columns.IdUsuario, value); }
}
#endregion
//no foreign key tables defined (0)
//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? varIdUsuario)
{
PnEvaluadore item = new PnEvaluadore();
item.IdUsuario = varIdUsuario;
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 varIdEvaluador,int? varIdUsuario)
{
PnEvaluadore item = new PnEvaluadore();
item.IdEvaluador = varIdEvaluador;
item.IdUsuario = varIdUsuario;
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 IdEvaluadorColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdUsuarioColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdEvaluador = @"id_evaluador";
public static string IdUsuario = @"id_usuario";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using DotSpatial.NTSExtension;
using GeoAPI.Geometries;
namespace DotSpatial.Data
{
/// <summary>
/// Represents segment between 2 vertices.
/// </summary>
public class Segment
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Segment"/> class.
/// </summary>
/// <param name="x1">The x value of the start point.</param>
/// <param name="y1">The y value of the start point.</param>
/// <param name="x2">The x value of the end point.</param>
/// <param name="y2">The y value of the end point.</param>
public Segment(double x1, double y1, double x2, double y2)
{
P1 = new Vertex(x1, y1);
P2 = new Vertex(x2, y2);
}
/// <summary>
/// Initializes a new instance of the <see cref="Segment"/> class.
/// </summary>
/// <param name="p1">The start point.</param>
/// <param name="p2">The end point.</param>
public Segment(Vertex p1, Vertex p2)
{
P1 = p1;
P2 = p2;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the precision for calculating equality, but this is just a re-direction to Vertex.Epsilon
/// </summary>
public static double Epsilon
{
get { return Vertex.Epsilon; }
set { Vertex.Epsilon = value; }
}
/// <summary>
/// Gets or sets the start point of the segment.
/// </summary>
public Vertex P1 { get; set; }
/// <summary>
/// Gets or sets the end point of the segment.
/// </summary>
public Vertex P2 { get; set; }
#endregion
#region Methods
/// <summary>
/// Uses the intersection count to detect if there is an intersection.
/// </summary>
/// <param name="other">Segment to check against.</param>
/// <returns>True if there was an intersection.</returns>
public bool Intersects(Segment other)
{
return IntersectionCount(other) > 0;
}
/// <summary>
/// Calculates the shortest distance to this line segment from the specified MapWinGIS.Point
/// </summary>
/// <param name="point">A MapWinGIS.Point specifing the location to find the distance to the line</param>
/// <returns>A double value that is the shortest distance from the given Point to this line segment</returns>
public double DistanceTo(Coordinate point)
{
Vertex p = new Vertex(point.X, point.Y);
Vertex pt = ClosestPointTo(p);
Vector dist = new Vector(new Coordinate(pt.X, pt.Y), point);
return dist.Length2D;
}
/// <summary>
/// Returns a vertex representing the closest point on this line segment from a given vertex
/// </summary>
/// <param name="point">The point we want to be close to</param>
/// <returns>The point on this segment that is closest to the given point</returns>
public Vertex ClosestPointTo(Vertex point)
{
EndPointInteraction endPointFlag;
return ClosestPointTo(point, false, out endPointFlag);
}
/// <summary>
/// Returns a vertex representing the closest point on this line segment from a given vertex
/// </summary>
/// <param name="point">The point we want to be close to</param>
/// <param name="isInfiniteLine">If true treat the line as infinitly long</param>
/// <param name="endPointFlag">Outputs 0 if the vertex is on the line segment, 1 if beyond P0, 2 if beyong P1 and -1 if P1=P2</param>
/// <returns>The point on this segment or infinite line that is closest to the given point</returns>
public Vertex ClosestPointTo(Vertex point, bool isInfiniteLine, out EndPointInteraction endPointFlag)
{
// If the points defining this segment are the same, we treat the segment as a point
// special handling to avoid 0 in denominator later
if (P2.X == P1.X && P2.Y == P1.Y)
{
endPointFlag = EndPointInteraction.P1EqualsP2;
return P1;
}
// http://softsurfer.com/Archive/algorithm_0102/algorithm_0102.htm
Vector v = ToVector(); // vector from p1 to p2 in the segment
v.Z = 0;
Vector w = new Vector(P1.ToCoordinate(), point.ToCoordinate()) // vector from p1 to Point
{
Z = 0
};
double c1 = w.Dot(v); // the dot product represents the projection onto the line
if (c1 < 0)
{
endPointFlag = EndPointInteraction.PastP1;
if (!isInfiniteLine) // The closest point on the segment to Point is p1
return P1;
}
double c2 = v.Dot(v);
if (c2 <= c1)
{
endPointFlag = EndPointInteraction.PastP2;
if (!isInfiniteLine) // The closest point on the segment to Point is p2
return P2;
}
// The closest point on the segment is perpendicular to the point,
// but somewhere on the segment between P1 and P2
endPointFlag = EndPointInteraction.OnLine;
double b = c1 / c2;
v = v.Multiply(b);
Vertex pb = new Vertex(P1.X + v.X, P1.Y + v.Y);
return pb;
}
/// <summary>
/// Casts this to a vector.
/// </summary>
/// <returns>This as vector.</returns>
public Vector ToVector()
{
double x = P2.X - P1.X;
double y = P2.Y - P1.Y;
return new Vector(x, y, 0);
}
/// <summary>
/// Determines the shortest distance between two segments
/// </summary>
/// <param name="lineSegment">Segment, The line segment to test against this segment</param>
/// <returns>Double, the shortest distance between two segments</returns>
public double DistanceTo(Segment lineSegment)
{
// http://www.geometryalgorithms.com/Archive/algorithm_0106/algorithm_0106.htm
const double SmallNum = 0.00000001;
Vector u = ToVector(); // Segment 1
Vector v = lineSegment.ToVector(); // Segment 2
Vector w = ToVector();
double a = u.Dot(u); // length of segment 1
double b = u.Dot(v); // length of segment 2 projected onto line 1
double c = v.Dot(v); // length of segment 2
double d = u.Dot(w);
double e = v.Dot(w);
double dist = (a * c) - (b * b);
double sc, sN, sD = dist;
double tc, tN, tD = dist;
// compute the line parameters of the two closest points
if (dist < SmallNum)
{
// the lines are almost parallel force using point P0 on segment 1
// to prevent possible division by 0 later
sN = 0.0;
sD = 1.0;
tN = e;
tD = c;
}
else
{
// get the closest points on the infinite lines
sN = (b * e) - (c * d);
tN = (a * e) - (b * d);
if (sN < 0.0)
{
// sc < 0 => the s=0 edge is visible
sN = 0.0;
tN = e;
tD = c;
}
else if (sN > sD)
{
// sc > 1 => the s=1 edge is visible
sN = sD;
tN = e + b;
tD = c;
}
}
if (tN < 0.0)
{
// tc < 0 => the t=0 edge is visible
tN = 0.0;
// recompute sc for this edge
if (-d < 0.0)
{
sN = 0.0;
}
else if (-d > a)
{
sN = sD;
}
else
{
sN = -d;
sD = a;
}
}
else if (tN > tD)
{
// tc > 1 => the t = 1 edge is visible
// recompute sc for this edge
if ((-d + b) < 0.0)
{
sN = 0;
}
else if ((-d + b) > a)
{
sN = sD;
}
else
{
sN = -d + b;
sD = a;
}
}
// finally do the division to get sc and tc
if (Math.Abs(sN) < SmallNum)
{
sc = 0.0;
}
else
{
sc = sN / sD;
}
if (Math.Abs(tN) < SmallNum)
{
tc = 0.0;
}
else
{
tc = tN / tD;
}
// get the difference of the two closest points
Vector dU = u.Multiply(sc);
Vector dV = v.Multiply(tc);
Vector dP = w.Add(dU).Subtract(dV);
// S1(sc) - S2(tc)
return dP.Length2D;
}
/// <summary>
/// Returns 0 if no intersections occur, 1 if an intersection point is found,
/// and 2 if the segments are colinear and overlap.
/// </summary>
/// <param name="other">The segment to check against.</param>
/// <returns>0 = no intersection, 1 = intersection point found, 2 = segments are collinear or overlap</returns>
public int IntersectionCount(Segment other)
{
double x1 = P1.X;
double y1 = P1.Y;
double x2 = P2.X;
double y2 = P2.Y;
double x3 = other.P1.X;
double y3 = other.P1.Y;
double x4 = other.P2.X;
double y4 = other.P2.Y;
double denom = ((y4 - y3) * (x2 - x1)) - ((x4 - x3) * (y2 - y1));
// The case of two degenerate segements
if ((x1 == x2) && (y1 == y2) && (x3 == x4) && (y3 == y4))
{
if ((x1 != x3) || (y1 != y3))
return 0;
}
// if denom is 0, then the two lines are parallel
double na = ((x4 - x3) * (y1 - y3)) - ((y4 - y3) * (x1 - x3));
double nb = ((x2 - x1) * (y1 - y3)) - ((y2 - y1) * (x1 - x3));
// if denom is 0 AND na and nb are 0, then the lines are coincident and DO intersect
if (Math.Abs(denom) < Epsilon && Math.Abs(na) < Epsilon && Math.Abs(nb) < Epsilon) return 2;
// If denom is 0, but na or nb are not 0, then the lines are parallel and not coincident
if (denom == 0) return 0;
double ua = na / denom;
double ub = nb / denom;
if (ua < 0 || ua > 1) return 0; // not intersecting with segment a
if (ub < 0 || ub > 1) return 0; // not intersecting with segment b
// If we get here, then one intersection exists and it is found on both line segments
return 1;
}
/// <summary>
/// Tests to see if the specified segment contains the point within Epsilon tollerance.
/// </summary>
/// <param name="point">The point to check.</param>
/// <returns>True if the point intersects with the segment.</returns>
public bool IntersectsVertex(Vertex point)
{
double x1 = P1.X;
double y1 = P1.Y;
double x2 = P2.X;
double y2 = P2.Y;
double pX = point.X;
double pY = point.Y;
// Collinear
if (Math.Abs(((x2 - x1) * (pY - y1)) - ((pX - x1) * (y2 - y1))) > Epsilon) return false;
// In the x is in bounds and it is colinear, it is on the segment
if (x1 < x2)
{
if (x1 <= pX && pX <= x2) return true;
}
else
{
if (x2 <= pX && pX <= x1) return true;
}
return false;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace WixSharp.Bootstrapper
{
/// <summary>
/// Container class for common members of the Bootstrapper packages
/// </summary>
public abstract class Package : ChainItem
{
/// <summary>
/// Specifies the display name to place in the bootstrapper application data manifest for the package.
/// By default, ExePackages use the ProductName field from the version information, MsiPackages use the ProductName property, and MspPackages use the DisplayName patch metadata property.
/// Other package types must use this attribute to define a display name in the bootstrapper application data manifest.
/// </summary>
[Xml]
public string DisplayName;
/// <summary>
/// Specifies whether the package can be uninstalled. The default is "no".
/// </summary>
[Xml]
public bool? Permanent;
/// <summary>
/// Location of the package to add to the bundle. The default value is the Name attribute, if provided. At a minimum, the SourceFile or Name attribute must be specified.
/// </summary>
[Xml]
public string SourceFile;
/// <summary>
/// Specifies the description to place in the bootstrapper application data manifest for the package. By default,
/// ExePackages use the FileName field from the version information, MsiPackages use the ARPCOMMENTS property, and MspPackages
/// use the Description patch metadata property. Other package types must use this attribute to define a description in the
/// bootstrapper application data manifest.
/// </summary>
[Xml]
public string Description;
/// <summary>
/// The URL to use to download the package. The following substitutions are supported:
/// <para>{0} is replaced by the package Id.</para>
/// <para>{1} is replaced by the payload Id.</para>
/// <para>{2} is replaced by the payload file name.</para>
/// </summary>
[Xml]
public string DownloadUrl;
/// <summary>
/// A condition to evaluate before installing the package. The package will only be installed if the condition evaluates to true.
/// If the condition evaluates to false and the bundle is being installed, repaired, or modified, the package will be uninstalled.
/// </summary>
[Xml]
public string InstallCondition;
/// <summary>
/// Whether the package payload should be embedded in a container or left as an external payload.
/// </summary>
[Xml]
public bool? Compressed;
/// <summary>
/// Whether to cache the package. The default is "yes".
/// </summary>
[Xml]
public bool? Cache;
/// <summary>
/// Name of a Variable that will hold the path to the log file.
/// An empty value will cause the variable to not be set.
/// The default is "WixBundleLog_[PackageId]" except for MSU packages which default to no logging.
/// </summary>
[Xml]
public string LogPathVariable;
/// <summary>
/// Name of a Variable that will hold the path to the log file used during rollback.
/// An empty value will cause the variable to not be set.
/// The default is "WixBundleRollbackLog_[PackageId]" except for MSU packages which default to no logging.
/// </summary>
[Xml]
public string RollbackLogPathVariable;
/// <summary>
/// Collection of Payloads (the package dependencies).
/// </summary>
/// <example>
/// <code>
/// var bootstrapper =
/// new Bundle("My Product",
/// new MsiPackage(productMsi)
/// {
/// DisplayInternalUI = true,
/// Payloads = new[] {
/// "script.dll".ToPayload()
/// "utils.dll".ToPayload()
/// }
/// ...
/// </code>
/// </example>
public Payload[] Payloads = new Payload[0];
internal void EnsureId()
{
if (!base.IsIdSet())
{
Name = System.IO.Path.GetFileName(SourceFile);
}
}
}
/// <summary>
/// Container class for common members of the Bootstrapper chained items
/// </summary>
public abstract class ChainItem : WixEntity
{
/// <summary>
/// Specifies whether the package/item must succeed for the chain to continue.
/// The default "yes" (true) indicates that if the package fails then the chain will fail and rollback or stop.
/// If "no" is specified then the chain will continue even if the package reports failure.
/// </summary>
[Xml]
public bool? Vital;
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
abstract public XContainer[] ToXml();
}
// /// <summary>
// /// The interface for the items that are XML-aware and capable of building
// /// XML elements based on the internal content.
// /// <para>YOu can use <see cref="IXmlBuilder"/> objects to extend WixSharp type system.
// /// See <see cref="Bundle.Items"/> for details.
// /// </para>
// /// </summary>
// public interface IXmlBuilder
// {
// /// <summary>
// /// Emits WiX XML.
// /// </summary>
// /// <returns></returns>
// XContainer[] ToXml();
// }
/// <summary>
/// Standard WiX ExePackage.
/// </summary>
public class ExePackage : Package
{
/// <summary>
/// Initializes a new instance of the <see cref="ExePackage"/> class.
/// </summary>
public ExePackage()
{
ExitCodes = new List<ExitCode>();
}
/// <summary>
/// Initializes a new instance of the <see cref="ExePackage"/> class.
/// </summary>
/// <param name="path">The path.</param>
public ExePackage(string path) : this()
{
//Name = System.IO.Path.GetFileName(path).Expand();
SourceFile = path;
}
/// <summary>
/// The command-line arguments provided to the ExePackage during install. If this attribute
/// is absent the executable will be launched with no command-line arguments
/// </summary>
[Xml]
public string InstallCommand;
/// <summary>
/// The command-line arguments to specify to indicate a repair. If the executable package can be repaired but does not require any
/// special command-line arguments to do so then set the attribute's value to blank. To indicate that the package does not support repair,
/// omit this attribute.
/// </summary>
[Xml]
public string RepairCommand;
/// <summary>
/// The command-line arguments provided to the ExePackage during uninstall. If this attribute is absent the executable will be launched
/// with no command-line arguments. To prevent an ExePackage from being uninstalled set the Permanent attribute to "yes".
/// </summary>
[Xml]
public string UninstallCommand;
/// <summary>
/// Indicates the package must be executed elevated. The default is "no".
/// </summary>
[Xml]
public bool? PerMachine;
/// <summary>
/// A condition that determines if the package is present on the target system.
/// This condition can use built-in variables and variables returned by searches.
/// This condition is necessary because Windows doesn't provide a method to detect the presence of an ExePackage.
/// Burn uses this condition to determine how to treat this package during a bundle action; for example, if this condition
/// is false or omitted and the bundle is being installed, Burn will install this package.
/// </summary>
[Xml]
public string DetectCondition;
/// <summary>
/// Describes map of exit code returned from executable package to a bootstrapper behavior.
///http://wixtoolset.org/documentation/manual/v3/xsd/wix/exitcode.html
/// </summary>
public List<ExitCode> ExitCodes;
/// <summary>
/// Collection of RemotePayloads (the package dependencies).
/// </summary>
/// <example>
/// <code>
/// var bootstrapper =
/// new Bundle("My Product",
/// new ExePackage()
/// {
/// ...,
/// RemotePayloads = new[] {
/// new RemotePayload
/// {
/// Size=50352408,
/// ...
/// }
/// }
/// ...
/// </code>
/// </example>
public RemotePayload[] RemotePayloads = new RemotePayload[0];
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
public override XContainer[] ToXml()
{
var root = new XElement("ExePackage");
root.SetAttribute("Name", Name); //will respect null
if (this.IsIdSet())
root.SetAttribute("Id", Id);
root.AddAttributes(this.Attributes)
.Add(this.MapToXmlAttributes());
if (Payloads.Any())
Payloads.ForEach(p => root.Add(p.ToXElement("Payload")));
if (RemotePayloads.Any())
RemotePayloads.ForEach(p => root.Add(p.ToXElement("RemotePayload")));
foreach (var exitCode in ExitCodes)
{
root.Add(exitCode.ToXElement());
}
return new[] { root };
}
}
/// <summary>
/// Standard WiX MsiPackage.
/// </summary>
public class MsiPackage : Package
{
/// <summary>
/// Specifies whether the bundle will allow individual control over the installation state of Features inside the msi package. Managing
/// feature selection requires special care to ensure the install, modify, update and uninstall behavior of the package is always correct.
/// The default is "no".
/// </summary>
[Xml]
public bool? EnableFeatureSelection;
/// <summary>
/// Initializes a new instance of the <see cref="MsiPackage"/> class.
/// </summary>
public MsiPackage()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MsiPackage"/> class.
/// </summary>
/// <param name="path">The path.</param>
public MsiPackage(string path)
{
SourceFile = path;
}
/// <summary>
/// Specifies whether the bundle will show the UI authored into the msi package. The default is "no" which means all information is routed to
/// the bootstrapper application to provide a unified installation experience. If "yes" is specified the UI authored into the msi package will be
/// displayed on top of any bootstrapper application UI.
/// <para>Please note that WiX has a pending issue (https://github.com/wixtoolset/issues/issues/4921) associated with the problem
/// that prevents EmbeddedUI (ManagedUI) to be displayed even if 'DisplayInternalUI' is set to <c>true</c>. The issue is scheduled to be
/// resolved in WiX v4.x.</para>
/// </summary>
[Xml]
public bool? DisplayInternalUI;
/// <summary>
/// Specifies whether the MSI will be displayed in Programs and Features (also known as Add/Remove Programs). If "yes" is specified the MSI package
/// information will be displayed in Programs and Features. The default "no" indicates the MSI will not be displayed.
/// </summary>
[Xml]
public bool? Visible;
/// <summary>
/// Override the automatic per-machine detection of MSI packages and force the package to be per-machine. The default is "no", which allows
/// the tools to detect the expected value.
/// </summary>
[Xml]
public bool? ForcePerMachine;
/// <summary>
/// MSI properties to be set based on the value of a burn engine expression. This is a KeyValue mapping expression of the following format:
/// <para><key>=<value>[;<key>=<value>]</para>
/// <para><c>Example:</c> "COMMANDARGS=[CommandArgs];GLOBAL=yes""</para>
/// </summary>
public string MsiProperties;
/// <summary>
/// The default MsiProperties of a package .
/// <para>This value is merged with user defined <see cref="WixSharp.Bootstrapper.MsiPackage.MsiProperties"/>.</para>
/// <para>The default value of this property is "WIXBUNDLEORIGINALSOURCE=[WixBundleOriginalSource]"</para>
/// </summary>
public string DefaultMsiProperties = "WIXBUNDLEORIGINALSOURCE=[WixBundleOriginalSource]";
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
public override XContainer[] ToXml()
{
var root = new XElement("MsiPackage");
root.SetAttribute("Name", Name); //will respect null
if (this.IsIdSet())
root.SetAttribute("Id", Id);
root.AddAttributes(this.Attributes)
.Add(this.MapToXmlAttributes());
if (Payloads.Any())
Payloads.ForEach(p => root.Add(p.ToXElement("Payload")));
string props = MsiProperties + ";" + DefaultMsiProperties;
props.ToDictionary().ForEach(p =>
{
root.Add(new XElement("MsiProperty").AddAttributes("Name={0};Value={1}".FormatWith(p.Key, p.Value)));
});
return new[] { root };
}
}
/// <summary>
/// Standard WiX MspPackage.
/// </summary>
public class MspPackage : Package
{
/// <summary>
/// Initializes a new instance of the <see cref="MspPackage"/> class.
/// </summary>
public MspPackage()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MspPackage"/> class.
/// </summary>
/// <param name="path">The path.</param>
public MspPackage(string path)
{
SourceFile = path;
}
/// <summary>
/// The identifier of another package that this one should be installed after. By default the After attribute is set to the previous sibling
/// package in the Chain or PackageGroup element. If this attribute is specified ensure that a cycle is not created explicitly or implicitly.
/// </summary>
[Xml]
public string After;
/// <summary>
/// The identifier to use when caching the package.
/// </summary>
[Xml]
public string CacheId;
/// <summary>
/// Specifies whether the bundle will show the UI authored into the msp package. The default is "no" which means all information is routed to the
/// bootstrapper application to provide a unified installation experience. If "yes" is specified the UI authored into the msp package will be
/// displayed on top of any bootstrapper application UI.
/// </summary>
[Xml]
public bool? DisplayInternalUI;
/// <summary>
/// The size this package will take on disk in bytes after it is installed. By default, the binder will calculate the install size by scanning
/// the package (File table for MSIs, Payloads for EXEs) and use the total for the install size of the package.
/// </summary>
[Xml]
public string InstallSize;
/// <summary>
/// Indicates the package must be executed elevated. The default is "no".
/// </summary>
[Xml]
public bool? PerMachine;
/// <summary>
/// Specifies whether to automatically slipstream the patch for any target msi packages in the chain. The default is "no". Even when the value is
/// "no", you can still author the SlipstreamMsp element under MsiPackage elements as desired.
/// </summary>
[Xml]
public bool? Slipstream;
/// <summary>
/// By default, a Bundle will use the hash of a package to verify its contents. If this attribute is explicitly set to "no" and the package
/// is signed with an Authenticode signature the Bundle will verify the contents of the package using the signature instead. Therefore, the
/// default for this attribute could be considered to be "yes". It is unusual for "yes" to be the default of an attribute. In this case, the
/// default was changed in WiX v3.9 after experiencing real world issues with Windows verifying Authenticode signatures. Since the
/// Authenticode signatures are no more secure than hashing the packages directly, the default was changed.
/// </summary>
public bool? SuppressSignatureVerification;
/// <summary>
/// When set to "yes", the Prereq BA will plan the package to be installed if its InstallCondition is "true" or empty.
/// (http://schemas.microsoft.com/wix/BalExtension)
/// </summary>
[Xml]
public bool? PrereqSupportPackage;
/// <summary>
/// The remote payloads
/// </summary>
public RemotePayload[] RemotePayloads = new RemotePayload[0];
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
public override XContainer[] ToXml()
{
var root = new XElement("MspPackage");
root.SetAttribute("Name", Name); //will respect null
if (this.IsIdSet())
root.SetAttribute("Id", Id);
root.AddAttributes(this.Attributes)
.Add(this.MapToXmlAttributes());
if (Payloads.Any())
Payloads.ForEach(p => root.Add(p.ToXElement("Payload")));
if (RemotePayloads.Any())
RemotePayloads.ForEach(p => root.Add(p.ToXElement("RemotePayload")));
return new[] { root };
}
}
/// <summary>
/// Standard WiX MsuPackage.
/// </summary>
public class MsuPackage : Package
{
/// <summary>
/// Initializes a new instance of the <see cref="MsuPackage"/> class.
/// </summary>
public MsuPackage()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MsuPackage"/> class.
/// </summary>
/// <param name="path">The path.</param>
public MsuPackage(string path)
{
SourceFile = path;
}
/// <summary>
/// A condition that determines if the package is present on the target system.
/// This condition can use built-in variables and variables returned by searches.
/// This condition is necessary because Windows doesn't provide a method to detect the presence of an ExePackage.
/// Burn uses this condition to determine how to treat this package during a bundle action;
/// for example, if this condition is false or omitted and the bundle is being installed, Burn will install this package.
/// </summary>
[Xml]
public string DetectCondition;
/// <summary>
/// The knowledge base identifier for the MSU.
/// The KB attribute must be specified to enable the MSU package to be uninstalled.
/// Even then MSU uninstallation is only supported on Windows 7 and later.
/// When the KB attribute is specified, the Permanent attribute will the control whether the package is uninstalled.
/// </summary>
[Xml]
public string KB;
/// <summary>
/// The remote payloads
/// </summary>
public RemotePayload[] RemotePayloads = new RemotePayload[0];
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
public override XContainer[] ToXml()
{
var root = new XElement("MsuPackage");
root.SetAttribute("Name", Name); //will respect null
if (this.IsIdSet())
root.SetAttribute("Id", Id);
root.AddAttributes(this.Attributes)
.Add(this.MapToXmlAttributes());
if (Payloads.Any())
Payloads.ForEach(p => root.Add(p.ToXElement("Payload")));
if (RemotePayloads.Any())
RemotePayloads.ForEach(p => root.Add(p.ToXElement("RemotePayload")));
return new[] { root };
}
}
/// <summary>
/// Standard WiX PackageGroupRef.
/// </summary>
public class PackageGroupRef : ChainItem
{
/// <summary>
/// Initializes a new instance of the <see cref="PackageGroupRef"/> class.
/// </summary>
/// <param name="name">The name.</param>
public PackageGroupRef(string name)
{
this.Id = new Id(name);
}
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
public override XContainer[] ToXml()
{
var root = new XElement("PackageGroupRef");
if (this.IsIdSet())
root.SetAttribute("Id", Id);
root.AddAttributes(this.Attributes)
.Add(this.MapToXmlAttributes());
return new[] { root };
}
}
/// <summary>
/// Standard WiX RollbackBoundary.
/// </summary>
public class RollbackBoundary : ChainItem
{
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
public override XContainer[] ToXml()
{
return new[] { new XElement("RollbackBoundary") };
}
}
/// <summary>
/// Exit code returned from executable package.
/// </summary>
public class ExitCode
{
/// <summary>
/// Exit code returned from executable package.
/// If no value is provided it means all values not explicitly set default to this behavior.
/// </summary>
[Xml]
public string Value;
/// <summary>
/// Choose one of the supported behaviors error codes: success, error, scheduleReboot, forceReboot.
/// This attribute's value must be one of the following:
/// success
/// error
/// scheduleReboot
/// forceReboot
/// </summary>
[Xml]
public BehaviorValues Behavior;
/// <summary>
/// Serializes the <see cref="WixSharp.Bootstrapper.ExitCode"/> into XML based on the members marked with
/// <see cref="WixSharp.XmlAttribute"/> and <see cref="WixSharp.WixObject.Attributes"/>.
/// </summary>
/// <returns></returns>
public XElement ToXElement()
{
var element = new XElement("ExitCode", new XAttribute("Behavior", Behavior));
if (Value != null)
{
element.Add(new XAttribute("Value", Value));
}
return element;
}
}
#pragma warning disable 1591
public enum YesNoAlways
{
yes,
no,
always
}
public enum BehaviorValues
{
/// <summary>
/// return success on specified error code
/// </summary>
success,
/// <summary>
/// return error on specified error code
/// </summary>
error,
/// <summary>
/// schedule reboot on specified error code
/// </summary>
scheduleReboot,
/// <summary>
/// force reboot on specified error code
/// </summary>
forceReboot,
}
public enum SearchResult
{
/// <summary>
/// Saves true if a matching registry entry or file is found; false otherwise.
/// </summary>
exists,
/// <summary>
/// Saves the value of the registry key in the variable. Can only be used with RegistrySearch. This is the default.
/// </summary>
value,
/// <summary>
/// Saves the version information for files that have it (.exe, .dll); zero-version (0.0.0.0) otherwise. Can only be used with FileSearch.
/// </summary>
version
}
public enum SearchFormat
{
/// <summary>
/// Returns the unformatted value directly from the registry. For example, a REG_DWORD value of '1' is returned as '1', not '#1'.
/// </summary>
raw,
/// <summary>
/// Returns the value formatted as Windows Installer would. For example, a REG_DWORD value of '1' is returned as '#1', not '1'.
/// </summary>
compatible
}
/// <summary>
/// The search result type to use for a <see cref="UtilProductSearch"/>
/// </summary>
public enum ProductSearchResultType
{
/// <summary>
/// Saves the version of a matching product if found; 0.0.0.0 otherwise. This is the default.
/// </summary>
version,
/// <summary>
/// Saves the language of a matching product if found; empty otherwise.
/// </summary>
language,
/// <summary>
/// Saves the state of the product: advertised (1), absent (2), or locally installed (5).
/// </summary>
state,
/// <summary>
/// Saves the assignment type of the product: per-user (0), or per-machine (1).
/// </summary>
assignment
}
#pragma warning restore 1591
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
** Class: ConditionalWeakTable
**
** <OWNER>[....]</OWNER>
**
** Description: Compiler support for runtime-generated "object fields."
**
** Lets DLR and other language compilers expose the ability to
** attach arbitrary "properties" to instanced managed objects at runtime.
**
** We expose this support as a dictionary whose keys are the
** instanced objects and the values are the "properties."
**
** Unlike a regular dictionary, ConditionalWeakTables will not
** keep keys alive.
**
**
** Lifetimes of keys and values:
**
** Inserting a key and value into the dictonary will not
** prevent the key from dying, even if the key is strongly reachable
** from the value.
**
** Prior to ConditionalWeakTable, the CLR did not expose
** the functionality needed to implement this guarantee.
**
** Once the key dies, the dictionary automatically removes
** the key/value entry.
**
**
** Relationship between ConditionalWeakTable and Dictionary:
**
** ConditionalWeakTable mirrors the form and functionality
** of the IDictionary interface for the sake of api consistency.
**
** Unlike Dictionary, ConditionalWeakTable is fully thread-safe
** and requires no additional locking to be done by callers.
**
** ConditionalWeakTable defines equality as Object.ReferenceEquals().
** ConditionalWeakTable does not invoke GetHashCode() overrides.
**
** It is not intended to be a general purpose collection
** and it does not formally implement IDictionary or
** expose the full public surface area.
**
**
**
** Thread safety guarantees:
**
** ConditionalWeakTable is fully thread-safe and requires no
** additional locking to be done by callers.
**
**
** OOM guarantees:
**
** Will not corrupt unmanaged handle table on OOM. No guarantees
** about managed weak table consistency. Native handles reclamation
** may be delayed until appdomain shutdown.
===========================================================*/
namespace System.Runtime.CompilerServices
{
using System;
using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Runtime.InteropServices;
#region ConditionalWeakTable
[System.Runtime.InteropServices.ComVisible(false)]
public sealed class ConditionalWeakTable<TKey, TValue>
where TKey : class
where TValue : class
{
#region Constructors
[System.Security.SecuritySafeCritical]
public ConditionalWeakTable()
{
_buckets = new int[0];
_entries = new Entry[0];
_freeList = -1;
_lock = new Object();
Resize(); // Resize at once (so won't need "if initialized" checks all over)
}
#endregion
#region Public Members
//--------------------------------------------------------------------------------------------
// key: key of the value to find. Cannot be null.
// value: if the key is found, contains the value associated with the key upon method return.
// if the key is not found, contains default(TValue).
//
// Method returns "true" if key was found, "false" otherwise.
//
// Note: The key may get garbaged collected during the TryGetValue operation. If so, TryGetValue
// may at its discretion, return "false" and set "value" to the default (as if the key was not present.)
//--------------------------------------------------------------------------------------------
[System.Security.SecuritySafeCritical]
public bool TryGetValue(TKey key, out TValue value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
lock(_lock)
{
VerifyIntegrity();
return TryGetValueWorker(key, out value);
}
}
//--------------------------------------------------------------------------------------------
// key: key to add. May not be null.
// value: value to associate with key.
//
// If the key is already entered into the dictionary, this method throws an exception.
//
// Note: The key may get garbage collected during the Add() operation. If so, Add()
// has the right to consider any prior entries successfully removed and add a new entry without
// throwing an exception.
//--------------------------------------------------------------------------------------------
[System.Security.SecuritySafeCritical]
public void Add(TKey key, TValue value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
lock(_lock)
{
VerifyIntegrity();
_invalid = true;
int entryIndex = FindEntry(key);
if (entryIndex != -1)
{
_invalid = false;
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
}
CreateEntry(key, value);
_invalid = false;
}
}
//--------------------------------------------------------------------------------------------
// key: key to remove. May not be null.
//
// Returns true if the key is found and removed. Returns false if the key was not in the dictionary.
//
// Note: The key may get garbage collected during the Remove() operation. If so,
// Remove() will not fail or throw, however, the return value can be either true or false
// depending on who wins the ----.
//--------------------------------------------------------------------------------------------
[System.Security.SecuritySafeCritical]
public bool Remove(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
lock(_lock)
{
VerifyIntegrity();
_invalid = true;
int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue;
int bucket = hashCode % _buckets.Length;
int last = -1;
for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
{
if (_entries[entriesIndex].hashCode == hashCode && _entries[entriesIndex].depHnd.GetPrimary() == key)
{
if (last == -1)
{
_buckets[bucket] = _entries[entriesIndex].next;
}
else
{
_entries[last].next = _entries[entriesIndex].next;
}
_entries[entriesIndex].depHnd.Free();
_entries[entriesIndex].next = _freeList;
_freeList = entriesIndex;
_invalid = false;
return true;
}
last = entriesIndex;
}
_invalid = false;
return false;
}
}
//--------------------------------------------------------------------------------------------
// key: key of the value to find. Cannot be null.
// createValueCallback: callback that creates value for key. Cannot be null.
//
// Atomically tests if key exists in table. If so, returns corresponding value. If not,
// invokes createValueCallback() passing it the key. The returned value is bound to the key in the table
// and returned as the result of GetValue().
//
// If multiple threads ---- to initialize the same key, the table may invoke createValueCallback
// multiple times with the same key. Exactly one of these calls will "win the ----" and the returned
// value of that call will be the one added to the table and returned by all the racing GetValue() calls.
//
// This rule permits the table to invoke createValueCallback outside the internal table lock
// to prevent deadlocks.
//--------------------------------------------------------------------------------------------
[System.Security.SecuritySafeCritical]
public TValue GetValue(TKey key, CreateValueCallback createValueCallback)
{
// Our call to TryGetValue() validates key so no need for us to.
//
// if (key == null)
// {
// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
// }
if (createValueCallback == null)
{
throw new ArgumentNullException("createValueCallback");
}
TValue existingValue;
if (TryGetValue(key, out existingValue))
{
return existingValue;
}
// If we got here, the key is not currently in table. Invoke the callback (outside the lock)
// to generate the new value for the key.
TValue newValue = createValueCallback(key);
lock(_lock)
{
VerifyIntegrity();
_invalid = true;
// Now that we've retaken the lock, must recheck in case we lost a ---- to add the key.
if (TryGetValueWorker(key, out existingValue))
{
_invalid = false;
return existingValue;
}
else
{
// Verified in-lock that we won the ---- to add the key. Add it now.
CreateEntry(key, newValue);
_invalid = false;
return newValue;
}
}
}
//--------------------------------------------------------------------------------------------
// key: key of the value to find. Cannot be null.
//
// Helper method to call GetValue without passing a creation delegate. Uses Activator.CreateInstance
// to create new instances as needed. If TValue does not have a default constructor, this will
// throw.
//--------------------------------------------------------------------------------------------
public TValue GetOrCreateValue(TKey key)
{
return GetValue(key, k => Activator.CreateInstance<TValue>());
}
public delegate TValue CreateValueCallback(TKey key);
#endregion
#region internal members
//--------------------------------------------------------------------------------------------
// Find a key that equals (value equality) with the given key - don't use in perf critical path
// Note that it calls out to Object.Equals which may calls the override version of Equals
// and that may take locks and leads to deadlock
// Currently it is only used by WinRT event code and you should only use this function
// if you know for sure that either you won't run into dead locks or you need to live with the
// possiblity
//--------------------------------------------------------------------------------------------
[System.Security.SecuritySafeCritical]
[FriendAccessAllowed]
internal TKey FindEquivalentKeyUnsafe(TKey key, out TValue value)
{
lock (_lock)
{
for (int bucket = 0; bucket < _buckets.Length; ++bucket)
{
for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
{
object thisKey, thisValue;
_entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out thisKey, out thisValue);
if (Object.Equals(thisKey, key))
{
value = (TValue) thisValue;
return (TKey) thisKey;
}
}
}
}
value = default(TValue);
return null;
}
//--------------------------------------------------------------------------------------------
// Returns a collection of keys - don't use in perf critical path
//--------------------------------------------------------------------------------------------
internal ICollection<TKey> Keys
{
[System.Security.SecuritySafeCritical]
get
{
List<TKey> list = new List<TKey>();
lock (_lock)
{
for (int bucket = 0; bucket < _buckets.Length; ++bucket)
{
for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
{
TKey thisKey = (TKey) _entries[entriesIndex].depHnd.GetPrimary();
if (thisKey != null)
{
list.Add(thisKey);
}
}
}
}
return list;
}
}
//--------------------------------------------------------------------------------------------
// Returns a collection of values - don't use in perf critical path
//--------------------------------------------------------------------------------------------
internal ICollection<TValue> Values
{
[System.Security.SecuritySafeCritical]
get
{
List<TValue> list = new List<TValue>();
lock (_lock)
{
for (int bucket = 0; bucket < _buckets.Length; ++bucket)
{
for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
{
Object primary = null;
Object secondary = null;
_entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary);
// Now that we've secured a strong reference to the secondary, must check the primary again
// to ensure it didn't expire (otherwise, we open a ---- where TryGetValue misreports an
// expired key as a live key with a null value.)
if (primary != null)
{
list.Add((TValue)secondary);
}
}
}
}
return list;
}
}
//--------------------------------------------------------------------------------------------
// Clear all the key/value pairs
//--------------------------------------------------------------------------------------------
[System.Security.SecuritySafeCritical]
internal void Clear()
{
lock (_lock)
{
// Clear the buckets
for (int bucketIndex = 0; bucketIndex < _buckets.Length; bucketIndex++)
{
_buckets[bucketIndex] = -1;
}
// Clear the entries and link them backwards together as part of free list
int entriesIndex;
for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
{
if (_entries[entriesIndex].depHnd.IsAllocated)
{
_entries[entriesIndex].depHnd.Free();
}
// Link back wards as free list
_entries[entriesIndex].next = entriesIndex - 1;
}
_freeList = entriesIndex - 1;
}
}
#endregion
#region Private Members
[System.Security.SecurityCritical]
//----------------------------------------------------------------------------------------
// Worker for finding a key/value pair
//
// Preconditions:
// Must hold _lock.
// Key already validated as non-null
//----------------------------------------------------------------------------------------
private bool TryGetValueWorker(TKey key, out TValue value)
{
int entryIndex = FindEntry(key);
if (entryIndex != -1)
{
Object primary = null;
Object secondary = null;
_entries[entryIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary);
// Now that we've secured a strong reference to the secondary, must check the primary again
// to ensure it didn't expire (otherwise, we open a ---- where TryGetValue misreports an
// expired key as a live key with a null value.)
if (primary != null)
{
value = (TValue)secondary;
return true;
}
}
value = default(TValue);
return false;
}
//----------------------------------------------------------------------------------------
// Worker for adding a new key/value pair.
//
// Preconditions:
// Must hold _lock.
// Key already validated as non-null and not already in table.
//----------------------------------------------------------------------------------------
[System.Security.SecurityCritical]
private void CreateEntry(TKey key, TValue value)
{
if (_freeList == -1)
{
Resize();
}
int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue;
int bucket = hashCode % _buckets.Length;
int newEntry = _freeList;
_freeList = _entries[newEntry].next;
_entries[newEntry].hashCode = hashCode;
_entries[newEntry].depHnd = new DependentHandle(key, value);
_entries[newEntry].next = _buckets[bucket];
_buckets[bucket] = newEntry;
}
//----------------------------------------------------------------------------------------
// This does two things: resize and scrub expired keys off bucket lists.
//
// Precondition:
// Must hold _lock.
//
// Postcondition:
// _freeList is non-empty on exit.
//----------------------------------------------------------------------------------------
[System.Security.SecurityCritical]
private void Resize()
{
// Start by assuming we won't resize.
int newSize = _buckets.Length;
// If any expired keys exist, we won't resize.
bool hasExpiredEntries = false;
int entriesIndex;
for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
{
if ( _entries[entriesIndex].depHnd.IsAllocated && _entries[entriesIndex].depHnd.GetPrimary() == null)
{
hasExpiredEntries = true;
break;
}
}
if (!hasExpiredEntries)
{
newSize = System.Collections.HashHelpers.GetPrime(_buckets.Length == 0 ? _initialCapacity + 1 : _buckets.Length * 2);
}
// Reallocate both buckets and entries and rebuild the bucket and freelists from scratch.
// This serves both to scrub entries with expired keys and to put the new entries in the proper bucket.
int newFreeList = -1;
int[] newBuckets = new int[newSize];
for (int bucketIndex = 0; bucketIndex < newSize; bucketIndex++)
{
newBuckets[bucketIndex] = -1;
}
Entry[] newEntries = new Entry[newSize];
// Migrate existing entries to the new table.
for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
{
DependentHandle depHnd = _entries[entriesIndex].depHnd;
if (depHnd.IsAllocated && depHnd.GetPrimary() != null)
{
// Entry is used and has not expired. Link it into the appropriate bucket list.
int bucket = _entries[entriesIndex].hashCode % newSize;
newEntries[entriesIndex].depHnd = depHnd;
newEntries[entriesIndex].hashCode = _entries[entriesIndex].hashCode;
newEntries[entriesIndex].next = newBuckets[bucket];
newBuckets[bucket] = entriesIndex;
}
else
{
// Entry has either expired or was on the freelist to begin with. Either way
// insert it on the new freelist.
_entries[entriesIndex].depHnd.Free();
newEntries[entriesIndex].depHnd = new DependentHandle();
newEntries[entriesIndex].next = newFreeList;
newFreeList = entriesIndex;
}
}
// Add remaining entries to freelist.
while (entriesIndex != newEntries.Length)
{
newEntries[entriesIndex].depHnd = new DependentHandle();
newEntries[entriesIndex].next = newFreeList;
newFreeList = entriesIndex;
entriesIndex++;
}
_buckets = newBuckets;
_entries = newEntries;
_freeList = newFreeList;
}
//----------------------------------------------------------------------------------------
// Returns -1 if not found (if key expires during FindEntry, this can be treated as "not found.")
//
// Preconditions:
// Must hold _lock.
// Key already validated as non-null.
//----------------------------------------------------------------------------------------
[System.Security.SecurityCritical]
private int FindEntry(TKey key)
{
int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue;
for (int entriesIndex = _buckets[hashCode % _buckets.Length]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
{
if (_entries[entriesIndex].hashCode == hashCode && _entries[entriesIndex].depHnd.GetPrimary() == key)
{
return entriesIndex;
}
}
return -1;
}
//----------------------------------------------------------------------------------------
// Precondition:
// Must hold _lock.
//----------------------------------------------------------------------------------------
private void VerifyIntegrity()
{
if (_invalid)
{
throw new InvalidOperationException(Environment.GetResourceString("CollectionCorrupted"));
}
}
//----------------------------------------------------------------------------------------
// Finalizer.
//----------------------------------------------------------------------------------------
[System.Security.SecuritySafeCritical]
~ConditionalWeakTable()
{
// We're just freeing per-appdomain unmanaged handles here. If we're already shutting down the AD,
// don't bother.
//
// (Despite its name, Environment.HasShutdownStart also returns true if the current AD is finalizing.)
if (Environment.HasShutdownStarted)
{
return;
}
if (_lock != null)
{
lock(_lock)
{
if (_invalid)
{
return;
}
Entry[] entries = _entries;
// Make sure anyone sneaking into the table post-resurrection
// gets booted before they can damage the native handle table.
_invalid = true;
_entries = null;
_buckets = null;
for (int entriesIndex = 0; entriesIndex < entries.Length; entriesIndex++)
{
entries[entriesIndex].depHnd.Free();
}
}
}
}
#endregion
#region Private Data Members
//--------------------------------------------------------------------------------------------
// Entry can be in one of three states:
//
// - Linked into the freeList (_freeList points to first entry)
// depHnd.IsAllocated == false
// hashCode == <dontcare>
// next links to next Entry on freelist)
//
// - Used with live key (linked into a bucket list where _buckets[hashCode % _buckets.Length] points to first entry)
// depHnd.IsAllocated == true, depHnd.GetPrimary() != null
// hashCode == RuntimeHelpers.GetHashCode(depHnd.GetPrimary()) & Int32.MaxValue
// next links to next Entry in bucket.
//
// - Used with dead key (linked into a bucket list where _buckets[hashCode % _buckets.Length] points to first entry)
// depHnd.IsAllocated == true, depHnd.GetPrimary() == null
// hashCode == <notcare>
// next links to next Entry in bucket.
//
// The only difference between "used with live key" and "used with dead key" is that
// depHnd.GetPrimary() returns null. The transition from "used with live key" to "used with dead key"
// happens asynchronously as a result of normal garbage collection. The dictionary itself
// receives no notification when this happens.
//
// When the dictionary grows the _entries table, it scours it for expired keys and puts those
// entries back on the freelist.
//--------------------------------------------------------------------------------------------
private struct Entry
{
public DependentHandle depHnd; // Holds key and value using a weak reference for the key and a strong reference
// for the value that is traversed only if the key is reachable without going through the value.
public int hashCode; // Cached copy of key's hashcode
public int next; // Index of next entry, -1 if last
}
private int[] _buckets; // _buckets[hashcode & _buckets.Length] contains index of first entry in bucket (-1 if empty)
private Entry[] _entries;
private int _freeList; // -1 = empty, else index of first unused Entry
private const int _initialCapacity = 5;
private readonly Object _lock; // this could be a ReaderWriterLock but CoreCLR does not support RWLocks.
private bool _invalid; // flag detects if OOM or other background exception threw us out of the lock.
#endregion
}
#endregion
#region DependentHandle
//=========================================================================================
// This struct collects all operations on native DependentHandles. The DependentHandle
// merely wraps an IntPtr so this struct serves mainly as a "managed typedef."
//
// DependentHandles exist in one of two states:
//
// IsAllocated == false
// No actual handle is allocated underneath. Illegal to call GetPrimary
// or GetPrimaryAndSecondary(). Ok to call Free().
//
// Initializing a DependentHandle using the nullary ctor creates a DependentHandle
// that's in the !IsAllocated state.
// (! Right now, we get this guarantee for free because (IntPtr)0 == NULL unmanaged handle.
// ! If that assertion ever becomes false, we'll have to add an _isAllocated field
// ! to compensate.)
//
//
// IsAllocated == true
// There's a handle allocated underneath. You must call Free() on this eventually
// or you cause a native handle table leak.
//
// This struct intentionally does no self-synchronization. It's up to the caller to
// to use DependentHandles in a thread-safe way.
//=========================================================================================
[ComVisible(false)]
struct DependentHandle
{
#region Constructors
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
#else
[System.Security.SecurityCritical]
#endif
public DependentHandle(Object primary, Object secondary)
{
IntPtr handle = (IntPtr)0;
nInitialize(primary, secondary, out handle);
// no need to check for null result: nInitialize expected to throw OOM.
_handle = handle;
}
#endregion
#region Public Members
public bool IsAllocated
{
get
{
return _handle != (IntPtr)0;
}
}
// Getting the secondary object is more expensive than getting the first so
// we provide a separate primary-only accessor for those times we only want the
// primary.
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
#else
[System.Security.SecurityCritical]
#endif
public Object GetPrimary()
{
Object primary;
nGetPrimary(_handle, out primary);
return primary;
}
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
#else
[System.Security.SecurityCritical]
#endif
public void GetPrimaryAndSecondary(out Object primary, out Object secondary)
{
nGetPrimaryAndSecondary(_handle, out primary, out secondary);
}
//----------------------------------------------------------------------
// Forces dependentHandle back to non-allocated state (if not already there)
// and frees the handle if needed.
//----------------------------------------------------------------------
[System.Security.SecurityCritical]
public void Free()
{
if (_handle != (IntPtr)0)
{
IntPtr handle = _handle;
_handle = (IntPtr)0;
nFree(handle);
}
}
#endregion
#region Private Members
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.AppDomain)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void nInitialize(Object primary, Object secondary, out IntPtr dependentHandle);
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void nGetPrimary(IntPtr dependentHandle, out Object primary);
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void nGetPrimaryAndSecondary(IntPtr dependentHandle, out Object primary, out Object secondary);
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void nFree(IntPtr dependentHandle);
#endregion
#region Private Data Member
private IntPtr _handle;
#endregion
} // struct DependentHandle
#endregion
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Adxstudio.Xrm.Partner;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Security;
using Adxstudio.Xrm.Services;
using Adxstudio.Xrm.Services.Query;
using Adxstudio.Xrm.Web.Mvc.Html;
using Adxstudio.Xrm.Web.UI.CrmEntityListView;
using Adxstudio.Xrm.Web.UI.WebControls;
using Adxstudio.Xrm.Web.UI.WebForms;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Configuration;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Portal.Web.UI.CrmEntityFormView;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
namespace Adxstudio.Xrm.Web.UI.CrmEntityFormView
{
/// <summary>
/// Template used when rendering a Lookup field with a record lookup dialog.
/// </summary>
public class ModalLookupControlTemplate : CellTemplate, ICustomFieldControlTemplate
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="field"></param>
/// <param name="metadata"></param>
/// <param name="validationGroup"></param>
/// <param name="bindings"></param>
/// <remarks>Localization of lookup display text is provided by retrieving the entity metadata and determine the primary name field and if the language code is not the base language for the organization it appends _ + language code to the primary name field and populates the control with the values from the localized attribute. i.e. if the primary name field is new_name and the language code is 1036 for French, the localized attribute name would be new_name_1036. An attribute would be added to the entity in this manner for each language to be supported and the attribute must be added to the view assigned to the lookup on the form.</remarks>
public ModalLookupControlTemplate(CrmEntityFormViewField field, FormXmlCellMetadata metadata, string validationGroup, IDictionary<string, CellBinding> bindings)
: base(metadata, validationGroup, bindings)
{
Field = field;
}
/// <summary>
/// Override the default RequiredFieldValidator class to allow validation of a hidden field.
/// </summary>
public class HiddenFieldValidator : RequiredFieldValidator
{
protected override bool ControlPropertiesValid()
{
return true;
}
}
/// <summary>
/// Form field.
/// </summary>
public CrmEntityFormViewField Field { get; private set; }
/// <summary>
/// CSS Class name(s) added to the table cell containing this control
/// </summary>
public override string CssClass
{
get { return "lookup form-control"; }
}
private string ValidationText
{
get { return Metadata.ValidationText; }
}
private ValidatorDisplay ValidatorDisplay
{
get { return string.IsNullOrWhiteSpace(ValidationText) ? ValidatorDisplay.None : ValidatorDisplay.Dynamic; }
}
protected override bool LabelIsAssociated
{
get
{
return false;
}
}
/// <summary>
/// Initialize an instance of the control
/// </summary>
protected override void InstantiateControlIn(Control container)
{
var inputGroup = new HtmlGenericControl("div");
if (Metadata.FormView.Mode != FormViewMode.ReadOnly && !Metadata.ReadOnly && !Metadata.Disabled)
{
inputGroup.Attributes.Add("class", "input-group");
}
var textbox = new TextBox { ID = string.Format("{0}_name", ControlID), CssClass = string.Join(" ", "text form-control", CssClass, Metadata.CssClass), ToolTip = Metadata.ToolTip };
textbox.Attributes.Add("readonly", string.Empty);
textbox.Attributes.Add("aria-readonly", "true");
textbox.Attributes.Add("aria-labelledby", string.Format("{0}_label", ControlID));
textbox.Attributes.Add("aria-label", Metadata.Label);
if (Metadata.FormView.Mode == FormViewMode.ReadOnly || Metadata.ReadOnly)
{
textbox.Enabled = false;
textbox.Attributes.Add("aria-disabled", "true");
}
var hiddenValue = new HtmlInputHidden { ID = ControlID };
var hiddenValueEntityName = new HtmlInputHidden { ID = string.Format("{0}_entityname", ControlID) };
inputGroup.Controls.Add(textbox);
inputGroup.Controls.Add(hiddenValue);
inputGroup.Controls.Add(hiddenValueEntityName);
container.Controls.Add(inputGroup);
if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired)
{
hiddenValue.Attributes.Add("aria-required", "true");
textbox.Attributes.Add("aria-labelledby", string.Empty);
textbox.Attributes["aria-label"] = string.Format(ResourceManager.GetString("Required_Field_Error"), Metadata.Label);
}
if (Metadata.FormView.Mode != FormViewMode.ReadOnly && !Metadata.ReadOnly && !Metadata.Disabled)
{
var buttonGroup = new HtmlGenericControl("div");
buttonGroup.Attributes.Add("class", "input-group-btn");
var clearLookupField = new HtmlGenericControl("button");
clearLookupField.Attributes.Add("type", "button");
clearLookupField.Attributes.Add("class", "btn btn-default clearlookupfield");
clearLookupField.InnerHtml = "<span class='sr-only'>" + ResourceManager.GetString("Clear_Lookup_Field") + "</span><span class='fa fa-times' aria-hidden='true'></span>";
clearLookupField.Attributes.Add("title", ResourceManager.GetString("Clear_Lookup_Field"));
clearLookupField.Attributes.Add("aria-label", ResourceManager.GetString("Clear_Lookup_Field"));
buttonGroup.Controls.Add(clearLookupField);
var launchModalLink = new HtmlGenericControl("button");
launchModalLink.Attributes.Add("type", "button");
launchModalLink.Attributes.Add("class", "btn btn-default launchentitylookup");
launchModalLink.InnerHtml = "<span class='sr-only'>" + ResourceManager.GetString("Launch_Lookup_Modal") + "</span><span class='fa fa-search' aria-hidden='true'></span>";
launchModalLink.Attributes.Add("title", ResourceManager.GetString("Launch_Lookup_Modal"));
launchModalLink.Attributes.Add("aria-label", ResourceManager.GetString("Launch_Lookup_Modal"));
buttonGroup.Controls.Add(launchModalLink);
inputGroup.Controls.Add(buttonGroup);
var lookupModalHtml = BuildLookupModal(container);
var lookupModalControl = new HtmlGenericControl("div")
{
ID = string.Format("{0}_lookupmodal", Metadata.ControlID),
InnerHtml = lookupModalHtml.ToString()
};
lookupModalControl.Attributes.Add("class", "lookup-modal");
container.Controls.Add(lookupModalControl);
}
Bindings[Metadata.DataFieldName] = new CellBinding
{
Get = () =>
{
Guid id;
return !Guid.TryParse(hiddenValue.Value, out id) || string.IsNullOrWhiteSpace(hiddenValueEntityName.Value) ||
!Metadata.LookupTargets.Contains(hiddenValueEntityName.Value)
? null
: new EntityReference(hiddenValueEntityName.Value, id);
},
Set = obj =>
{
var entityReference = (EntityReference)obj;
hiddenValue.Value = entityReference.Id.ToString();
textbox.Text = entityReference.Name ?? string.Empty;
hiddenValueEntityName.Value = entityReference.LogicalName;
}
};
}
/// <summary>
/// Initialize validator controls
/// </summary>
protected override void InstantiateValidatorsIn(Control container)
{
if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired)
{
container.Controls.Add(new HiddenFieldValidator
{
ID = string.Format("RequiredFieldValidator{0}", ControlID),
ControlToValidate = ControlID,
ValidationGroup = ValidationGroup,
Display = ValidatorDisplay,
ErrorMessage = ValidationSummaryMarkup((string.IsNullOrWhiteSpace(Metadata.RequiredFieldValidationErrorMessage) ? (Metadata.Messages == null || !Metadata.Messages.ContainsKey("required")) ? ResourceManager.GetString("Required_Field_Error").FormatWith(Metadata.Label) : Metadata.Messages["required"].FormatWith(Metadata.Label) : Metadata.RequiredFieldValidationErrorMessage)),
Text = Metadata.ValidationText,
});
}
this.InstantiateCustomValidatorsIn(container);
}
/// <summary>
/// Generate the HTML to render a modal lookup records dialog.
/// </summary>
protected virtual IHtmlString BuildLookupModal(Control container)
{
var html = Mvc.Html.EntityExtensions.GetHtmlHelper(Metadata.FormView.ContextName, container.Page.Request.RequestContext, container.Page.Response); //new HtmlHelper(new ViewContext(), new ViewPage());
var context = CrmConfigurationManager.CreateContext(Metadata.FormView.ContextName);
var portal = PortalCrmConfigurationManager.CreatePortalContext(Metadata.FormView.ContextName);
var user = portal == null ? null : portal.User;
var viewConfigurations = new List<ViewConfiguration>();
var defaultViewId = Metadata.LookupViewID;
var modalGridSearchPlaceholderText = html.SnippetLiteral("Portal/Lookup/Modal/Grid/Search/PlaceholderText");
var modalGridSearchTooltipText = html.SnippetLiteral("Portal/Lookup/Modal/Grid/Search/TooltipText");
var modalGridPageSize = html.IntegerSetting("Portal/Lookup/Modal/Grid/PageSize") ?? 10;
var modalSizeSetting = html.Setting("Portal/Lookup/Modal/Size");
var modalSize = BootstrapExtensions.BootstrapModalSize.Large;
if (modalSizeSetting != null && modalSizeSetting.ToLower() == "default") modalSize = BootstrapExtensions.BootstrapModalSize.Default;
if (modalSizeSetting != null && modalSizeSetting.ToLower() == "small") modalSize = BootstrapExtensions.BootstrapModalSize.Small;
var formEntityReferenceInfo = GetFormEntityReferenceInfo(container.Page.Request);
if (defaultViewId == Guid.Empty)
{
// By default a lookup field cell defined in the form XML does not contain view parameters unless the user has specified a view that is not the default for that entity and we must query to find the default view. Saved Query entity's QueryType code 64 indicates a lookup view.
viewConfigurations.AddRange(
Metadata.LookupTargets.Select(
target => new ViewConfiguration(new SavedQueryView(context, target, 64, true, Metadata.LanguageCode), modalGridPageSize)
{
Search = new ViewSearch(!Metadata.LookupDisableQuickFind) { PlaceholderText = modalGridSearchPlaceholderText, TooltipText = modalGridSearchTooltipText },
EnableEntityPermissions = Metadata.FormView.EnableEntityPermissions,
PortalName = Metadata.FormView.ContextName,
LanguageCode = Metadata.LanguageCode,
ModalLookupAttributeLogicalName = Metadata.DataFieldName,
ModalLookupEntityLogicalName = Metadata.TargetEntityName,
ModalLookupFormReferenceEntityId = formEntityReferenceInfo.Item2,
ModalLookupFormReferenceEntityLogicalName = formEntityReferenceInfo.Item1,
ModalLookupFormReferenceRelationshipName = formEntityReferenceInfo.Item3,
ModalLookupFormReferenceRelationshipRole = formEntityReferenceInfo.Item4
}));
}
else
{
viewConfigurations.Add(new ViewConfiguration(new SavedQueryView(context, defaultViewId, Metadata.LanguageCode), modalGridPageSize)
{
Search = new ViewSearch(!Metadata.LookupDisableQuickFind) { PlaceholderText = modalGridSearchPlaceholderText, TooltipText = modalGridSearchTooltipText },
EnableEntityPermissions = Metadata.FormView.EnableEntityPermissions,
PortalName = Metadata.FormView.ContextName,
LanguageCode = Metadata.LanguageCode,
ModalLookupAttributeLogicalName = Metadata.DataFieldName,
ModalLookupEntityLogicalName = Metadata.TargetEntityName,
ModalLookupFormReferenceEntityId = formEntityReferenceInfo.Item2,
ModalLookupFormReferenceEntityLogicalName = formEntityReferenceInfo.Item1,
ModalLookupFormReferenceRelationshipName = formEntityReferenceInfo.Item3,
ModalLookupFormReferenceRelationshipRole = formEntityReferenceInfo.Item4
});
}
if (!Metadata.LookupDisableViewPicker && !string.IsNullOrWhiteSpace(Metadata.LookupAvailableViewIds))
{
var addViewConfigurations = new List<ViewConfiguration>();
var viewids = Metadata.LookupAvailableViewIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (viewids.Length >= 1)
{
var viewGuids = Array.ConvertAll(viewids, Guid.Parse).AsEnumerable().OrderBy(o => o != defaultViewId).ThenBy(o => o).ToArray();
addViewConfigurations.AddRange(from viewGuid in viewGuids
from viewConfiguration in viewConfigurations
where viewConfiguration.ViewId != viewGuid
select new ViewConfiguration(new SavedQueryView(context, viewGuid, Metadata.LanguageCode), modalGridPageSize)
{
Search = new ViewSearch(!Metadata.LookupDisableQuickFind) { PlaceholderText = modalGridSearchPlaceholderText, TooltipText = modalGridSearchTooltipText },
EnableEntityPermissions = Metadata.FormView.EnableEntityPermissions,
PortalName = Metadata.FormView.ContextName,
LanguageCode = Metadata.LanguageCode,
ModalLookupAttributeLogicalName = Metadata.DataFieldName,
ModalLookupEntityLogicalName = Metadata.TargetEntityName,
ModalLookupFormReferenceEntityId = formEntityReferenceInfo.Item2,
ModalLookupFormReferenceEntityLogicalName = formEntityReferenceInfo.Item1,
ModalLookupFormReferenceRelationshipName = formEntityReferenceInfo.Item3,
ModalLookupFormReferenceRelationshipRole = formEntityReferenceInfo.Item4
});
}
viewConfigurations.AddRange(addViewConfigurations);
}
var applyRelatedRecordFilter = !string.IsNullOrWhiteSpace(Metadata.LookupFilterRelationshipName);
string filterFieldName = null;
if (!string.IsNullOrWhiteSpace(Metadata.LookupDependentAttributeName)) // entity.attribute (i.e. contact.adx_subject)
{
var pos = Metadata.LookupDependentAttributeName.IndexOf(".", StringComparison.InvariantCulture);
filterFieldName = pos >= 0
? Metadata.LookupDependentAttributeName.Substring(pos + 1)
: Metadata.LookupDependentAttributeName;
}
var modalTitle = html.SnippetLiteral("Portal/Lookup/Modal/Title");
var modalPrimaryButtonText = html.SnippetLiteral("Portal/Lookup/Modal/PrimaryButtonText");
var modalCancelButtonText = html.SnippetLiteral("Portal/Lookup/Modal/CancelButtonText");
var modalDismissButtonSrText = html.SnippetLiteral("Portal/Lookup/Modal/DismissButtonSrText");
var modalRemoveValueButtonText = html.SnippetLiteral("Portal/Lookup/Modal/RemoveValueButtonText");
var modalNewValueButtonText = html.SnippetLiteral("Portal/Lookup/Modal/NewValueButtonText");
var modalDefaultErrorMessage = html.SnippetLiteral("Portal/Lookup/Modal/DefaultErrorMessage");
var modalGridLoadingMessage = html.SnippetLiteral("Portal/Lookup/Modal/Grid/LoadingMessage");
var modalGridErrorMessage = html.SnippetLiteral("Portal/Lookup/Modal/Grid/ErrorMessage");
var modalGridAccessDeniedMessage = html.SnippetLiteral("Portal/Lookup/Modal/Grid/AccessDeniedMessage");
var modalGridEmptyMessage = html.SnippetLiteral("Portal/Lookup/Modal/Grid/EmptyMessage");
var modalGridToggleFilterText = html.SnippetLiteral("Portal/Lookup/Modal/Grid/ToggleFilterText");
return html.LookupModal(ControlID, viewConfigurations,
BuildControllerActionUrl("GetLookupGridData", "EntityGrid", new { area = "Portal", __portalScopeId__ = portal == null ? Guid.Empty : portal.Website.Id }), user, applyRelatedRecordFilter,
Metadata.LookupAllowFilterOff, Metadata.LookupFilterRelationshipName, Metadata.LookupDependentAttributeType,
filterFieldName, null, null, modalTitle, modalPrimaryButtonText, modalCancelButtonText, modalDismissButtonSrText,
modalRemoveValueButtonText, modalNewValueButtonText, null, null, modalGridLoadingMessage, modalGridErrorMessage, modalGridAccessDeniedMessage,
modalGridEmptyMessage, modalGridToggleFilterText, modalDefaultErrorMessage, null, null, null, Metadata.FormView.ContextName,
Metadata.LanguageCode, null, modalSize, Metadata.LookupReferenceEntityFormId, EvaluateCreatePrivilege(portal.ServiceContext),
ControlID == "entitlementid" ? BuildControllerActionUrl("GetDefaultEntitlements", "Entitlements", new { area = "CaseManagement", __portalScopeId__ = portal == null ? Guid.Empty : portal.Website.Id }) : null);
}
/// <summary>
/// Generates a URL to a controller action
/// </summary>
protected string BuildControllerActionUrl(string actionName, string controllerName, object routeValues)
{
var httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
var routeData = RouteTable.Routes.GetRouteData(httpContextWrapper) ?? new RouteData();
var urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, routeData));
return urlHelper.Action(actionName, controllerName, routeValues);
}
/// <summary>
/// Evaluating whether user has create privilege or not
/// <param name="serviceContext">serviceContext</param>
/// <returns>True if user has create Privilege otherwise returns False</returns>
/// </summary>
protected bool EvaluateCreatePrivilege(OrganizationServiceContext serviceContext)
{
bool hasCreatePrivilege = false;
if (Metadata.LookupReferenceEntityFormId != null)
{
var entityForm = serviceContext.RetrieveSingle(
"adx_entityform",
new[] { "adx_entityname", "adx_mode" },
new[] {
new Condition("adx_entityformid", ConditionOperator.Equal, Metadata.LookupReferenceEntityFormId),
new Condition("statuscode", ConditionOperator.NotNull),
new Condition("statuscode", ConditionOperator.Equal, (int)Enums.EntityFormStatusCode.Active)
});
if (entityForm != null)
{
var entityLogicalName = entityForm.GetAttributeValue<string>("adx_entityname");
var mode = entityForm.GetAttributeValue<OptionSetValue>("adx_mode");
if ((mode.Value == (int)WebFormStepMode.Insert) && (Metadata.LookupTargets.Contains(entityLogicalName))) // Insert
{
var crmEntityPermissionProvider = new CrmEntityPermissionProvider();
hasCreatePrivilege = crmEntityPermissionProvider.TryAssert(serviceContext, CrmEntityPermissionRight.Create, entityLogicalName);
return hasCreatePrivilege;
}
else { return hasCreatePrivilege; }
}
else { return hasCreatePrivilege; }
}
else { return hasCreatePrivilege; }
}
private static Tuple<string, Guid?, string, string> GetFormEntityReferenceInfo(HttpRequest request)
{
var entityLogicalName = request["refentity"];
Guid parsedEntityId;
var entityId = Guid.TryParse(request["refid"], out parsedEntityId)
? new Guid?(parsedEntityId)
: null;
var relationshipName = request["refrel"];
var relationshipRole = request["refrelrole"];
return new Tuple<string, Guid?, string, string>(entityLogicalName, entityId, relationshipName, relationshipRole);
}
}
}
| |
// 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.ComponentModel.Composition.Primitives;
using System.Linq;
using Microsoft.Internal.Collections;
namespace System.ComponentModel.Composition.Hosting
{
public partial class ImportEngine
{
/// <summary>
/// Used by the <see cref="ImportEngine"/> to manage the composition of a given part.
/// It stores things like the list of disposable exports used to satisfy the imports as
/// well as the caching of the exports discovered during previewing of a part.
/// </summary>
private class PartManager
{
private Dictionary<ImportDefinition, List<IDisposable>> _importedDisposableExports;
private Dictionary<ImportDefinition, Export[]> _importCache;
private string[] _importedContractNames;
private ComposablePart _part;
private ImportState _state = ImportState.NoImportsSatisfied;
private readonly ImportEngine _importEngine;
public PartManager(ImportEngine importEngine, ComposablePart part)
{
_importEngine = importEngine;
_part = part;
}
public ComposablePart Part
{
get
{
return _part;
}
}
public ImportState State
{
get
{
using (_importEngine._lock.LockStateForRead())
{
return _state;
}
}
set
{
using (_importEngine._lock.LockStateForWrite())
{
_state = value;
}
}
}
public bool TrackingImports { get; set; }
public IEnumerable<string> GetImportedContractNames()
{
if (Part == null)
{
return Enumerable.Empty<string>();
}
if (_importedContractNames == null)
{
_importedContractNames = Part.ImportDefinitions.Select(import => import.ContractName ?? ImportDefinition.EmptyContractName).Distinct().ToArray();
}
return _importedContractNames;
}
public CompositionResult TrySetImport(ImportDefinition import, Export[] exports)
{
try
{
Part.SetImport(import, exports);
UpdateDisposableDependencies(import, exports);
return CompositionResult.SucceededResult;
}
catch (CompositionException ex)
{ // Pulling on one of the exports failed
return new CompositionResult(
ErrorBuilder.CreatePartCannotSetImport(Part, import, ex));
}
catch (ComposablePartException ex)
{ // Type mismatch between export and import
return new CompositionResult(
ErrorBuilder.CreatePartCannotSetImport(Part, import, ex));
}
}
public void SetSavedImport(ImportDefinition import, Export[] exports, AtomicComposition atomicComposition)
{
if (atomicComposition != null)
{
var savedExports = GetSavedImport(import);
// Add a revert action to revert the stored exports
// in the case that this atomicComposition gets rolled back.
atomicComposition.AddRevertAction(() =>
SetSavedImport(import, savedExports, null));
}
if (_importCache == null)
{
_importCache = new Dictionary<ImportDefinition, Export[]>();
}
_importCache[import] = exports;
}
public Export[] GetSavedImport(ImportDefinition import)
{
Export[] exports = null;
if (_importCache != null)
{
// We don't care about the return value we just want the exports
// and if it isn't present we just return the initialized null value
_importCache.TryGetValue(import, out exports);
}
return exports;
}
public void ClearSavedImports()
{
_importCache = null;
}
public CompositionResult TryOnComposed()
{
try
{
Part.Activate();
return CompositionResult.SucceededResult;
}
catch (ComposablePartException ex)
{ // Type failed to be constructed, imports could not be set, etc
return new CompositionResult(
ErrorBuilder.CreatePartCannotActivate(Part, ex));
}
}
public void UpdateDisposableDependencies(ImportDefinition import, Export[] exports)
{
// Determine if there are any new disposable exports, optimizing for the most
// likely case, which is that there aren't any
List<IDisposable> disposableExports = null;
foreach (var export in exports)
{
IDisposable disposableExport = export as IDisposable;
if (disposableExport != null)
{
if (disposableExports == null)
{
disposableExports = new List<IDisposable>();
}
disposableExports.Add(disposableExport);
}
}
// Dispose any existing references previously set on this import
List<IDisposable> oldDisposableExports = null;
if (_importedDisposableExports != null &&
_importedDisposableExports.TryGetValue(import, out oldDisposableExports))
{
oldDisposableExports.ForEach(disposable => disposable.Dispose());
// If there aren't any replacements, get rid of the old storage
if (disposableExports == null)
{
_importedDisposableExports.Remove(import);
if (!_importedDisposableExports.FastAny())
{
_importedDisposableExports = null;
}
return;
}
}
// Record the new collection
if (disposableExports != null)
{
if (_importedDisposableExports == null)
{
_importedDisposableExports = new Dictionary<ImportDefinition, List<IDisposable>>();
}
_importedDisposableExports[import] = disposableExports;
}
}
public void DisposeAllDependencies()
{
if (_importedDisposableExports != null)
{
IEnumerable<IDisposable> dependencies = _importedDisposableExports.Values
.SelectMany(exports => exports);
_importedDisposableExports = null;
dependencies.ForEach(disposableExport => disposableExport.Dispose());
}
}
}
}
}
| |
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 NurseReporting.Web.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;
}
}
}
| |
/*``The contents of this file are subject to the Erlang Public License,
* Version 1.1, (the "License"); you may not use this file except in
* compliance with the License. You should have received a copy of the
* Erlang Public License along with this software. If not, it can be
* retrieved via the world wide web at http://www.erlang.org/.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* The Initial Developer of the Original Code is Ericsson Utvecklings AB.
* Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
* AB. All Rights Reserved.''
*
* Converted from Java to C# by Vlad Dumitrescu (vlad_Dumitrescu@hotmail.com)
*/
namespace Otp
{
using System;
/*
* Provides a stream for decoding Erlang terms from external format.
*
* <p> Note that this class is not synchronized, if you need
* synchronization you must provide it yourself.
**/
public class OtpInputStream:System.IO.MemoryStream
{
/*
* Create a stream from a buffer containing encoded Erlang terms.
**/
public OtpInputStream(byte[] buf):base(buf)
{
}
/*
* Create a stream from a buffer containing encoded
* Erlang terms at the given offset and length.
**/
public OtpInputStream(byte[] buf, int offset, int length):base(buf, offset, length)
{
}
/*
* Get the current position in the stream.
*
* @return the current position in the stream.
**/
public virtual int getPos()
{
return (int) base.Position;
}
/*
* Set the current position in the stream.
*
* @param pos the position to move to in the stream. If pos
* indicates a position beyond the end of the stream, the position
* is move to the end of the stream instead. If pos is negative, the
* position is moved to the beginning of the stream instead.
*
* @return the previous position in the stream.
**/
public virtual int setPos(int pos)
{
int oldpos = (int) base.Position;
if (pos > (int) base.Length)
pos = (int) base.Length;
else if (pos < 0)
pos = 0;
base.Position = (System.Int64) pos;
return oldpos;
}
/*
* Read an array of bytes from the stream. The method reads at most
* buf.length bytes from the input stream.
*
* @return the number of bytes read.
*
* @exception OtpErlangDecodeException if the next byte cannot be
* read.
**/
public virtual int readN(byte[] buf)
{
try
{
return base.Read(buf, 0, buf.Length);
}
catch (System.IO.IOException)
{
throw new Erlang.DecodeException("Cannot read from input stream");
}
}
/*
* Look ahead one position in the stream without consuming the byte
* found there.
*
* @return the next byte in the stream, as an integer.
*
* @exception Erlang.DecodeException if the next byte cannot be
* read.
**/
public virtual int peek()
{
int i;
try
{
i = base.ReadByte();
base.Seek(-1, System.IO.SeekOrigin.Current);
if (i < 0)
i += 256;
return i;
}
catch (System.Exception)
{
throw new Erlang.DecodeException("Cannot read from input stream");
}
}
/*
* Read a one byte integer from the stream.
*
* @return the byte read, as an integer.
*
* @exception Erlang.DecodeException if the next byte cannot be
* read.
**/
public virtual int read1()
{
int i;
i = base.ReadByte();
if (i < 0)
{
throw new Erlang.DecodeException("Cannot read from input stream");
}
return i;
}
/*
* Read a two byte big endian integer from the stream.
*
* @return the bytes read, converted from big endian to an integer.
*
* @exception Erlang.DecodeException if the next byte cannot be
* read.
**/
public virtual int read2BE()
{
byte[] b = new byte[2];
try
{
base.Read(b, 0, b.Length);
}
catch (System.IO.IOException)
{
throw new Erlang.DecodeException("Cannot read from input stream");
}
return ((((int) b[0] << 8) & 0xff00) + (((int) b[1]) & 0xff));
}
/*
* Read a four byte big endian integer from the stream.
*
* @return the bytes read, converted from big endian to an integer.
*
* @exception Erlang.DecodeException if the next byte cannot be
* read.
**/
public virtual int read4BE()
{
byte[] b = new byte[4];
try
{
base.Read(b, 0, b.Length);
}
catch (System.IO.IOException)
{
throw new Erlang.DecodeException("Cannot read from input stream");
}
return (int)((((int) b[0] << 24) & 0xff000000) + (((int) b[1] << 16) & 0xff0000) + (((int) b[2] << 8) & 0xff00) + (((int) b[3]) & 0xff));
}
/*
* Read an eight byte big endian integer from the stream.
*
* @return the bytes read, converted from big endian to an integer.
*
* @exception Erlang.DecodeException if the next byte cannot be
* read.
**/
public System.UInt64 read8BE()
{
byte[] b = new byte[8];
try
{
base.Read(b, 0, b.Length);
}
catch (System.IO.IOException)
{
throw new Erlang.DecodeException("Cannot read from input stream");
}
System.UInt64 i1 = (System.UInt64)((((int)b[0] << 24) & 0xff000000) + (((int)b[1] << 16) & 0xff0000) + (((int)b[2] << 8) & 0xff00) + (((int)b[3]) & 0xff));
System.UInt64 i2 = (i1 << 32) & 0xffffffff00000000
+ (System.UInt64)((((int)b[4] << 24) & 0xff000000) + (((int)b[5] << 16) & 0xff0000) + (((int)b[6] << 8) & 0xff00) + (((int)b[7]) & 0xff));
return i2;
}
/*
* Read a two byte little endian integer from the stream.
*
* @return the bytes read, converted from little endian to an
* integer.
*
* @exception Erlang.DecodeException if the next byte cannot be
* read.
**/
public virtual int read2LE()
{
byte[] b = new byte[2];
try
{
base.Read(b, 0, b.Length);
}
catch (System.IO.IOException)
{
throw new Erlang.DecodeException("Cannot read from input stream");
}
return ((((int) b[1] << 8) & 0xff00) + (((int) b[0]) & 0xff));
}
/*
* Read a four byte little endian integer from the stream.
*
* @return the bytes read, converted from little endian to an
* integer.
*
* @exception Erlang.DecodeException if the next byte cannot be
* read.
**/
public virtual int read4LE()
{
byte[] b = new byte[4];
try
{
base.Read(b, 0, b.Length);
}
catch (System.IO.IOException)
{
throw new Erlang.DecodeException("Cannot read from input stream");
}
return (int)((((int) b[3] << 24) & 0xff000000) + (((int) b[2] << 16) & 0xff0000) + (((int) b[1] << 8) & 0xff00) + (((int) b[0]) & 0xff));
}
/*
* Read an Erlang atom from the stream and interpret the value as a
* boolean.
*
* @return true if the atom at the current position in the stream
* contains the value 'true' (ignoring case), false otherwise.
*
* @exception Erlang.DecodeException if the next term in the
* stream is not an atom.
**/
public virtual bool read_boolean()
{
return System.Boolean.Parse(this.read_atom());
}
/*
* Read an Erlang atom from the stream.
*
* @return a String containing the value of the atom.
*
* @exception Erlang.DecodeException if the next term in the
* stream is not an atom.
**/
public virtual System.String read_atom()
{
int tag;
int len;
byte[] strbuf;
System.String atom;
tag = this.read1();
if (tag == OtpExternal.versionTag)
{
tag = this.read1();
}
if (tag != OtpExternal.atomTag)
{
throw new Erlang.DecodeException("wrong tag encountered, expected " + OtpExternal.atomTag + ", got " + tag);
}
len = this.read2BE();
strbuf = new byte[len];
this.readN(strbuf);
char[] tmpChar;
tmpChar = new char[strbuf.Length];
strbuf.CopyTo(tmpChar, 0);
atom = new System.String(tmpChar);
if (atom.Length > OtpExternal.maxAtomLength)
{
atom = atom.Substring(0, (OtpExternal.maxAtomLength) - (0));
}
return atom;
}
/*
* Read an Erlang binary from the stream.
*
* @return a byte array containing the value of the binary.
*
* @exception Erlang.DecodeException if the next term in the
* stream is not a binary.
**/
public virtual byte[] read_binary()
{
int tag;
int len;
byte[] bin;
tag = this.read1();
if (tag == OtpExternal.versionTag)
{
tag = this.read1();
}
if (tag != OtpExternal.binTag)
{
throw new Erlang.DecodeException("Wrong tag encountered, expected " + OtpExternal.binTag + ", got " + tag);
}
len = this.read4BE();
bin = new byte[len];
this.readN(bin);
return bin;
}
/*
* Read an Erlang float from the stream.
*
* @return the float value.
*
* @exception Erlang.DecodeException if the next term in the
* stream is not a float.
**/
public virtual float read_float()
{
double d = this.read_double();
float f = (float)d;
if (System.Math.Abs(d - f) >= 1.0E-20)
throw new Erlang.DecodeException("Value cannot be represented as float: " + d);
return f;
}
/*
* Read an Erlang float from the stream.
*
* @return the float value, as a double.
*
* @exception Erlang.DecodeException if the next term in the
* stream is not a float.
*
**/
public virtual double read_double()
{
return getFloatOrDouble();
}
private double getFloatOrDouble()
{
// parse the stream
int tag = this.read1();
if (tag == OtpExternal.versionTag)
{
tag = this.read1();
}
byte[] strbuf;
double parsedValue = 0.0;
if (tag == OtpExternal.floatTag)
{
// get the string
strbuf = new byte[31];
this.readN(strbuf);
char[] tmpChar = new char[strbuf.Length];
strbuf.CopyTo(tmpChar, 0);
System.String str = new System.String(tmpChar);
//System.Diagnostics.Debug.WriteLine("getFloatOrDouble: str = " + str);
try
{
// Easier than the java version.
parsedValue = System.Double.Parse(str);
return parsedValue;
}
catch
{
throw new Erlang.DecodeException("Error parsing float format: '" + str + "'");
}
}
else if (tag == OtpExternal.newFloatTag)
{
byte[] data = new byte[8];
this.readN(data);
// IEEE 754 decoder
if (BitConverter.IsLittleEndian)
{
Array.Reverse(data);
}
return BitConverter.ToDouble(data, 0);
}
else
{
throw new Erlang.DecodeException("Wrong tag encountered, expected " + OtpExternal.floatTag + ", got " + tag);
}
}
/*
* Read one byte from the stream.
*
* @return the byte read.
*
* @exception Erlang.DecodeException if the next byte cannot be
* read.
**/
public virtual byte read_byte()
{
long l = this.read_long();
byte i = (byte) l;
if (l != i)
{
throw new Erlang.DecodeException("Value too large for byte: " + l);
}
return i;
}
/*
* Read a character from the stream.
*
* @return the character value.
*
* @exception Erlang.DecodeException if the next term in the
* stream is not an integer that can be represented as a char.
**/
public virtual char read_char()
{
long l = this.read_long();
char i = (char) l;
if (l != i)
{
throw new Erlang.DecodeException("Value too large for byte: " + l);
}
return i;
}
/*
* Read an unsigned integer from the stream.
*
* @return the integer value.
*
* @exception Erlang.DecodeException if the next term in the
* stream can not be represented as a positive integer.
**/
public virtual int read_uint()
{
long l = this.read_long();
int i = (int) l;
if (l != i)
{
throw new Erlang.DecodeException("Value too large for integer: " + l);
}
else if (l < 0)
{
throw new Erlang.DecodeException("Value not unsigned: " + l);
}
return i;
}
/*
* Read an integer from the stream.
*
* @return the integer value.
*
* @exception Erlang.DecodeException if the next term in the
* stream can not be represented as an integer.
**/
public virtual int read_int()
{
long l = this.read_long();
int i = (int) l;
if (l != i)
{
throw new Erlang.DecodeException("Value too large for byte: " + l);
}
return i;
}
/*
* Read an unsigned short from the stream.
*
* @return the short value.
*
* @exception Erlang.DecodeException if the next term in the
* stream can not be represented as a positive short.
**/
public virtual short read_ushort()
{
long l = this.read_long();
short i = (short) l;
if (l != i)
{
throw new Erlang.DecodeException("Value too large for byte: " + l);
}
else if (l < 0)
{
throw new Erlang.DecodeException("Value not unsigned: " + l);
}
return i;
}
/*
* Read a short from the stream.
*
* @return the short value.
*
* @exception Erlang.DecodeException if the next term in the
* stream can not be represented as a short.
**/
public virtual short read_short()
{
long l = this.read_long();
short i = (short) l;
if (l != i)
{
throw new Erlang.DecodeException("Value too large for byte: " + l);
}
return i;
}
/*
* Read an unsigned long from the stream.
*
* @return the long value.
*
* @exception Erlang.DecodeException if the next term in the
* stream can not be represented as a positive long.
**/
public virtual long read_ulong()
{
long l = this.read_long();
if (l < 0)
{
throw new Erlang.DecodeException("Value not unsigned: " + l);
}
return l;
}
/*
* Read a long from the stream.
*
* @return the long value.
*
* @exception Erlang.DecodeException if the next term in the
* stream can not be represented as a long.
**/
public virtual long read_long()
{
int tag;
int sign;
int arity;
long val;
tag = this.read1();
if (tag == OtpExternal.versionTag)
{
tag = this.read1();
}
switch (tag)
{
case OtpExternal.smallIntTag:
val = this.read1();
break;
case OtpExternal.intTag:
val = this.read4BE();
break;
case OtpExternal.smallBigTag: {
arity = this.read1();
sign = this.read1();
byte[] nb = new byte[arity];
if (arity != this.readN(nb))
{
throw new Erlang.DecodeException("Cannot read from input stream. Expected smallBigTag arity " + arity);
}
if (arity > 8)
throw new Erlang.DecodeException("Value too large for long type (arity=" + arity + ")");
val = 0;
for (int i = 0; i < arity; i++)
{
val |= (long)nb[i] << (i * 8);
}
val = (sign == 0 ? val : -val); // should deal with overflow
break;
}
case OtpExternal.largeBigTag: default:
throw new Erlang.DecodeException("Not valid integer tag: " + tag);
}
return val;
}
/*
* Read a list header from the stream.
*
* @return the arity of the list.
*
* @exception Erlang.DecodeException if the next term in the
* stream is not a list.
**/
public virtual int read_list_head()
{
int arity = 0;
int tag = this.read1();
if (tag == OtpExternal.versionTag)
{
tag = this.read1();
}
switch (tag)
{
case OtpExternal.nilTag:
arity = 0;
break;
case OtpExternal.stringTag:
arity = this.read2BE();
break;
case OtpExternal.listTag:
arity = this.read4BE();
break;
default:
throw new Erlang.DecodeException("Not valid list tag: " + tag);
}
return arity;
}
/*
* Read a tuple header from the stream.
*
* @return the arity of the tuple.
*
* @exception Erlang.DecodeException if the next term in the
* stream is not a tuple.
**/
public virtual int read_tuple_head()
{
int arity = 0;
int tag = this.read1();
if (tag == OtpExternal.versionTag)
{
tag = this.read1();
}
// decode the tuple header and get arity
switch (tag)
{
case OtpExternal.smallTupleTag:
arity = this.read1();
break;
case OtpExternal.largeTupleTag:
arity = this.read4BE();
break;
default:
throw new Erlang.DecodeException("Not valid tuple tag: " + tag);
}
return arity;
}
/*
* Read an empty list from the stream.
*
* @return zero (the arity of the list).
*
* @exception Erlang.DecodeException if the next term in the
* stream is not an empty list.
**/
public virtual int read_nil()
{
int arity = 0;
int tag = this.read1();
if (tag == OtpExternal.versionTag)
{
tag = this.read1();
}
switch (tag)
{
case OtpExternal.nilTag:
arity = 0;
break;
default:
throw new Erlang.DecodeException("Not valid nil tag: " + tag);
}
return arity;
}
/*
* Read an Erlang PID from the stream.
*
* @return the value of the PID.
*
* @exception Erlang.DecodeException if the next term in the
* stream is not an Erlang PID.
**/
public virtual Erlang.Pid read_pid()
{
System.String node;
int id;
int serial;
int creation;
int tag;
tag = this.read1();
if (tag == OtpExternal.versionTag)
{
tag = this.read1();
}
if (tag != OtpExternal.pidTag)
{
throw new Erlang.DecodeException("Wrong tag encountered, expected " + OtpExternal.pidTag + ", got " + tag);
}
node = this.read_atom();
id = this.read4BE() & 0x7fff; // 15 bits
serial = this.read4BE() & 0x07; // 3 bits
creation = this.read1() & 0x03; // 2 bits
return new Erlang.Pid(node, id, serial, creation);
}
/*
* Read an Erlang port from the stream.
*
* @return the value of the port.
*
* @exception DecodeException if the next term in the
* stream is not an Erlang port.
**/
public virtual Erlang.Port read_port()
{
System.String node;
int id;
int creation;
int tag;
tag = this.read1();
if (tag == OtpExternal.versionTag)
{
tag = this.read1();
}
if (tag != OtpExternal.portTag)
{
throw new Erlang.DecodeException("Wrong tag encountered, expected " + OtpExternal.portTag + ", got " + tag);
}
node = this.read_atom();
id = this.read4BE() & 0x3ffff; // 18 bits
creation = this.read1() & 0x03; // 2 bits
return new Erlang.Port(node, id, creation);
}
/*
* Read an Erlang reference from the stream.
*
* @return the value of the reference
*
* @exception DecodeException if the next term in the
* stream is not an Erlang reference.
**/
public virtual Erlang.Ref read_ref()
{
System.String node;
int id;
int creation;
int tag;
tag = this.read1();
if (tag == OtpExternal.versionTag)
{
tag = this.read1();
}
switch (tag)
{
case OtpExternal.refTag:
node = this.read_atom();
id = this.read4BE() & 0x3ffff; // 18 bits
creation = this.read1() & 0x03; // 2 bits
return new Erlang.Ref(node, id, creation);
case OtpExternal.newRefTag:
int arity = this.read2BE();
node = this.read_atom();
creation = this.read1() & 0x03; // 2 bits
int[] ids = new int[arity];
for (int i = 0; i < arity; i++)
{
ids[i] = this.read4BE();
}
ids[0] &= 0x3ffff; // first id gets truncated to 18 bits
return new Erlang.Ref(node, ids, creation);
default:
throw new Erlang.DecodeException("Wrong tag encountered, expected ref, got " + tag);
}
}
/*
* Read a string from the stream.
*
* @return the value of the string.
*
* @exception DecodeException if the next term in the
* stream is not a string.
**/
public virtual System.String read_string()
{
int tag;
int len;
byte[] strbuf;
char[] charbuf;
tag = this.read1();
if (tag == OtpExternal.versionTag)
{
tag = this.read1();
}
switch (tag)
{
case OtpExternal.stringTag:
char[] tmpChar;
len = this.read2BE();
strbuf = new byte[len];
this.readN(strbuf);
tmpChar = new char[strbuf.Length];
strbuf.CopyTo(tmpChar, 0);
return new System.String(tmpChar);
case OtpExternal.nilTag:
return "";
case OtpExternal.listTag:
// List when unicode +
len = this.read4BE();
charbuf = new char[len];
for (int i = 0; i < len; i++)
charbuf[i] = this.read_char();
this.read_nil();
return new System.String(charbuf);
default:
throw new Erlang.DecodeException("Wrong tag encountered, expected " + OtpExternal.stringTag + " or " + OtpExternal.listTag + ", got " + tag);
}
}
/*
* Read an arbitrary Erlang term from the stream.
*
* @return the Erlang term.
*
* @exception DecodeException if the stream does not
* contain a known Erlang type at the next position.
**/
public virtual Erlang.Object read_any()
{
// calls one of the above functions, depending on o
int tag = this.peek();
if (tag == OtpExternal.versionTag)
{
this.read1();
tag = this.peek();
}
//System.Diagnostics.Debug.WriteLine("read_any: tag = " + tag);
switch (tag)
{
case OtpExternal.smallIntTag: case OtpExternal.intTag: case OtpExternal.smallBigTag:
return new Erlang.Long(this);
case OtpExternal.atomTag:
return new Erlang.Atom(this);
case OtpExternal.floatTag:
case OtpExternal.newFloatTag:
return new Erlang.Double(this);
case OtpExternal.refTag: case OtpExternal.newRefTag:
return new Erlang.Ref(this);
case OtpExternal.portTag:
return new Erlang.Port(this);
case OtpExternal.pidTag:
return new Erlang.Pid(this);
case OtpExternal.stringTag:
return new Erlang.String(this);
case OtpExternal.listTag: case OtpExternal.nilTag:
return new Erlang.List(this);
case OtpExternal.smallTupleTag: case OtpExternal.largeTupleTag:
return new Erlang.Tuple(this);
case OtpExternal.binTag:
return new Erlang.Binary(this);
case OtpExternal.largeBigTag: default:
throw new Erlang.DecodeException("Uknown data type: " + tag);
}
}
}
}
| |
#region Header
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Copyright (c) 2007-2008 James Nies and NArrange contributors.
* All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the Common Public License v1.0 which accompanies this
* distribution.
*
* 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.
*
* 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.
*
*<author>James Nies</author>
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#endregion Header
namespace NArrange.Gui.Configuration
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using NArrange.Core.Configuration;
/// <summary>
/// Custom type descriptor provider for the CodeConfiguration class.
/// </summary>
public sealed class ConfigurationElementTypeDescriptionProvider : TypeDescriptionProvider
{
#region Fields
/// <summary>
/// Base type descriptor provider.
/// </summary>
private TypeDescriptionProvider _baseProvider;
#endregion Fields
#region Constructors
/// <summary>
/// Creates a new ConfigurationElementTypeDescriptionProvider.
/// </summary>
/// <param name="type">Type to get property descriptions for.</param>
public ConfigurationElementTypeDescriptionProvider(Type type)
{
_baseProvider = TypeDescriptor.GetProvider(type);
}
#endregion Constructors
#region Methods
/// <summary>
/// Create and return the custom type descriptor and chain it with the original
/// custom type descriptor.
/// </summary>
/// <param name="objectType">The type of object for which to retrieve the type descriptor.</param>
/// <param name="instance">An instance of the type. Can be null if no instance was passed to the <see cref="T:System.ComponentModel.TypeDescriptor"></see>.</param>
/// <returns>
/// An <see cref="T:System.ComponentModel.ICustomTypeDescriptor"></see> that can provide metadata for the type.
/// </returns>
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
{
return new CodeConfigurationTypeDescriptor(_baseProvider.GetTypeDescriptor(objectType, instance));
}
#endregion Methods
#region Nested Types
/// <summary>
/// Custom type descriptor. It creates a new property and returns it along
/// with the original list.
/// </summary>
private sealed class CodeConfigurationTypeDescriptor : CustomTypeDescriptor
{
#region Constructors
/// <summary>
/// Creates a new type descriptor using the specified parent.
/// </summary>
/// <param name="parent">The parent custom type descriptor.</param>
internal CodeConfigurationTypeDescriptor(ICustomTypeDescriptor parent)
: base(parent)
{
}
#endregion Constructors
#region Methods
/// <summary>
/// Gets the PropertyDescriptors for the Type.
/// </summary>
/// <param name="attributes">An array of attributes to use as a filter. This can be null.</param>
/// <returns>
/// A <see cref="T:System.ComponentModel.PropertyDescriptorCollection"></see> containing the property descriptions for the object represented by this type descriptor. The default is <see cref="F:System.ComponentModel.PropertyDescriptorCollection.Empty"></see>.
/// </returns>
/// <remarks>
/// All ConfigurationElementCollection properties are overriden to specify the
/// collection editor.
/// </remarks>
public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
// Enumerate the original set of properties and create our new set with it
PropertyDescriptorCollection originalProperties = base.GetProperties(attributes);
List<PropertyDescriptor> newProperties = new List<PropertyDescriptor>();
foreach (PropertyDescriptor originalProperty in originalProperties)
{
if (originalProperty.PropertyType == typeof(ConfigurationElementCollection))
{
newProperties.Add(new ElementCollectionPropertyDescriptor(originalProperty));
}
else
{
newProperties.Add(originalProperty);
}
}
// Finally return the list
return new PropertyDescriptorCollection(newProperties.ToArray());
}
/// <summary>
/// This method add a new property to the original collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.ComponentModel.PropertyDescriptorCollection"></see> containing the property descriptions for the object represented by this type descriptor. The default is <see cref="F:System.ComponentModel.PropertyDescriptorCollection.Empty"></see>.
/// </returns>
public override PropertyDescriptorCollection GetProperties()
{
return this.GetProperties(null);
}
#endregion Methods
}
/// <summary>
/// Elements property descriptor.
/// </summary>
private class ElementCollectionPropertyDescriptor : PropertyDescriptor
{
#region Fields
/// <summary>
/// Original, reflected property.
/// </summary>
private PropertyDescriptor _originalProperty;
#endregion Fields
#region Constructors
/// <summary>
/// Creates a new ElementCollectionPropertyDescriptor.
/// </summary>
/// <param name="originalProperty">The original property.</param>
public ElementCollectionPropertyDescriptor(PropertyDescriptor originalProperty)
: base(originalProperty, new Attribute[] { })
{
_originalProperty = originalProperty;
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets the type of the component for which this property belongs.
/// </summary>
public override Type ComponentType
{
get
{
return _originalProperty.ComponentType;
}
}
/// <summary>
/// Gets a value indicating whether or not this property is read-only.
/// </summary>
public override bool IsReadOnly
{
get
{
return _originalProperty.IsReadOnly;
}
}
/// <summary>
/// Gets the Type of this property.
/// </summary>
public override Type PropertyType
{
get
{
return _originalProperty.PropertyType;
}
}
#endregion Properties
#region Methods
/// <summary>
/// Gets a value indicating whether or not the properties value can be
/// reset for the specified component.
/// </summary>
/// <param name="component">The component to test for reset capability.</param>
/// <returns>
/// true if resetting the component changes its value; otherwise, false.
/// </returns>
public override bool CanResetValue(object component)
{
return _originalProperty.CanResetValue(component);
}
/// <summary>
/// Gets the editor for this property.
/// </summary>
/// <param name="editorBaseType">The base type of editor, which is used to differentiate between multiple editors that a property supports.</param>
/// <returns>
/// An instance of the requested editor type, or null if an editor cannot be found.
/// </returns>
public override object GetEditor(Type editorBaseType)
{
return new ConfigurationElementCollectionEditor(_originalProperty.PropertyType);
}
/// <summary>
/// Gets the property value for the specified component.
/// </summary>
/// <param name="component">The component with the property for which to retrieve the value.</param>
/// <returns>
/// The value of a property for a given component.
/// </returns>
public override object GetValue(object component)
{
return _originalProperty.GetValue(component);
}
/// <summary>
/// Resets the value for this property.
/// </summary>
/// <param name="component">The component with the property value that is to be reset to the default value.</param>
public override void ResetValue(object component)
{
_originalProperty.ResetValue(component);
}
/// <summary>
/// Sets the value for this property.
/// </summary>
/// <param name="component">The component with the property value that is to be set.</param>
/// <param name="value">The new value.</param>
public override void SetValue(object component, object value)
{
_originalProperty.SetValue(component, value);
}
/// <summary>
/// Gets a value indicating whether the property should be
/// serialized by designers.
/// </summary>
/// <param name="component">The component with the property to be examined for persistence.</param>
/// <returns>
/// true if the property should be persisted; otherwise, false.
/// </returns>
public override bool ShouldSerializeValue(object component)
{
return _originalProperty.ShouldSerializeValue(component);
}
#endregion Methods
}
#endregion Nested Types
}
}
| |
/*
** Copyright (c) Microsoft. All rights reserved.
** Licensed under the MIT license.
** See LICENSE file in the project root for full license information.
**
** This program was translated to C# and adapted for xunit-performance.
** New variants of several tests were added to compare class versus
** struct and to compare jagged arrays vs multi-dimensional arrays.
*/
/*
** BYTEmark (tm)
** BYTE Magazine's Native Mode benchmarks
** Rick Grehan, BYTE Magazine
**
** Create:
** Revision: 3/95
**
** DISCLAIMER
** The source, executable, and documentation files that comprise
** the BYTEmark benchmarks are made available on an "as is" basis.
** This means that we at BYTE Magazine have made every reasonable
** effort to verify that the there are no errors in the source and
** executable code. We cannot, however, guarantee that the programs
** are error-free. Consequently, McGraw-HIll and BYTE Magazine make
** no claims in regard to the fitness of the source code, executable
** code, and documentation of the BYTEmark.
**
** Furthermore, BYTE Magazine, McGraw-Hill, and all employees
** of McGraw-Hill cannot be held responsible for any damages resulting
** from the use of this code or the results obtained from using
** this code.
*/
using Microsoft.Xunit.Performance;
using System;
using System.IO;
[assembly: OptimizeForBenchmarks]
[assembly: MeasureInstructionsRetired]
internal class global
{
// Following should be modified accordingly per each compilation.
public const String SysName = "Generic 486/Pentium";
public const String CompilerName = "CoreCLR";
public const String CompilerVersion = "ver 0.0";
public static long min_ticks;
public static int min_secs;
public static bool allstats;
public static String ofile_name; // Output file name
public static StreamWriter ofile; // Output file
public static bool custrun; // Custom run flag
public static bool write_to_file; // Write output to file
public static int align; // Memory alignment
/*
** Following are global structures, one built for
** each of the tests.
*/
public static SortStruct numsortstruct_jagged; // For numeric sort
public static SortStruct numsortstruct_rect; // For numeric sort
public static StringSort strsortstruct; // For string sort
public static BitOpStruct bitopstruct; // For bitfield ops
public static EmFloatStruct emfloatstruct_struct; // For emul. float. pt.
public static EmFloatStruct emfloatstruct_class; // For emul. float. pt.
public static FourierStruct fourierstruct; // For fourier test
public static AssignStruct assignstruct_jagged; // For assignment algs
public static AssignStruct assignstruct_rect; // For assignment algs
public static IDEAStruct ideastruct; // For IDEA encryption
public static HuffStruct huffstruct; // For Huffman compression
public static NNetStruct nnetstruct_jagged; // For Neural Net
public static NNetStruct nnetstruct_rect; // For Neural Net
public static LUStruct lustruct; // For LU decomposition
public const long TICKS_PER_SEC = 1000;
public const long MINIMUM_TICKS = 60; // 60 msecs
#if DEBUG
public const int MINIMUM_SECONDS = 1;
#else
public const int MINIMUM_SECONDS = 1;
#endif
public const int NUMNUMARRAYS = 1000;
public const int NUMARRAYSIZE = 8111;
public const int STRINGARRAYSIZE = 8111;
// This is the upper limit of number of string arrays to sort in one
// iteration. If we can sort more than this number of arrays in less
// than MINIMUM_TICKS an exception is thrown.
public const int NUMSTRARRAYS = 100;
public const int HUFFARRAYSIZE = 5000;
public const int MAXHUFFLOOPS = 50000;
// Assignment constants
public const int ASSIGNROWS = 101;
public const int ASSIGNCOLS = 101;
public const int MAXPOSLONG = 0x7FFFFFFF;
// BitOps constants
#if LONG64
public const int BITFARRAYSIZE = 16384;
#else
public const int BITFARRAYSIZE = 32768;
#endif
// IDEA constants
public const int MAXIDEALOOPS = 5000;
public const int IDEAARRAYSIZE = 4000;
public const int IDEAKEYSIZE = 16;
public const int IDEABLOCKSIZE = 8;
public const int ROUNDS = 8;
public const int KEYLEN = (6 * ROUNDS + 4);
// LUComp constants
public const int LUARRAYROWS = 101;
public const int LUARRAYCOLS = 101;
// EMFLOAT constants
public const int CPUEMFLOATLOOPMAX = 50000;
public const int EMFARRAYSIZE = 3000;
}
/*
** TYPEDEFS
*/
public abstract class HarnessTest
{
public bool bRunTest = true;
public double score;
public int adjust; /* Set adjust code */
public int request_secs; /* # of seconds requested */
public abstract string Name();
public abstract void ShowStats();
public abstract double Run();
}
public abstract class SortStruct : HarnessTest
{
public short numarrays = global.NUMNUMARRAYS; /* # of arrays */
public int arraysize = global.NUMARRAYSIZE; /* # of elements in array */
public override void ShowStats()
{
ByteMark.OutputString(
string.Format(" Number of arrays: {0}", numarrays));
ByteMark.OutputString(
string.Format(" Array size: {0}", arraysize));
}
}
public abstract class StringSortStruct : HarnessTest
{
public short numarrays = global.NUMNUMARRAYS; /* # of arrays */
public int arraysize = global.STRINGARRAYSIZE; /* # of elements in array */
public override void ShowStats()
{
ByteMark.OutputString(
string.Format(" Number of arrays: {0}", numarrays));
ByteMark.OutputString(
string.Format(" Array size: {0}", arraysize));
}
}
public abstract class HuffStruct : HarnessTest
{
public int arraysize = global.HUFFARRAYSIZE;
public int loops = 0;
public override void ShowStats()
{
ByteMark.OutputString(
string.Format(" Array size: {0}", arraysize));
ByteMark.OutputString(
string.Format(" Number of loops: {0}", loops));
}
}
public abstract class FourierStruct : HarnessTest
{
public int arraysize; /* Size of coeff. arrays */
public override void ShowStats()
{
ByteMark.OutputString(
string.Format(" Number of coefficients: {0}", arraysize));
}
}
public abstract class AssignStruct : HarnessTest
{
public short numarrays = global.NUMNUMARRAYS; /* # of elements in array */
public override void ShowStats()
{
ByteMark.OutputString(
string.Format(" Number of arrays: {0}", numarrays));
}
}
public abstract class BitOpStruct : HarnessTest
{
public int bitoparraysize; /* Total # of bitfield ops */
public int bitfieldarraysize = global.BITFARRAYSIZE; /* Bit field array size */
public override void ShowStats()
{
ByteMark.OutputString(
string.Format(" Operations array size: {0}", bitoparraysize));
ByteMark.OutputString(
string.Format(" Bitfield array size: {0}", bitfieldarraysize));
}
}
public abstract class IDEAStruct : HarnessTest
{
public int arraysize = global.IDEAARRAYSIZE; /* Size of array */
public int loops; /* # of times to convert */
public override void ShowStats()
{
ByteMark.OutputString(
string.Format(" Array size: {0}", arraysize));
ByteMark.OutputString(
string.Format(" Number of loops: {0}", loops));
}
}
public abstract class LUStruct : HarnessTest
{
public int numarrays;
public override void ShowStats()
{
ByteMark.OutputString(
string.Format(" Number of arrays: {0}", numarrays));
}
}
public abstract class NNetStruct : HarnessTest
{
public int loops; /* # of times to learn */
public double iterspersec; /* Results */
public override void ShowStats()
{
ByteMark.OutputString(
string.Format(" Number of loops: {0}", loops));
}
}
public abstract class EmFloatStruct : HarnessTest
{
public int arraysize = global.EMFARRAYSIZE; /* Size of array */
public int loops; /* Loops per iterations */
public override void ShowStats()
{
ByteMark.OutputString(
string.Format(" Number of loops: {0}", loops));
ByteMark.OutputString(
string.Format(" Array size: {0}", arraysize));
}
}
public class ByteMark
{
private static int[] s_randw;
private static double[] s_bindex;
private static HarnessTest[] s_tests;
public static int Main(string[] args)
{
ByteMark app = new ByteMark();
int result = app.ExecuteCore(args);
return result;
}
public int ExecuteCore(string[] argv)
{
s_randw = new int[2] { 13, 117 };
global.min_ticks = global.MINIMUM_TICKS;
global.min_secs = global.MINIMUM_SECONDS;
global.allstats = false;
global.custrun = false;
global.align = 8;
global.write_to_file = false;
/*
** Indexes -- Baseline is DELL Pentium XP90
** 11/28/94
*/
// JTR: Should make member of HarnessTest, but left
// this way to keep similar to original test.
s_bindex = new double[14] {
38.993, /* Numeric sort */
38.993, /* Numeric sort */
2.238, /* String sort */
5829704, /* Bitfield */
2.084, /* FP Emulation */
2.084, /* FP Emulation */
879.278, /* Fourier */
.2628, /* Assignment */
.2628, /* Assignment */
65.382, /* IDEA */
36.062, /* Huffman */
.6225, /* Neural Net */
.6225, /* Neural Net */
19.3031 /* LU Decomposition */
};
s_tests = new HarnessTest[14]
{
global.numsortstruct_jagged = new NumericSortJagged(),
global.numsortstruct_rect = new NumericSortRect(),
global.strsortstruct = new StringSort(),
global.bitopstruct = new BitOps(),
global.emfloatstruct_struct = new EMFloat(),
global.emfloatstruct_class = new EMFloatClass(),
global.fourierstruct = new Fourier(),
global.assignstruct_jagged = new AssignJagged(),
global.assignstruct_rect = new AssignRect(),
global.ideastruct = new IDEAEncryption(),
global.huffstruct = new Huffman(),
global.nnetstruct_jagged = new NeuralJagged(),
global.nnetstruct_rect = new Neural(),
global.lustruct = new LUDecomp(),
};
SetRequestSecs();
/*
** Handle any command-line arguments.
*/
int argc = argv.Length;
if (argc > 0)
{
for (int i = 0; i < argc; i++)
{
if (parse_arg(argv[i]) == -1)
{
display_help("Bytemark");
return -1;
}
}
}
/*
** Output header
*/
OutputString("BBBBBB YYY Y TTTTTTT EEEEEEE");
OutputString("BBB B YYY Y TTT EEE");
OutputString("BBB B YYY Y TTT EEE");
OutputString("BBBBBB YYY Y TTT EEEEEEE");
OutputString("BBB B YYY TTT EEE");
OutputString("BBB B YYY TTT EEE");
OutputString("BBBBBB YYY TTT EEEEEEE");
OutputString("");
OutputString("BYTEmark (tm) C# Mode Benchmark ver. 2 (06/99)");
if (global.allstats)
{
OutputString("========== ALL STATISTICS ==========");
DateTime time_and_date = DateTime.Now;
OutputString("**" +
time_and_date.ToString("ddd MMM dd HH:mm:ss yyyy"));
OutputString("**" + global.SysName);
OutputString("**" + global.CompilerName);
OutputString("**" + global.CompilerVersion);
OutputString("**Sizeof: int:4 short:2 long:8");
OutputString("====================================");
OutputString("");
}
try
{
/*
** Execute the tests.
*/
int fpcount = 0;
int intcount = 0;
double intindex = 1.0; /* Integer index */
double fpindex = 1.0; /* Floating-point index */
for (int i = 0; i < s_tests.Length; i++)
{
if (s_tests[i].bRunTest)
{
double bmean; /* Benchmark mean */
double bstdev; /* Benchmark stdev */
int bnumrun; /* # of runs */
OutputStringPart(
string.Format("{0}:", s_tests[i].Name()));
bench_with_confidence(i,
out bmean,
out bstdev,
out bnumrun);
OutputString(
string.Format(" Iterations/sec: {0:F5} Index: {1:F5}",
bmean,
bmean / s_bindex[i]));
/*
** Gather integer or FP indexes
*/
// JTR: indexes all have 1 added to them to compensate
// for splitting int sort into 2 tests
if ((i == 6) || (i == 12) || (i == 13) || (i == 11))
{
/* FP index */
fpindex = fpindex * (bmean / s_bindex[i]);
fpcount++;
}
else
{
/* Integer index */
intindex = intindex * (bmean / s_bindex[i]);
intcount++;
}
if (global.allstats)
{
OutputString(
string.Format(" Standard Deviation: {0}", bstdev));
OutputString(
string.Format(" Number of runs: {0}", bnumrun));
s_tests[i].ShowStats();
}
}
}
/*
** Output the total indexes
*/
if (!global.custrun)
{
OutputString("===========OVERALL============");
OutputString(
string.Format("INTEGER INDEX: {0:F5}", Math.Pow(intindex, (double)1.0 / (double)intcount)));
OutputString(
string.Format("FLOATING-POINT INDEX: {0:F5}", Math.Pow(fpindex, (double)1.0 / (double)fpcount)));
OutputString(" (90 MHz Dell Pentium = 1.00)");
OutputString("==============================");
}
}
catch (Exception e)
{
Console.WriteLine("ExecuteCore - Exception {0}", e.ToString());
if (global.ofile != null)
{
global.ofile.Flush();
}
Console.WriteLine("Exception: {0}", e.ToString());
return -1;
}
return 100;
}
/**************
** parse_arg **
***************
** Given a pointer to a string, we assume that's an argument.
** Parse that argument and act accordingly.
** Return 0 if ok, else return -1.
*/
private int parse_arg(String arg)
{
int i = 0; /* Index */
StreamReader cfile = null; /* Command file identifier */
/*
** First character has got to be a hyphen.
*/
if (arg[i++] != '-') return (-1);
/*
** Convert the rest of the argument to upper case
** so there's little chance of confusion.
*/
arg = arg.ToUpper();
/*
** Next character picks the action.
*/
switch (arg[i++])
{
case '?': return (-1); /* Will display help */
case 'C': /* Command file name */
/*
** First try to open the file for reading.
*/
String inputFileName = arg.Substring(i);
try
{
cfile = File.OpenText(inputFileName);
}
catch (IOException)
{
Console.WriteLine("**Error opening file: {0}", inputFileName);
return (-1);
}
read_comfile(cfile); /* Read commands */
break;
default:
return (-1);
}
return (0);
}
/*******************
** display_help() **
********************
** Display a help message showing argument requirements and such.
** Exit when you're done...I mean, REALLY exit.
*/
private static void display_help(String progname)
{
Console.WriteLine("Usage: {0} [-c<FILE>]", progname);
Console.WriteLine(" -c = Input parameters thru command file <FILE>");
}
private enum PF
{ // parameter flags
GMTICKS = 0, /* GLOBALMINTICKS */
MINSECONDS = 1, /* MINSECONDS */
ALLSTATS = 2, /* ALLSTATS */
OUTFILE = 3, /* OUTFILE */
CUSTOMRUN = 4, /* CUSTOMRUN */
DONUM = 5, /* DONUMSORT */
NUMNUMA = 6, /* NUMNUMARRAYS */
NUMASIZE = 7, /* NUMARRAYSIZE */
NUMMINS = 8, /* NUMMINSECONDS */
DOSTR = 9, /* DOSTRINGSORT */
STRASIZE = 10, /* STRARRAYSIZE */
NUMSTRA = 11, /* NUMSTRARRAYS */
STRMINS = 12, /* STRMINSECONDS */
DOBITF = 13, /* DOBITFIELD */
NUMBITOPS = 14, /* NUMBITOPS */
BITFSIZE = 15, /* BITFIELDSIZE */
BITMINS = 16, /* BITMINSECONDS */
DOEMF = 17, /* DOEMF */
EMFASIZE = 18, /* EMFARRAYSIZE */
EMFLOOPS = 19, /* EMFLOOPS */
EMFMINS = 20, /* EMFMINSECOND */
DOFOUR = 21, /* DOFOUR */
FOURASIZE = 22, /* FOURASIZE */
FOURMINS = 23, /* FOURMINSECONDS */
DOASSIGN = 24, /* DOASSIGN */
AARRAYS = 25, /* ASSIGNARRAYS */
ASSIGNMINS = 26, /* ASSIGNMINSECONDS */
DOIDEA = 27, /* DOIDEA */
IDEAASIZE = 28, /* IDEAARRAYSIZE */
IDEALOOPS = 29, /* IDEALOOPS */
IDEAMINS = 30, /* IDEAMINSECONDS */
DOHUFF = 31, /* DOHUFF */
HUFFASIZE = 32, /* HUFFARRAYSIZE */
HUFFLOOPS = 33, /* HUFFLOOPS */
HUFFMINS = 34, /* HUFFMINSECONDS */
DONNET = 35, /* DONNET */
NNETLOOPS = 36, /* NNETLOOPS */
NNETMINS = 37, /* NNETMINSECONDS */
DOLU = 38, /* DOLU */
LUNARRAYS = 39, /* LUNUMARRAYS */
LUMINS = 40, /* LUMINSECONDS */
ALIGN = 41, /* ALIGN */
// Added for control of new C# rect/jagged struct/class tests
DONUMJAGGED = 42, /* DONUMSORTJAGGED */
DONUMRECT = 43, /* DONUMSORTRECT */
DOEMFSTRUCT = 44, /* DOEMFSTRUCT */
DOEMFCLASS = 45, /* DOEMFCLASS */
DOASSIGNJAGGED = 46, /* DOASSIGNJAGGED */
DOASSIGNRECT = 47, /* DOASSIGNRECT */
DONNETJAGGED = 48, /* DONNETJAGGED */
DONNETRECT = 49, /* DONNETRECT */
MAXPARAM = 49
}
/* Parameter names */
private static String[] s_paramnames = {
"GLOBALMINTICKS",
"MINSECONDS",
"ALLSTATS",
"OUTFILE",
"CUSTOMRUN",
"DONUMSORT",
"NUMNUMARRAYS",
"NUMARRAYSIZE",
"NUMMINSECONDS",
"DOSTRINGSORT",
"STRARRAYSIZE",
"NUMSTRARRAYS",
"STRMINSECONDS",
"DOBITFIELD",
"NUMBITOPS",
"BITFIELDSIZE",
"BITMINSECONDS",
"DOEMF",
"EMFARRAYSIZE",
"EMFLOOPS",
"EMFMINSECONDS",
"DOFOUR",
"FOURSIZE",
"FOURMINSECONDS",
"DOASSIGN",
"ASSIGNARRAYS",
"ASSIGNMINSECONDS",
"DOIDEA",
"IDEARRAYSIZE",
"IDEALOOPS",
"IDEAMINSECONDS",
"DOHUFF",
"HUFARRAYSIZE",
"HUFFLOOPS",
"HUFFMINSECONDS",
"DONNET",
"NNETLOOPS",
"NNETMINSECONDS",
"DOLU",
"LUNUMARRAYS",
"LUMINSECONDS",
"ALIGN",
// Added for control of new C# rect/jagged struct/class tests
"DONUMSORTJAGGED",
"DONUMSORTRECT",
"DOEMFSTRUCT",
"DOEMFCLASS",
"DOASSIGNJAGGED",
"DOASSIGNRECT",
"DONNETJAGGED",
"DONNETRECT"
};
/*****************
** read_comfile **
******************
** Read the command file. Set global parameters as
** specified. This routine assumes that the command file
** is already open.
*/
private static void read_comfile(StreamReader cfile)
{
String inbuf;
String eptr; /* Offset to "=" sign */
/* markples: now the value half of the key=value pair */
int eIndex; /* markples: now this is the "=" offset */
PF i; /* Index */
/*
** Sit in a big loop, reading a line from the file at each
** pass. Terminate on EOF.
*/
while ((inbuf = cfile.ReadLine()) != null)
{
/*
** Parse up to the "=" sign. If we don't find an
** "=", then flag an error.
*/
if ((eIndex = inbuf.IndexOf('=')) == -1)
{
Console.WriteLine("**COMMAND FILE ERROR at LINE:");
Console.WriteLine(" " + inbuf);
goto skipswitch; /* A GOTO!!!! */
}
/*
** Insert a null where the "=" was, then convert
** the substring to uppercase. That will enable
** us to perform the match.
*/
String name = inbuf.Substring(0, eIndex);
eptr = inbuf.Substring(eIndex + 1);
name = name.ToUpper();
i = PF.MAXPARAM;
do
{
if (name == s_paramnames[(int)i])
{
break;
}
} while (--i >= 0);
if (i < 0)
{
Console.WriteLine("**COMMAND FILE ERROR -- UNKNOWN PARAM: "
+ name);
goto skipswitch;
}
/*
** Advance eptr to the next field...which should be
** the value assigned to the parameter.
*/
switch (i)
{
case PF.GMTICKS: /* GLOBALMINTICKS */
global.min_ticks = Int64.Parse(eptr);
break;
case PF.MINSECONDS: /* MINSECONDS */
global.min_secs = Int32.Parse(eptr);
SetRequestSecs();
break;
case PF.ALLSTATS: /* ALLSTATS */
global.allstats = getflag(eptr);
break;
case PF.OUTFILE: /* OUTFILE */
global.ofile_name = eptr;
try
{
global.ofile = File.AppendText(global.ofile_name);
global.write_to_file = true;
/*
** Open the output file.
*/
}
catch (IOException)
{
Console.WriteLine("**Error opening output file: {0}", global.ofile_name);
global.write_to_file = false;
}
break;
case PF.CUSTOMRUN: /* CUSTOMRUN */
global.custrun = getflag(eptr);
for (i = 0; (int)i < s_tests.Length; i++)
{
s_tests[(int)i].bRunTest = !global.custrun;
}
break;
case PF.DONUM: /* DONUMSORT */
global.numsortstruct_jagged.bRunTest =
global.numsortstruct_rect.bRunTest = getflag(eptr);
break;
case PF.NUMNUMA: /* NUMNUMARRAYS */
global.numsortstruct_rect.numarrays = Int16.Parse(eptr);
global.numsortstruct_jagged.numarrays = global.numsortstruct_rect.numarrays;
global.numsortstruct_jagged.adjust =
global.numsortstruct_rect.adjust = 1;
break;
case PF.NUMASIZE: /* NUMARRAYSIZE */
global.numsortstruct_rect.arraysize = Int32.Parse(eptr);
global.numsortstruct_jagged.arraysize = global.numsortstruct_rect.arraysize;
break;
case PF.NUMMINS: /* NUMMINSECONDS */
global.numsortstruct_rect.request_secs = Int32.Parse(eptr);
global.numsortstruct_jagged.request_secs = global.numsortstruct_rect.request_secs;
break;
case PF.DOSTR: /* DOSTRINGSORT */
global.strsortstruct.bRunTest = getflag(eptr);
break;
case PF.STRASIZE: /* STRARRAYSIZE */
global.strsortstruct.arraysize = Int32.Parse(eptr);
break;
case PF.NUMSTRA: /* NUMSTRARRAYS */
global.strsortstruct.numarrays = Int16.Parse(eptr);
global.strsortstruct.adjust = 1;
break;
case PF.STRMINS: /* STRMINSECONDS */
global.strsortstruct.request_secs = Int32.Parse(eptr);
break;
case PF.DOBITF: /* DOBITFIELD */
global.bitopstruct.bRunTest = getflag(eptr);
break;
case PF.NUMBITOPS: /* NUMBITOPS */
global.bitopstruct.bitoparraysize = Int32.Parse(eptr);
global.bitopstruct.adjust = 1;
break;
case PF.BITFSIZE: /* BITFIELDSIZE */
global.bitopstruct.bitfieldarraysize = Int32.Parse(eptr);
break;
case PF.BITMINS: /* BITMINSECONDS */
global.bitopstruct.request_secs = Int32.Parse(eptr);
break;
case PF.DOEMF: /* DOEMF */
global.emfloatstruct_struct.bRunTest =
global.emfloatstruct_class.bRunTest = getflag(eptr);
break;
case PF.EMFASIZE: /* EMFARRAYSIZE */
global.emfloatstruct_class.arraysize = Int32.Parse(eptr);
global.emfloatstruct_struct.arraysize = global.emfloatstruct_class.arraysize;
break;
case PF.EMFLOOPS: /* EMFLOOPS */
global.emfloatstruct_class.loops = Int32.Parse(eptr);
break;
case PF.EMFMINS: /* EMFMINSECOND */
global.emfloatstruct_class.request_secs = Int32.Parse(eptr);
global.emfloatstruct_struct.request_secs = global.emfloatstruct_class.request_secs;
break;
case PF.DOFOUR: /* DOFOUR */
global.fourierstruct.bRunTest = getflag(eptr);
break;
case PF.FOURASIZE: /* FOURASIZE */
global.fourierstruct.arraysize = Int32.Parse(eptr);
global.fourierstruct.adjust = 1;
break;
case PF.FOURMINS: /* FOURMINSECONDS */
global.fourierstruct.request_secs = Int32.Parse(eptr);
break;
case PF.DOASSIGN: /* DOASSIGN */
global.assignstruct_jagged.bRunTest =
global.assignstruct_rect.bRunTest = getflag(eptr);
break;
case PF.AARRAYS: /* ASSIGNARRAYS */
global.assignstruct_rect.numarrays = Int16.Parse(eptr);
global.assignstruct_jagged.numarrays = global.assignstruct_rect.numarrays;
break;
case PF.ASSIGNMINS: /* ASSIGNMINSECONDS */
global.assignstruct_rect.request_secs = Int32.Parse(eptr);
global.assignstruct_jagged.request_secs = global.assignstruct_rect.request_secs;
break;
case PF.DOIDEA: /* DOIDEA */
global.ideastruct.bRunTest = getflag(eptr);
break;
case PF.IDEAASIZE: /* IDEAARRAYSIZE */
global.ideastruct.arraysize = Int32.Parse(eptr);
break;
case PF.IDEALOOPS: /* IDEALOOPS */
global.ideastruct.loops = Int32.Parse(eptr);
break;
case PF.IDEAMINS: /* IDEAMINSECONDS */
global.ideastruct.request_secs = Int32.Parse(eptr);
break;
case PF.DOHUFF: /* DOHUFF */
global.huffstruct.bRunTest = getflag(eptr);
break;
case PF.HUFFASIZE: /* HUFFARRAYSIZE */
global.huffstruct.arraysize = Int32.Parse(eptr);
break;
case PF.HUFFLOOPS: /* HUFFLOOPS */
global.huffstruct.loops = Int32.Parse(eptr);
global.huffstruct.adjust = 1;
break;
case PF.HUFFMINS: /* HUFFMINSECONDS */
global.huffstruct.request_secs = Int32.Parse(eptr);
break;
case PF.DONNET: /* DONNET */
global.nnetstruct_jagged.bRunTest =
global.nnetstruct_rect.bRunTest = getflag(eptr);
break;
case PF.NNETLOOPS: /* NNETLOOPS */
global.nnetstruct_rect.loops = Int32.Parse(eptr);
global.nnetstruct_jagged.loops = global.nnetstruct_rect.loops;
global.nnetstruct_jagged.adjust =
global.nnetstruct_rect.adjust = 1;
break;
case PF.NNETMINS: /* NNETMINSECONDS */
global.nnetstruct_rect.request_secs = Int32.Parse(eptr);
global.nnetstruct_jagged.request_secs = global.nnetstruct_rect.request_secs;
break;
case PF.DOLU: /* DOLU */
global.lustruct.bRunTest = getflag(eptr);
break;
case PF.LUNARRAYS: /* LUNUMARRAYS */
global.lustruct.numarrays = Int32.Parse(eptr);
global.lustruct.adjust = 1;
break;
case PF.LUMINS: /* LUMINSECONDS */
global.lustruct.request_secs = Int32.Parse(eptr);
break;
case PF.ALIGN: /* ALIGN */
global.align = Int32.Parse(eptr);
break;
case PF.DONUMJAGGED: /* DONUMSORTJAGGED */
global.numsortstruct_jagged.bRunTest = getflag(eptr);
break;
case PF.DONUMRECT: /* DONUMSORTRECT */
global.numsortstruct_rect.bRunTest = getflag(eptr);
break;
case PF.DOEMFSTRUCT: /* DOEMFSTRUCT */
global.emfloatstruct_struct.bRunTest = getflag(eptr);
break;
case PF.DOEMFCLASS: /* DOEMFCLASS */
global.emfloatstruct_class.bRunTest = getflag(eptr);
break;
case PF.DOASSIGNJAGGED: /* DOASSIGNJAGGED */
global.assignstruct_jagged.bRunTest = getflag(eptr);
break;
case PF.DOASSIGNRECT: /* DOASSIGNRECT */
global.assignstruct_rect.bRunTest = getflag(eptr);
break;
case PF.DONNETJAGGED: /* DONNETJAGGED */
global.nnetstruct_jagged.bRunTest = getflag(eptr);
break;
case PF.DONNETRECT: /* DONNETRECT */
global.nnetstruct_rect.bRunTest = getflag(eptr);
break;
}
skipswitch:
continue;
} /* End while */
return;
}
/************
** getflag **
*************
** Return 1 if cptr points to "T"; 0 otherwise.
*/
private static bool getflag(String cptr)
{
return cptr[0] == 'T' || cptr[0] == 't';
}
/*********************
** set_request_secs **
**********************
** Set everyone's "request_secs" entry to whatever
** value is in global.min_secs. This is done
** at the beginning, and possibly later if the
** user redefines global.min_secs in the command file.
*/
private static void SetRequestSecs()
{
foreach (HarnessTest ht in s_tests)
{
ht.request_secs = global.min_secs;
}
return;
}
/**************************
** bench_with_confidence **
***************************
** Given a benchmark id that indicates a function, this
** routine repeatedly calls that benchmark, seeking
** to collect enough scores to get 5 that meet the confidence
** criteria. Return 0 if ok, -1 if failure.
** Returns mean ans std. deviation of results if successful.
*/
private static
int bench_with_confidence(int fid, /* Function id */
out double mean, /* Mean of scores */
out double stdev, /* Standard deviation */
out int numtries) /* # of attempts */
{
double[] myscores = new double[5]; /* Need at least 5 scores */
double c_half_interval; /* Confidence half interval */
int i; /* Index */
double newscore; /* For improving confidence interval */
/*
** Get first 5 scores. Then begin confidence testing.
*/
for (i = 0; i < 5; i++)
{
myscores[i] = s_tests[fid].Run();
}
numtries = 5; /* Show 5 attempts */
/*
** The system allows a maximum of 10 tries before it gives
** up. Since we've done 5 already, we'll allow 5 more.
*/
/*
** Enter loop to test for confidence criteria.
*/
while (true)
{
/*
** Calculate confidence.
*/
calc_confidence(myscores,
out c_half_interval,
out mean,
out stdev);
/*
** Is half interval 5% or less of mean?
** If so, we can go home. Otherwise,
** we have to continue.
*/
if (c_half_interval / mean <= (double)0.05)
break;
/*
** Go get a new score and see if it
** improves existing scores.
*/
do
{
if (numtries == 10)
return (-1);
newscore = s_tests[fid].Run();
numtries += 1;
} while (seek_confidence(myscores, ref newscore,
out c_half_interval, out mean, out stdev) == 0);
}
return (0);
}
/********************
** seek_confidence **
*********************
** Pass this routine an array of 5 scores PLUS a new score.
** This routine tries the new score in place of each of
** the other five scores to determine if the new score,
** when replacing one of the others, improves the confidence
** half-interval.
** Return 0 if failure. Original 5 scores unchanged.
** Return -1 if success. Also returns new half-interval,
** mean, and stand. dev.
*/
private static int seek_confidence(double[] scores,
ref double newscore,
out double c_half_interval,
out double smean,
out double sdev)
{
double sdev_to_beat; /* Original sdev to be beaten */
double temp; /* For doing a swap */
int is_beaten; /* Indicates original was beaten */
int i; /* Index */
/*
** First calculate original standard deviation
*/
calc_confidence(scores, out c_half_interval, out smean, out sdev);
sdev_to_beat = sdev;
is_beaten = -1;
/*
** Try to beat original score. We'll come out of this
** loop with a flag.
*/
for (i = 0; i < 5; i++)
{
temp = scores[i];
scores[i] = newscore;
calc_confidence(scores, out c_half_interval, out smean, out sdev);
scores[i] = temp;
if (sdev_to_beat > sdev)
{
is_beaten = i;
sdev_to_beat = sdev;
}
}
if (is_beaten != -1)
{
scores[is_beaten] = newscore;
return (-1);
}
return (0);
}
/********************
** calc_confidence **
*********************
** Given a set of 5 scores, calculate the confidence
** half-interval. We'l also return the sample mean and sample
** standard deviation.
** NOTE: This routines presumes a confidence of 95% and
** a confidence coefficient of .95
*/
private static void calc_confidence(double[] scores, /* Array of scores */
out double c_half_interval, /* Confidence half-int */
out double smean, /* Standard mean */
out double sdev) /* Sample stand dev */
{
int i; /* Index */
/*
** First calculate mean.
*/
smean = (scores[0] + scores[1] + scores[2] + scores[3] + scores[4]) /
(double)5.0;
/*
** Get standard deviation - first get variance
*/
sdev = (double)0.0;
for (i = 0; i < 5; i++)
{
sdev += (scores[i] - smean) * (scores[i] - smean);
}
sdev /= (double)4.0;
sdev = Math.Sqrt(sdev) / Math.Sqrt(5.0);
/*
** Now calculate the confidence half-interval.
** For a confidence level of 95% our confidence coefficient
** gives us a multiplying factor of 2.776
** (The upper .025 quartile of a t distribution with 4 degrees
** of freedom.)
*/
c_half_interval = (double)2.776 * sdev;
return;
}
public static void OutputStringPart(String s)
{
Console.Write(s);
if (global.write_to_file)
{
global.ofile.Write(s);
}
}
public static void OutputString(String s)
{
Console.WriteLine(s);
if (global.write_to_file)
{
global.ofile.WriteLine(s);
global.ofile.Flush();
}
}
/****************************
** TicksToSecs
** Converts ticks to seconds. Converts ticks to integer
** seconds, discarding any fractional amount.
*/
public static int TicksToSecs(long tickamount)
{
return ((int)(tickamount / global.TICKS_PER_SEC));
}
/****************************
** TicksToFracSecs
** Converts ticks to fractional seconds. In other words,
** this returns the exact conversion from ticks to
** seconds.
*/
public static double TicksToFracSecs(long tickamount)
{
return ((double)tickamount / (double)global.TICKS_PER_SEC);
}
public static long StartStopwatch()
{
//DateTime t = DateTime.Now;
//return(t.Ticks);
return Environment.TickCount;
}
public static long StopStopwatch(long start)
{
//DateTime t = DateTime.Now;
//Console.WriteLine(t.Ticks - start);
//return(t.Ticks-start);
long x = Environment.TickCount - start;
//Console.WriteLine(x);
return x;
}
/****************************
* randwc() *
*****************************
** Returns int random modulo num.
*/
public static int randwc(int num)
{
return (randnum(0) % num);
}
/***************************
** abs_randwc() **
****************************
** Same as randwc(), only this routine returns only
** positive numbers.
*/
public static int abs_randwc(int num)
{
int temp; /* Temporary storage */
temp = randwc(num);
if (temp < 0) temp = 0 - temp;
return temp;
}
/****************************
* randnum() *
*****************************
** Second order linear congruential generator.
** Constants suggested by J. G. Skellam.
** If val==0, returns next member of sequence.
** val!=0, restart generator.
*/
public static int randnum(int lngval)
{
int interm;
if (lngval != 0L)
{ s_randw[0] = 13; s_randw[1] = 117; }
unchecked
{
interm = (s_randw[0] * 254754 + s_randw[1] * 529562) % 999563;
}
s_randw[1] = s_randw[0];
s_randw[0] = interm;
return (interm);
}
static void Setup()
{
s_randw = new int[2] { 13, 117 };
global.min_ticks = global.MINIMUM_TICKS;
global.min_secs = global.MINIMUM_SECONDS;
global.allstats = false;
global.custrun = false;
global.align = 8;
global.write_to_file = false;
}
const int NumericSortJaggedIterations = 20;
[Benchmark]
public static void BenchNumericSortJagged()
{
Setup();
NumericSortJagged t = new NumericSortJagged();
t.numarrays = 1000;
t.adjust = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < NumericSortJaggedIterations; i++)
{
t.Run();
}
}
}
}
const int NumericSortRectangularIterations = 20;
[Benchmark]
public static void BenchNumericSortRectangular()
{
Setup();
NumericSortRect t = new NumericSortRect();
t.numarrays = 1000;
t.adjust = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < NumericSortRectangularIterations; i++)
{
t.Run();
}
}
}
}
const int StringSortIterations = 15;
[Benchmark]
public static void BenchStringSort()
{
Setup();
StringSort t = new StringSort();
t.numarrays = 1000;
t.adjust = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < StringSortIterations; i++)
{
t.Run();
}
}
}
}
const int BitOpsIterations = 15;
[Benchmark]
public static void BenchBitOps()
{
Setup();
BitOps t = new BitOps();
t.adjust = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < BitOpsIterations; i++)
{
t.Run();
}
}
}
}
const int EmFloatIterations = 8;
[Benchmark]
public static void BenchEmFloat()
{
Setup();
EmFloatStruct t = new EMFloat();
t.loops = 100;
t.adjust = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < EmFloatIterations; i++)
{
t.Run();
}
}
}
}
const int EmFloatClassIterations = 8;
[Benchmark]
public static void BenchEmFloatClass()
{
Setup();
EmFloatStruct t = new EMFloatClass();
t.loops = 100;
t.adjust = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < EmFloatClassIterations; i++)
{
t.Run();
}
}
}
}
const int FourierIterations = 20;
[Benchmark]
public static void BenchFourier()
{
Setup();
FourierStruct t = new Fourier();
t.adjust = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < FourierIterations; i++)
{
t.Run();
}
}
}
}
const int AssignJaggedIterations = 15;
[Benchmark]
public static void BenchAssignJagged()
{
Setup();
AssignStruct t = new AssignJagged();
t.numarrays = 1000;
t.adjust = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < AssignJaggedIterations; i++)
{
t.Run();
}
}
}
}
const int AssignRectangularIterations = 20;
[Benchmark]
public static void BenchAssignRectangular()
{
Setup();
AssignStruct t = new AssignRect();
t.numarrays = 1000;
t.adjust = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < AssignRectangularIterations; i++)
{
t.Run();
}
}
}
}
const int IDEAEncryptionIterations = 20;
[Benchmark]
public static void BenchIDEAEncryption()
{
Setup();
IDEAStruct t = new IDEAEncryption();
t.loops = 100;
t.adjust = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < IDEAEncryptionIterations; i++)
{
t.Run();
}
}
}
}
const int NeuralJaggedIterations = 20;
[Benchmark]
public static void BenchNeuralJagged()
{
Setup();
NNetStruct t = new NeuralJagged();
t.loops = 100;
t.adjust = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < NeuralJaggedIterations; i++)
{
t.Run();
}
}
}
}
const int NeuralIterations = 12;
[Benchmark]
public static void BenchNeural()
{
Setup();
NNetStruct t = new Neural();
t.loops = 100;
t.adjust = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < NeuralIterations; i++)
{
t.Run();
}
}
}
}
const int LUDecompIterations = 20;
[Benchmark]
public static void BenchLUDecomp()
{
Setup();
LUStruct t = new LUDecomp();
t.numarrays = 1000;
t.adjust = 0;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < LUDecompIterations; i++)
{
t.Run();
}
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) Under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You Under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed Under the License is distributed on an "AS Is" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations Under the License.
*/
namespace NPOI.SS.Formula.Functions
{
using System;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula;
using System.Collections.Generic;
using System.Linq;
public class SingleValueVector : ValueVector
{
private ValueEval _value;
public SingleValueVector(ValueEval value)
{
_value = value;
}
public ValueEval GetItem(int index)
{
if (index != 0)
{
throw new ArgumentException("Invalid index ("
+ index + ") only zero is allowed");
}
return _value;
}
public int Size
{
get
{
return 1;
}
}
}
/**
* Implementation for the MATCH() Excel function.<p/>
*
* <b>Syntax:</b><br/>
* <b>MATCH</b>(<b>lookup_value</b>, <b>lookup_array</b>, match_type)<p/>
*
* Returns a 1-based index specifying at what position in the <b>lookup_array</b> the specified
* <b>lookup_value</b> Is found.<p/>
*
* Specific matching behaviour can be modified with the optional <b>match_type</b> parameter.
*
* <table border="0" cellpAdding="1" cellspacing="0" summary="match_type parameter description">
* <tr><th>Value</th><th>Matching Behaviour</th></tr>
* <tr><td>1</td><td>(default) Find the largest value that Is less than or equal to lookup_value.
* The lookup_array must be in ascending <i>order</i>*.</td></tr>
* <tr><td>0</td><td>Find the first value that Is exactly equal to lookup_value.
* The lookup_array can be in any order.</td></tr>
* <tr><td>-1</td><td>Find the smallest value that Is greater than or equal to lookup_value.
* The lookup_array must be in descending <i>order</i>*.</td></tr>
* </table>
*
* * Note regarding <i>order</i> - For the <b>match_type</b> cases that require the lookup_array to
* be ordered, MATCH() can produce incorrect results if this requirement Is not met. Observed
* behaviour in Excel Is to return the lowest index value for which every item after that index
* breaks the match rule.<br/>
* The (ascending) sort order expected by MATCH() Is:<br/>
* numbers (low to high), strings (A to Z), bool (FALSE to TRUE)<br/>
* MATCH() ignores all elements in the lookup_array with a different type to the lookup_value.
* Type conversion of the lookup_array elements Is never performed.
*
*
* @author Josh Micich
*/
public class Match : Function
{
public ValueEval Evaluate(ValueEval[] args, int srcCellRow, int srcCellCol)
{
double match_type = 1; // default
switch (args.Length)
{
case 3:
try
{
match_type = EvaluateMatchTypeArg(args[2], srcCellRow, srcCellCol);
}
catch (EvaluationException)
{
// Excel/MATCH() seems to have slightly abnormal handling of errors with
// the last parameter. Errors do not propagate up. Every error Gets
// translated into #REF!
return ErrorEval.REF_INVALID;
}
break;
case 2:
break;
default:
return ErrorEval.VALUE_INVALID;
}
bool matchExact = match_type == 0;
// Note - Excel does not strictly require -1 and +1
bool FindLargestLessThanOrEqual = match_type > 0;
try
{
ValueEval lookupValue = OperandResolver.GetSingleValue(args[0], srcCellRow, srcCellCol);
ValueVector lookupRange = EvaluateLookupRange(args[1]);
int index = FindIndexOfValue(lookupValue, lookupRange, matchExact, FindLargestLessThanOrEqual);
return new NumberEval(index + 1); // +1 to Convert to 1-based
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
}
private static ValueVector EvaluateLookupRange(ValueEval eval)
{
if (eval is RefEval)
{
RefEval re = (RefEval)eval;
if (re.NumberOfSheets == 1)
{
return new SingleValueVector(re.GetInnerValueEval(re.FirstSheetIndex));
}
else
{
return LookupUtils.CreateVector(re);
}
}
if (eval is TwoDEval)
{
ValueVector result = LookupUtils.CreateVector((TwoDEval)eval);
if (result == null)
{
throw new EvaluationException(ErrorEval.NA);
}
return result;
}
// Error handling for lookup_range arg Is also Unusual
if (eval is NumericValueEval)
{
throw new EvaluationException(ErrorEval.NA);
}
if (eval is StringEval)
{
StringEval se = (StringEval)eval;
double d = OperandResolver.ParseDouble(se.StringValue);
if (double.IsNaN(d))
{
// plain string
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
// else looks like a number
throw new EvaluationException(ErrorEval.NA);
}
throw new Exception("Unexpected eval type (" + eval.GetType().Name + ")");
}
private static double EvaluateMatchTypeArg(ValueEval arg, int srcCellRow, int srcCellCol)
{
ValueEval match_type = OperandResolver.GetSingleValue(arg, srcCellRow, srcCellCol);
if (match_type is ErrorEval)
{
throw new EvaluationException((ErrorEval)match_type);
}
if (match_type is NumericValueEval)
{
NumericValueEval ne = (NumericValueEval)match_type;
return ne.NumberValue;
}
if (match_type is StringEval)
{
StringEval se = (StringEval)match_type;
double d = OperandResolver.ParseDouble(se.StringValue);
if (double.IsNaN(d))
{
// plain string
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
// if the string Parses as a number, it Is OK
return d;
}
//if the 3rd argument is missing, use the default value
if (match_type is MissingArgEval)
{
return 1d;
}
throw new Exception("Unexpected match_type type (" + match_type.GetType().Name + ")");
}
/**
* @return zero based index
*/
private static int FindIndexOfValue(ValueEval lookupValue, ValueVector lookupRange,
bool matchExact, bool FindLargestLessThanOrEqual)
{
LookupValueComparer lookupComparer = CreateLookupComparer(lookupValue, matchExact);
int size = lookupRange.Size;
if (matchExact)
{
for (int i = 0; i < size; i++)
{
if (lookupComparer.CompareTo(lookupRange.GetItem(i)).IsEqual)
{
return i;
}
}
throw new EvaluationException(ErrorEval.NA);
}
if (FindLargestLessThanOrEqual)
{
//in case the lookupRange area is not sorted, still try to get the right index
if (lookupValue is NumericValueEval nve)
{
Dictionary<int, double> dicDeltas = new Dictionary<int, double>();
for (int i = 0; i < size; i++)
{
var item = lookupRange.GetItem(i) as NumericValueEval;
if (lookupComparer.CompareTo(item).IsEqual)
{
return i;
}
else
{
dicDeltas.Add(i, item.NumberValue - nve.NumberValue);
}
}
return dicDeltas.Where(kv => kv.Value < 0).OrderByDescending(kv => kv.Value).First().Key;
}
// Note - backward iteration
for (int i = size - 1; i >= 0; i--)
{
CompareResult cmp = lookupComparer.CompareTo(lookupRange.GetItem(i));
if (cmp.IsTypeMismatch)
{
continue;
}
if (!cmp.IsLessThan)
{
return i;
}
}
throw new EvaluationException(ErrorEval.NA);
}
// else - Find smallest greater than or equal to
// TODO - Is binary search used for (match_type==+1) ?
for (int i = 0; i < size; i++)
{
CompareResult cmp = lookupComparer.CompareTo(lookupRange.GetItem(i));
if (cmp.IsEqual)
{
return i;
}
if (cmp.IsGreaterThan)
{
if (i < 1)
{
throw new EvaluationException(ErrorEval.NA);
}
return i - 1;
}
}
return size - 1;
}
private static LookupValueComparer CreateLookupComparer(ValueEval lookupValue, bool matchExact)
{
return LookupUtils.CreateLookupComparer(lookupValue, matchExact, true);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedMember.Global
#if BUILD_PEANUTBUTTER_INTERNAL
namespace Imported.PeanutButter.Utils.Dictionaries
#else
namespace PeanutButter.Utils.Dictionaries
#endif
{
/// <summary>
/// Wraps a NameValueCollection in an IDictionary interface
/// </summary>
#if BUILD_PEANUTBUTTER_INTERNAL
internal
#else
public
#endif
class DictionaryWrappingNameValueCollection : IDictionary<string, object>
{
private readonly NameValueCollection _data;
/// <summary>
/// Comparer to use for the keys of this dictionary
/// </summary>
public StringComparer Comparer { get; }
/// <summary>
/// Construct this dictionary with a NameValueCollection to wrap,
/// specifying whether or not key lookups are to be case-sensitive
/// </summary>
/// <param name="data"></param>
/// <param name="caseInsensitive">Flag: is this collection to treat keys case-insensitive?</param>
public DictionaryWrappingNameValueCollection(
NameValueCollection data,
bool caseInsensitive
) : this(data, caseInsensitive
? StringComparer.OrdinalIgnoreCase
: StringComparer.Ordinal)
{
}
/// <summary>
/// Construct this dictionary with a NameValueCollection to wrap
/// </summary>
/// <param name="data"></param>
public DictionaryWrappingNameValueCollection(
NameValueCollection data
) : this(data, StringComparer.Ordinal)
{
}
/// <summary>
/// Construct this dictionary with a NameValueCollection to wrap,
/// specifying the StringComparer to use when comparing requested
/// keys with available keys
/// </summary>
/// <param name="data"></param>
/// <param name="comparer"></param>
public DictionaryWrappingNameValueCollection(
NameValueCollection data,
StringComparer comparer
)
{
_data = data;
Comparer = comparer;
}
/// <inheritdoc />
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return new DictionaryWrappingNameValueCollectionEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <inheritdoc />
public void Add(KeyValuePair<string, object> item)
{
_data.Add(item.Key, item.Value as string ?? item.Value?.ToString());
}
/// <inheritdoc />
public void Clear()
{
_data.Clear();
}
/// <inheritdoc />
public bool Contains(KeyValuePair<string, object> item)
{
var key = GetKeyFor(item.Key);
if (key == null || !_data.AllKeys.Contains(key))
return false;
return _data[key] == item.Value?.ToString();
}
private string GetKeyFor(string key)
{
return _data.AllKeys.FirstOrDefault(k => KeysMatch(k, key));
}
private bool KeysMatch(string one, string other)
{
return Comparer.Equals(one, other);
}
/// <inheritdoc />
public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
foreach (var kvp in this)
{
array[arrayIndex++] = kvp;
}
}
/// <inheritdoc />
public bool Remove(KeyValuePair<string, object> item)
{
if (!Contains(item))
return false;
var key = GetKeyFor(item.Key);
_data.Remove(key);
return true;
}
/// <inheritdoc />
public int Count => _data.Count;
/// <inheritdoc />
public bool IsReadOnly => false;
/// <inheritdoc />
public bool ContainsKey(string key)
{
return GetKeyFor(key) != null;
}
/// <inheritdoc />
public void Add(string key, object value)
{
_data.Add(key, value as string ?? value?.ToString());
}
/// <inheritdoc />
public bool Remove(string key)
{
var result = _data.AllKeys.Contains(key);
if (result)
_data.Remove(key);
return result;
}
/// <inheritdoc />
public bool TryGetValue(string key, out object value)
{
key = GetKeyFor(key);
if (key == null)
{
value = null;
return false;
}
value = _data[key];
return true;
}
/// <inheritdoc />
public object this[string key]
{
get
{
key = GetKeyFor(key);
return _data[key];
}
set
{
key = GetKeyFor(key) ?? key; // allow adding items
_data[key] = value?.ToString(); // TODO: could be better
}
}
/// <inheritdoc />
public ICollection<string> Keys => _data.AllKeys;
/// <inheritdoc />
public ICollection<object> Values => _data.AllKeys.Select(k => _data[k]).ToArray();
}
// TODO: add explicit tests around this class, which is currently only tested by indirection
/// <summary>
/// Wraps a NameValueCollection in a Dictionary interface
/// </summary>
internal class DictionaryWrappingNameValueCollectionEnumerator : IEnumerator<KeyValuePair<string, object>>
{
internal DictionaryWrappingNameValueCollection Data => _data;
private readonly DictionaryWrappingNameValueCollection _data;
private string[] _keys;
private int _current;
/// <summary>
/// Provides an IEnumerator for a DictionaryWrappingNameValueCollection
/// </summary>
/// <param name="data"></param>
public DictionaryWrappingNameValueCollectionEnumerator(
DictionaryWrappingNameValueCollection data
)
{
_data = data;
Reset();
}
/// <inheritdoc />
public void Dispose()
{
/* empty on purpose, just need to implement IEnumerator */
}
/// <inheritdoc />
public bool MoveNext()
{
RefreshKeys();
_current++;
return _current < _keys.Length;
}
/// <inheritdoc />
public void Reset()
{
_current = -1;
_keys = new string[] { };
}
public KeyValuePair<string, object> Current
{
get
{
RefreshKeys();
if (_current >= _keys.Length)
throw new InvalidOperationException("Current index is out of bounds");
return new KeyValuePair<string, object>(_keys[_current], _data[_keys[_current]]);
}
}
private void RefreshKeys()
{
if (!_keys.Any())
_keys = _data.Keys.ToArray();
}
object IEnumerator.Current => Current;
}
}
| |
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.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;
namespace System.Data.Common
{
internal abstract class AbstractDataContainer
{
#region Fields
BitArray _nullValues;
System.Type _type;
DataColumn _column;
#endregion //Fields
#region Properties
internal abstract object this[int index] {
get;
set;
}
internal virtual int Capacity {
get {
return (_nullValues != null) ? _nullValues.Count : 0;
}
set {
if (_nullValues == null) {
_nullValues = new BitArray(value);
}
else {
_nullValues.Length = value;
}
}
}
internal Type Type {
get {
return _type;
}
}
protected DataColumn Column {
get {
return _column;
}
}
#endregion //Properties
#region Methods
internal static AbstractDataContainer CreateInstance(Type type, DataColumn column)
{
AbstractDataContainer container;
switch (Type.GetTypeCode(type)) {
case TypeCode.Int16 :
container = new Int16DataContainer();
break;
case TypeCode.Int32 :
container = new Int32DataContainer();
break;
case TypeCode.Int64 :
container = new Int64DataContainer();
break;
case TypeCode.String :
container = new StringDataContainer();
break;
case TypeCode.Boolean:
container = new BitDataContainer();
break;
case TypeCode.Byte :
container = new ByteDataContainer();
break;
case TypeCode.Char :
container = new CharDataContainer();
break;
case TypeCode.Double :
container = new DoubleDataContainer();
break;
case TypeCode.SByte :
container = new SByteDataContainer();
break;
case TypeCode.Single :
container = new SingleDataContainer();
break;
case TypeCode.UInt16 :
container = new UInt16DataContainer();
break;
case TypeCode.UInt32 :
container = new UInt32DataContainer();
break;
case TypeCode.UInt64 :
container = new UInt64DataContainer();
break;
case TypeCode.DateTime :
container = new DateTimeDataContainer();
break;
case TypeCode.Decimal :
container = new DecimalDataContainer();
break;
default :
container = new ObjectDataContainer();
break;
}
container._type = type;
container._column = column;
return container;
}
internal bool IsNull(int index)
{
return (_nullValues != null) ? _nullValues[index] : true;
}
internal void SetNullBit(int index,bool isNull)
{
_nullValues[index] = isNull;
}
protected void SetNull(int index,bool isNull,bool isDbNull)
{
SetNullBit(index,isDbNull);
// this method must be called after setting the value into value array
// otherwise the dafault value will be overriden
if ( isNull ) {
// set the value to default
CopyValue(Column.Table.DefaultValuesRowIndex,index);
}
}
internal void FillValues(int fromIndex)
{
for(int i=0; i < Capacity; i++) {
CopyValue(fromIndex,i);
_nullValues[i] = _nullValues[fromIndex];
}
}
internal virtual void CopyValue(AbstractDataContainer fromContainer, int fromIndex, int toIndex)
{
_nullValues[toIndex] = fromContainer._nullValues[fromIndex];
}
internal virtual void CopyValue(int fromIndex, int toIndex)
{
_nullValues[toIndex] = _nullValues[fromIndex];
}
internal abstract void SetItemFromDataRecord(int index, IDataRecord record, int field);
protected int CompareNulls(int index1, int index2)
{
bool null1 = IsNull(index1);
bool null2 = IsNull(index2);
if ( null1 ^ null2 ) {
return null1 ? -1 : 1;
}
else {
return 0;
}
}
internal abstract int CompareValues(int index1, int index2);
internal abstract long GetInt64(int index);
#endregion //Methods
sealed class Int16DataContainer : AbstractDataContainer
{
#region Fields
short[] _values;
#endregion //Fields
#region Properties
internal override object this[int index] {
get {
if (IsNull(index)) {
return DBNull.Value;
}
else {
return _values[index];
}
}
set {
bool isDbNull = (value == DBNull.Value);
if (value == null || isDbNull) {
SetValue(index,0);
}
else if( value is short ) {
SetValue(index,(short)value);
}
else {
SetValue(index,Convert.ToInt16(value));
}
SetNull(index,value == null,isDbNull);
}
}
internal override int Capacity {
set {
base.Capacity = value;
if (_values == null) {
_values = new short[value];
}
else {
short[] tmp = new short[value];
Array.Copy(_values,0,tmp,0,_values.Length);
_values = tmp;
}
}
}
#endregion //Properties
#region Methods
private void SetValue(int index, short value)
{
_values[index] = value;
}
internal override void SetItemFromDataRecord(int index, IDataRecord record, int field)
{
bool isDbNull = record.IsDBNull(field);
if (isDbNull) {
SetNull(index,false,isDbNull);
return;
}
// if exception thrown, it should be caught in the caller method
if (record is ISafeDataRecord) {
SetValue(index,((ISafeDataRecord)record).GetInt16Safe(field));
}
else {
this[index] = record.GetValue(field);
}
}
internal override void CopyValue(int fromIndex, int toIndex)
{
base.CopyValue(fromIndex, toIndex);
_values[toIndex] = _values[fromIndex];
}
internal override void CopyValue(AbstractDataContainer fromContainer, int fromIndex, int toIndex)
{
base.CopyValue(fromContainer, fromIndex, toIndex);
_values[toIndex] = ((Int16DataContainer)fromContainer)._values[fromIndex];
}
internal override int CompareValues(int index1, int index2)
{
short s1 = _values[index1];
short s2 = _values[index2];
if ( s1 == 0 || s2 == 0 ) {
int cn = CompareNulls(index1, index2);
if (cn != 0)
return cn;
}
return s1 - s2;
}
internal override long GetInt64(int index)
{
return (long) _values[index];
}
#endregion //Methods
}
sealed class Int32DataContainer : AbstractDataContainer
{
#region Fields
int[] _values;
#endregion //Fields
#region Properties
internal override object this[int index] {
get {
if (IsNull(index)) {
return DBNull.Value;
}
else {
return _values[index];
}
}
set {
bool isDbNull = (value == DBNull.Value);
if (value == null || isDbNull) {
SetValue(index,0);
}
else if( value is int ) {
SetValue(index,(int)value);
}
else {
SetValue(index,Convert.ToInt32(value));
}
SetNull(index,value == null,isDbNull);
}
}
internal override int Capacity {
set {
base.Capacity = value;
if (_values == null) {
_values = new int[value];
}
else {
int[] tmp = new int[value];
Array.Copy(_values,0,tmp,0,_values.Length);
_values = tmp;
}
}
}
#endregion //Properties
#region Methods
private void SetValue(int index, int value)
{
_values[index] = value;
}
internal override void SetItemFromDataRecord(int index, IDataRecord record, int field)
{
bool isDbNull = record.IsDBNull(field);
if (isDbNull) {
SetNull(index,false,isDbNull);
return;
}
// if exception thrown, it should be caught in the caller method
if (record is ISafeDataRecord) {
SetValue(index,((ISafeDataRecord)record).GetInt32Safe(field));
}
else {
this[index] = record.GetValue(field);
}
}
internal override void CopyValue(int fromIndex, int toIndex)
{
base.CopyValue(fromIndex, toIndex);
_values[toIndex] = _values[fromIndex];
}
internal override void CopyValue(AbstractDataContainer fromContainer, int fromIndex, int toIndex)
{
base.CopyValue(fromContainer, fromIndex, toIndex);
_values[toIndex] = ((Int32DataContainer)fromContainer)._values[fromIndex];
}
internal override int CompareValues(int index1, int index2)
{
int i1 = _values[index1];
int i2 = _values[index2];
if (i1 == 0 || i2 == 0) {
int cn = CompareNulls(index1, index2);
if (cn != 0)
return cn;
}
if ( i1 <= i2 ) {
return ( i1 == i2 ) ? 0 : -1;
}
return 1;
}
internal override long GetInt64(int index)
{
return (long) _values[index];
}
#endregion //Methods
}
sealed class Int64DataContainer : AbstractDataContainer
{
#region Fields
long[] _values;
#endregion //Fields
#region Properties
internal override object this[int index] {
get {
if (IsNull(index)) {
return DBNull.Value;
}
else {
return _values[index];
}
}
set {
bool isDbNull = (value == DBNull.Value);
if (value == null || isDbNull) {
SetValue(index,0);
}
else if( value is long ) {
SetValue(index,(long)value);
}
else {
SetValue(index,Convert.ToInt64(value));
}
SetNull(index,value == null,isDbNull);
}
}
internal override int Capacity {
set {
base.Capacity = value;
if (_values == null) {
_values = new long[value];
}
else {
long[] tmp = new long[value];
Array.Copy(_values,0,tmp,0,_values.Length);
_values = tmp;
}
}
}
#endregion //Properties
#region Methods
private void SetValue(int index, long value)
{
_values[index] = value;
}
internal override void SetItemFromDataRecord(int index, IDataRecord record, int field)
{
bool isDbNull = record.IsDBNull(field);
if (isDbNull) {
SetNull(index,false,isDbNull);
return;
}
// if exception thrown, it should be caught in the caller method
if (record is ISafeDataRecord) {
SetValue(index,((ISafeDataRecord)record).GetInt64Safe(field));
}
else {
this[index] = record.GetValue(field);
}
}
internal override void CopyValue(int fromIndex, int toIndex)
{
base.CopyValue(fromIndex, toIndex);
_values[toIndex] = _values[fromIndex];
}
internal override void CopyValue(AbstractDataContainer fromContainer, int fromIndex, int toIndex)
{
base.CopyValue(fromContainer, fromIndex, toIndex);
_values[toIndex] = ((Int64DataContainer)fromContainer)._values[fromIndex];
}
internal override int CompareValues(int index1, int index2)
{
long l1 = _values[index1];
long l2 = _values[index2];
if ( l1 == 0 || l2 == 0 ) {
int cn = CompareNulls(index1, index2);
if (cn != 0) {
return cn;
}
}
if ( l1 <= l2 ) {
return ( l1 != l2 ) ? -1 : 0;
}
return 1;
}
internal override long GetInt64(int index)
{
return _values[index];
}
#endregion //Methods
}
sealed class SingleDataContainer : AbstractDataContainer
{
#region Fields
float[] _values;
#endregion //Fields
#region Properties
internal override object this[int index] {
get {
if (IsNull(index)) {
return DBNull.Value;
}
else {
return _values[index];
}
}
set {
bool isDbNull = (value == DBNull.Value);
if (value == null || isDbNull) {
SetValue(index,0);
}
else if( value is float ) {
SetValue(index,(float)value);
}
else {
SetValue(index,Convert.ToSingle(value));
}
SetNull(index,value == null,isDbNull);
}
}
internal override int Capacity {
set {
base.Capacity = value;
if (_values == null) {
_values = new float[value];
}
else {
float[] tmp = new float[value];
Array.Copy(_values,0,tmp,0,_values.Length);
_values = tmp;
}
}
}
#endregion //Properties
#region Methods
private void SetValue(int index, float value)
{
_values[index] = value;
}
internal override void SetItemFromDataRecord(int index, IDataRecord record, int field)
{
bool isDbNull = record.IsDBNull(field);
if (isDbNull) {
SetNull(index,false,isDbNull);
return;
}
// if exception thrown, it should be caught in the caller method
if (record is ISafeDataRecord) {
SetValue(index,((ISafeDataRecord)record).GetFloatSafe(field));
}
else {
this[index] = record.GetValue(field);
}
}
internal override void CopyValue(int fromIndex, int toIndex)
{
base.CopyValue(fromIndex, toIndex);
_values[toIndex] = _values[fromIndex];
}
internal override void CopyValue(AbstractDataContainer fromContainer, int fromIndex, int toIndex)
{
base.CopyValue(fromContainer, fromIndex, toIndex);
_values[toIndex] = ((SingleDataContainer)fromContainer)._values[fromIndex];
}
internal override int CompareValues(int index1, int index2)
{
float f1 = _values[index1];
float f2 = _values[index2];
if ( f1 == 0 || f2 == 0 ) {
int cn = CompareNulls(index1, index2);
if (cn != 0) {
return cn;
}
}
if ( f1 <= f2 ) {
return ( f1 != f2 ) ? -1 : 0;
}
return 1;
}
internal override long GetInt64(int index)
{
return Convert.ToInt64(_values[index]);
}
#endregion //Methods
}
sealed class DoubleDataContainer : AbstractDataContainer
{
#region Fields
double[] _values;
#endregion //Fields
#region Properties
internal override object this[int index] {
get {
if (IsNull(index)) {
return DBNull.Value;
}
else {
return _values[index];
}
}
set {
bool isDbNull = (value == DBNull.Value);
if (value == null || isDbNull) {
SetValue(index,0);
}
else if( value is double ) {
SetValue(index,(double)value);
}
else {
SetValue(index,Convert.ToDouble(value));
}
SetNull(index,value == null,isDbNull);
}
}
internal override int Capacity {
set {
base.Capacity = value;
if (_values == null) {
_values = new double[value];
}
else {
double[] tmp = new double[value];
Array.Copy(_values,0,tmp,0,_values.Length);
_values = tmp;
}
}
}
#endregion //Properties
#region Methods
private void SetValue(int index, double value)
{
_values[index] = value;
}
internal override void SetItemFromDataRecord(int index, IDataRecord record, int field)
{
bool isDbNull = record.IsDBNull(field);
if (isDbNull) {
SetNull(index,false,isDbNull);
return;
}
// if exception thrown, it should be caught in the caller method
if (record is ISafeDataRecord) {
SetValue(index,((ISafeDataRecord)record).GetDoubleSafe(field));
}
else {
this[index] = record.GetValue(field);
}
}
internal override void CopyValue(int fromIndex, int toIndex)
{
base.CopyValue(fromIndex, toIndex);
_values[toIndex] = _values[fromIndex];
}
internal override void CopyValue(AbstractDataContainer fromContainer, int fromIndex, int toIndex)
{
base.CopyValue(fromContainer, fromIndex, toIndex);
_values[toIndex] = ((DoubleDataContainer)fromContainer)._values[fromIndex];
}
internal override int CompareValues(int index1, int index2)
{
double d1 = _values[index1];
double d2 = _values[index2];
if ( d1 == 0 || d2 == 0 ) {
int cn = CompareNulls(index1, index2);
if (cn != 0) {
return cn;
}
}
if ( d1 <= d2 ) {
return ( d1 != d2 ) ? -1 : 0;
}
return 1;
}
internal override long GetInt64(int index)
{
return Convert.ToInt64(_values[index]);
}
#endregion //Methods
}
sealed class ByteDataContainer : AbstractDataContainer
{
#region Fields
byte[] _values;
#endregion //Fields
#region Properties
internal override object this[int index] {
get {
if (IsNull(index)) {
return DBNull.Value;
}
else {
return _values[index];
}
}
set {
bool isDbNull = (value == DBNull.Value);
if (value == null || isDbNull) {
SetValue(index,0);
}
else if( value is byte ) {
SetValue(index,(byte)value);
}
else {
SetValue(index,Convert.ToByte(value));
}
SetNull(index,value == null,isDbNull);
}
}
internal override int Capacity {
set {
base.Capacity = value;
if (_values == null) {
_values = new byte[value];
}
else {
byte[] tmp = new byte[value];
Array.Copy(_values,0,tmp,0,_values.Length);
_values = tmp;
}
}
}
#endregion //Properties
#region Methods
private void SetValue(int index, byte value)
{
_values[index] = value;
}
internal override void SetItemFromDataRecord(int index, IDataRecord record, int field)
{
bool isDbNull = record.IsDBNull(field);
if (isDbNull) {
SetNull(index,false,isDbNull);
return;
}
// if exception thrown, it should be caught in the caller method
if (record is ISafeDataRecord) {
SetValue(index,((ISafeDataRecord)record).GetByteSafe(field));
}
else {
this[index] = record.GetValue(field);
}
}
internal override void CopyValue(int fromIndex, int toIndex)
{
base.CopyValue(fromIndex, toIndex);
_values[toIndex] = _values[fromIndex];
}
internal override void CopyValue(AbstractDataContainer fromContainer, int fromIndex, int toIndex)
{
base.CopyValue(fromContainer, fromIndex, toIndex);
_values[toIndex] = ((ByteDataContainer)fromContainer)._values[fromIndex];
}
internal override int CompareValues(int index1, int index2)
{
byte b1 = _values[index1];
byte b2 = _values[index2];
if ( b1 == 0 || b2 == 0 ) {
int cn = CompareNulls(index1, index2);
if (cn != 0) {
return cn;
}
}
return b1 - b2;
}
internal override long GetInt64(int index)
{
return (long) _values[index];
}
#endregion //Methods
}
sealed class BitDataContainer : AbstractDataContainer
{
#region Fields
bool[] _values;
#endregion //Fields
#region Properties
internal override object this[int index] {
get {
bool isNull = IsNull(index);
if (isNull) {
return DBNull.Value;
}
else {
return _values[index];
}
}
set {
bool isDbNull = (value == DBNull.Value);
if (value == null || isDbNull) {
SetValue(index,false);
}
else if( value is bool ) {
SetValue(index,(bool)value);
}
else {
SetValue(index,Convert.ToBoolean(value));
}
SetNull(index,value == null,isDbNull);
}
}
internal override int Capacity {
set {
base.Capacity = value;
if (_values == null) {
_values = new bool[value];
}
else {
bool[] tmp = new bool[value];
Array.Copy(_values,0,tmp,0,_values.Length);
_values = tmp;
}
}
}
#endregion //Properties
#region Methods
private void SetValue(int index, bool value)
{
_values[index] = value;
}
internal override void SetItemFromDataRecord(int index, IDataRecord record, int field)
{
bool isDbNull = record.IsDBNull(field);
if (isDbNull) {
SetNull(index,false,isDbNull);
return;
}
// if exception thrown, it should be caught in the caller method
if (record is ISafeDataRecord) {
SetValue(index,((ISafeDataRecord)record).GetBooleanSafe(field));
}
else {
this[index] = record.GetValue(field);
}
}
internal override void CopyValue(int fromIndex, int toIndex)
{
base.CopyValue(fromIndex, toIndex);
_values[toIndex] = _values[fromIndex];
}
internal override void CopyValue(AbstractDataContainer fromContainer, int fromIndex, int toIndex)
{
base.CopyValue(fromContainer, fromIndex, toIndex);
_values[toIndex] = ((BitDataContainer)fromContainer)._values[fromIndex];
}
internal override int CompareValues(int index1, int index2)
{
bool b1 = _values[index1];
bool b2 = _values[index2];
if ( b1 ^ b2 ) {
return b1 ? 1 : -1;
}
if ( b1 ) {
return 0;
}
return CompareNulls(index1, index2);
}
internal override long GetInt64(int index)
{
return Convert.ToInt64(_values[index]);
}
#endregion //Methods
}
abstract class AbstractObjectDataContainer : AbstractDataContainer
{
#region Fields
object[] _values;
#endregion //Fields
#region Properties
internal override object this[int index] {
get {
if (IsNull(index))
return DBNull.Value;
return _values[index];
}
set {
SetValue(index,value);
SetNull(index,value == null,value == DBNull.Value);
}
}
internal override int Capacity {
set {
base.Capacity = value;
if (_values == null) {
_values = new object[value];
}
else {
object[] tmp = new object[value];
Array.Copy(_values,0,tmp,0,_values.Length);
_values = tmp;
}
}
}
#endregion //Properties
#region Methods
protected virtual void SetValue(int index, object value)
{
if(value == null) {
value = Column.DefaultValue;
}
_values[index] = value;
}
internal override void CopyValue(int fromIndex, int toIndex)
{
base.CopyValue(fromIndex, toIndex);
_values[toIndex] = _values[fromIndex];
}
internal override void CopyValue(AbstractDataContainer fromContainer, int fromIndex, int toIndex)
{
base.CopyValue(fromContainer, fromIndex, toIndex);
_values[toIndex] = ((AbstractObjectDataContainer)fromContainer)._values[fromIndex];
}
internal override int CompareValues(int index1, int index2)
{
object obj1 = _values[index1];
object obj2 = _values[index2];
if(obj1 == obj2)
{
return 0;
}
else
{
int cn = CompareNulls(index1, index2);
if (cn != 0)
return cn;
if (obj1 is IComparable)
{
try
{
return ((IComparable)obj1).CompareTo(obj2);
}
catch
{
//just suppress
}
if (obj2 is IComparable)
{
obj2 = Convert.ChangeType(obj2, Type.GetTypeCode(obj1.GetType()));
return ((IComparable)obj1).CompareTo(obj2);
}
}
}
return String.Compare(obj1.ToString(), obj2.ToString());
}
internal override long GetInt64(int index)
{
return Convert.ToInt64(_values[index]);
}
#endregion //Methods
}
sealed class ObjectDataContainer : AbstractObjectDataContainer
{
#region Methods
internal override void SetItemFromDataRecord(int index, IDataRecord record, int field)
{
bool isDbNull = record.IsDBNull(field);
if (isDbNull) {
SetNull(index,false,isDbNull);
return;
}
// if exception thrown, it should be caught
// in the caller method
SetValue(index,record.GetValue(field));
}
protected override void SetValue(int index, object value)
{
if(value != null && value != DBNull.Value && !Type.IsAssignableFrom(value.GetType()))
value = Convert.ChangeType(value, Type);
base.SetValue(index, value);
}
#endregion //Methods
}
sealed class DateTimeDataContainer : AbstractObjectDataContainer
{
#region Methods
internal override void SetItemFromDataRecord(int index, IDataRecord record, int field)
{
bool isDbNull = record.IsDBNull(field);
if (isDbNull) {
SetNull(index,false,isDbNull);
return;
}
// if exception thrown, it should be caught
// in the caller method
// if exception thrown, it should be caught in the caller method
if (record is ISafeDataRecord) {
SetValue(index,((ISafeDataRecord)record).GetDateTimeSafe(field));
}
else {
this[index] = record.GetValue(field);
}
}
protected override void SetValue(int index, object value)
{
if (value != null && value != DBNull.Value)
value = Convert.ToDateTime(value);
base.SetValue(index, value);
}
#endregion //Methods
}
sealed class DecimalDataContainer : AbstractObjectDataContainer
{
#region Methods
internal override void SetItemFromDataRecord(int index, IDataRecord record, int field)
{
bool isDbNull = record.IsDBNull(field);
if (isDbNull) {
SetNull(index,false,isDbNull);
return;
}
// if exception thrown, it should be caught in the caller method
if (record is ISafeDataRecord) {
SetValue(index,((ISafeDataRecord)record).GetDecimalSafe(field));
}
else {
this[index] = record.GetValue(field);
}
}
protected override void SetValue(int index, object value)
{
if (value != null && value != DBNull.Value)
value = Convert.ToDecimal(value);
base.SetValue(index, value);
}
#endregion //Methods
}
sealed class StringDataContainer : AbstractObjectDataContainer
{
#region Methods
private void SetValue(int index, string value)
{
if (value != null && Column.MaxLength >= 0 && Column.MaxLength < value.Length ) {
throw new ArgumentException("Cannot set column '" + Column.ColumnName + "' to '" + value + "'. The value violates the MaxLength limit of this column.");
}
base.SetValue(index,value);
}
protected override void SetValue(int index, object value)
{
if ( value != null && value != DBNull.Value ) {
if ( value is string ) {
SetValue(index, (string) value);
}
else {
SetValue(index, Convert.ToString(value));
}
return;
}
base.SetValue(index, value);
}
internal override void SetItemFromDataRecord(int index, IDataRecord record, int field)
{
bool isDbNull = record.IsDBNull(field);
if (isDbNull) {
SetNull(index,false,isDbNull);
return;
}
// if exception thrown, it should be caught
// in the caller method
if (record is ISafeDataRecord) {
SetValue(index,((ISafeDataRecord)record).GetStringSafe(field));
}
else {
this[index] = record.GetValue(field);
}
}
internal override int CompareValues(int index1, int index2)
{
bool isNull1 = IsNull(index1);
bool isNull2 = IsNull(index2);
if (isNull1) {
return isNull2 ? 0 : -1;
}
else {
if (isNull2) {
return 1;
}
}
return String.Compare((string)this[index1], (string)this[index2], !Column.Table.CaseSensitive);
}
#endregion //Methods
}
sealed class CharDataContainer : AbstractDataContainer
{
#region Fields
char[] _values;
#endregion //Fields
#region Properties
internal override object this[int index] {
get {
if (IsNull(index)) {
return DBNull.Value;
}
else {
return _values[index];
}
}
set {
bool isDbNull = (value == DBNull.Value);
if (value == null || isDbNull) {
SetValue(index,'\0');
}
else if( value is char ) {
SetValue(index,(char)value);
}
else {
SetValue(index,Convert.ToChar(value));
}
SetNull(index,value == null,isDbNull);
}
}
internal override int Capacity {
set {
base.Capacity = value;
if (_values == null) {
_values = new char[value];
}
else {
char[] tmp = new char[value];
Array.Copy(_values,0,tmp,0,_values.Length);
_values = tmp;
}
}
}
#endregion //Properties
#region Methods
private void SetValue(int index, char value)
{
_values[index] = value;
}
internal override void SetItemFromDataRecord(int index, IDataRecord record, int field)
{
bool isDbNull = record.IsDBNull(field);
if (isDbNull) {
SetNull(index,false,isDbNull);
return;
}
// if exception thrown, it should be caught in the caller method
if (record is ISafeDataRecord) {
SetValue(index,((ISafeDataRecord)record).GetCharSafe(field));
}
else {
this[index] = record.GetValue(field);
}
}
internal override void CopyValue(int fromIndex, int toIndex)
{
base.CopyValue(fromIndex, toIndex);
_values[toIndex] = _values[fromIndex];
}
internal override void CopyValue(AbstractDataContainer fromContainer, int fromIndex, int toIndex)
{
base.CopyValue(fromContainer, fromIndex, toIndex);
_values[toIndex] = ((CharDataContainer)fromContainer)._values[fromIndex];
}
internal override int CompareValues(int index1, int index2)
{
char c1 = _values[index1];
char c2 = _values[index2];
if ( c1 == '\0' || c2 == '\0' )
{
int cn = CompareNulls(index1, index2);
if (cn != 0)
return cn;
}
return c1 - c2;
}
internal override long GetInt64(int index)
{
return Convert.ToInt64(_values[index]);
}
#endregion //Methods
}
sealed class UInt16DataContainer : AbstractDataContainer
{
#region Fields
ushort[] _values;
#endregion //Fields
#region Properties
internal override object this[int index] {
get {
if (IsNull(index)) {
return DBNull.Value;
}
else {
return _values[index];
}
}
set {
bool isDbNull = (value == DBNull.Value);
if (value == null || isDbNull) {
SetValue(index,0);
}
else if( value is ushort ) {
SetValue(index,(ushort)value);
}
else {
SetValue(index,Convert.ToUInt16(value));
}
SetNull(index,value == null,isDbNull);
}
}
internal override int Capacity {
set {
base.Capacity = value;
if (_values == null) {
_values = new ushort[value];
}
else {
ushort[] tmp = new ushort[value];
Array.Copy(_values,0,tmp,0,_values.Length);
_values = tmp;
}
}
}
#endregion //Properties
#region Methods
private void SetValue(int index, ushort value)
{
_values[index] = value;
}
internal override void SetItemFromDataRecord(int index, IDataRecord record, int field)
{
bool isDbNull = record.IsDBNull(field);
if (isDbNull) {
SetNull(index,false,isDbNull);
return;
}
// if exception thrown, it should be caught in the caller method
if (record is ISafeDataRecord) {
SetValue(index,(ushort)((ISafeDataRecord)record).GetInt16Safe(field));
}
else {
this[index] = record.GetValue(field);
}
}
internal override void CopyValue(int fromIndex, int toIndex)
{
base.CopyValue(fromIndex, toIndex);
_values[toIndex] = _values[fromIndex];
}
internal override void CopyValue(AbstractDataContainer fromContainer, int fromIndex, int toIndex)
{
base.CopyValue(fromContainer, fromIndex, toIndex);
_values[toIndex] = ((UInt16DataContainer)fromContainer)._values[fromIndex];
}
internal override int CompareValues(int index1, int index2)
{
ushort s1 = _values[index1];
ushort s2 = _values[index2];
if ( s1 == 0 || s2 == 0 ) {
int cn = CompareNulls(index1, index2);
if (cn != 0)
return cn;
}
return s1 - s2;
}
internal override long GetInt64(int index)
{
return Convert.ToInt64(_values[index]);
}
#endregion //Methods
}
sealed class UInt32DataContainer : AbstractDataContainer
{
#region Fields
uint[] _values;
#endregion //Fields
#region Properties
internal override object this[int index] {
get {
if (IsNull(index)) {
return DBNull.Value;
}
else {
return _values[index];
}
}
set {
bool isDbNull = (value == DBNull.Value);
if (value == null || isDbNull) {
SetValue(index,0);
}
else if( value is uint ) {
SetValue(index,(uint)value);
}
else {
SetValue(index,Convert.ToUInt32(value));
}
SetNull(index,value == null,isDbNull);
}
}
internal override int Capacity {
set {
base.Capacity = value;
if (_values == null) {
_values = new uint[value];
}
else {
uint[] tmp = new uint[value];
Array.Copy(_values,0,tmp,0,_values.Length);
_values = tmp;
}
}
}
#endregion //Properties
#region Methods
private void SetValue(int index, uint value)
{
_values[index] = value;
}
internal override void SetItemFromDataRecord(int index, IDataRecord record, int field)
{
bool isDbNull = record.IsDBNull(field);
if (isDbNull) {
SetNull(index,false,isDbNull);
return;
}
// if exception thrown, it should be caught in the caller method
if (record is ISafeDataRecord) {
SetValue(index,(uint)((ISafeDataRecord)record).GetInt32Safe(field));
}
else {
this[index] = record.GetValue(field);
}
}
internal override void CopyValue(int fromIndex, int toIndex)
{
base.CopyValue(fromIndex, toIndex);
_values[toIndex] = _values[fromIndex];
}
internal override void CopyValue(AbstractDataContainer fromContainer, int fromIndex, int toIndex)
{
base.CopyValue(fromContainer, fromIndex, toIndex);
_values[toIndex] = ((UInt32DataContainer)fromContainer)._values[fromIndex];
}
internal override int CompareValues(int index1, int index2)
{
uint i1 = _values[index1];
uint i2 = _values[index2];
if ( i1 == 0 || i2 == 0 ) {
int cn = CompareNulls(index1, index2);
if (cn != 0)
return cn;
}
if ( i1 <= i2 ) {
return ( i1 != i2 ) ? -1 : 0;
}
return 1;
}
internal override long GetInt64(int index)
{
return Convert.ToInt64(_values[index]);
}
#endregion //Methods
}
sealed class UInt64DataContainer : AbstractDataContainer
{
#region Fields
ulong[] _values;
#endregion //Fields
#region Properties
internal override object this[int index] {
get {
if (IsNull(index)) {
return DBNull.Value;
}
else {
return _values[index];
}
}
set {
bool isDbNull = (value == DBNull.Value);
if (value == null || isDbNull) {
SetValue(index,0);
}
else if( value is ulong ) {
SetValue(index,(ulong)value);
}
else {
SetValue(index,Convert.ToUInt64(value));
}
SetNull(index,value == null,isDbNull);
}
}
internal override int Capacity {
set {
base.Capacity = value;
if (_values == null) {
_values = new ulong[value];
}
else {
ulong[] tmp = new ulong[value];
Array.Copy(_values,0,tmp,0,_values.Length);
_values = tmp;
}
}
}
#endregion //Properties
#region Methods
private void SetValue(int index, ulong value)
{
_values[index] = value;
}
internal override void SetItemFromDataRecord(int index, IDataRecord record, int field)
{
bool isDbNull = record.IsDBNull(field);
if (isDbNull) {
SetNull(index,false,isDbNull);
return;
}
// if exception thrown, it should be caught in the caller method
if (record is ISafeDataRecord) {
SetValue(index,(ulong)((ISafeDataRecord)record).GetInt64Safe(field));
}
else {
this[index] = record.GetValue(field);
}
}
internal override void CopyValue(int fromIndex, int toIndex)
{
base.CopyValue(fromIndex, toIndex);
_values[toIndex] = _values[fromIndex];
}
internal override void CopyValue(AbstractDataContainer fromContainer, int fromIndex, int toIndex)
{
base.CopyValue(fromContainer, fromIndex, toIndex);
_values[toIndex] = ((UInt64DataContainer)fromContainer)._values[fromIndex];
}
internal override int CompareValues(int index1, int index2)
{
ulong l1 = _values[index1];
ulong l2 = _values[index2];
if ( l1 == 0 || l2 == 0 ) {
int cn = CompareNulls(index1, index2);
if (cn != 0) {
return cn;
}
}
if ( l1 <= l2 ) {
return ( l1 != l2 ) ? -1 : 0;
}
return 1;
}
internal override long GetInt64(int index)
{
return Convert.ToInt64(_values[index]);
}
#endregion //Methods
}
sealed class SByteDataContainer : AbstractDataContainer
{
#region Fields
sbyte[] _values;
#endregion //Fields
#region Properties
internal override object this[int index] {
get {
if (IsNull(index)) {
return DBNull.Value;
}
else {
return _values[index];
}
}
set {
bool isDbNull = (value == DBNull.Value);
if (value == null || isDbNull) {
SetValue(index,0);
}
else if( value is sbyte ) {
SetValue(index,(sbyte)value);
}
else {
SetValue(index,Convert.ToSByte(value));
}
SetNull(index,value == null,isDbNull);
}
}
internal override int Capacity {
set {
base.Capacity = value;
if (_values == null) {
_values = new sbyte[value];
}
else {
sbyte[] tmp = new sbyte[value];
Array.Copy(_values,0,tmp,0,_values.Length);
_values = tmp;
}
}
}
#endregion //Properties
#region Methods
private void SetValue(int index, sbyte value)
{
_values[index] = value;
}
internal override void SetItemFromDataRecord(int index, IDataRecord record, int field)
{
bool isDbNull = record.IsDBNull(field);
if (isDbNull) {
SetNull(index,false,isDbNull);
return;
}
// if exception thrown, it should be caught in the caller method
if (record is ISafeDataRecord) {
SetValue(index,(sbyte)((ISafeDataRecord)record).GetByteSafe(field));
}
else {
this[index] = record.GetValue(field);
}
}
internal override void CopyValue(int fromIndex, int toIndex)
{
base.CopyValue(fromIndex, toIndex);
_values[toIndex] = _values[fromIndex];
}
internal override void CopyValue(AbstractDataContainer fromContainer, int fromIndex, int toIndex)
{
base.CopyValue(fromContainer, fromIndex, toIndex);
_values[toIndex] = ((SByteDataContainer)fromContainer)._values[fromIndex];
}
internal override int CompareValues(int index1, int index2)
{
sbyte b1 = _values[index1];
sbyte b2 = _values[index2];
if ( b1 == 0 || b2 == 0 ) {
int cn = CompareNulls(index1, index2);
if (cn != 0) {
return cn;
}
}
return b1 - b2;
}
internal override long GetInt64(int index)
{
return Convert.ToSByte(_values[index]);
}
#endregion //Methods
}
}
}
| |
using System;
using ColossalFramework;
using UnityEngine;
namespace TrafficManager.CustomAI
{
class CustomCargoTruckAI : CarAI
{
public void CustomSimulationStep(ushort vehicleId, ref Vehicle data, Vector3 physicsLodRefPos)
{
if ((data.m_flags & Vehicle.Flags.Congestion) != Vehicle.Flags.None && LoadingExtension.Instance.DespawnEnabled)
{
Singleton<VehicleManager>.instance.ReleaseVehicle(vehicleId);
}
else
{
if ((data.m_flags & Vehicle.Flags.WaitingTarget) != Vehicle.Flags.None && (data.m_waitCounter += 1) > 20)
{
RemoveOffers(vehicleId, ref data);
data.m_flags &= ~Vehicle.Flags.WaitingTarget;
data.m_flags |= Vehicle.Flags.GoingBack;
data.m_waitCounter = 0;
if (!StartPathFind(vehicleId, ref data))
{
data.Unspawn(vehicleId);
}
}
BaseSimulationStep(vehicleId, ref data, physicsLodRefPos);
}
}
// TODO: inherit CarAI
private static void RemoveOffers(ushort vehicleId, ref Vehicle data)
{
if ((data.m_flags & Vehicle.Flags.WaitingTarget) != Vehicle.Flags.None)
{
var offer = default(TransferManager.TransferOffer);
offer.Vehicle = vehicleId;
if ((data.m_flags & Vehicle.Flags.TransferToSource) != Vehicle.Flags.None)
{
Singleton<TransferManager>.instance.RemoveIncomingOffer((TransferManager.TransferReason)data.m_transferType, offer);
}
else if ((data.m_flags & Vehicle.Flags.TransferToTarget) != Vehicle.Flags.None)
{
Singleton<TransferManager>.instance.RemoveOutgoingOffer((TransferManager.TransferReason)data.m_transferType, offer);
}
}
}
protected void BaseSimulationStep(ushort vehicleId, ref Vehicle data, Vector3 physicsLodRefPos)
{
if ((data.m_flags & Vehicle.Flags.WaitingPath) != Vehicle.Flags.None)
{
PathManager instance = Singleton<PathManager>.instance;
byte pathFindFlags = instance.m_pathUnits.m_buffer[(int)((UIntPtr)data.m_path)].m_pathFindFlags;
if ((pathFindFlags & 4) != 0)
{
data.m_pathPositionIndex = 255;
data.m_flags &= ~Vehicle.Flags.WaitingPath;
data.m_flags &= ~Vehicle.Flags.Arriving;
PathfindSuccess(vehicleId, ref data);
TrySpawn(vehicleId, ref data);
}
else if ((pathFindFlags & 8) != 0)
{
data.m_flags &= ~Vehicle.Flags.WaitingPath;
Singleton<PathManager>.instance.ReleasePath(data.m_path);
data.m_path = 0u;
PathfindFailure(vehicleId, ref data);
return;
}
}
else if ((data.m_flags & Vehicle.Flags.WaitingSpace) != Vehicle.Flags.None)
{
TrySpawn(vehicleId, ref data);
}
Vector3 lastFramePosition = data.GetLastFramePosition();
int lodPhysics;
if (Vector3.SqrMagnitude(physicsLodRefPos - lastFramePosition) >= 1210000f)
{
lodPhysics = 2;
}
else if (
Vector3.SqrMagnitude(Singleton<SimulationManager>.instance.m_simulationView.m_position -
lastFramePosition) >= 250000f)
{
lodPhysics = 1;
}
else
{
lodPhysics = 0;
}
SimulationStep(vehicleId, ref data, vehicleId, ref data, lodPhysics);
if (data.m_leadingVehicle == 0 && data.m_trailingVehicle != 0)
{
VehicleManager instance2 = Singleton<VehicleManager>.instance;
ushort num = data.m_trailingVehicle;
int num2 = 0;
while (num != 0)
{
ushort trailingVehicle = instance2.m_vehicles.m_buffer[num].m_trailingVehicle;
VehicleInfo info = instance2.m_vehicles.m_buffer[num].Info;
info.m_vehicleAI.SimulationStep(num, ref instance2.m_vehicles.m_buffer[num], vehicleId,
ref data, lodPhysics);
num = trailingVehicle;
if (++num2 > 16384)
{
CODebugBase<LogChannel>.Error(LogChannel.Core,
"Invalid list detected!\n" + Environment.StackTrace);
break;
}
}
}
int num3 = (m_info.m_class.m_service > ItemClass.Service.Office) ? 150 : 100;
if ((data.m_flags & (Vehicle.Flags.Spawned | Vehicle.Flags.WaitingPath | Vehicle.Flags.WaitingSpace)) ==
Vehicle.Flags.None && data.m_cargoParent == 0)
{
Singleton<VehicleManager>.instance.ReleaseVehicle(vehicleId);
}
else if (data.m_blockCounter >= num3 && LoadingExtension.Instance.DespawnEnabled)
{
Singleton<VehicleManager>.instance.ReleaseVehicle(vehicleId);
}
}
public bool StartPathFind2(ushort vehicleId, ref Vehicle vehicleData, Vector3 startPos, Vector3 endPos, bool startBothWays, bool endBothWays)
{
if ((vehicleData.m_flags & (Vehicle.Flags.TransferToSource | Vehicle.Flags.GoingBack)) != Vehicle.Flags.None)
{
return StartPathFind(vehicleId, ref vehicleData, startPos, endPos, startBothWays, endBothWays);
}
bool allowUnderground = (vehicleData.m_flags & (Vehicle.Flags.Underground | Vehicle.Flags.Transition)) != Vehicle.Flags.None;
PathUnit.Position startPosA;
PathUnit.Position startPosB;
float num;
float num2;
bool requireConnect = true;
float maxDistance = 32f;
bool flag = PathManager.FindPathPosition(startPos, ItemClass.Service.Road, NetInfo.LaneType.Vehicle, VehicleInfo.VehicleType.Car, allowUnderground, requireConnect, maxDistance, out startPosA, out startPosB, out num, out num2);
PathUnit.Position position;
PathUnit.Position position2;
float num3;
float num4;
if (PathManager.FindPathPosition(startPos, ItemClass.Service.PublicTransport, NetInfo.LaneType.Vehicle, VehicleInfo.VehicleType.Train | VehicleInfo.VehicleType.Ship, allowUnderground, requireConnect, maxDistance, out position, out position2, out num3, out num4))
{
if (!flag || num3 < num)
{
startPosA = position;
startPosB = position2;
num = num3;
/*
num2 = num4;
*/
}
flag = true;
}
PathUnit.Position endPosA;
PathUnit.Position endPosB;
float num5;
float num6;
bool flag2 = PathManager.FindPathPosition(endPos, ItemClass.Service.Road, NetInfo.LaneType.Vehicle, VehicleInfo.VehicleType.Car, !allowUnderground, requireConnect, maxDistance, out endPosA, out endPosB, out num5, out num6);
PathUnit.Position position3;
PathUnit.Position position4;
float num7;
float num8;
if (PathManager.FindPathPosition(endPos, ItemClass.Service.PublicTransport, NetInfo.LaneType.Vehicle, VehicleInfo.VehicleType.Train | VehicleInfo.VehicleType.Ship, !allowUnderground, requireConnect, maxDistance, out position3, out position4, out num7, out num8))
{
if (!flag2 || num7 < num5)
{
endPosA = position3;
endPosB = position4;
num5 = num7;
/*
num6 = num8;
*/
}
flag2 = true;
}
if (flag && flag2)
{
CustomPathManager instance = Singleton<CustomPathManager>.instance;
if (!startBothWays || num < 10f)
{
startPosB = default(PathUnit.Position);
}
if (!endBothWays || num5 < 10f)
{
endPosB = default(PathUnit.Position);
}
NetInfo.LaneType laneTypes = NetInfo.LaneType.Vehicle | NetInfo.LaneType.CargoVehicle;
VehicleInfo.VehicleType vehicleTypes = VehicleInfo.VehicleType.Car | VehicleInfo.VehicleType.Train | VehicleInfo.VehicleType.Ship;
uint path;
if (instance.CreatePath(out path, ref Singleton<SimulationManager>.instance.m_randomizer, Singleton<SimulationManager>.instance.m_currentBuildIndex, startPosA, startPosB, endPosA, endPosB, laneTypes, vehicleTypes, 20000f, IsHeavyVehicle(), IgnoreBlocked(vehicleId, ref vehicleData), false, false, ItemClass.Service.Industrial))
{
if (vehicleData.m_path != 0u)
{
instance.ReleasePath(vehicleData.m_path);
}
vehicleData.m_path = path;
vehicleData.m_flags |= Vehicle.Flags.WaitingPath;
return true;
}
}
return false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Options;
using Microsoft.PowerShell;
using Microsoft.PowerShell.Commands;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
internal class RemoteDiscoveryHelper
{
#region PSRP
private static Collection<string> RehydrateHashtableKeys(PSObject pso, string propertyName)
{
var rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk |
DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk;
Hashtable hashtable = DeserializingTypeConverter.GetPropertyValue<Hashtable>(pso, propertyName, rehydrationFlags);
if (hashtable == null)
{
return new Collection<string>();
}
else
{
List<string> list = hashtable
.Keys
.Cast<object>()
.Where(k => k != null)
.Select(k => k.ToString())
.Where(s => s != null)
.ToList();
return new Collection<string>(list);
}
}
internal static PSModuleInfo RehydratePSModuleInfo(PSObject deserializedModuleInfo)
{
var rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk |
DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk;
string name = DeserializingTypeConverter.GetPropertyValue<string>(deserializedModuleInfo, "Name", rehydrationFlags);
string path = DeserializingTypeConverter.GetPropertyValue<string>(deserializedModuleInfo, "Path", rehydrationFlags);
PSModuleInfo moduleInfo = new PSModuleInfo(name, path, context: null, sessionState: null);
moduleInfo.SetGuid(DeserializingTypeConverter.GetPropertyValue<Guid>(deserializedModuleInfo, "Guid", rehydrationFlags));
moduleInfo.SetModuleType(DeserializingTypeConverter.GetPropertyValue<ModuleType>(deserializedModuleInfo, "ModuleType", rehydrationFlags));
moduleInfo.SetVersion(DeserializingTypeConverter.GetPropertyValue<Version>(deserializedModuleInfo, "Version", rehydrationFlags));
moduleInfo.SetHelpInfoUri(DeserializingTypeConverter.GetPropertyValue<string>(deserializedModuleInfo, "HelpInfoUri", rehydrationFlags));
moduleInfo.AccessMode = DeserializingTypeConverter.GetPropertyValue<ModuleAccessMode>(deserializedModuleInfo, "AccessMode", rehydrationFlags);
moduleInfo.Author = DeserializingTypeConverter.GetPropertyValue<string>(deserializedModuleInfo, "Author", rehydrationFlags);
moduleInfo.ClrVersion = DeserializingTypeConverter.GetPropertyValue<Version>(deserializedModuleInfo, "ClrVersion", rehydrationFlags);
moduleInfo.CompanyName = DeserializingTypeConverter.GetPropertyValue<string>(deserializedModuleInfo, "CompanyName", rehydrationFlags);
moduleInfo.Copyright = DeserializingTypeConverter.GetPropertyValue<string>(deserializedModuleInfo, "Copyright", rehydrationFlags);
moduleInfo.Description = DeserializingTypeConverter.GetPropertyValue<string>(deserializedModuleInfo, "Description", rehydrationFlags);
moduleInfo.DotNetFrameworkVersion = DeserializingTypeConverter.GetPropertyValue<Version>(deserializedModuleInfo, "DotNetFrameworkVersion", rehydrationFlags);
moduleInfo.PowerShellHostName = DeserializingTypeConverter.GetPropertyValue<string>(deserializedModuleInfo, "PowerShellHostName", rehydrationFlags);
moduleInfo.PowerShellHostVersion = DeserializingTypeConverter.GetPropertyValue<Version>(deserializedModuleInfo, "PowerShellHostVersion", rehydrationFlags);
moduleInfo.PowerShellVersion = DeserializingTypeConverter.GetPropertyValue<Version>(deserializedModuleInfo, "PowerShellVersion", rehydrationFlags);
moduleInfo.ProcessorArchitecture = DeserializingTypeConverter.GetPropertyValue<Reflection.ProcessorArchitecture>(deserializedModuleInfo, "ProcessorArchitecture", rehydrationFlags);
moduleInfo.DeclaredAliasExports = RehydrateHashtableKeys(deserializedModuleInfo, "ExportedAliases");
moduleInfo.DeclaredCmdletExports = RehydrateHashtableKeys(deserializedModuleInfo, "ExportedCmdlets");
moduleInfo.DeclaredFunctionExports = RehydrateHashtableKeys(deserializedModuleInfo, "ExportedFunctions");
moduleInfo.DeclaredVariableExports = RehydrateHashtableKeys(deserializedModuleInfo, "ExportedVariables");
var compatiblePSEditions = DeserializingTypeConverter.GetPropertyValue<string[]>(deserializedModuleInfo, "CompatiblePSEditions", rehydrationFlags);
if (compatiblePSEditions != null && compatiblePSEditions.Any())
{
foreach (var edition in compatiblePSEditions)
{
moduleInfo.AddToCompatiblePSEditions(edition);
}
}
// PowerShellGet related properties
var tags = DeserializingTypeConverter.GetPropertyValue<string[]>(deserializedModuleInfo, "Tags", rehydrationFlags);
if (tags != null && tags.Any())
{
foreach (var tag in tags)
{
moduleInfo.AddToTags(tag);
}
}
moduleInfo.ReleaseNotes = DeserializingTypeConverter.GetPropertyValue<string>(deserializedModuleInfo, "ReleaseNotes", rehydrationFlags);
moduleInfo.ProjectUri = DeserializingTypeConverter.GetPropertyValue<Uri>(deserializedModuleInfo, "ProjectUri", rehydrationFlags);
moduleInfo.LicenseUri = DeserializingTypeConverter.GetPropertyValue<Uri>(deserializedModuleInfo, "LicenseUri", rehydrationFlags);
moduleInfo.IconUri = DeserializingTypeConverter.GetPropertyValue<Uri>(deserializedModuleInfo, "IconUri", rehydrationFlags);
moduleInfo.RepositorySourceLocation = DeserializingTypeConverter.GetPropertyValue<Uri>(deserializedModuleInfo, "RepositorySourceLocation", rehydrationFlags);
return moduleInfo;
}
private static EventHandler<DataAddedEventArgs> GetStreamForwarder<T>(Action<T> forwardingAction, bool swallowInvalidOperationExceptions = false)
{
// TODO/FIXME: ETW event for extended semantics streams
return delegate (object sender, DataAddedEventArgs eventArgs)
{
var psDataCollection = (PSDataCollection<T>)sender;
foreach (T t in psDataCollection.ReadAll())
{
try
{
forwardingAction(t);
}
catch (InvalidOperationException)
{
if (!swallowInvalidOperationExceptions)
{
throw;
}
}
}
};
}
// This is a static field (instead of a constant) to make it possible to set through tests (and/or by customers if needed for a workaround)
private static readonly int s_blockingCollectionCapacity = 1000;
private static IEnumerable<PSObject> InvokeTopLevelPowerShell(
PowerShell powerShell,
CancellationToken cancellationToken,
PSCmdlet cmdlet,
PSInvocationSettings invocationSettings,
string errorMessageTemplate)
{
using (var mergedOutput = new BlockingCollection<Func<PSCmdlet, IEnumerable<PSObject>>>(s_blockingCollectionCapacity))
{
var asyncOutput = new PSDataCollection<PSObject>();
EventHandler<DataAddedEventArgs> outputHandler = GetStreamForwarder<PSObject>(
output => mergedOutput.Add(_ => new[] { output }),
swallowInvalidOperationExceptions: true);
EventHandler<DataAddedEventArgs> errorHandler = GetStreamForwarder<ErrorRecord>(
errorRecord => mergedOutput.Add(
delegate (PSCmdlet c)
{
errorRecord = GetErrorRecordForRemotePipelineInvocation(errorRecord, errorMessageTemplate);
HandleErrorFromPipeline(c, errorRecord, powerShell);
return Enumerable.Empty<PSObject>();
}),
swallowInvalidOperationExceptions: true);
EventHandler<DataAddedEventArgs> warningHandler = GetStreamForwarder<WarningRecord>(
warningRecord => mergedOutput.Add(
delegate (PSCmdlet c)
{
c.WriteWarning(warningRecord.Message);
return Enumerable.Empty<PSObject>();
}),
swallowInvalidOperationExceptions: true);
EventHandler<DataAddedEventArgs> verboseHandler = GetStreamForwarder<VerboseRecord>(
verboseRecord => mergedOutput.Add(
delegate (PSCmdlet c)
{
c.WriteVerbose(verboseRecord.Message);
return Enumerable.Empty<PSObject>();
}),
swallowInvalidOperationExceptions: true);
EventHandler<DataAddedEventArgs> debugHandler = GetStreamForwarder<DebugRecord>(
debugRecord => mergedOutput.Add(
delegate (PSCmdlet c)
{
c.WriteDebug(debugRecord.Message);
return Enumerable.Empty<PSObject>();
}),
swallowInvalidOperationExceptions: true);
EventHandler<DataAddedEventArgs> informationHandler = GetStreamForwarder<InformationRecord>(
informationRecord => mergedOutput.Add(
delegate (PSCmdlet c)
{
c.WriteInformation(informationRecord);
return Enumerable.Empty<PSObject>();
}),
swallowInvalidOperationExceptions: true);
asyncOutput.DataAdded += outputHandler;
powerShell.Streams.Error.DataAdded += errorHandler;
powerShell.Streams.Warning.DataAdded += warningHandler;
powerShell.Streams.Verbose.DataAdded += verboseHandler;
powerShell.Streams.Debug.DataAdded += debugHandler;
powerShell.Streams.Information.DataAdded += informationHandler;
try
{
// TODO/FIXME: ETW event for PowerShell invocation
var asyncResult = powerShell.BeginInvoke<PSObject, PSObject>(
input: null,
output: asyncOutput,
settings: invocationSettings,
callback: delegate
{
try
{
mergedOutput.CompleteAdding();
}
catch (InvalidOperationException)
// ignore exceptions thrown because mergedOutput.CompleteAdding was called
{
}
},
state: null);
using (cancellationToken.Register(powerShell.Stop))
{
try
{
foreach (Func<PSCmdlet, IEnumerable<PSObject>> mergedOutputItem in mergedOutput.GetConsumingEnumerable())
{
foreach (PSObject outputObject in mergedOutputItem(cmdlet))
{
yield return outputObject;
}
}
}
finally
{
mergedOutput.CompleteAdding();
powerShell.EndInvoke(asyncResult);
}
}
}
finally
{
asyncOutput.DataAdded -= outputHandler;
powerShell.Streams.Error.DataAdded -= errorHandler;
powerShell.Streams.Warning.DataAdded -= warningHandler;
powerShell.Streams.Verbose.DataAdded -= verboseHandler;
powerShell.Streams.Debug.DataAdded -= debugHandler;
powerShell.Streams.Information.DataAdded -= informationHandler;
}
}
}
private static IEnumerable<PSObject> InvokeNestedPowerShell(
PowerShell powerShell,
CancellationToken cancellationToken,
PSCmdlet cmdlet,
PSInvocationSettings invocationSettings,
string errorMessageTemplate)
{
EventHandler<DataAddedEventArgs> errorHandler = GetStreamForwarder<ErrorRecord>(
delegate (ErrorRecord errorRecord)
{
errorRecord = GetErrorRecordForRemotePipelineInvocation(errorRecord, errorMessageTemplate);
HandleErrorFromPipeline(cmdlet, errorRecord, powerShell);
});
powerShell.Streams.Error.DataAdded += errorHandler;
try
{
using (cancellationToken.Register(powerShell.Stop))
{
// TODO/FIXME: ETW event for PowerShell invocation
foreach (PSObject outputObject in powerShell.Invoke<PSObject>(null, invocationSettings))
{
yield return outputObject;
}
}
}
finally
{
powerShell.Streams.Error.DataAdded -= errorHandler;
}
}
private static void CopyParameterFromCmdletToPowerShell(Cmdlet cmdlet, PowerShell powerShell, string parameterName)
{
object parameterValue;
if (!cmdlet.MyInvocation.BoundParameters.TryGetValue(parameterName, out parameterValue))
{
return;
}
var commandParameter = new CommandParameter(parameterName, parameterValue);
foreach (var command in powerShell.Commands.Commands)
{
if (command.Parameters.Any(existingParameter => existingParameter.Name.Equals(parameterName, StringComparison.OrdinalIgnoreCase)))
{
continue;
}
command.Parameters.Add(commandParameter);
}
}
internal static ErrorRecord GetErrorRecordForProcessingOfCimModule(Exception innerException, string moduleName)
{
string errorMessage = string.Format(
CultureInfo.InvariantCulture,
Modules.RemoteDiscoveryFailedToProcessRemoteModule,
moduleName,
innerException.Message);
Exception outerException = new InvalidOperationException(errorMessage, innerException);
ErrorRecord errorRecord = new ErrorRecord(outerException, innerException.GetType().Name, ErrorCategory.NotSpecified, moduleName);
return errorRecord;
}
private const string DiscoveryProviderNotFoundErrorId = "DiscoveryProviderNotFound";
private static ErrorRecord GetErrorRecordForRemoteDiscoveryProvider(Exception innerException)
{
CimException cimException = innerException as CimException;
if ((cimException != null) &&
((cimException.NativeErrorCode == NativeErrorCode.InvalidNamespace) ||
(cimException.NativeErrorCode == NativeErrorCode.InvalidClass) ||
(cimException.NativeErrorCode == NativeErrorCode.MethodNotFound) ||
(cimException.NativeErrorCode == NativeErrorCode.MethodNotAvailable)))
{
string errorMessage = string.Format(
CultureInfo.InvariantCulture,
Modules.RemoteDiscoveryProviderNotFound,
innerException.Message);
Exception outerException = new InvalidOperationException(errorMessage, innerException);
ErrorRecord errorRecord = new ErrorRecord(outerException, DiscoveryProviderNotFoundErrorId, ErrorCategory.NotImplemented, null);
return errorRecord;
}
else
{
string errorMessage = string.Format(
CultureInfo.InvariantCulture,
Modules.RemoteDiscoveryFailureFromDiscoveryProvider,
innerException.Message);
Exception outerException = new InvalidOperationException(errorMessage, innerException);
ErrorRecord errorRecord = new ErrorRecord(outerException, "DiscoveryProviderFailure", ErrorCategory.NotSpecified, null);
return errorRecord;
}
}
private static ErrorRecord GetErrorRecordForRemotePipelineInvocation(Exception innerException, string errorMessageTemplate)
{
string errorMessage = string.Format(
CultureInfo.InvariantCulture,
errorMessageTemplate,
innerException.Message);
Exception outerException = new InvalidOperationException(errorMessage, innerException);
RemoteException remoteException = innerException as RemoteException;
ErrorRecord remoteErrorRecord = remoteException != null ? remoteException.ErrorRecord : null;
string errorId = remoteErrorRecord != null ? remoteErrorRecord.FullyQualifiedErrorId : innerException.GetType().Name;
ErrorCategory errorCategory = remoteErrorRecord != null ? remoteErrorRecord.CategoryInfo.Category : ErrorCategory.NotSpecified;
ErrorRecord errorRecord = new ErrorRecord(outerException, errorId, errorCategory, null);
return errorRecord;
}
private static ErrorRecord GetErrorRecordForRemotePipelineInvocation(ErrorRecord innerErrorRecord, string errorMessageTemplate)
{
string innerErrorMessage;
if (innerErrorRecord.ErrorDetails != null && innerErrorRecord.ErrorDetails.Message != null)
{
innerErrorMessage = innerErrorRecord.ErrorDetails.Message;
}
else if (innerErrorRecord.Exception != null && innerErrorRecord.Exception.Message != null)
{
innerErrorMessage = innerErrorRecord.Exception.Message;
}
else
{
innerErrorMessage = innerErrorRecord.ToString();
}
string errorMessage = string.Format(
CultureInfo.InvariantCulture,
errorMessageTemplate,
innerErrorMessage);
ErrorRecord outerErrorRecord = new ErrorRecord(innerErrorRecord, null /* null means: do not replace the exception */);
ErrorDetails outerErrorDetails = new ErrorDetails(errorMessage);
outerErrorRecord.ErrorDetails = outerErrorDetails;
return outerErrorRecord;
}
private static IEnumerable<T> EnumerateWithCatch<T>(IEnumerable<T> enumerable, Action<Exception> exceptionHandler)
{
IEnumerator<T> enumerator = null;
try
{
enumerator = enumerable.GetEnumerator();
}
catch (Exception e)
{
exceptionHandler(e);
}
if (enumerator != null)
using (enumerator)
{
bool gotResults = false;
do
{
try
{
gotResults = false;
gotResults = enumerator.MoveNext();
}
catch (Exception e)
{
exceptionHandler(e);
}
if (gotResults)
{
T currentItem = default(T);
bool gotCurrentItem = false;
try
{
currentItem = enumerator.Current;
gotCurrentItem = true;
}
catch (Exception e)
{
exceptionHandler(e);
}
if (gotCurrentItem)
{
yield return currentItem;
}
else
{
yield break;
}
}
} while (gotResults);
}
}
private static void HandleErrorFromPipeline(Cmdlet cmdlet, ErrorRecord errorRecord, PowerShell powerShell)
{
if (!cmdlet.MyInvocation.ExpectingInput)
{
if (((powerShell.Runspace != null) && (powerShell.Runspace.RunspaceStateInfo.State != RunspaceState.Opened)) ||
((powerShell.RunspacePool != null) && (powerShell.RunspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Opened)))
{
cmdlet.ThrowTerminatingError(errorRecord);
}
}
cmdlet.WriteError(errorRecord);
}
internal static IEnumerable<PSObject> InvokePowerShell(
PowerShell powerShell,
CancellationToken cancellationToken,
PSCmdlet cmdlet,
string errorMessageTemplate)
{
CopyParameterFromCmdletToPowerShell(cmdlet, powerShell, "ErrorAction");
CopyParameterFromCmdletToPowerShell(cmdlet, powerShell, "WarningAction");
CopyParameterFromCmdletToPowerShell(cmdlet, powerShell, "InformationAction");
CopyParameterFromCmdletToPowerShell(cmdlet, powerShell, "Verbose");
CopyParameterFromCmdletToPowerShell(cmdlet, powerShell, "Debug");
var invocationSettings = new PSInvocationSettings { Host = cmdlet.Host };
// TODO/FIXME: ETW events for the output stream
IEnumerable<PSObject> outputStream = powerShell.IsNested
? InvokeNestedPowerShell(powerShell, cancellationToken, cmdlet, invocationSettings, errorMessageTemplate)
: InvokeTopLevelPowerShell(powerShell, cancellationToken, cmdlet, invocationSettings, errorMessageTemplate);
return EnumerateWithCatch(
outputStream,
delegate (Exception exception)
{
ErrorRecord errorRecord = GetErrorRecordForRemotePipelineInvocation(exception, errorMessageTemplate);
HandleErrorFromPipeline(cmdlet, errorRecord, powerShell);
});
}
#endregion PSRP
#region CIM
private const string DiscoveryProviderNamespace = "root/Microsoft/Windows/Powershellv3";
private const string DiscoveryProviderModuleClass = "PS_Module";
private const string DiscoveryProviderFileClass = "PS_ModuleFile";
private const string DiscoveryProviderAssociationClass = "PS_ModuleToModuleFile";
private static T GetPropertyValue<T>(CimInstance cimInstance, string propertyName, T defaultValue)
{
CimProperty cimProperty = cimInstance.CimInstanceProperties[propertyName];
if (cimProperty == null)
{
return defaultValue;
}
object propertyValue = cimProperty.Value;
if (propertyValue is T)
{
return (T)propertyValue;
}
if (propertyValue is string)
{
string stringValue = (string)propertyValue;
try
{
if (typeof(T) == typeof(bool))
{
return (T)(object)XmlConvert.ToBoolean(stringValue);
}
else if (typeof(T) == typeof(UInt16))
{
return (T)(object)UInt16.Parse(stringValue, CultureInfo.InvariantCulture);
}
else if (typeof(T) == typeof(byte[]))
{
byte[] contentBytes = Convert.FromBase64String(stringValue);
byte[] lengthBytes = BitConverter.GetBytes(contentBytes.Length + 4);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(lengthBytes);
}
return (T)(object)(lengthBytes.Concat(contentBytes).ToArray());
}
}
catch (Exception)
{
return defaultValue;
}
}
return defaultValue;
}
internal enum CimFileCode
{
Unknown = 0,
PsdV1,
TypesV1,
FormatV1,
CmdletizationV1,
}
internal abstract class CimModuleFile
{
public CimFileCode FileCode
{
get
{
if (this.FileName.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase))
{
return CimFileCode.PsdV1;
}
if (this.FileName.EndsWith(".cdxml", StringComparison.OrdinalIgnoreCase))
{
return CimFileCode.CmdletizationV1;
}
if (this.FileName.EndsWith(".types.ps1xml", StringComparison.OrdinalIgnoreCase))
{
return CimFileCode.TypesV1;
}
if (this.FileName.EndsWith(".format.ps1xml", StringComparison.OrdinalIgnoreCase))
{
return CimFileCode.FormatV1;
}
return CimFileCode.Unknown;
}
}
public abstract string FileName { get; }
internal abstract byte[] RawFileDataCore { get; }
public byte[] RawFileData
{
get { return this.RawFileDataCore.Skip(4).ToArray(); }
}
public string FileData
{
get
{
if (_fileData == null)
{
using (var ms = new MemoryStream(this.RawFileData))
using (var sr = new StreamReader(ms, detectEncodingFromByteOrderMarks: true))
{
_fileData = sr.ReadToEnd();
}
}
return _fileData;
}
}
private string _fileData;
}
internal class CimModule
{
private readonly CimInstance _baseObject;
internal CimModule(CimInstance baseObject)
{
Dbg.Assert(baseObject != null, "Caller should make sure baseObject != null");
Dbg.Assert(
baseObject.CimSystemProperties.ClassName.Equals(DiscoveryProviderModuleClass, StringComparison.OrdinalIgnoreCase),
"Caller should make sure baseObject is an instance of the right CIM class");
_baseObject = baseObject;
}
public string ModuleName
{
get
{
var rawModuleName = GetPropertyValue<string>(_baseObject, "ModuleName", string.Empty);
return Path.GetFileName(rawModuleName);
}
}
private enum DiscoveredModuleType : ushort
{
Unknown = 0,
Cim = 1,
}
public bool IsPsCimModule
{
get
{
UInt16 moduleTypeInt = GetPropertyValue<UInt16>(_baseObject, "ModuleType", 0);
DiscoveredModuleType moduleType = (DiscoveredModuleType)moduleTypeInt;
bool isPsCimModule = (moduleType == DiscoveredModuleType.Cim);
return isPsCimModule;
}
}
public CimModuleFile MainManifest
{
get
{
byte[] rawFileData = GetPropertyValue<byte[]>(_baseObject, "moduleManifestFileData", Utils.EmptyArray<byte>());
return new CimModuleManifestFile(this.ModuleName + ".psd1", rawFileData);
}
}
public IEnumerable<CimModuleFile> ModuleFiles
{
get { return _moduleFiles; }
}
internal void FetchAllModuleFiles(CimSession cimSession, string cimNamespace, CimOperationOptions operationOptions)
{
IEnumerable<CimInstance> associatedInstances = cimSession.EnumerateAssociatedInstances(
cimNamespace,
_baseObject,
DiscoveryProviderAssociationClass,
DiscoveryProviderFileClass,
"Antecedent",
"Dependent",
operationOptions);
IEnumerable<CimModuleFile> associatedFiles = associatedInstances.Select(i => new CimModuleImplementationFile(i));
_moduleFiles = associatedFiles.ToList();
}
private List<CimModuleFile> _moduleFiles;
private class CimModuleManifestFile : CimModuleFile
{
internal CimModuleManifestFile(string fileName, byte[] rawFileData)
{
Dbg.Assert(fileName != null, "Caller should make sure fileName != null");
Dbg.Assert(rawFileData != null, "Caller should make sure rawFileData != null");
FileName = fileName;
RawFileDataCore = rawFileData;
}
public override string FileName { get; }
internal override byte[] RawFileDataCore { get; }
}
private class CimModuleImplementationFile : CimModuleFile
{
private readonly CimInstance _baseObject;
internal CimModuleImplementationFile(CimInstance baseObject)
{
Dbg.Assert(baseObject != null, "Caller should make sure baseObject != null");
Dbg.Assert(
baseObject.CimSystemProperties.ClassName.Equals(DiscoveryProviderFileClass, StringComparison.OrdinalIgnoreCase),
"Caller should make sure baseObject is an instance of the right CIM class");
_baseObject = baseObject;
}
public override string FileName
{
get
{
string rawFileName = GetPropertyValue<string>(_baseObject, "FileName", string.Empty);
return Path.GetFileName(rawFileName);
}
}
internal override byte[] RawFileDataCore
{
get { return GetPropertyValue<byte[]>(_baseObject, "FileData", Utils.EmptyArray<byte>()); }
}
}
}
internal static IEnumerable<CimModule> GetCimModules(
CimSession cimSession,
Uri resourceUri,
string cimNamespace,
IEnumerable<string> moduleNamePatterns,
bool onlyManifests,
Cmdlet cmdlet,
CancellationToken cancellationToken)
{
moduleNamePatterns = moduleNamePatterns ?? new[] { "*" };
HashSet<string> alreadyEmittedNamesOfCimModules = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
IEnumerable<CimModule> remoteModules = moduleNamePatterns
.SelectMany(moduleNamePattern =>
RemoteDiscoveryHelper.GetCimModules(cimSession, resourceUri, cimNamespace, moduleNamePattern, onlyManifests, cmdlet, cancellationToken));
foreach (CimModule remoteModule in remoteModules)
{
if (!alreadyEmittedNamesOfCimModules.Contains(remoteModule.ModuleName))
{
alreadyEmittedNamesOfCimModules.Add(remoteModule.ModuleName);
yield return remoteModule;
}
}
}
private static IEnumerable<CimModule> GetCimModules(
CimSession cimSession,
Uri resourceUri,
string cimNamespace,
string moduleNamePattern,
bool onlyManifests,
Cmdlet cmdlet,
CancellationToken cancellationToken)
{
Dbg.Assert(cimSession != null, "Caller should verify cimSession != null");
Dbg.Assert(moduleNamePattern != null, "Caller should verify that moduleNamePattern != null");
const WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant;
var wildcardPattern = WildcardPattern.Get(moduleNamePattern, wildcardOptions);
string dosWildcard = WildcardPatternToDosWildcardParser.Parse(wildcardPattern);
var options = new CimOperationOptions { CancellationToken = cancellationToken };
options.SetCustomOption("PS_ModuleNamePattern", dosWildcard, mustComply: false);
if (resourceUri != null)
{
options.ResourceUri = resourceUri;
}
if (string.IsNullOrEmpty(cimNamespace) && (resourceUri == null))
{
cimNamespace = DiscoveryProviderNamespace;
}
// TODO/FIXME: ETW for method invocation
IEnumerable<CimInstance> syncResults = cimSession.EnumerateInstances(
cimNamespace,
DiscoveryProviderModuleClass,
options);
// TODO/FIXME: ETW for method results
IEnumerable<CimModule> cimModules = syncResults
.Select(cimInstance => new CimModule(cimInstance))
.Where(cimModule => wildcardPattern.IsMatch(cimModule.ModuleName));
if (!onlyManifests)
{
cimModules = cimModules.Select(
delegate (CimModule cimModule)
{
cimModule.FetchAllModuleFiles(cimSession, cimNamespace, options);
return cimModule;
});
}
return EnumerateWithCatch(
cimModules,
delegate (Exception exception)
{
ErrorRecord errorRecord = GetErrorRecordForRemoteDiscoveryProvider(exception);
if (!cmdlet.MyInvocation.ExpectingInput)
{
if (((-1) != errorRecord.FullyQualifiedErrorId.IndexOf(DiscoveryProviderNotFoundErrorId, StringComparison.OrdinalIgnoreCase)) ||
(cancellationToken.IsCancellationRequested || (exception is OperationCanceledException)) ||
(!cimSession.TestConnection()))
{
cmdlet.ThrowTerminatingError(errorRecord);
}
}
cmdlet.WriteError(errorRecord);
});
}
internal static Hashtable RewriteManifest(Hashtable originalManifest)
{
return RewriteManifest(originalManifest, null, null, null);
}
private static readonly string[] s_manifestEntriesToKeepAsString = new[] {
"GUID",
"Author",
"CompanyName",
"Copyright",
"ModuleVersion",
"Description",
"HelpInfoURI",
};
private static readonly string[] s_manifestEntriesToKeepAsStringArray = new[] {
"FunctionsToExport",
"VariablesToExport",
"AliasesToExport",
"CmdletsToExport",
};
internal static Hashtable RewriteManifest(
Hashtable originalManifest,
IEnumerable<string> nestedModules,
IEnumerable<string> typesToProcess,
IEnumerable<string> formatsToProcess)
{
nestedModules = nestedModules ?? Utils.EmptyArray<string>();
typesToProcess = typesToProcess ?? Utils.EmptyArray<string>();
formatsToProcess = formatsToProcess ?? Utils.EmptyArray<string>();
var newManifest = new Hashtable(StringComparer.OrdinalIgnoreCase);
newManifest["NestedModules"] = nestedModules;
newManifest["TypesToProcess"] = typesToProcess;
newManifest["FormatsToProcess"] = formatsToProcess;
newManifest["PrivateData"] = originalManifest["PrivateData"];
foreach (DictionaryEntry entry in originalManifest)
{
if (s_manifestEntriesToKeepAsString.Contains(entry.Key as string, StringComparer.OrdinalIgnoreCase))
{
var value = (string)LanguagePrimitives.ConvertTo(entry.Value, typeof(string), CultureInfo.InvariantCulture);
newManifest[entry.Key] = value;
}
else if (s_manifestEntriesToKeepAsStringArray.Contains(entry.Key as string, StringComparer.OrdinalIgnoreCase))
{
var values = (string[])LanguagePrimitives.ConvertTo(entry.Value, typeof(string[]), CultureInfo.InvariantCulture);
newManifest[entry.Key] = values;
}
}
return newManifest;
}
private static CimCredential GetCimCredentials(PasswordAuthenticationMechanism authenticationMechanism, PSCredential credential)
{
NetworkCredential networkCredential = credential.GetNetworkCredential();
return new CimCredential(authenticationMechanism, networkCredential.Domain, networkCredential.UserName, credential.Password);
}
private static Exception GetExceptionWhenAuthenticationRequiresCredential(string authentication)
{
string errorMessage = string.Format(
CultureInfo.InvariantCulture,
RemotingErrorIdStrings.AuthenticationMechanismRequiresCredential,
authentication);
throw new ArgumentException(errorMessage);
}
private static CimCredential GetCimCredentials(string authentication, PSCredential credential)
{
if (authentication == null || (authentication.Equals("Default", StringComparison.OrdinalIgnoreCase)))
{
if (credential == null)
{
return null;
}
else
{
return GetCimCredentials(PasswordAuthenticationMechanism.Default, credential);
}
}
if (authentication.Equals("Basic", StringComparison.OrdinalIgnoreCase))
{
if (credential == null)
{
throw GetExceptionWhenAuthenticationRequiresCredential(authentication);
}
else
{
return GetCimCredentials(PasswordAuthenticationMechanism.Basic, credential);
}
}
if (authentication.Equals("Negotiate", StringComparison.OrdinalIgnoreCase))
{
if (credential == null)
{
return new CimCredential(ImpersonatedAuthenticationMechanism.Negotiate);
}
else
{
return GetCimCredentials(PasswordAuthenticationMechanism.Negotiate, credential);
}
}
if (authentication.Equals("CredSSP", StringComparison.OrdinalIgnoreCase))
{
if (credential == null)
{
throw GetExceptionWhenAuthenticationRequiresCredential(authentication);
}
else
{
return GetCimCredentials(PasswordAuthenticationMechanism.CredSsp, credential);
}
}
if (authentication.Equals("Digest", StringComparison.OrdinalIgnoreCase))
{
if (credential == null)
{
throw GetExceptionWhenAuthenticationRequiresCredential(authentication);
}
else
{
return GetCimCredentials(PasswordAuthenticationMechanism.Digest, credential);
}
}
if (authentication.Equals("Kerberos", StringComparison.OrdinalIgnoreCase))
{
if (credential == null)
{
return new CimCredential(ImpersonatedAuthenticationMechanism.Kerberos);
}
else
{
return GetCimCredentials(PasswordAuthenticationMechanism.Kerberos, credential);
}
}
Dbg.Assert(false, "Unrecognized authentication mechanism [ValidateSet should prevent that from happening]");
throw new ArgumentOutOfRangeException("authentication");
}
internal static CimSession CreateCimSession(
string computerName,
PSCredential credential,
string authentication,
CancellationToken cancellationToken,
PSCmdlet cmdlet)
{
var sessionOptions = new CimSessionOptions();
CimCredential cimCredentials = GetCimCredentials(authentication, credential);
if (cimCredentials != null)
{
sessionOptions.AddDestinationCredentials(cimCredentials);
}
CimSession cimSession = CimSession.Create(computerName, sessionOptions);
return cimSession;
}
internal static Hashtable ConvertCimModuleFileToManifestHashtable(RemoteDiscoveryHelper.CimModuleFile cimModuleFile, string temporaryModuleManifestPath, ModuleCmdletBase cmdlet, ref bool containedErrors)
{
Dbg.Assert(cimModuleFile.FileCode == RemoteDiscoveryHelper.CimFileCode.PsdV1, "Caller should verify the file is of the right type");
ScriptBlockAst scriptBlockAst = null;
if (!containedErrors)
{
System.Management.Automation.Language.Token[] throwAwayTokens;
ParseError[] parseErrors;
scriptBlockAst = System.Management.Automation.Language.Parser.ParseInput(cimModuleFile.FileData, temporaryModuleManifestPath, out throwAwayTokens, out parseErrors);
if ((scriptBlockAst == null) || (parseErrors != null && parseErrors.Length > 0))
{
containedErrors = true;
}
}
Hashtable data = null;
if (!containedErrors)
{
ScriptBlock scriptBlock = new ScriptBlock(scriptBlockAst, isFilter: false);
data = cmdlet.LoadModuleManifestData(
temporaryModuleManifestPath,
scriptBlock,
ModuleCmdletBase.ModuleManifestMembers,
0 /* - don't write errors, don't load elements, don't return null on first error */,
ref containedErrors);
}
return data;
}
#endregion CIM
#region Protocol/transport agnostic functionality
internal static string GetModulePath(string remoteModuleName, Version remoteModuleVersion, string computerName, Runspace localRunspace)
{
computerName = computerName ?? string.Empty;
string sanitizedRemoteModuleName = Regex.Replace(remoteModuleName, "[^a-zA-Z0-9]", string.Empty);
string sanitizedComputerName = Regex.Replace(computerName, "[^a-zA-Z0-9]", string.Empty);
string moduleName = string.Format(
CultureInfo.InvariantCulture,
"remoteIpMoProxy_{0}_{1}_{2}_{3}",
sanitizedRemoteModuleName.Substring(0, Math.Min(sanitizedRemoteModuleName.Length, 100)),
remoteModuleVersion,
sanitizedComputerName.Substring(0, Math.Min(sanitizedComputerName.Length, 100)),
localRunspace.InstanceId);
string modulePath = Path.Combine(Path.GetTempPath(), moduleName);
return modulePath;
}
internal static void AssociatePSModuleInfoWithSession(PSModuleInfo moduleInfo, CimSession cimSession, Uri resourceUri, string cimNamespace)
{
AssociatePSModuleInfoWithSession(moduleInfo, (object)new Tuple<CimSession, Uri, string>(cimSession, resourceUri, cimNamespace));
}
internal static void AssociatePSModuleInfoWithSession(PSModuleInfo moduleInfo, PSSession psSession)
{
AssociatePSModuleInfoWithSession(moduleInfo, (object)psSession);
}
private static void AssociatePSModuleInfoWithSession(PSModuleInfo moduleInfo, object weaklyTypedSession)
{
s_moduleInfoToSession.Add(moduleInfo, weaklyTypedSession);
}
private static readonly ConditionalWeakTable<PSModuleInfo, object> s_moduleInfoToSession = new ConditionalWeakTable<PSModuleInfo, object>();
internal static void DispatchModuleInfoProcessing(
PSModuleInfo moduleInfo,
Action localAction,
Action<CimSession, Uri, string> cimSessionAction,
Action<PSSession> psSessionAction)
{
object weaklyTypeSession;
if (!s_moduleInfoToSession.TryGetValue(moduleInfo, out weaklyTypeSession))
{
localAction();
return;
}
Tuple<CimSession, Uri, string> cimSessionInfo = weaklyTypeSession as Tuple<CimSession, Uri, string>;
if (cimSessionInfo != null)
{
cimSessionAction(cimSessionInfo.Item1, cimSessionInfo.Item2, cimSessionInfo.Item3);
return;
}
PSSession psSession = weaklyTypeSession as PSSession;
if (psSession != null)
{
psSessionAction(psSession);
return;
}
Dbg.Assert(false, "PSModuleInfo was associated with an unrecognized session type");
}
#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 copyrightD
* 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.Reflection;
using log4net;
using OMV = OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
namespace OpenSim.Region.Physics.BulletSPlugin
{
public sealed class BSCharacter : BSPhysObject
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[BULLETS CHAR]";
// private bool _stopped;
private OMV.Vector3 _size;
private bool _grabbed;
private bool _selected;
private float _mass;
private float _avatarVolume;
private float _collisionScore;
private OMV.Vector3 _acceleration;
private int _physicsActorType;
private bool _isPhysical;
private bool _flying;
private bool _setAlwaysRun;
private bool _throttleUpdates;
private bool _floatOnWater;
private OMV.Vector3 _rotationalVelocity;
private bool _kinematic;
private float _buoyancy;
private BSActorAvatarMove m_moveActor;
private const string AvatarMoveActorName = "BSCharacter.AvatarMove";
private OMV.Vector3 _PIDTarget;
private bool _usePID;
private float _PIDTau;
// public override OMV.Vector3 RawVelocity
// { get { return base.RawVelocity; }
// set {
// if (value != base.RawVelocity)
// Util.PrintCallStack();
// Console.WriteLine("Set rawvel to {0}", value);
// base.RawVelocity = value; }
// }
// Avatars are always complete (in the physics engine sense)
public override bool IsIncomplete { get { return false; } }
public BSCharacter(
uint localID, String avName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 vel, OMV.Vector3 size, bool isFlying)
: base(parent_scene, localID, avName, "BSCharacter")
{
_physicsActorType = (int)ActorTypes.Agent;
RawPosition = pos;
_flying = isFlying;
RawOrientation = OMV.Quaternion.Identity;
RawVelocity = vel;
_buoyancy = ComputeBuoyancyFromFlying(isFlying);
Friction = BSParam.AvatarStandingFriction;
Density = BSParam.AvatarDensity;
// Old versions of ScenePresence passed only the height. If width and/or depth are zero,
// replace with the default values.
_size = size;
if (_size.X == 0f) _size.X = BSParam.AvatarCapsuleDepth;
if (_size.Y == 0f) _size.Y = BSParam.AvatarCapsuleWidth;
// The dimensions of the physical capsule are kept in the scale.
// Physics creates a unit capsule which is scaled by the physics engine.
Scale = ComputeAvatarScale(_size);
// set _avatarVolume and _mass based on capsule size, _density and Scale
ComputeAvatarVolumeAndMass();
DetailLog(
"{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5},pos={6},vel={7}",
LocalID, _size, Scale, Density, _avatarVolume, RawMass, pos, vel);
// do actual creation in taint time
PhysScene.TaintedObject(LocalID, "BSCharacter.create", delegate()
{
DetailLog("{0},BSCharacter.create,taint", LocalID);
// New body and shape into PhysBody and PhysShape
PhysScene.Shapes.GetBodyAndShape(true, PhysScene.World, this);
// The avatar's movement is controlled by this motor that speeds up and slows down
// the avatar seeking to reach the motor's target speed.
// This motor runs as a prestep action for the avatar so it will keep the avatar
// standing as well as moving. Destruction of the avatar will destroy the pre-step action.
m_moveActor = new BSActorAvatarMove(PhysScene, this, AvatarMoveActorName);
PhysicalActors.Add(AvatarMoveActorName, m_moveActor);
SetPhysicalProperties();
IsInitialized = true;
});
return;
}
// called when this character is being destroyed and the resources should be released
public override void Destroy()
{
IsInitialized = false;
base.Destroy();
DetailLog("{0},BSCharacter.Destroy", LocalID);
PhysScene.TaintedObject(LocalID, "BSCharacter.destroy", delegate()
{
PhysScene.Shapes.DereferenceBody(PhysBody, null /* bodyCallback */);
PhysBody.Clear();
PhysShape.Dereference(PhysScene);
PhysShape = new BSShapeNull();
});
}
private void SetPhysicalProperties()
{
PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody);
ForcePosition = RawPosition;
// Set the velocity
if (m_moveActor != null)
m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false);
ForceVelocity = RawVelocity;
TargetVelocity = RawVelocity;
// This will enable or disable the flying buoyancy of the avatar.
// Needs to be reset especially when an avatar is recreated after crossing a region boundry.
Flying = _flying;
PhysScene.PE.SetRestitution(PhysBody, BSParam.AvatarRestitution);
PhysScene.PE.SetMargin(PhysShape.physShapeInfo, PhysScene.Params.collisionMargin);
PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale);
PhysScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold);
if (BSParam.CcdMotionThreshold > 0f)
{
PhysScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold);
PhysScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius);
}
UpdatePhysicalMassProperties(RawMass, false);
// Make so capsule does not fall over
PhysScene.PE.SetAngularFactorV(PhysBody, OMV.Vector3.Zero);
// The avatar mover sets some parameters.
PhysicalActors.Refresh();
PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_CHARACTER_OBJECT);
PhysScene.PE.AddObjectToWorld(PhysScene.World, PhysBody);
// PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.ACTIVE_TAG);
PhysScene.PE.ForceActivationState(PhysBody, ActivationState.DISABLE_DEACTIVATION);
PhysScene.PE.UpdateSingleAabb(PhysScene.World, PhysBody);
// Do this after the object has been added to the world
if (BSParam.AvatarToAvatarCollisionsByDefault)
PhysBody.collisionType = CollisionType.Avatar;
else
PhysBody.collisionType = CollisionType.PhantomToOthersAvatar;
PhysBody.ApplyCollisionMask(PhysScene);
}
public override void RequestPhysicsterseUpdate()
{
base.RequestPhysicsterseUpdate();
}
// No one calls this method so I don't know what it could possibly mean
public override bool Stopped { get { return false; } }
public override OMV.Vector3 Size {
get
{
// Avatar capsule size is kept in the scale parameter.
return _size;
}
set {
// This is how much the avatar size is changing. Positive means getting bigger.
// The avatar altitude must be adjusted for this change.
float heightChange = value.Z - _size.Z;
_size = value;
// Old versions of ScenePresence passed only the height. If width and/or depth are zero,
// replace with the default values.
if (_size.X == 0f) _size.X = BSParam.AvatarCapsuleDepth;
if (_size.Y == 0f) _size.Y = BSParam.AvatarCapsuleWidth;
Scale = ComputeAvatarScale(_size);
ComputeAvatarVolumeAndMass();
DetailLog("{0},BSCharacter.setSize,call,size={1},scale={2},density={3},volume={4},mass={5}",
LocalID, _size, Scale, Density, _avatarVolume, RawMass);
PhysScene.TaintedObject(LocalID, "BSCharacter.setSize", delegate()
{
if (PhysBody.HasPhysicalBody && PhysShape.physShapeInfo.HasPhysicalShape)
{
PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale);
UpdatePhysicalMassProperties(RawMass, true);
// Adjust the avatar's position to account for the increase/decrease in size
ForcePosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, RawPosition.Z + heightChange / 2f);
// Make sure this change appears as a property update event
PhysScene.PE.PushUpdate(PhysBody);
}
});
}
}
public override PrimitiveBaseShape Shape
{
set { BaseShape = value; }
}
public override bool Grabbed {
set { _grabbed = value; }
}
public override bool Selected {
set { _selected = value; }
}
public override bool IsSelected
{
get { return _selected; }
}
public override void CrossingFailure() { return; }
public override void link(PhysicsActor obj) { return; }
public override void delink() { return; }
// Set motion values to zero.
// Do it to the properties so the values get set in the physics engine.
// Push the setting of the values to the viewer.
// Called at taint time!
public override void ZeroMotion(bool inTaintTime)
{
RawVelocity = OMV.Vector3.Zero;
_acceleration = OMV.Vector3.Zero;
_rotationalVelocity = OMV.Vector3.Zero;
// Zero some other properties directly into the physics engine
PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate()
{
if (PhysBody.HasPhysicalBody)
PhysScene.PE.ClearAllForces(PhysBody);
});
}
public override void ZeroAngularMotion(bool inTaintTime)
{
_rotationalVelocity = OMV.Vector3.Zero;
PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate()
{
if (PhysBody.HasPhysicalBody)
{
PhysScene.PE.SetInterpolationAngularVelocity(PhysBody, OMV.Vector3.Zero);
PhysScene.PE.SetAngularVelocity(PhysBody, OMV.Vector3.Zero);
// The next also get rid of applied linear force but the linear velocity is untouched.
PhysScene.PE.ClearForces(PhysBody);
}
});
}
public override void LockAngularMotion(OMV.Vector3 axis) { return; }
public override OMV.Vector3 Position {
get {
// Don't refetch the position because this function is called a zillion times
// RawPosition = PhysicsScene.PE.GetObjectPosition(Scene.World, LocalID);
return RawPosition;
}
set {
RawPosition = value;
PhysScene.TaintedObject(LocalID, "BSCharacter.setPosition", delegate()
{
DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
PositionSanityCheck();
ForcePosition = RawPosition;
});
}
}
public override OMV.Vector3 ForcePosition {
get {
RawPosition = PhysScene.PE.GetPosition(PhysBody);
return RawPosition;
}
set {
RawPosition = value;
if (PhysBody.HasPhysicalBody)
{
PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
}
}
}
// Check that the current position is sane and, if not, modify the position to make it so.
// Check for being below terrain or on water.
// Returns 'true' of the position was made sane by some action.
private bool PositionSanityCheck()
{
bool ret = false;
// TODO: check for out of bounds
if (!PhysScene.TerrainManager.IsWithinKnownTerrain(RawPosition))
{
// The character is out of the known/simulated area.
// Force the avatar position to be within known. ScenePresence will use the position
// plus the velocity to decide if the avatar is moving out of the region.
RawPosition = PhysScene.TerrainManager.ClampPositionIntoKnownTerrain(RawPosition);
DetailLog("{0},BSCharacter.PositionSanityCheck,notWithinKnownTerrain,clampedPos={1}", LocalID, RawPosition);
return true;
}
// If below the ground, move the avatar up
float terrainHeight = PhysScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition);
if (Position.Z < terrainHeight)
{
DetailLog("{0},BSCharacter.PositionSanityCheck,adjustForUnderGround,pos={1},terrain={2}", LocalID, RawPosition, terrainHeight);
RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, terrainHeight + BSParam.AvatarBelowGroundUpCorrectionMeters);
ret = true;
}
if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0)
{
float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(RawPosition);
if (Position.Z < waterHeight)
{
RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, waterHeight);
ret = true;
}
}
return ret;
}
// A version of the sanity check that also makes sure a new position value is
// pushed back to the physics engine. This routine would be used by anyone
// who is not already pushing the value.
private bool PositionSanityCheck(bool inTaintTime)
{
bool ret = false;
if (PositionSanityCheck())
{
// The new position value must be pushed into the physics engine but we can't
// just assign to "Position" because of potential call loops.
PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.PositionSanityCheck", delegate()
{
DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
ForcePosition = RawPosition;
});
ret = true;
}
return ret;
}
public override float Mass { get { return _mass; } }
// used when we only want this prim's mass and not the linkset thing
public override float RawMass {
get {return _mass; }
}
public override void UpdatePhysicalMassProperties(float physMass, bool inWorld)
{
OMV.Vector3 localInertia = PhysScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass);
PhysScene.PE.SetMassProps(PhysBody, physMass, localInertia);
}
public override OMV.Vector3 Force {
get { return RawForce; }
set {
RawForce = value;
// m_log.DebugFormat("{0}: Force = {1}", LogHeader, _force);
PhysScene.TaintedObject(LocalID, "BSCharacter.SetForce", delegate()
{
DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, RawForce);
if (PhysBody.HasPhysicalBody)
PhysScene.PE.SetObjectForce(PhysBody, RawForce);
});
}
}
// Avatars don't do vehicles
public override int VehicleType { get { return (int)Vehicle.TYPE_NONE; } set { return; } }
public override void VehicleFloatParam(int param, float value) { }
public override void VehicleVectorParam(int param, OMV.Vector3 value) {}
public override void VehicleRotationParam(int param, OMV.Quaternion rotation) { }
public override void VehicleFlags(int param, bool remove) { }
// Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more
public override void SetVolumeDetect(int param) { return; }
public override bool IsVolumeDetect { get { return false; } }
public override OMV.Vector3 GeometricCenter { get { return OMV.Vector3.Zero; } }
public override OMV.Vector3 CenterOfMass { get { return OMV.Vector3.Zero; } }
// Sets the target in the motor. This starts the changing of the avatar's velocity.
public override OMV.Vector3 TargetVelocity
{
get
{
return base.m_targetVelocity;
}
set
{
DetailLog("{0},BSCharacter.setTargetVelocity,call,vel={1}", LocalID, value);
m_targetVelocity = value;
OMV.Vector3 targetVel = value;
if (_setAlwaysRun && !_flying)
targetVel *= new OMV.Vector3(BSParam.AvatarAlwaysRunFactor, BSParam.AvatarAlwaysRunFactor, 1f);
if (m_moveActor != null)
m_moveActor.SetVelocityAndTarget(RawVelocity, targetVel, false /* inTaintTime */);
}
}
// Directly setting velocity means this is what the user really wants now.
public override OMV.Vector3 Velocity {
get { return RawVelocity; }
set {
RawVelocity = value;
OMV.Vector3 vel = RawVelocity;
DetailLog("{0}: set Velocity = {1}", LogHeader, value);
PhysScene.TaintedObject(LocalID, "BSCharacter.setVelocity", delegate()
{
if (m_moveActor != null)
m_moveActor.SetVelocityAndTarget(vel, vel, true /* inTaintTime */);
DetailLog("{0},BSCharacter.setVelocity,taint,vel={1}", LocalID, vel);
ForceVelocity = vel;
});
}
}
public override OMV.Vector3 ForceVelocity {
get { return RawVelocity; }
set {
PhysScene.AssertInTaintTime("BSCharacter.ForceVelocity");
// Util.PrintCallStack();
DetailLog("{0}: set ForceVelocity = {1}", LogHeader, value);
RawVelocity = value;
PhysScene.PE.SetLinearVelocity(PhysBody, RawVelocity);
PhysScene.PE.Activate(PhysBody, true);
}
}
public override OMV.Vector3 Torque {
get { return RawTorque; }
set { RawTorque = value;
}
}
public override float CollisionScore {
get { return _collisionScore; }
set { _collisionScore = value;
}
}
public override OMV.Vector3 Acceleration {
get { return _acceleration; }
set { _acceleration = value; }
}
public override OMV.Quaternion Orientation {
get { return RawOrientation; }
set {
// Orientation is set zillions of times when an avatar is walking. It's like
// the viewer doesn't trust us.
if (RawOrientation != value)
{
RawOrientation = value;
PhysScene.TaintedObject(LocalID, "BSCharacter.setOrientation", delegate()
{
// Bullet assumes we know what we are doing when forcing orientation
// so it lets us go against all the rules and just compensates for them later.
// This forces rotation to be only around the Z axis and doesn't change any of the other axis.
// This keeps us from flipping the capsule over which the veiwer does not understand.
float oRoll, oPitch, oYaw;
RawOrientation.GetEulerAngles(out oRoll, out oPitch, out oYaw);
OMV.Quaternion trimmedOrientation = OMV.Quaternion.CreateFromEulers(0f, 0f, oYaw);
// DetailLog("{0},BSCharacter.setOrientation,taint,val={1},valDir={2},conv={3},convDir={4}",
// LocalID, RawOrientation, OMV.Vector3.UnitX * RawOrientation,
// trimmedOrientation, OMV.Vector3.UnitX * trimmedOrientation);
ForceOrientation = trimmedOrientation;
});
}
}
}
// Go directly to Bullet to get/set the value.
public override OMV.Quaternion ForceOrientation
{
get
{
RawOrientation = PhysScene.PE.GetOrientation(PhysBody);
return RawOrientation;
}
set
{
RawOrientation = value;
if (PhysBody.HasPhysicalBody)
{
// RawPosition = PhysicsScene.PE.GetPosition(BSBody);
PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
}
}
}
public override int PhysicsActorType {
get { return _physicsActorType; }
set { _physicsActorType = value;
}
}
public override bool IsPhysical {
get { return _isPhysical; }
set { _isPhysical = value;
}
}
public override bool IsSolid {
get { return true; }
}
public override bool IsStatic {
get { return false; }
}
public override bool IsPhysicallyActive {
get { return true; }
}
public override bool Flying {
get { return _flying; }
set {
_flying = value;
// simulate flying by changing the effect of gravity
Buoyancy = ComputeBuoyancyFromFlying(_flying);
}
}
// Flying is implimented by changing the avatar's buoyancy.
// Would this be done better with a vehicle type?
private float ComputeBuoyancyFromFlying(bool ifFlying) {
return ifFlying ? 1f : 0f;
}
public override bool
SetAlwaysRun {
get { return _setAlwaysRun; }
set { _setAlwaysRun = value; }
}
public override bool ThrottleUpdates {
get { return _throttleUpdates; }
set { _throttleUpdates = value; }
}
public override bool FloatOnWater {
set {
_floatOnWater = value;
PhysScene.TaintedObject(LocalID, "BSCharacter.setFloatOnWater", delegate()
{
if (PhysBody.HasPhysicalBody)
{
if (_floatOnWater)
CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
else
CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
}
});
}
}
public override OMV.Vector3 RotationalVelocity {
get { return _rotationalVelocity; }
set { _rotationalVelocity = value; }
}
public override OMV.Vector3 ForceRotationalVelocity {
get { return _rotationalVelocity; }
set { _rotationalVelocity = value; }
}
public override bool Kinematic {
get { return _kinematic; }
set { _kinematic = value; }
}
// neg=fall quickly, 0=1g, 1=0g, pos=float up
public override float Buoyancy {
get { return _buoyancy; }
set { _buoyancy = value;
PhysScene.TaintedObject(LocalID, "BSCharacter.setBuoyancy", delegate()
{
DetailLog("{0},BSCharacter.setBuoyancy,taint,buoy={1}", LocalID, _buoyancy);
ForceBuoyancy = _buoyancy;
});
}
}
public override float ForceBuoyancy {
get { return _buoyancy; }
set {
PhysScene.AssertInTaintTime("BSCharacter.ForceBuoyancy");
_buoyancy = value;
DetailLog("{0},BSCharacter.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy);
// Buoyancy is faked by changing the gravity applied to the object
float grav = BSParam.Gravity * (1f - _buoyancy);
Gravity = new OMV.Vector3(0f, 0f, grav);
if (PhysBody.HasPhysicalBody)
PhysScene.PE.SetGravity(PhysBody, Gravity);
}
}
// Used for MoveTo
public override OMV.Vector3 PIDTarget {
set { _PIDTarget = value; }
}
public override bool PIDActive { get; set; }
public override float PIDTau {
set { _PIDTau = value; }
}
public override void AddForce(OMV.Vector3 force, bool pushforce)
{
// Since this force is being applied in only one step, make this a force per second.
OMV.Vector3 addForce = force / PhysScene.LastTimeStep;
AddForce(addForce, pushforce, false);
}
public override void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) {
if (force.IsFinite())
{
OMV.Vector3 addForce = Util.ClampV(force, BSParam.MaxAddForceMagnitude);
// DetailLog("{0},BSCharacter.addForce,call,force={1}", LocalID, addForce);
PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.AddForce", delegate()
{
// Bullet adds this central force to the total force for this tick
// DetailLog("{0},BSCharacter.addForce,taint,force={1}", LocalID, addForce);
if (PhysBody.HasPhysicalBody)
{
PhysScene.PE.ApplyCentralForce(PhysBody, addForce);
}
});
}
else
{
m_log.WarnFormat("{0}: Got a NaN force applied to a character. LocalID={1}", LogHeader, LocalID);
return;
}
}
public override void AddAngularForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) {
}
public override void SetMomentum(OMV.Vector3 momentum) {
}
private OMV.Vector3 ComputeAvatarScale(OMV.Vector3 size)
{
OMV.Vector3 newScale = size;
// Bullet's capsule total height is the "passed height + radius * 2";
// The base capsule is 1 unit in diameter and 2 units in height (passed radius=0.5, passed height = 1)
// The number we pass in for 'scaling' is the multiplier to get that base
// shape to be the size desired.
// So, when creating the scale for the avatar height, we take the passed height
// (size.Z) and remove the caps.
// An oddity of the Bullet capsule implementation is that it presumes the Y
// dimension is the radius of the capsule. Even though some of the code allows
// for a asymmetrical capsule, other parts of the code presume it is cylindrical.
// Scale is multiplier of radius with one of "0.5"
float heightAdjust = BSParam.AvatarHeightMidFudge;
if (BSParam.AvatarHeightLowFudge != 0f || BSParam.AvatarHeightHighFudge != 0f)
{
const float AVATAR_LOW = 1.1f;
const float AVATAR_MID = 1.775f; // 1.87f
const float AVATAR_HI = 2.45f;
// An avatar is between 1.1 and 2.45 meters. Midpoint is 1.775m.
float midHeightOffset = size.Z - AVATAR_MID;
if (midHeightOffset < 0f)
{
// Small avatar. Add the adjustment based on the distance from midheight
heightAdjust += ((-1f * midHeightOffset) / (AVATAR_MID - AVATAR_LOW)) * BSParam.AvatarHeightLowFudge;
}
else
{
// Large avatar. Add the adjustment based on the distance from midheight
heightAdjust += ((midHeightOffset) / (AVATAR_HI - AVATAR_MID)) * BSParam.AvatarHeightHighFudge;
}
}
if (BSParam.AvatarShape == BSShapeCollection.AvatarShapeCapsule)
{
newScale.X = size.X / 2f;
newScale.Y = size.Y / 2f;
// The total scale height is the central cylindar plus the caps on the two ends.
newScale.Z = (size.Z + (Math.Min(size.X, size.Y) * 2) + heightAdjust) / 2f;
}
else
{
newScale.Z = size.Z + heightAdjust;
}
// m_log.DebugFormat("{0} ComputeAvatarScale: size={1},adj={2},scale={3}", LogHeader, size, heightAdjust, newScale);
// If smaller than the endcaps, just fake like we're almost that small
if (newScale.Z < 0)
newScale.Z = 0.1f;
DetailLog("{0},BSCharacter.ComputerAvatarScale,size={1},lowF={2},midF={3},hiF={4},adj={5},newScale={6}",
LocalID, size, BSParam.AvatarHeightLowFudge, BSParam.AvatarHeightMidFudge, BSParam.AvatarHeightHighFudge, heightAdjust, newScale);
return newScale;
}
// set _avatarVolume and _mass based on capsule size, _density and Scale
private void ComputeAvatarVolumeAndMass()
{
_avatarVolume = (float)(
Math.PI
* Size.X / 2f
* Size.Y / 2f // the area of capsule cylinder
* Size.Z // times height of capsule cylinder
+ 1.33333333f
* Math.PI
* Size.X / 2f
* Math.Min(Size.X, Size.Y) / 2
* Size.Y / 2f // plus the volume of the capsule end caps
);
_mass = Density * BSParam.DensityScaleFactor * _avatarVolume;
}
// The physics engine says that properties have updated. Update same and inform
// the world that things have changed.
public override void UpdateProperties(EntityProperties entprop)
{
// Let anyone (like the actors) modify the updated properties before they are pushed into the object and the simulator.
TriggerPreUpdatePropertyAction(ref entprop);
RawPosition = entprop.Position;
RawOrientation = entprop.Rotation;
// Smooth velocity. OpenSimulator is VERY sensitive to changes in velocity of the avatar
// and will send agent updates to the clients if velocity changes by more than
// 0.001m/s. Bullet introduces a lot of jitter in the velocity which causes many
// extra updates.
//
// XXX: Contrary to the above comment, setting an update threshold here above 0.4 actually introduces jitter to
// avatar movement rather than removes it. The larger the threshold, the bigger the jitter.
// This is most noticeable in level flight and can be seen with
// the "show updates" option in a viewer. With an update threshold, the RawVelocity cycles between a lower
// bound and an upper bound, where the difference between the two is enough to trigger a large delta v update
// and subsequently trigger an update in ScenePresence.SendTerseUpdateToAllClients(). The cause of this cycle (feedback?)
// has not yet been identified.
//
// If there is a threshold below 0.4 or no threshold check at all (as in ODE), then RawVelocity stays constant and extra
// updates are not triggered in ScenePresence.SendTerseUpdateToAllClients().
// if (!entprop.Velocity.ApproxEquals(RawVelocity, 0.1f))
RawVelocity = entprop.Velocity;
_acceleration = entprop.Acceleration;
_rotationalVelocity = entprop.RotationalVelocity;
// Do some sanity checking for the avatar. Make sure it's above ground and inbounds.
if (PositionSanityCheck(true))
{
DetailLog("{0},BSCharacter.UpdateProperties,updatePosForSanity,pos={1}", LocalID, RawPosition);
entprop.Position = RawPosition;
}
// remember the current and last set values
LastEntityProperties = CurrentEntityProperties;
CurrentEntityProperties = entprop;
// Tell the linkset about value changes
// Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this);
// Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop.
// PhysScene.PostUpdate(this);
DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}",
LocalID, RawPosition, RawOrientation, RawVelocity, _acceleration, _rotationalVelocity);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Description
{
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
public class ServiceDebugBehavior : IServiceBehavior
{
bool includeExceptionDetailInFaults = false;
bool httpHelpPageEnabled = true;
Uri httpHelpPageUrl;
bool httpsHelpPageEnabled = true;
Uri httpsHelpPageUrl;
Binding httpHelpPageBinding;
Binding httpsHelpPageBinding;
[DefaultValue(true)]
public bool HttpHelpPageEnabled
{
get { return this.httpHelpPageEnabled; }
set { this.httpHelpPageEnabled = value; }
}
[DefaultValue(null)]
[TypeConverter(typeof(UriTypeConverter))]
public Uri HttpHelpPageUrl
{
get { return this.httpHelpPageUrl; }
set
{
if (value != null && value.IsAbsoluteUri && value.Scheme != Uri.UriSchemeHttp)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxServiceMetadataBehaviorUrlMustBeHttpOrRelative,
"HttpHelpPageUrl", Uri.UriSchemeHttp, value.ToString(), value.Scheme));
}
this.httpHelpPageUrl = value;
}
}
[DefaultValue(true)]
public bool HttpsHelpPageEnabled
{
get { return this.httpsHelpPageEnabled; }
set { this.httpsHelpPageEnabled = value; }
}
[DefaultValue(null)]
[TypeConverter(typeof(UriTypeConverter))]
public Uri HttpsHelpPageUrl
{
get { return this.httpsHelpPageUrl; }
set
{
if (value != null && value.IsAbsoluteUri && value.Scheme != Uri.UriSchemeHttps)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxServiceMetadataBehaviorUrlMustBeHttpOrRelative,
"HttpsHelpPageUrl", Uri.UriSchemeHttps, value.ToString(), value.Scheme));
}
this.httpsHelpPageUrl = value;
}
}
public Binding HttpHelpPageBinding
{
get { return this.httpHelpPageBinding; }
set
{
if (value != null)
{
if (!value.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxBindingSchemeDoesNotMatch,
value.Scheme, value.GetType().ToString(), Uri.UriSchemeHttp));
}
CustomBinding customBinding = new CustomBinding(value);
TextMessageEncodingBindingElement textMessageEncodingBindingElement = customBinding.Elements.Find<TextMessageEncodingBindingElement>();
if (textMessageEncodingBindingElement != null && !textMessageEncodingBindingElement.MessageVersion.IsMatch(MessageVersion.None))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxIncorrectMessageVersion,
textMessageEncodingBindingElement.MessageVersion.ToString(), MessageVersion.None.ToString()));
}
HttpTransportBindingElement httpTransportBindingElement = customBinding.Elements.Find<HttpTransportBindingElement>();
if (httpTransportBindingElement != null)
{
httpTransportBindingElement.Method = "GET";
}
this.httpHelpPageBinding = customBinding;
}
}
}
public Binding HttpsHelpPageBinding
{
get { return this.httpsHelpPageBinding; }
set
{
if (value != null)
{
if (!value.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxBindingSchemeDoesNotMatch,
value.Scheme, value.GetType().ToString(), Uri.UriSchemeHttps));
}
CustomBinding customBinding = new CustomBinding(value);
TextMessageEncodingBindingElement textMessageEncodingBindingElement = customBinding.Elements.Find<TextMessageEncodingBindingElement>();
if (textMessageEncodingBindingElement != null && !textMessageEncodingBindingElement.MessageVersion.IsMatch(MessageVersion.None))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SFxIncorrectMessageVersion,
textMessageEncodingBindingElement.MessageVersion.ToString(), MessageVersion.None.ToString()));
}
HttpsTransportBindingElement httpsTransportBindingElement = customBinding.Elements.Find<HttpsTransportBindingElement>();
if (httpsTransportBindingElement != null)
{
httpsTransportBindingElement.Method = "GET";
}
this.httpsHelpPageBinding = customBinding;
}
}
}
[DefaultValue(false)]
public bool IncludeExceptionDetailInFaults
{
get { return this.includeExceptionDetailInFaults; }
set { this.includeExceptionDetailInFaults = value; }
}
void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
{
}
void IServiceBehavior.AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters)
{
if (parameters == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters");
}
ServiceDebugBehavior param = parameters.Find<ServiceDebugBehavior>();
if (param == null)
{
parameters.Add(this);
}
}
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
{
if (this.includeExceptionDetailInFaults)
{
for (int i = 0; i < serviceHostBase.ChannelDispatchers.Count; i++)
{
ChannelDispatcher channelDispatcher = serviceHostBase.ChannelDispatchers[i] as ChannelDispatcher;
if (channelDispatcher != null)
{
channelDispatcher.IncludeExceptionDetailInFaults = true;
}
}
}
if (!(this.httpHelpPageEnabled || this.httpsHelpPageEnabled))
return;
ServiceMetadataExtension mex = ServiceMetadataExtension.EnsureServiceMetadataExtension(description, serviceHostBase);
SetExtensionProperties(mex, serviceHostBase);
CreateHelpPageEndpoints(description, serviceHostBase, mex);
}
private void SetExtensionProperties(ServiceMetadataExtension mex, ServiceHostBase host)
{
mex.HttpHelpPageEnabled = this.httpHelpPageEnabled;
mex.HttpHelpPageUrl = host.GetVia(Uri.UriSchemeHttp, this.httpHelpPageUrl == null ? new Uri(string.Empty, UriKind.Relative) : this.httpHelpPageUrl);
mex.HttpHelpPageBinding = this.HttpHelpPageBinding;
mex.HttpsHelpPageEnabled = this.httpsHelpPageEnabled;
mex.HttpsHelpPageUrl = host.GetVia(Uri.UriSchemeHttps, this.httpsHelpPageUrl == null ? new Uri(string.Empty, UriKind.Relative) : this.httpsHelpPageUrl);
mex.HttpsHelpPageBinding = this.HttpsHelpPageBinding;
}
bool EnsureHelpPageDispatcher(ServiceHostBase host, ServiceMetadataExtension mex, Uri url, string scheme)
{
Uri address = host.GetVia(scheme, url == null ? new Uri(string.Empty, UriKind.Relative) : url);
if (address == null)
{
return false;
}
ChannelDispatcher channelDispatcher = mex.EnsureGetDispatcher(address, true /* isServiceDebugBehavior */);
((ServiceMetadataExtension.HttpGetImpl)channelDispatcher.Endpoints[0].DispatchRuntime.SingletonInstanceContext.UserObject).HelpPageEnabled = true;
return true;
}
void CreateHelpPageEndpoints(ServiceDescription description, ServiceHostBase host, ServiceMetadataExtension mex)
{
if (this.httpHelpPageEnabled)
{
if (!EnsureHelpPageDispatcher(host, mex, this.httpHelpPageUrl, Uri.UriSchemeHttp))
{
TraceWarning(this.httpHelpPageUrl, "ServiceDebugBehaviorHttpHelpPageUrl", "ServiceDebugBehaviorHttpHelpPageEnabled");
}
}
if (this.httpsHelpPageEnabled)
{
if (!EnsureHelpPageDispatcher(host, mex, this.httpsHelpPageUrl, Uri.UriSchemeHttps))
{
TraceWarning(this.httpHelpPageUrl, "ServiceDebugBehaviorHttpsHelpPageUrl", "ServiceDebugBehaviorHttpsHelpPageEnabled");
}
}
}
static void TraceWarning(Uri address, string urlProperty, string enabledProperty)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
Hashtable h = new Hashtable(2)
{
{ enabledProperty, "true" },
{ urlProperty, (address == null) ? string.Empty : address.ToString() }
};
TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.WarnHelpPageEnabledNoBaseAddress,
SR.GetString(SR.TraceCodeWarnHelpPageEnabledNoBaseAddress), new DictionaryTraceRecord(h), null, null);
}
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Management.TACACSConfigurationBinding", Namespace="urn:iControl")]
public partial class ManagementTACACSConfiguration : iControlInterface {
public ManagementTACACSConfiguration() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
public void add_server(
string [] config_names,
string [] [] servers
) {
this.Invoke("add_server", new object [] {
config_names,
servers});
}
public System.IAsyncResult Beginadd_server(string [] config_names,string [] [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_server", new object[] {
config_names,
servers}, callback, asyncState);
}
public void Endadd_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
public void create(
string [] config_names,
string [] secrets,
string [] service_names,
string [] protocol_names,
string [] [] servers
) {
this.Invoke("create", new object [] {
config_names,
secrets,
service_names,
protocol_names,
servers});
}
public System.IAsyncResult Begincreate(string [] config_names,string [] secrets,string [] service_names,string [] protocol_names,string [] [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
config_names,
secrets,
service_names,
protocol_names,
servers}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_configurations
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
public void delete_all_configurations(
) {
this.Invoke("delete_all_configurations", new object [0]);
}
public System.IAsyncResult Begindelete_all_configurations(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_configurations", new object[0], callback, asyncState);
}
public void Enddelete_all_configurations(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_configuration
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
public void delete_configuration(
string [] config_names
) {
this.Invoke("delete_configuration", new object [] {
config_names});
}
public System.IAsyncResult Begindelete_configuration(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_configuration", new object[] {
config_names}, callback, asyncState);
}
public void Enddelete_configuration(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_accounting_to_all_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_accounting_to_all_state(
string [] config_names
) {
object [] results = this.Invoke("get_accounting_to_all_state", new object [] {
config_names});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_accounting_to_all_state(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_accounting_to_all_state", new object[] {
config_names}, callback, asyncState);
}
public CommonEnabledState [] Endget_accounting_to_all_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_debug_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_debug_state(
string [] config_names
) {
object [] results = this.Invoke("get_debug_state", new object [] {
config_names});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_debug_state(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_debug_state", new object[] {
config_names}, callback, asyncState);
}
public CommonEnabledState [] Endget_debug_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] config_names
) {
object [] results = this.Invoke("get_description", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_encryption_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_encryption_state(
string [] config_names
) {
object [] results = this.Invoke("get_encryption_state", new object [] {
config_names});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_encryption_state(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_encryption_state", new object[] {
config_names}, callback, asyncState);
}
public CommonEnabledState [] Endget_encryption_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_first_hit_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_first_hit_state(
string [] config_names
) {
object [] results = this.Invoke("get_first_hit_state", new object [] {
config_names});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_first_hit_state(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_first_hit_state", new object[] {
config_names}, callback, asyncState);
}
public CommonEnabledState [] Endget_first_hit_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_protocol_name
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_protocol_name(
string [] config_names
) {
object [] results = this.Invoke("get_protocol_name", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_protocol_name(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_protocol_name", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_protocol_name(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_secret
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_secret(
string [] config_names
) {
object [] results = this.Invoke("get_secret", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_secret(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_secret", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_secret(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_server(
string [] config_names
) {
object [] results = this.Invoke("get_server", new object [] {
config_names});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_server(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_server", new object[] {
config_names}, callback, asyncState);
}
public string [] [] Endget_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_service_name
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_service_name(
string [] config_names
) {
object [] results = this.Invoke("get_service_name", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_service_name(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_service_name", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_service_name(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// remove_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
public void remove_server(
string [] config_names,
string [] [] servers
) {
this.Invoke("remove_server", new object [] {
config_names,
servers});
}
public System.IAsyncResult Beginremove_server(string [] config_names,string [] [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_server", new object[] {
config_names,
servers}, callback, asyncState);
}
public void Endremove_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_accounting_to_all_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
public void set_accounting_to_all_state(
string [] config_names,
CommonEnabledState [] states
) {
this.Invoke("set_accounting_to_all_state", new object [] {
config_names,
states});
}
public System.IAsyncResult Beginset_accounting_to_all_state(string [] config_names,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_accounting_to_all_state", new object[] {
config_names,
states}, callback, asyncState);
}
public void Endset_accounting_to_all_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_debug_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
public void set_debug_state(
string [] config_names,
CommonEnabledState [] states
) {
this.Invoke("set_debug_state", new object [] {
config_names,
states});
}
public System.IAsyncResult Beginset_debug_state(string [] config_names,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_debug_state", new object[] {
config_names,
states}, callback, asyncState);
}
public void Endset_debug_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
public void set_description(
string [] config_names,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
config_names,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] config_names,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
config_names,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_encryption_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
public void set_encryption_state(
string [] config_names,
CommonEnabledState [] states
) {
this.Invoke("set_encryption_state", new object [] {
config_names,
states});
}
public System.IAsyncResult Beginset_encryption_state(string [] config_names,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_encryption_state", new object[] {
config_names,
states}, callback, asyncState);
}
public void Endset_encryption_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_first_hit_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
public void set_first_hit_state(
string [] config_names,
CommonEnabledState [] states
) {
this.Invoke("set_first_hit_state", new object [] {
config_names,
states});
}
public System.IAsyncResult Beginset_first_hit_state(string [] config_names,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_first_hit_state", new object[] {
config_names,
states}, callback, asyncState);
}
public void Endset_first_hit_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_protocol_name
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
public void set_protocol_name(
string [] config_names,
string [] protocol_names
) {
this.Invoke("set_protocol_name", new object [] {
config_names,
protocol_names});
}
public System.IAsyncResult Beginset_protocol_name(string [] config_names,string [] protocol_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_protocol_name", new object[] {
config_names,
protocol_names}, callback, asyncState);
}
public void Endset_protocol_name(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_secret
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
public void set_secret(
string [] config_names,
string [] secrets
) {
this.Invoke("set_secret", new object [] {
config_names,
secrets});
}
public System.IAsyncResult Beginset_secret(string [] config_names,string [] secrets, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_secret", new object[] {
config_names,
secrets}, callback, asyncState);
}
public void Endset_secret(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_service_name
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/TACACSConfiguration",
RequestNamespace="urn:iControl:Management/TACACSConfiguration", ResponseNamespace="urn:iControl:Management/TACACSConfiguration")]
public void set_service_name(
string [] config_names,
string [] service_names
) {
this.Invoke("set_service_name", new object [] {
config_names,
service_names});
}
public System.IAsyncResult Beginset_service_name(string [] config_names,string [] service_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_service_name", new object[] {
config_names,
service_names}, callback, asyncState);
}
public void Endset_service_name(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
//Copyright 2010 Microsoft Corporation
//
//Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
//"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and limitations under the License.
namespace System.Data.Services.Client
{
using System;
using System.Resources;
internal static class Strings {
internal static string BatchStream_MissingBoundary {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_MissingBoundary);
}
}
internal static string BatchStream_ContentExpected(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_ContentExpected,p0);
}
internal static string BatchStream_ContentUnexpected(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_ContentUnexpected,p0);
}
internal static string BatchStream_GetMethodNotSupportedInChangeset {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_GetMethodNotSupportedInChangeset);
}
}
internal static string BatchStream_InvalidBatchFormat {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_InvalidBatchFormat);
}
}
internal static string BatchStream_InvalidDelimiter(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_InvalidDelimiter,p0);
}
internal static string BatchStream_MissingEndChangesetDelimiter {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_MissingEndChangesetDelimiter);
}
}
internal static string BatchStream_InvalidHeaderValueSpecified(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_InvalidHeaderValueSpecified,p0);
}
internal static string BatchStream_InvalidContentLengthSpecified(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_InvalidContentLengthSpecified,p0);
}
internal static string BatchStream_OnlyGETOperationsCanBeSpecifiedInBatch {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_OnlyGETOperationsCanBeSpecifiedInBatch);
}
}
internal static string BatchStream_InvalidOperationHeaderSpecified {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_InvalidOperationHeaderSpecified);
}
}
internal static string BatchStream_InvalidHttpMethodName(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_InvalidHttpMethodName,p0);
}
internal static string BatchStream_MoreDataAfterEndOfBatch {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_MoreDataAfterEndOfBatch);
}
}
internal static string BatchStream_InternalBufferRequestTooSmall {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_InternalBufferRequestTooSmall);
}
}
internal static string BatchStream_InvalidMethodHeaderSpecified(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_InvalidMethodHeaderSpecified,p0);
}
internal static string BatchStream_InvalidHttpVersionSpecified(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_InvalidHttpVersionSpecified,p0,p1);
}
internal static string BatchStream_InvalidNumberOfHeadersAtOperationStart(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_InvalidNumberOfHeadersAtOperationStart,p0,p1);
}
internal static string BatchStream_MissingOrInvalidContentEncodingHeader(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_MissingOrInvalidContentEncodingHeader,p0,p1);
}
internal static string BatchStream_InvalidNumberOfHeadersAtChangeSetStart(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_InvalidNumberOfHeadersAtChangeSetStart,p0,p1);
}
internal static string BatchStream_MissingContentTypeHeader(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_MissingContentTypeHeader,p0);
}
internal static string BatchStream_InvalidContentTypeSpecified(object p0, object p1, object p2, object p3) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.BatchStream_InvalidContentTypeSpecified,p0,p1,p2,p3);
}
internal static string Batch_ExpectedContentType(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Batch_ExpectedContentType,p0);
}
internal static string Batch_ExpectedResponse(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Batch_ExpectedResponse,p0);
}
internal static string Batch_IncompleteResponseCount {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Batch_IncompleteResponseCount);
}
}
internal static string Batch_UnexpectedContent(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Batch_UnexpectedContent,p0);
}
internal static string Context_BaseUri {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_BaseUri);
}
}
internal static string Context_CannotConvertKey(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_CannotConvertKey,p0);
}
internal static string Context_TrackingExpectsAbsoluteUri {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_TrackingExpectsAbsoluteUri);
}
}
internal static string Context_LinkResourceInsertFailure {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_LinkResourceInsertFailure);
}
}
internal static string Context_InternalError(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_InternalError,p0);
}
internal static string Context_BatchExecuteError {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_BatchExecuteError);
}
}
internal static string Context_EntitySetName {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_EntitySetName);
}
}
internal static string Context_MissingEditLinkInResponseBody {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_MissingEditLinkInResponseBody);
}
}
internal static string Context_MissingSelfLinkInResponseBody {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_MissingSelfLinkInResponseBody);
}
}
internal static string Context_MissingEditMediaLinkInResponseBody {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_MissingEditMediaLinkInResponseBody);
}
}
internal static string Content_EntityWithoutKey {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Content_EntityWithoutKey);
}
}
internal static string Content_EntityIsNotEntityType {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Content_EntityIsNotEntityType);
}
}
internal static string Context_EntityNotContained {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_EntityNotContained);
}
}
internal static string Context_EntityAlreadyContained {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_EntityAlreadyContained);
}
}
internal static string Context_DifferentEntityAlreadyContained {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_DifferentEntityAlreadyContained);
}
}
internal static string Context_DidNotOriginateAsync {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_DidNotOriginateAsync);
}
}
internal static string Context_AsyncAlreadyDone {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_AsyncAlreadyDone);
}
}
internal static string Context_OperationCanceled {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_OperationCanceled);
}
}
internal static string Context_NoLoadWithInsertEnd {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_NoLoadWithInsertEnd);
}
}
internal static string Context_NoRelationWithInsertEnd {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_NoRelationWithInsertEnd);
}
}
internal static string Context_NoRelationWithDeleteEnd {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_NoRelationWithDeleteEnd);
}
}
internal static string Context_RelationAlreadyContained {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_RelationAlreadyContained);
}
}
internal static string Context_RelationNotRefOrCollection {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_RelationNotRefOrCollection);
}
}
internal static string Context_AddLinkCollectionOnly {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_AddLinkCollectionOnly);
}
}
internal static string Context_AddRelatedObjectCollectionOnly {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_AddRelatedObjectCollectionOnly);
}
}
internal static string Context_AddRelatedObjectSourceDeleted {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_AddRelatedObjectSourceDeleted);
}
}
internal static string Context_SetLinkReferenceOnly {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_SetLinkReferenceOnly);
}
}
internal static string Context_NoContentTypeForMediaLink(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_NoContentTypeForMediaLink,p0,p1);
}
internal static string Context_BatchNotSupportedForMediaLink {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_BatchNotSupportedForMediaLink);
}
}
internal static string Context_UnexpectedZeroRawRead {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_UnexpectedZeroRawRead);
}
}
internal static string Context_VersionNotSupported(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_VersionNotSupported,p0,p1);
}
internal static string Context_SendingRequestEventArgsNotHttp {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_SendingRequestEventArgsNotHttp);
}
}
internal static string Context_ChildResourceExists {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_ChildResourceExists);
}
}
internal static string Context_EntityNotMediaLinkEntry {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_EntityNotMediaLinkEntry);
}
}
internal static string Context_MLEWithoutSaveStream(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_MLEWithoutSaveStream,p0);
}
internal static string Context_SetSaveStreamOnMediaEntryProperty(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_SetSaveStreamOnMediaEntryProperty,p0);
}
internal static string Context_SetSaveStreamWithoutEditMediaLink {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Context_SetSaveStreamWithoutEditMediaLink);
}
}
internal static string Collection_NullCollectionReference(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Collection_NullCollectionReference,p0,p1);
}
internal static string ClientType_MissingOpenProperty(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ClientType_MissingOpenProperty,p0,p1);
}
internal static string Clienttype_MultipleOpenProperty(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Clienttype_MultipleOpenProperty,p0);
}
internal static string ClientType_MissingProperty(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ClientType_MissingProperty,p0,p1);
}
internal static string ClientType_KeysMustBeSimpleTypes(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ClientType_KeysMustBeSimpleTypes,p0);
}
internal static string ClientType_KeysOnDifferentDeclaredType(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ClientType_KeysOnDifferentDeclaredType,p0);
}
internal static string ClientType_MissingMimeTypeProperty(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ClientType_MissingMimeTypeProperty,p0,p1);
}
internal static string ClientType_MissingMediaEntryProperty(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ClientType_MissingMediaEntryProperty,p0);
}
internal static string ClientType_NoSettableFields(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ClientType_NoSettableFields,p0);
}
internal static string ClientType_MultipleImplementationNotSupported {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ClientType_MultipleImplementationNotSupported);
}
}
internal static string ClientType_NullOpenProperties(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ClientType_NullOpenProperties,p0);
}
internal static string ClientType_CollectionOfNonEntities {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ClientType_CollectionOfNonEntities);
}
}
internal static string ClientType_Ambiguous(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ClientType_Ambiguous,p0,p1);
}
internal static string ClientType_UnsupportedType(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ClientType_UnsupportedType,p0);
}
internal static string DataServiceException_GeneralError {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataServiceException_GeneralError);
}
}
internal static string DataServiceRequest_FailGetCount {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataServiceRequest_FailGetCount);
}
}
internal static string Deserialize_GetEnumerator {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Deserialize_GetEnumerator);
}
}
internal static string Deserialize_Current(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Deserialize_Current,p0,p1);
}
internal static string Deserialize_MixedTextWithComment {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Deserialize_MixedTextWithComment);
}
}
internal static string Deserialize_ExpectingSimpleValue {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Deserialize_ExpectingSimpleValue);
}
}
internal static string Deserialize_NotApplicationXml {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Deserialize_NotApplicationXml);
}
}
internal static string Deserialize_MismatchAtomLinkLocalSimple {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Deserialize_MismatchAtomLinkLocalSimple);
}
}
internal static string Deserialize_MismatchAtomLinkFeedPropertyNotCollection(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Deserialize_MismatchAtomLinkFeedPropertyNotCollection,p0);
}
internal static string Deserialize_MismatchAtomLinkEntryPropertyIsCollection(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Deserialize_MismatchAtomLinkEntryPropertyIsCollection,p0);
}
internal static string Deserialize_UnknownMimeTypeSpecified(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Deserialize_UnknownMimeTypeSpecified,p0);
}
internal static string Deserialize_ExpectedEmptyMediaLinkEntryContent {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Deserialize_ExpectedEmptyMediaLinkEntryContent);
}
}
internal static string Deserialize_ContentPlusPropertiesNotAllowed {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Deserialize_ContentPlusPropertiesNotAllowed);
}
}
internal static string Deserialize_NoLocationHeader {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Deserialize_NoLocationHeader);
}
}
internal static string Deserialize_ServerException(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Deserialize_ServerException,p0);
}
internal static string Deserialize_MissingIdElement {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Deserialize_MissingIdElement);
}
}
internal static string EpmClientType_PropertyIsComplex(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.EpmClientType_PropertyIsComplex,p0);
}
internal static string EpmClientType_PropertyIsPrimitive(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.EpmClientType_PropertyIsPrimitive,p0);
}
internal static string EpmSourceTree_InvalidSourcePath(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.EpmSourceTree_InvalidSourcePath,p0,p1);
}
internal static string EpmSourceTree_DuplicateEpmAttrsWithSameSourceName(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.EpmSourceTree_DuplicateEpmAttrsWithSameSourceName,p0,p1);
}
internal static string EpmSourceTree_InaccessiblePropertyOnType(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.EpmSourceTree_InaccessiblePropertyOnType,p0,p1);
}
internal static string EpmTargetTree_InvalidTargetPath(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.EpmTargetTree_InvalidTargetPath,p0);
}
internal static string EpmTargetTree_AttributeInMiddle(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.EpmTargetTree_AttributeInMiddle,p0);
}
internal static string EpmTargetTree_DuplicateEpmAttrsWithSameTargetName(object p0, object p1, object p2, object p3) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.EpmTargetTree_DuplicateEpmAttrsWithSameTargetName,p0,p1,p2,p3);
}
internal static string EntityPropertyMapping_EpmAttribute(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.EntityPropertyMapping_EpmAttribute,p0);
}
internal static string EntityPropertyMapping_TargetNamespaceUriNotValid(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.EntityPropertyMapping_TargetNamespaceUriNotValid,p0);
}
internal static string HttpProcessUtility_ContentTypeMissing {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.HttpProcessUtility_ContentTypeMissing);
}
}
internal static string HttpProcessUtility_MediaTypeMissingValue {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.HttpProcessUtility_MediaTypeMissingValue);
}
}
internal static string HttpProcessUtility_MediaTypeRequiresSemicolonBeforeParameter {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.HttpProcessUtility_MediaTypeRequiresSemicolonBeforeParameter);
}
}
internal static string HttpProcessUtility_MediaTypeRequiresSlash {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.HttpProcessUtility_MediaTypeRequiresSlash);
}
}
internal static string HttpProcessUtility_MediaTypeRequiresSubType {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.HttpProcessUtility_MediaTypeRequiresSubType);
}
}
internal static string HttpProcessUtility_MediaTypeUnspecified {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.HttpProcessUtility_MediaTypeUnspecified);
}
}
internal static string HttpProcessUtility_EncodingNotSupported(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.HttpProcessUtility_EncodingNotSupported,p0);
}
internal static string HttpProcessUtility_EscapeCharWithoutQuotes(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.HttpProcessUtility_EscapeCharWithoutQuotes,p0);
}
internal static string HttpProcessUtility_EscapeCharAtEnd(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.HttpProcessUtility_EscapeCharAtEnd,p0);
}
internal static string HttpProcessUtility_ClosingQuoteNotFound(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.HttpProcessUtility_ClosingQuoteNotFound,p0);
}
internal static string MaterializeFromAtom_CountNotPresent {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.MaterializeFromAtom_CountNotPresent);
}
}
internal static string MaterializeFromAtom_CountFormatError {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.MaterializeFromAtom_CountFormatError);
}
}
internal static string MaterializeFromAtom_TopLevelLinkNotAvailable {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.MaterializeFromAtom_TopLevelLinkNotAvailable);
}
}
internal static string MaterializeFromAtom_CollectionKeyNotPresentInLinkTable {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.MaterializeFromAtom_CollectionKeyNotPresentInLinkTable);
}
}
internal static string MaterializeFromAtom_GetNestLinkForFlatCollection {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.MaterializeFromAtom_GetNestLinkForFlatCollection);
}
}
internal static string Serializer_NullKeysAreNotSupported(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Serializer_NullKeysAreNotSupported,p0);
}
internal static string Util_EmptyString {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Util_EmptyString);
}
}
internal static string Util_EmptyArray {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Util_EmptyArray);
}
}
internal static string Util_NullArrayElement {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.Util_NullArrayElement);
}
}
internal static string ALinq_UnsupportedExpression(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_UnsupportedExpression,p0);
}
internal static string ALinq_CouldNotConvert(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CouldNotConvert,p0);
}
internal static string ALinq_MethodNotSupported(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_MethodNotSupported,p0);
}
internal static string ALinq_UnaryNotSupported(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_UnaryNotSupported,p0);
}
internal static string ALinq_BinaryNotSupported(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_BinaryNotSupported,p0);
}
internal static string ALinq_ConstantNotSupported(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_ConstantNotSupported,p0);
}
internal static string ALinq_TypeBinaryNotSupported {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_TypeBinaryNotSupported);
}
}
internal static string ALinq_ConditionalNotSupported {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_ConditionalNotSupported);
}
}
internal static string ALinq_ParameterNotSupported {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_ParameterNotSupported);
}
}
internal static string ALinq_MemberAccessNotSupported(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_MemberAccessNotSupported,p0);
}
internal static string ALinq_LambdaNotSupported {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_LambdaNotSupported);
}
}
internal static string ALinq_NewNotSupported {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_NewNotSupported);
}
}
internal static string ALinq_MemberInitNotSupported {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_MemberInitNotSupported);
}
}
internal static string ALinq_ListInitNotSupported {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_ListInitNotSupported);
}
}
internal static string ALinq_NewArrayNotSupported {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_NewArrayNotSupported);
}
}
internal static string ALinq_InvocationNotSupported {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_InvocationNotSupported);
}
}
internal static string ALinq_QueryOptionsOnlyAllowedOnLeafNodes {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_QueryOptionsOnlyAllowedOnLeafNodes);
}
}
internal static string ALinq_CantExpand {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CantExpand);
}
}
internal static string ALinq_CantCastToUnsupportedPrimitive(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CantCastToUnsupportedPrimitive,p0);
}
internal static string ALinq_CantNavigateWithoutKeyPredicate {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CantNavigateWithoutKeyPredicate);
}
}
internal static string ALinq_CanOnlyApplyOneKeyPredicate {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CanOnlyApplyOneKeyPredicate);
}
}
internal static string ALinq_CantTranslateExpression(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CantTranslateExpression,p0);
}
internal static string ALinq_TranslationError(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_TranslationError,p0);
}
internal static string ALinq_CantAddQueryOption {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CantAddQueryOption);
}
}
internal static string ALinq_CantAddDuplicateQueryOption(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CantAddDuplicateQueryOption,p0);
}
internal static string ALinq_CantAddAstoriaQueryOption(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CantAddAstoriaQueryOption,p0);
}
internal static string ALinq_CantAddQueryOptionStartingWithDollarSign(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CantAddQueryOptionStartingWithDollarSign,p0);
}
internal static string ALinq_CantReferToPublicField(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CantReferToPublicField,p0);
}
internal static string ALinq_QueryOptionsOnlyAllowedOnSingletons {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_QueryOptionsOnlyAllowedOnSingletons);
}
}
internal static string ALinq_QueryOptionOutOfOrder(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_QueryOptionOutOfOrder,p0,p1);
}
internal static string ALinq_CannotAddCountOption {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CannotAddCountOption);
}
}
internal static string ALinq_CannotAddCountOptionConflict {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CannotAddCountOptionConflict);
}
}
internal static string ALinq_ProjectionOnlyAllowedOnLeafNodes {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_ProjectionOnlyAllowedOnLeafNodes);
}
}
internal static string ALinq_ProjectionCanOnlyHaveOneProjection {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_ProjectionCanOnlyHaveOneProjection);
}
}
internal static string ALinq_ProjectionMemberAssignmentMismatch(object p0, object p1, object p2) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_ProjectionMemberAssignmentMismatch,p0,p1,p2);
}
internal static string ALinq_ExpressionNotSupportedInProjectionToEntity(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_ExpressionNotSupportedInProjectionToEntity,p0,p1);
}
internal static string ALinq_ExpressionNotSupportedInProjection(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_ExpressionNotSupportedInProjection,p0,p1);
}
internal static string ALinq_CannotConstructKnownEntityTypes {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CannotConstructKnownEntityTypes);
}
}
internal static string ALinq_CannotCreateConstantEntity {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CannotCreateConstantEntity);
}
}
internal static string ALinq_PropertyNamesMustMatchInProjections(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_PropertyNamesMustMatchInProjections,p0,p1);
}
internal static string ALinq_CanOnlyProjectTheLeaf {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CanOnlyProjectTheLeaf);
}
}
internal static string ALinq_CannotProjectWithExplicitExpansion {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.ALinq_CannotProjectWithExplicitExpansion);
}
}
internal static string DSKAttribute_MustSpecifyAtleastOnePropertyName {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DSKAttribute_MustSpecifyAtleastOnePropertyName);
}
}
internal static string DataServiceCollection_LoadRequiresTargetCollectionObserved {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataServiceCollection_LoadRequiresTargetCollectionObserved);
}
}
internal static string DataServiceCollection_CannotStopTrackingChildCollection {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataServiceCollection_CannotStopTrackingChildCollection);
}
}
internal static string DataServiceCollection_OperationForTrackedOnly {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataServiceCollection_OperationForTrackedOnly);
}
}
internal static string DataServiceCollection_CannotDetermineContextFromItems {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataServiceCollection_CannotDetermineContextFromItems);
}
}
internal static string DataServiceCollection_InsertIntoTrackedButNotLoadedCollection {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataServiceCollection_InsertIntoTrackedButNotLoadedCollection);
}
}
internal static string DataBinding_DataServiceCollectionArgumentMustHaveEntityType(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataBinding_DataServiceCollectionArgumentMustHaveEntityType,p0);
}
internal static string DataBinding_CollectionPropertySetterValueHasObserver(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataBinding_CollectionPropertySetterValueHasObserver,p0,p1);
}
internal static string DataBinding_CollectionChangedUnknownAction(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataBinding_CollectionChangedUnknownAction,p0);
}
internal static string DataBinding_BindingOperation_DetachedSource {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataBinding_BindingOperation_DetachedSource);
}
}
internal static string DataBinding_BindingOperation_ArrayItemNull(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataBinding_BindingOperation_ArrayItemNull,p0);
}
internal static string DataBinding_BindingOperation_ArrayItemNotEntity(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataBinding_BindingOperation_ArrayItemNotEntity,p0);
}
internal static string DataBinding_Util_UnknownEntitySetName(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataBinding_Util_UnknownEntitySetName,p0);
}
internal static string DataBinding_EntityAlreadyInCollection(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataBinding_EntityAlreadyInCollection,p0);
}
internal static string DataBinding_NotifyPropertyChangedNotImpl(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataBinding_NotifyPropertyChangedNotImpl,p0);
}
internal static string DataBinding_ComplexObjectAssociatedWithMultipleEntities(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.DataBinding_ComplexObjectAssociatedWithMultipleEntities,p0);
}
internal static string AtomParser_FeedUnexpected {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.AtomParser_FeedUnexpected);
}
}
internal static string AtomParser_PagingLinkOutsideOfFeed {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.AtomParser_PagingLinkOutsideOfFeed);
}
}
internal static string AtomParser_ManyFeedCounts {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.AtomParser_ManyFeedCounts);
}
}
internal static string AtomParser_FeedCountNotUnderFeed {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.AtomParser_FeedCountNotUnderFeed);
}
}
internal static string AtomParser_UnexpectedContentUnderExpandedLink {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.AtomParser_UnexpectedContentUnderExpandedLink);
}
}
internal static string AtomMaterializer_CannotAssignNull(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.AtomMaterializer_CannotAssignNull,p0,p1);
}
internal static string AtomMaterializer_DuplicatedNextLink {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.AtomMaterializer_DuplicatedNextLink);
}
}
internal static string AtomMaterializer_EntryIntoCollectionMismatch(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.AtomMaterializer_EntryIntoCollectionMismatch,p0,p1);
}
internal static string AtomMaterializer_EntryToAccessIsNull(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.AtomMaterializer_EntryToAccessIsNull,p0);
}
internal static string AtomMaterializer_EntryToInitializeIsNull(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.AtomMaterializer_EntryToInitializeIsNull,p0);
}
internal static string AtomMaterializer_ProjectEntityTypeMismatch(object p0, object p1, object p2) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.AtomMaterializer_ProjectEntityTypeMismatch,p0,p1,p2);
}
internal static string AtomMaterializer_LinksMissingHref {
get {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.AtomMaterializer_LinksMissingHref);
}
}
internal static string AtomMaterializer_PropertyMissing(object p0) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.AtomMaterializer_PropertyMissing,p0);
}
internal static string AtomMaterializer_PropertyMissingFromEntry(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.AtomMaterializer_PropertyMissingFromEntry,p0,p1);
}
internal static string AtomMaterializer_PropertyNotExpectedEntry(object p0, object p1) {
return System.Data.Services.Client.TextRes.GetString(System.Data.Services.Client.TextRes.AtomMaterializer_PropertyNotExpectedEntry,p0,p1);
}
}
internal static partial class Error {
internal static Exception ArgumentNull(string paramName) {
return new ArgumentNullException(paramName);
}
internal static Exception ArgumentOutOfRange(string paramName) {
return new ArgumentOutOfRangeException(paramName);
}
internal static Exception NotImplemented() {
return new NotImplementedException();
}
internal static Exception NotSupported() {
return new NotSupportedException();
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Java.Nio.Channels.Spi.cs
//
// 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.
#pragma warning disable 1717
namespace Java.Nio.Channels.Spi
{
/// <summary>
/// <para><c> SelectorProvider </c> is an abstract base class that declares methods for providing instances of DatagramChannel, Pipe, java.nio.channels.Selector , ServerSocketChannel, and SocketChannel. All the methods of this class are thread-safe.</para><para>A provider instance can be retrieved through a system property or the configuration file in a jar file; if no provider is available that way then the system default provider is returned. </para>
/// </summary>
/// <java-name>
/// java/nio/channels/spi/SelectorProvider
/// </java-name>
[Dot42.DexImport("java/nio/channels/spi/SelectorProvider", AccessFlags = 1057)]
public abstract partial class SelectorProvider
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs a new <c> SelectorProvider </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 4)]
protected internal SelectorProvider() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets a provider instance by executing the following steps when called for the first time: <ul><li><para>if the system property "java.nio.channels.spi.SelectorProvider" is set, the value of this property is the class name of the provider returned; </para></li><li><para>if there is a provider-configuration file named "java.nio.channels.spi.SelectorProvider" in META-INF/services of a jar file valid in the system class loader, the first class name is the provider's class name; </para></li><li><para>otherwise, a system default provider will be returned. </para></li></ul></para><para></para>
/// </summary>
/// <returns>
/// <para>the provider. </para>
/// </returns>
/// <java-name>
/// provider
/// </java-name>
[Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 41)]
public static global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.Spi.SelectorProvider);
}
/// <summary>
/// <para>Creates a new open <c> DatagramChannel </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the new channel. </para>
/// </returns>
/// <java-name>
/// openDatagramChannel
/// </java-name>
[Dot42.DexImport("openDatagramChannel", "()Ljava/nio/channels/DatagramChannel;", AccessFlags = 1025)]
public abstract global::Java.Nio.Channels.DatagramChannel OpenDatagramChannel() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Creates a new <c> Pipe </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the new pipe. </para>
/// </returns>
/// <java-name>
/// openPipe
/// </java-name>
[Dot42.DexImport("openPipe", "()Ljava/nio/channels/Pipe;", AccessFlags = 1025)]
public abstract global::Java.Nio.Channels.Pipe OpenPipe() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Creates a new selector.</para><para></para>
/// </summary>
/// <returns>
/// <para>the new selector. </para>
/// </returns>
/// <java-name>
/// openSelector
/// </java-name>
[Dot42.DexImport("openSelector", "()Ljava/nio/channels/spi/AbstractSelector;", AccessFlags = 1025)]
public abstract global::Java.Nio.Channels.Spi.AbstractSelector OpenSelector() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Creates a new open <c> ServerSocketChannel </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the new channel. </para>
/// </returns>
/// <java-name>
/// openServerSocketChannel
/// </java-name>
[Dot42.DexImport("openServerSocketChannel", "()Ljava/nio/channels/ServerSocketChannel;", AccessFlags = 1025)]
public abstract global::Java.Nio.Channels.ServerSocketChannel OpenServerSocketChannel() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Create a new open <c> SocketChannel </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the new channel. </para>
/// </returns>
/// <java-name>
/// openSocketChannel
/// </java-name>
[Dot42.DexImport("openSocketChannel", "()Ljava/nio/channels/SocketChannel;", AccessFlags = 1025)]
public abstract global::Java.Nio.Channels.SocketChannel OpenSocketChannel() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the channel inherited from the process that created this VM. On Android, this method always returns null because stdin and stdout are never connected to a socket.</para><para></para>
/// </summary>
/// <returns>
/// <para>the channel. </para>
/// </returns>
/// <java-name>
/// inheritedChannel
/// </java-name>
[Dot42.DexImport("inheritedChannel", "()Ljava/nio/channels/Channel;", AccessFlags = 1)]
public virtual global::Java.Nio.Channels.IChannel InheritedChannel() /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.IChannel);
}
}
/// <summary>
/// <para><c> AbstractInterruptibleChannel </c> is the root class for interruptible channels. </para><para>The basic usage pattern for an interruptible channel is to invoke <c> begin() </c> before any I/O operation that potentially blocks indefinitely, then <c> end(boolean) </c> after completing the operation. The argument to the <c> end </c> method should indicate if the I/O operation has actually completed so that any change may be visible to the invoker. </para>
/// </summary>
/// <java-name>
/// java/nio/channels/spi/AbstractInterruptibleChannel
/// </java-name>
[Dot42.DexImport("java/nio/channels/spi/AbstractInterruptibleChannel", AccessFlags = 1057)]
public abstract partial class AbstractInterruptibleChannel : global::Java.Nio.Channels.IChannel, global::Java.Nio.Channels.IInterruptibleChannel
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 4)]
protected internal AbstractInterruptibleChannel() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns true if this channel is open. </para>
/// </summary>
/// <java-name>
/// isOpen
/// </java-name>
[Dot42.DexImport("isOpen", "()Z", AccessFlags = 49)]
public bool IsOpen() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Closes an open channel. If the channel is already closed then this method has no effect, otherwise it closes the receiver via the <c> implCloseChannel </c> method. </para><para>If an attempt is made to perform an operation on a closed channel then a java.nio.channels.ClosedChannelException is thrown. </para><para>If multiple threads attempt to simultaneously close a channel, then only one thread will run the closure code and the others will be blocked until the first one completes.</para><para><para>java.nio.channels.Channel::close() </para></para>
/// </summary>
/// <java-name>
/// close
/// </java-name>
[Dot42.DexImport("close", "()V", AccessFlags = 17)]
public void Close() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Indicates the beginning of a code section that includes an I/O operation that is potentially blocking. After this operation, the application should invoke the corresponding <c> end(boolean) </c> method. </para>
/// </summary>
/// <java-name>
/// begin
/// </java-name>
[Dot42.DexImport("begin", "()V", AccessFlags = 20)]
protected internal void Begin() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Indicates the end of a code section that has been started with <c> begin() </c> and that includes a potentially blocking I/O operation.</para><para></para>
/// </summary>
/// <java-name>
/// end
/// </java-name>
[Dot42.DexImport("end", "(Z)V", AccessFlags = 20)]
protected internal void End(bool success) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Implements the channel closing behavior. </para><para>Closes the channel with a guarantee that the channel is not currently closed through another invocation of <c> close() </c> and that the method is thread-safe. </para><para>Any outstanding threads blocked on I/O operations on this channel must be released with either a normal return code, or by throwing an <c> AsynchronousCloseException </c> .</para><para></para>
/// </summary>
/// <java-name>
/// implCloseChannel
/// </java-name>
[Dot42.DexImport("implCloseChannel", "()V", AccessFlags = 1028)]
protected internal abstract void ImplCloseChannel() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para><c> AbstractSelector </c> is the base implementation class for selectors. It realizes the interruption of selection by <c> begin </c> and <c> end </c> . It also holds the cancellation and the deletion of the key set. </para>
/// </summary>
/// <java-name>
/// java/nio/channels/spi/AbstractSelector
/// </java-name>
[Dot42.DexImport("java/nio/channels/spi/AbstractSelector", AccessFlags = 1057)]
public abstract partial class AbstractSelector : global::Java.Nio.Channels.Selector
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/nio/channels/spi/SelectorProvider;)V", AccessFlags = 4)]
protected internal AbstractSelector(global::Java.Nio.Channels.Spi.SelectorProvider selectorProvider) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Closes this selector. This method does nothing if this selector is already closed. The actual closing must be implemented by subclasses in <c> implCloseSelector() </c> . </para>
/// </summary>
/// <java-name>
/// close
/// </java-name>
[Dot42.DexImport("close", "()V", AccessFlags = 17)]
public override void Close() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Implements the closing of this channel. </para>
/// </summary>
/// <java-name>
/// implCloseSelector
/// </java-name>
[Dot42.DexImport("implCloseSelector", "()V", AccessFlags = 1028)]
protected internal abstract void ImplCloseSelector() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns true if this selector is open. </para>
/// </summary>
/// <java-name>
/// isOpen
/// </java-name>
[Dot42.DexImport("isOpen", "()Z", AccessFlags = 17)]
public override bool IsOpen() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns this selector's provider. </para>
/// </summary>
/// <java-name>
/// provider
/// </java-name>
[Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 17)]
public override global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.Spi.SelectorProvider);
}
/// <summary>
/// <para>Returns this channel's set of canceled selection keys. </para>
/// </summary>
/// <java-name>
/// cancelledKeys
/// </java-name>
[Dot42.DexImport("cancelledKeys", "()Ljava/util/Set;", AccessFlags = 20, Signature = "()Ljava/util/Set<Ljava/nio/channels/SelectionKey;>;")]
protected internal global::Java.Util.ISet<global::Java.Nio.Channels.SelectionKey> CancelledKeys() /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<global::Java.Nio.Channels.SelectionKey>);
}
/// <summary>
/// <para>Registers <c> channel </c> with this selector.</para><para></para>
/// </summary>
/// <returns>
/// <para>the key related to the channel and this selector. </para>
/// </returns>
/// <java-name>
/// register
/// </java-name>
[Dot42.DexImport("register", "(Ljava/nio/channels/spi/AbstractSelectableChannel;ILjava/lang/Object;)Ljava/nio/c" +
"hannels/SelectionKey;", AccessFlags = 1028)]
protected internal abstract global::Java.Nio.Channels.SelectionKey Register(global::Java.Nio.Channels.Spi.AbstractSelectableChannel channel, int operations, object attachment) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Deletes the key from the channel's key set. </para>
/// </summary>
/// <java-name>
/// deregister
/// </java-name>
[Dot42.DexImport("deregister", "(Ljava/nio/channels/spi/AbstractSelectionKey;)V", AccessFlags = 20)]
protected internal void Deregister(global::Java.Nio.Channels.Spi.AbstractSelectionKey key) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Indicates the beginning of a code section that includes an I/O operation that is potentially blocking. After this operation, the application should invoke the corresponding <c> end(boolean) </c> method. </para>
/// </summary>
/// <java-name>
/// begin
/// </java-name>
[Dot42.DexImport("begin", "()V", AccessFlags = 20)]
protected internal void Begin() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Indicates the end of a code section that has been started with <c> begin() </c> and that includes a potentially blocking I/O operation. </para>
/// </summary>
/// <java-name>
/// end
/// </java-name>
[Dot42.DexImport("end", "()V", AccessFlags = 20)]
protected internal void End() /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal AbstractSelector() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para><c> AbstractSelectableChannel </c> is the base implementation class for selectable channels. It declares methods for registering, unregistering and closing selectable channels. It is thread-safe. </para>
/// </summary>
/// <java-name>
/// java/nio/channels/spi/AbstractSelectableChannel
/// </java-name>
[Dot42.DexImport("java/nio/channels/spi/AbstractSelectableChannel", AccessFlags = 1057)]
public abstract partial class AbstractSelectableChannel : global::Java.Nio.Channels.SelectableChannel
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs a new <c> AbstractSelectableChannel </c> .</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/nio/channels/spi/SelectorProvider;)V", AccessFlags = 4)]
protected internal AbstractSelectableChannel(global::Java.Nio.Channels.Spi.SelectorProvider selectorProvider) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the selector provider that has created this channel.</para><para><para>java.nio.channels.SelectableChannel::provider() </para></para>
/// </summary>
/// <returns>
/// <para>this channel's selector provider. </para>
/// </returns>
/// <java-name>
/// provider
/// </java-name>
[Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 17)]
public override global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.Spi.SelectorProvider);
}
/// <summary>
/// <para>Indicates whether this channel is registered with one or more selectors.</para><para></para>
/// </summary>
/// <returns>
/// <para><c> true </c> if this channel is registered with a selector, <c> false </c> otherwise. </para>
/// </returns>
/// <java-name>
/// isRegistered
/// </java-name>
[Dot42.DexImport("isRegistered", "()Z", AccessFlags = 49)]
public override bool IsRegistered() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Gets this channel's selection key for the specified selector.</para><para></para>
/// </summary>
/// <returns>
/// <para>the selection key for the channel or <c> null </c> if this channel has not been registered with <c> selector </c> . </para>
/// </returns>
/// <java-name>
/// keyFor
/// </java-name>
[Dot42.DexImport("keyFor", "(Ljava/nio/channels/Selector;)Ljava/nio/channels/SelectionKey;", AccessFlags = 49)]
public override global::Java.Nio.Channels.SelectionKey KeyFor(global::Java.Nio.Channels.Selector selector) /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.SelectionKey);
}
/// <summary>
/// <para>Registers this channel with the specified selector for the specified interest set. If the channel is already registered with the selector, the interest set is updated to <c> interestSet </c> and the corresponding selection key is returned. If the channel is not yet registered, this method calls the <c> register </c> method of <c> selector </c> and adds the selection key to this channel's key set.</para><para></para>
/// </summary>
/// <returns>
/// <para>the selection key for this registration. </para>
/// </returns>
/// <java-name>
/// register
/// </java-name>
[Dot42.DexImport("register", "(Ljava/nio/channels/Selector;ILjava/lang/Object;)Ljava/nio/channels/SelectionKey;" +
"", AccessFlags = 17)]
public override global::Java.Nio.Channels.SelectionKey Register(global::Java.Nio.Channels.Selector selector, int interestSet, object attachment) /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.SelectionKey);
}
/// <summary>
/// <para>Implements the channel closing behavior. Calls <c> implCloseSelectableChannel() </c> first, then loops through the list of selection keys and cancels them, which unregisters this channel from all selectors it is registered with.</para><para></para>
/// </summary>
/// <java-name>
/// implCloseChannel
/// </java-name>
[Dot42.DexImport("implCloseChannel", "()V", AccessFlags = 52)]
protected internal override void ImplCloseChannel() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Implements the closing function of the SelectableChannel. This method is called from <c> implCloseChannel() </c> .</para><para></para>
/// </summary>
/// <java-name>
/// implCloseSelectableChannel
/// </java-name>
[Dot42.DexImport("implCloseSelectableChannel", "()V", AccessFlags = 1028)]
protected internal abstract void ImplCloseSelectableChannel() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Indicates whether this channel is in blocking mode.</para><para></para>
/// </summary>
/// <returns>
/// <para><c> true </c> if this channel is blocking, <c> false </c> otherwise. </para>
/// </returns>
/// <java-name>
/// isBlocking
/// </java-name>
[Dot42.DexImport("isBlocking", "()Z", AccessFlags = 17)]
public override bool IsBlocking() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Gets the object used for the synchronization of <c> register </c> and <c> configureBlocking </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the synchronization object. </para>
/// </returns>
/// <java-name>
/// blockingLock
/// </java-name>
[Dot42.DexImport("blockingLock", "()Ljava/lang/Object;", AccessFlags = 17)]
public override object BlockingLock() /* MethodBuilder.Create */
{
return default(object);
}
/// <summary>
/// <para>Sets the blocking mode of this channel. A call to this method blocks if other calls to this method or to <c> register </c> are executing. The actual setting of the mode is done by calling <c> implConfigureBlocking(boolean) </c> .</para><para><para>java.nio.channels.SelectableChannel::configureBlocking(boolean) </para></para>
/// </summary>
/// <returns>
/// <para>this channel. </para>
/// </returns>
/// <java-name>
/// configureBlocking
/// </java-name>
[Dot42.DexImport("configureBlocking", "(Z)Ljava/nio/channels/SelectableChannel;", AccessFlags = 17)]
public override global::Java.Nio.Channels.SelectableChannel ConfigureBlocking(bool blockingMode) /* MethodBuilder.Create */
{
return default(global::Java.Nio.Channels.SelectableChannel);
}
/// <summary>
/// <para>Implements the configuration of blocking/non-blocking mode.</para><para></para>
/// </summary>
/// <java-name>
/// implConfigureBlocking
/// </java-name>
[Dot42.DexImport("implConfigureBlocking", "(Z)V", AccessFlags = 1028)]
protected internal abstract void ImplConfigureBlocking(bool blocking) /* MethodBuilder.Create */ ;
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal AbstractSelectableChannel() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para><c> AbstractSelectionKey </c> is the base implementation class for selection keys. It implements validation and cancellation methods. </para>
/// </summary>
/// <java-name>
/// java/nio/channels/spi/AbstractSelectionKey
/// </java-name>
[Dot42.DexImport("java/nio/channels/spi/AbstractSelectionKey", AccessFlags = 1057)]
public abstract partial class AbstractSelectionKey : global::Java.Nio.Channels.SelectionKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructs a new <c> AbstractSelectionKey </c> . </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 4)]
protected internal AbstractSelectionKey() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Indicates whether this key is valid. A key is valid as long as it has not been canceled.</para><para></para>
/// </summary>
/// <returns>
/// <para><c> true </c> if this key has not been canceled, <c> false </c> otherwise. </para>
/// </returns>
/// <java-name>
/// isValid
/// </java-name>
[Dot42.DexImport("isValid", "()Z", AccessFlags = 17)]
public override bool IsValid() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Cancels this key. </para><para>A key that has been canceled is no longer valid. Calling this method on an already canceled key does nothing. </para>
/// </summary>
/// <java-name>
/// cancel
/// </java-name>
[Dot42.DexImport("cancel", "()V", AccessFlags = 17)]
public override void Cancel() /* MethodBuilder.Create */
{
}
}
}
| |
/*
* 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 Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace OpenSim.Services.Connectors
{
public class AssetServicesConnector : BaseServiceConnector, IAssetService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
private IImprovedAssetCache m_Cache = null;
private int m_maxAssetRequestConcurrency = 30;
private delegate void AssetRetrievedEx(AssetBase asset);
// Keeps track of concurrent requests for the same asset, so that it's only loaded once.
// Maps: Asset ID -> Handlers which will be called when the asset has been loaded
private Dictionary<string, AssetRetrievedEx> m_AssetHandlers = new Dictionary<string, AssetRetrievedEx>();
public int MaxAssetRequestConcurrency
{
get { return m_maxAssetRequestConcurrency; }
set { m_maxAssetRequestConcurrency = value; }
}
public AssetServicesConnector()
{
}
public AssetServicesConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public AssetServicesConnector(IConfigSource source)
: base(source, "AssetService")
{
Initialise(source);
}
public virtual void Initialise(IConfigSource source)
{
IConfig netconfig = source.Configs["Network"];
if (netconfig != null)
m_maxAssetRequestConcurrency = netconfig.GetInt("MaxRequestConcurrency",m_maxAssetRequestConcurrency);
IConfig assetConfig = source.Configs["AssetService"];
if (assetConfig == null)
{
m_log.Error("[ASSET CONNECTOR]: AssetService missing from OpenSim.ini");
throw new Exception("Asset connector init error");
}
string serviceURI = assetConfig.GetString("AssetServerURI",
String.Empty);
if (serviceURI == String.Empty)
{
m_log.Error("[ASSET CONNECTOR]: No Server URI named in section AssetService");
throw new Exception("Asset connector init error");
}
m_ServerURI = serviceURI;
}
protected void SetCache(IImprovedAssetCache cache)
{
m_Cache = cache;
}
public AssetBase Get(string id)
{
// m_log.DebugFormat("[ASSET SERVICE CONNECTOR]: Synchronous get request for {0}", id);
string uri = m_ServerURI + "/assets/" + id;
AssetBase asset = null;
if (m_Cache != null)
asset = m_Cache.Get(id);
if (asset == null)
{
asset = SynchronousRestObjectRequester.MakeRequest<int, AssetBase>("GET", uri, 0, m_Auth);
if (m_Cache != null)
m_Cache.Cache(asset);
}
return asset;
}
public AssetBase GetCached(string id)
{
// m_log.DebugFormat("[ASSET SERVICE CONNECTOR]: Cache request for {0}", id);
if (m_Cache != null)
return m_Cache.Get(id);
return null;
}
public AssetMetadata GetMetadata(string id)
{
if (m_Cache != null)
{
AssetBase fullAsset = m_Cache.Get(id);
if (fullAsset != null)
return fullAsset.Metadata;
}
string uri = m_ServerURI + "/assets/" + id + "/metadata";
AssetMetadata asset = SynchronousRestObjectRequester.MakeRequest<int, AssetMetadata>("GET", uri, 0, m_Auth);
return asset;
}
public byte[] GetData(string id)
{
if (m_Cache != null)
{
AssetBase fullAsset = m_Cache.Get(id);
if (fullAsset != null)
return fullAsset.Data;
}
RestClient rc = new RestClient(m_ServerURI);
rc.AddResourcePath("assets");
rc.AddResourcePath(id);
rc.AddResourcePath("data");
rc.RequestMethod = "GET";
Stream s = rc.Request();
if (s == null)
return null;
if (s.Length > 0)
{
byte[] ret = new byte[s.Length];
s.Read(ret, 0, (int)s.Length);
return ret;
}
return null;
}
public bool Get(string id, Object sender, AssetRetrieved handler)
{
// m_log.DebugFormat("[ASSET SERVICE CONNECTOR]: Potentially asynchronous get request for {0}", id);
string uri = m_ServerURI + "/assets/" + id;
AssetBase asset = null;
if (m_Cache != null)
asset = m_Cache.Get(id);
if (asset == null)
{
AssetRetrievedEx handlerEx = new AssetRetrievedEx(delegate(AssetBase _asset) { handler(id, sender, _asset); });
lock (m_AssetHandlers)
{
AssetRetrievedEx handlers;
if (m_AssetHandlers.TryGetValue(id, out handlers))
{
// Someone else is already loading this asset. It will notify our handler when done.
handlers += handlerEx;
return true;
}
// Load the asset ourselves
handlers += handlerEx;
m_AssetHandlers.Add(id, handlers);
}
bool success = false;
try
{
AsynchronousRestObjectRequester.MakeRequest<int, AssetBase>("GET", uri, 0,
delegate(AssetBase a)
{
if (a != null && m_Cache != null)
m_Cache.Cache(a);
AssetRetrievedEx handlers;
lock (m_AssetHandlers)
{
handlers = m_AssetHandlers[id];
m_AssetHandlers.Remove(id);
}
handlers.Invoke(a);
}, m_maxAssetRequestConcurrency, m_Auth);
success = true;
}
finally
{
if (!success)
{
lock (m_AssetHandlers)
{
m_AssetHandlers.Remove(id);
}
}
}
}
else
{
handler(id, sender, asset);
}
return true;
}
public virtual bool[] AssetsExist(string[] ids)
{
string uri = m_ServerURI + "/get_assets_exist";
bool[] exist = null;
try
{
exist = SynchronousRestObjectRequester.MakeRequest<string[], bool[]>("POST", uri, ids, m_Auth);
}
catch (Exception)
{
// This is most likely to happen because the server doesn't support this function,
// so just silently return "doesn't exist" for all the assets.
}
if (exist == null)
exist = new bool[ids.Length];
return exist;
}
public string Store(AssetBase asset)
{
if (asset.Local)
{
if (m_Cache != null)
m_Cache.Cache(asset);
return asset.ID;
}
string uri = m_ServerURI + "/assets/";
string newID;
try
{
newID = SynchronousRestObjectRequester.MakeRequest<AssetBase, string>("POST", uri, asset, m_Auth);
}
catch (Exception e)
{
m_log.Warn(string.Format("[ASSET CONNECTOR]: Unable to send asset {0} to asset server. Reason: {1} ", asset.ID, e.Message), e);
return string.Empty;
}
// TEMPORARY: SRAS returns 'null' when it's asked to store existing assets
if (newID == null)
{
m_log.DebugFormat("[ASSET CONNECTOR]: Storing of asset {0} returned null; assuming the asset already exists", asset.ID);
return asset.ID;
}
if (string.IsNullOrEmpty(newID))
return string.Empty;
asset.ID = newID;
if (m_Cache != null)
m_Cache.Cache(asset);
return newID;
}
public bool UpdateContent(string id, byte[] data)
{
AssetBase asset = null;
if (m_Cache != null)
asset = m_Cache.Get(id);
if (asset == null)
{
AssetMetadata metadata = GetMetadata(id);
if (metadata == null)
return false;
asset = new AssetBase(metadata.FullID, metadata.Name, metadata.Type, UUID.Zero.ToString());
asset.Metadata = metadata;
}
asset.Data = data;
string uri = m_ServerURI + "/assets/" + id;
if (SynchronousRestObjectRequester.MakeRequest<AssetBase, bool>("POST", uri, asset, m_Auth))
{
if (m_Cache != null)
m_Cache.Cache(asset);
return true;
}
return false;
}
public bool Delete(string id)
{
string uri = m_ServerURI + "/assets/" + id;
if (SynchronousRestObjectRequester.MakeRequest<int, bool>("DELETE", uri, 0, m_Auth))
{
if (m_Cache != null)
m_Cache.Expire(id);
return true;
}
return false;
}
}
}
| |
/*
* Copyright (c) 2013 Calvin Rien
*
* Based on the JSON parser by Patrick van Bergen
* http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
*
* Simplified it so that it doesn't throw exceptions
* and can be used in Unity iPhone with maximum code stripping.
*
* 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.
*
* --------------
*
* Heavily modified to remove generic collections (unpredictable results).
*
*/
using System;
using System.Collections;
using System.IO;
using System.Text;
namespace Chartboost {
public static class CBJSON {
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An ArrayList, a Hashtable, a double, an integer,a string, null, true, or false</returns>
public static object Deserialize(string json) {
// save the string for debug information
if (json == null) {
return null;
}
return Parser.Parse(json);
}
sealed class Parser : IDisposable {
const string WORD_BREAK = "{}[],:\"";
public static bool IsWordBreak(char c) {
return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1;
}
enum TOKEN {
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
};
StringReader json;
Parser(string jsonString) {
json = new StringReader(jsonString);
}
public static object Parse(string jsonString) {
using (var instance = new Parser(jsonString)) {
return instance.ParseValue();
}
}
public void Dispose() {
json.Dispose();
json = null;
}
Hashtable ParseObject() {
Hashtable table = new Hashtable();
// ditch opening brace
json.Read();
// {
while (true) {
switch (NextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
default:
// name
string name = ParseString();
if (name == null) {
return null;
}
// :
if (NextToken != TOKEN.COLON) {
return null;
}
// ditch the colon
json.Read();
// value
table[name] = ParseValue();
break;
}
}
}
ArrayList ParseArray() {
ArrayList array = new ArrayList();
// ditch opening bracket
json.Read();
// [
var parsing = true;
while (parsing) {
TOKEN nextToken = NextToken;
switch (nextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object nextValue = ParseByToken(nextToken);
array.Add(nextValue);
break;
}
}
return array;
}
object ParseValue() {
TOKEN nextToken = NextToken;
return ParseByToken(nextToken);
}
object ParseByToken(TOKEN token) {
switch (token) {
case TOKEN.STRING:
return ParseString();
case TOKEN.NUMBER:
return ParseNumber();
case TOKEN.CURLY_OPEN:
return ParseObject();
case TOKEN.SQUARED_OPEN:
return ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
}
string ParseString() {
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
json.Read();
bool parsing = true;
while (parsing) {
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new char[4];
for (int i=0; i< 4; i++) {
hex[i] = NextChar;
}
s.Append((char) Convert.ToInt32(new string(hex), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
object ParseNumber() {
string number = NextWord;
if (number.IndexOf('.') == -1) {
long parsedInt;
Int64.TryParse(number, out parsedInt);
return parsedInt;
}
double parsedDouble;
Double.TryParse(number, out parsedDouble);
return parsedDouble;
}
void EatWhitespace() {
while (Char.IsWhiteSpace(PeekChar)) {
json.Read();
if (json.Peek() == -1) {
break;
}
}
}
char PeekChar {
get {
return Convert.ToChar(json.Peek());
}
}
char NextChar {
get {
return Convert.ToChar(json.Read());
}
}
string NextWord {
get {
StringBuilder word = new StringBuilder();
while (!IsWordBreak(PeekChar)) {
word.Append(NextChar);
if (json.Peek() == -1) {
break;
}
}
return word.ToString();
}
}
TOKEN NextToken {
get {
EatWhitespace();
if (json.Peek() == -1) {
return TOKEN.NONE;
}
switch (PeekChar) {
case '{':
return TOKEN.CURLY_OPEN;
case '}':
json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
}
switch (NextWord) {
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
}
return TOKEN.NONE;
}
}
}
/// <summary>
/// Converts a Hashtable / ArrayList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Hashtable / Arraylist</param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj) {
return Serializer.Serialize(obj);
}
sealed class Serializer {
StringBuilder builder;
Serializer() {
builder = new StringBuilder();
}
public static string Serialize(object obj) {
var instance = new Serializer();
instance.SerializeValue(obj);
return instance.builder.ToString();
}
void SerializeValue(object val) {
ArrayList asList;
Hashtable asDict;
string asStr;
if (val == null) {
builder.Append("null");
} else if ((asStr = val as string) != null) {
SerializeString(asStr);
} else if (val is bool) {
builder.Append((bool) val ? "true" : "false");
} else if ((asList = val as ArrayList) != null) {
SerializeArray(asList);
} else if ((asDict = val as Hashtable) != null) {
SerializeObject(asDict);
} else if (val is char) {
SerializeString(new string((char) val, 1));
} else {
SerializeOther(val);
}
}
void SerializeObject(Hashtable obj) {
bool first = true;
builder.Append('{');
foreach (DictionaryEntry e in obj) {
if (!first) {
builder.Append(',');
}
SerializeString(e.Key.ToString());
builder.Append(':');
SerializeValue(e.Value);
first = false;
}
builder.Append('}');
}
void SerializeArray(ArrayList anArray) {
builder.Append('[');
bool first = true;
for (int i = 0; i < anArray.Count; i++) {
object obj = anArray[i];
if (!first) {
builder.Append(',');
}
SerializeValue(obj);
first = false;
}
builder.Append(']');
}
void SerializeString(string str) {
builder.Append('\"');
char[] charArray = str.ToCharArray();
for (int i = 0; i < charArray.Length; i++) {
char c = charArray[i];
switch (c) {
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
} else {
builder.Append("\\u");
builder.Append(codepoint.ToString("x4"));
}
break;
}
}
builder.Append('\"');
}
void SerializeOther(object val) {
// NOTE: decimals lose precision during serialization.
// They always have, I'm just letting you know.
// Previously floats and doubles lost precision too.
if (val is float) {
builder.Append(((float) val).ToString("R"));
} else if (val is int
|| val is uint
|| val is long
|| val is sbyte
|| val is byte
|| val is short
|| val is ushort
|| val is ulong) {
builder.Append(val);
} else if (val is double
|| val is decimal) {
builder.Append(Convert.ToDouble(val).ToString("R"));
} else {
SerializeString(val.ToString());
}
}
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Xaml.Actipro.Code.Xaml.ActiproPublic
File: CodePanel.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Serialization;
using ICSharpCode.AvalonEdit.Document;
using StockSharp.Localization;
using StockSharp.Xaml.Code;
namespace StockSharp.Hydra.Panes
{
/// <summary>
/// The visual panel for code editing and compiling.
/// </summary>
public partial class CodePanel : UserControl, IPersistable
{
/// <summary>
/// The command for the code compilation.
/// </summary>
public static RoutedCommand CompileCommand = new RoutedCommand();
/// <summary>
/// The command for the code saving.
/// </summary>
public static RoutedCommand SaveCommand = new RoutedCommand();
/// <summary>
/// The command for the references modification.
/// </summary>
public static RoutedCommand ReferencesCommand = new RoutedCommand();
/// <summary>
/// The command for undo the changes.
/// </summary>
public static RoutedCommand UndoCommand = new RoutedCommand();
/// <summary>
/// The command for return the changes.
/// </summary>
public static RoutedCommand RedoCommand = new RoutedCommand();
/// <summary>
/// <see cref="DependencyProperty" /> for <see cref="CodePanel.ShowToolBar" />.
/// </summary>
public static readonly DependencyProperty ShowToolBarProperty = DependencyProperty.Register("ShowToolBar",
typeof (bool), typeof (CodePanel), new PropertyMetadata(true));
private static readonly SynchronizedDictionary<CodeReference, ITextAnchor> _references =
new SynchronizedDictionary<CodeReference, ITextAnchor>();
// private readonly IProjectAssembly _projectAssembly;
private readonly ObservableCollection<CompileResultItem> _errorsSource;
private bool isModified;
/// <summary>
/// Initializes a new instance of the <see cref="CodePanel" />.
/// </summary>
public CodePanel()
{
InitializeComponent();
// _projectAssembly = new CSharpProjectAssembly("StudioStrategy");
//_projectAssembly.AssemblyReferences.AddMsCorLib();
//var language = new CSharpSyntaxLanguage();
//language.RegisterProjectAssembly(_projectAssembly);
//CodeEditor.Document.Language = language;
isModified = false;
_errorsSource = new ObservableCollection<CompileResultItem>();
ErrorsGrid.ItemsSource = _errorsSource;
/*
var references = new SynchronizedList<CodeReference>();
references.Added += r => _references.SafeAdd(r, r1 =>
{
ITextAnchor asmRef = null;
try
{
asmRef =
_projectAssembly.AssemblyReferences.AddFrom(r1.Location);
}
catch (Exception ex)
{
ex.LogError();
}
return asmRef;
});
references.Removed += r =>
{
var item = _projectAssembly
.AssemblyReferences
.FirstOrDefault(p =>
{
var assm = p.Assembly as IBinaryAssembly;
if (assm == null)
return false;
return assm.Location == r.Location;
});
if (item != null)
_projectAssembly.AssemblyReferences.Remove(item);
};
references.Cleared += () =>
{
_projectAssembly.AssemblyReferences.Clear();
_projectAssembly.AssemblyReferences.AddMsCorLib();
};
References = references;*/
}
/// <summary>
/// To show the review panel.
/// </summary>
public bool ShowToolBar
{
get { return (bool) GetValue(ShowToolBarProperty); }
set { SetValue(ShowToolBarProperty, value); }
}
/// <summary>
/// Code.
/// </summary>
public string Code
{
get
{
isModified = false;
return CodeEditor.Text;
}
set { CodeEditor.Text = value; }
}
/// <summary>
/// References.
/// </summary>
public IList<CodeReference> References { get; }
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public void Load(SettingsStorage storage)
{
ErrorsGrid.Load(storage.GetValue<SettingsStorage>("ErrorsGrid"));
// var layout = storage.GetValue<string>("Layout");
// if (layout != null)
// DockSite.LoadLayout(layout, true);
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public void Save(SettingsStorage storage)
{
storage.SetValue("ErrorsGrid", ErrorsGrid.Save());
// storage.SetValue("Layout", DockSite.SaveLayout(true));
}
/// <summary>
/// The links update event.
/// </summary>
public event Action ReferencesUpdated;
/// <summary>
/// The code compilation event.
/// </summary>
public event Action CompilingCode;
/// <summary>
/// The code saving event.
/// </summary>
public event Action SavingCode;
/// <summary>
/// The code change event.
/// </summary>
public event Action CodeChanged;
/// <summary>
/// The compilation possibility check event.
/// </summary>
public event Func<bool> CanCompile;
/// <summary>
/// To show the result of the compilation.
/// </summary>
/// <param name="result">The result of the compilation.</param>
/// <param name="isRunning">Whether the previously compiled code launched in the current moment.</param>
public void ShowCompilationResult(CompilationResult result, bool isRunning)
{
if (result == null)
throw new ArgumentNullException(nameof(result));
_errorsSource.Clear();
_errorsSource.AddRange(result.Errors.Select(error => new CompileResultItem
{
Type = error.Type,
Line = error.NativeError.Line,
Column = error.NativeError.Column,
Message = error.NativeError.ErrorText
}));
if (_errorsSource.All(e => e.Type != CompilationErrorTypes.Error))
{
if (isRunning)
{
_errorsSource.Add(new CompileResultItem
{
Type = CompilationErrorTypes.Warning,
Message = LocalizedStrings.Str1420
});
}
_errorsSource.Add(new CompileResultItem
{
Type = CompilationErrorTypes.Info,
Message = LocalizedStrings.Str1421
});
}
}
/// <summary>
/// To edit links.
/// </summary>
public void EditReferences()
{
var window = new CodeReferencesWindow();
window.References.AddRange(References);
// if (!window.ShowModal(this)) return;
var toAdd = window.References.Except(References);
var toRemove = References.Except(window.References);
References.RemoveRange(toRemove);
References.AddRange(toAdd);
ReferencesUpdated.SafeInvoke();
}
private void ExecutedSaveCommand(object sender, ExecutedRoutedEventArgs e)
{
SavingCode.SafeInvoke();
isModified = false;
}
private void CanExecuteSaveCodeCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = CodeEditor != null && isModified;
}
private void ExecutedCompileCommand(object sender, ExecutedRoutedEventArgs e)
{
CompilingCode.SafeInvoke();
//var compiler = Compiler.Create(CodeLanguage, AssemblyPath, TempPath);
//CodeCompiled.SafeInvoke(compiler.Compile(AssemblyName, Code, References.Select(s => s.Location)));
}
private void ExecutedReferencesCommand(object sender, ExecutedRoutedEventArgs e)
{
EditReferences();
}
private void CanExecuteReferencesCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void ErrorsGrid_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
var error = (CompileResultItem) ErrorsGrid.SelectedItem;
if (error == null)
return;
CodeEditor.ScrollTo(error.Line - 1, error.Column - 1);
CodeEditor.Focus();
}
private void CanExecuteCompileCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = CanCompile == null || CanCompile();
}
private void ExecutedUndoCommand(object sender, ExecutedRoutedEventArgs e)
{
CodeEditor.Document.UndoStack.Undo();
}
private void CanExecuteUndoCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = CodeEditor != null && CodeEditor.Document.UndoStack.CanUndo;
}
private void ExecutedRedoCommand(object sender, ExecutedRoutedEventArgs e)
{
CodeEditor.Document.UndoStack.Redo();
}
private void CanExecuteRedoCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = CodeEditor != null && CodeEditor.Document.UndoStack.CanRedo;
}
private void CodeEditor_OnTextChanged(object sender, EventArgs e)
{
isModified = true;
CodeChanged.SafeInvoke();
}
private void CodeEditor_OnTextChanged(object sender, DocumentChangeEventArgs e)
{
isModified = true;
// if (!e.OldSnapshot.Text.IsEmpty())
CodeChanged.SafeInvoke();
}
private class CompileResultItem
{
public CompilationErrorTypes Type { get; set; }
public int Line { get; set; }
public int Column { get; set; }
public string Message { get; set; }
}
}
}
| |
using System;
using System.Collections.Generic;
using ModestTree;
using Zenject.Internal;
using System.Linq;
#if !NOT_UNITY3D
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
#endif
namespace Zenject
{
internal static class BindingUtil
{
#if !NOT_UNITY3D
public static void AssertIsValidPrefab(UnityEngine.Object prefab)
{
Assert.That(!ZenUtilInternal.IsNull(prefab), "Received null prefab during bind command");
#if UNITY_EDITOR
// This won't execute in dll builds sadly
Assert.That(PrefabUtility.GetPrefabType(prefab) == PrefabType.Prefab,
"Expected prefab but found game object with name '{0}' during bind command", prefab.name);
#endif
}
public static void AssertIsValidGameObject(GameObject gameObject)
{
Assert.That(!ZenUtilInternal.IsNull(gameObject), "Received null game object during bind command");
#if UNITY_EDITOR
Assert.That(PrefabUtility.GetPrefabType(gameObject) != PrefabType.Prefab,
"Expected game object but found prefab instead with name '{0}' during bind command", gameObject.name);
#endif
}
public static void AssertIsNotComponent(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsNotComponent(type);
}
}
public static void AssertIsNotComponent<T>()
{
AssertIsNotComponent(typeof(T));
}
public static void AssertIsNotComponent(Type type)
{
Assert.That(!type.DerivesFrom(typeof(Component)),
"Invalid type given during bind command. Expected type '{0}' to NOT derive from UnityEngine.Component", type.Name());
}
public static void AssertDerivesFromUnityObject(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertDerivesFromUnityObject(type);
}
}
public static void AssertDerivesFromUnityObject<T>()
{
AssertDerivesFromUnityObject(typeof(T));
}
public static void AssertDerivesFromUnityObject(Type type)
{
Assert.That(type.DerivesFrom<UnityEngine.Object>(),
"Invalid type given during bind command. Expected type '{0}' to derive from UnityEngine.Object", type.Name());
}
public static void AssertTypesAreNotComponents(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsNotComponent(type);
}
}
public static void AssertIsValidResourcePath(string resourcePath)
{
Assert.That(!string.IsNullOrEmpty(resourcePath), "Null or empty resource path provided");
// We'd like to validate the path here but unfortunately there doesn't appear to be
// a way to do this besides loading it
}
public static void AssertIsAbstractOrComponent(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsAbstractOrComponent(type);
}
}
public static void AssertIsAbstractOrComponent<T>()
{
AssertIsAbstractOrComponent(typeof(T));
}
public static void AssertIsAbstractOrComponent(Type type)
{
Assert.That(type.DerivesFrom(typeof(Component)) || type.IsInterface(),
"Invalid type given during bind command. Expected type '{0}' to either derive from UnityEngine.Component or be an interface", type.Name());
}
public static void AssertIsAbstractOrComponentOrGameObject(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsAbstractOrComponentOrGameObject(type);
}
}
public static void AssertIsAbstractOrComponentOrGameObject<T>()
{
AssertIsAbstractOrComponentOrGameObject(typeof(T));
}
public static void AssertIsAbstractOrComponentOrGameObject(Type type)
{
Assert.That(type.DerivesFrom(typeof(Component)) || type.IsInterface() || type == typeof(GameObject) || type == typeof(UnityEngine.Object),
"Invalid type given during bind command. Expected type '{0}' to either derive from UnityEngine.Component or be an interface or be GameObject", type.Name());
}
public static void AssertIsComponent(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsComponent(type);
}
}
public static void AssertIsComponent<T>()
{
AssertIsComponent(typeof(T));
}
public static void AssertIsComponent(Type type)
{
Assert.That(type.DerivesFrom(typeof(Component)),
"Invalid type given during bind command. Expected type '{0}' to derive from UnityEngine.Component", type.Name());
}
public static void AssertIsComponentOrGameObject(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsComponentOrGameObject(type);
}
}
public static void AssertIsComponentOrGameObject<T>()
{
AssertIsComponentOrGameObject(typeof(T));
}
public static void AssertIsComponentOrGameObject(Type type)
{
Assert.That(type.DerivesFrom(typeof(Component)) || type == typeof(GameObject),
"Invalid type given during bind command. Expected type '{0}' to derive from UnityEngine.Component", type.Name());
}
#else
public static void AssertTypesAreNotComponents(IEnumerable<Type> types)
{
}
public static void AssertIsNotComponent(Type type)
{
}
public static void AssertIsNotComponent<T>()
{
}
public static void AssertIsNotComponent(IEnumerable<Type> types)
{
}
#endif
public static void AssertTypesAreNotAbstract(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsNotAbstract(type);
}
}
public static void AssertIsNotAbstract(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsNotAbstract(type);
}
}
public static void AssertIsNotAbstract<T>()
{
AssertIsNotAbstract(typeof(T));
}
public static void AssertIsNotAbstract(Type type)
{
Assert.That(!type.IsAbstract(),
"Invalid type given during bind command. Expected type '{0}' to not be abstract.", type);
}
public static void AssertIsDerivedFromType(Type concreteType, Type parentType)
{
Assert.That(concreteType.DerivesFromOrEqual(parentType),
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'", concreteType.Name(), parentType.Name());
}
public static void AssertConcreteTypeListIsNotEmpty(IEnumerable<Type> concreteTypes)
{
Assert.That(concreteTypes.Count() >= 1,
"Must supply at least one concrete type to the current binding");
}
public static void AssertIsDerivedFromTypes(
IEnumerable<Type> concreteTypes, IEnumerable<Type> parentTypes, InvalidBindResponses invalidBindResponse)
{
if (invalidBindResponse == InvalidBindResponses.Assert)
{
AssertIsDerivedFromTypes(concreteTypes, parentTypes);
}
else
{
Assert.IsEqual(invalidBindResponse, InvalidBindResponses.Skip);
}
}
public static void AssertIsDerivedFromTypes(IEnumerable<Type> concreteTypes, IEnumerable<Type> parentTypes)
{
foreach (var concreteType in concreteTypes)
{
AssertIsDerivedFromTypes(concreteType, parentTypes);
}
}
public static void AssertIsDerivedFromTypes(Type concreteType, IEnumerable<Type> parentTypes)
{
foreach (var parentType in parentTypes)
{
AssertIsDerivedFromType(concreteType, parentType);
}
}
public static void AssertInstanceDerivesFromOrEqual(object instance, IEnumerable<Type> parentTypes)
{
if (!ZenUtilInternal.IsNull(instance))
{
foreach (var baseType in parentTypes)
{
AssertInstanceDerivesFromOrEqual(instance, baseType);
}
}
}
public static void AssertInstanceDerivesFromOrEqual(object instance, Type baseType)
{
if (!ZenUtilInternal.IsNull(instance))
{
Assert.That(instance.GetType().DerivesFromOrEqual(baseType),
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'", instance.GetType().Name(), baseType.Name());
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// NotificationResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Api.V2010.Account
{
public class NotificationResource : Resource
{
private static Request BuildFetchRequest(FetchNotificationOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Notifications/" + options.PathSid + ".json",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Fetch a notification belonging to the account used to make the request
/// </summary>
/// <param name="options"> Fetch Notification parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Notification </returns>
public static NotificationResource Fetch(FetchNotificationOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Fetch a notification belonging to the account used to make the request
/// </summary>
/// <param name="options"> Fetch Notification parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Notification </returns>
public static async System.Threading.Tasks.Task<NotificationResource> FetchAsync(FetchNotificationOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Fetch a notification belonging to the account used to make the request
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="pathAccountSid"> The SID of the Account that created the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Notification </returns>
public static NotificationResource Fetch(string pathSid,
string pathAccountSid = null,
ITwilioRestClient client = null)
{
var options = new FetchNotificationOptions(pathSid){PathAccountSid = pathAccountSid};
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Fetch a notification belonging to the account used to make the request
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource </param>
/// <param name="pathAccountSid"> The SID of the Account that created the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Notification </returns>
public static async System.Threading.Tasks.Task<NotificationResource> FetchAsync(string pathSid,
string pathAccountSid = null,
ITwilioRestClient client = null)
{
var options = new FetchNotificationOptions(pathSid){PathAccountSid = pathAccountSid};
return await FetchAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadNotificationOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Notifications.json",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a list of notifications belonging to the account used to make the request
/// </summary>
/// <param name="options"> Read Notification parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Notification </returns>
public static ResourceSet<NotificationResource> Read(ReadNotificationOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<NotificationResource>.FromJson("notifications", response.Content);
return new ResourceSet<NotificationResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of notifications belonging to the account used to make the request
/// </summary>
/// <param name="options"> Read Notification parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Notification </returns>
public static async System.Threading.Tasks.Task<ResourceSet<NotificationResource>> ReadAsync(ReadNotificationOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<NotificationResource>.FromJson("notifications", response.Content);
return new ResourceSet<NotificationResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve a list of notifications belonging to the account used to make the request
/// </summary>
/// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param>
/// <param name="log"> Filter by log level </param>
/// <param name="messageDateBefore"> Filter by date </param>
/// <param name="messageDate"> Filter by date </param>
/// <param name="messageDateAfter"> Filter by date </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Notification </returns>
public static ResourceSet<NotificationResource> Read(string pathAccountSid = null,
int? log = null,
DateTime? messageDateBefore = null,
DateTime? messageDate = null,
DateTime? messageDateAfter = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadNotificationOptions(){PathAccountSid = pathAccountSid, Log = log, MessageDateBefore = messageDateBefore, MessageDate = messageDate, MessageDateAfter = messageDateAfter, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of notifications belonging to the account used to make the request
/// </summary>
/// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param>
/// <param name="log"> Filter by log level </param>
/// <param name="messageDateBefore"> Filter by date </param>
/// <param name="messageDate"> Filter by date </param>
/// <param name="messageDateAfter"> Filter by date </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Notification </returns>
public static async System.Threading.Tasks.Task<ResourceSet<NotificationResource>> ReadAsync(string pathAccountSid = null,
int? log = null,
DateTime? messageDateBefore = null,
DateTime? messageDate = null,
DateTime? messageDateAfter = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadNotificationOptions(){PathAccountSid = pathAccountSid, Log = log, MessageDateBefore = messageDateBefore, MessageDate = messageDate, MessageDateAfter = messageDateAfter, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<NotificationResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<NotificationResource>.FromJson("notifications", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<NotificationResource> NextPage(Page<NotificationResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<NotificationResource>.FromJson("notifications", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<NotificationResource> PreviousPage(Page<NotificationResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<NotificationResource>.FromJson("notifications", response.Content);
}
/// <summary>
/// Converts a JSON string into a NotificationResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> NotificationResource object represented by the provided JSON </returns>
public static NotificationResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<NotificationResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The API version used to generate the notification
/// </summary>
[JsonProperty("api_version")]
public string ApiVersion { get; private set; }
/// <summary>
/// The SID of the Call the resource is associated with
/// </summary>
[JsonProperty("call_sid")]
public string CallSid { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT that the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT that the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// A unique error code corresponding to the notification
/// </summary>
[JsonProperty("error_code")]
public string ErrorCode { get; private set; }
/// <summary>
/// An integer log level
/// </summary>
[JsonProperty("log")]
public string Log { get; private set; }
/// <summary>
/// The date the notification was generated
/// </summary>
[JsonProperty("message_date")]
public DateTime? MessageDate { get; private set; }
/// <summary>
/// The text of the notification
/// </summary>
[JsonProperty("message_text")]
public string MessageText { get; private set; }
/// <summary>
/// A URL for more information about the error code
/// </summary>
[JsonProperty("more_info")]
public Uri MoreInfo { get; private set; }
/// <summary>
/// HTTP method used with the request url
/// </summary>
[JsonProperty("request_method")]
[JsonConverter(typeof(HttpMethodConverter))]
public Twilio.Http.HttpMethod RequestMethod { get; private set; }
/// <summary>
/// URL of the resource that generated the notification
/// </summary>
[JsonProperty("request_url")]
public Uri RequestUrl { get; private set; }
/// <summary>
/// Twilio-generated HTTP variables sent to the server
/// </summary>
[JsonProperty("request_variables")]
public string RequestVariables { get; private set; }
/// <summary>
/// The HTTP body returned by your server
/// </summary>
[JsonProperty("response_body")]
public string ResponseBody { get; private set; }
/// <summary>
/// The HTTP headers returned by your server
/// </summary>
[JsonProperty("response_headers")]
public string ResponseHeaders { get; private set; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The URI of the resource, relative to `https://api.twilio.com`
/// </summary>
[JsonProperty("uri")]
public string Uri { get; private set; }
private NotificationResource()
{
}
}
}
| |
//
// CairoExtensions.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using Gdk;
using Cairo;
namespace Hyena.Gui
{
[Flags]
public enum CairoCorners
{
None = 0,
TopLeft = 1,
TopRight = 2,
BottomLeft = 4,
BottomRight = 8,
All = 15
}
public static class CairoExtensions
{
public static Pango.Layout CreateLayout (Gtk.Widget widget, Cairo.Context cairo_context)
{
Pango.Layout layout = PangoCairoHelper.CreateLayout (cairo_context);
layout.FontDescription = widget.PangoContext.FontDescription.Copy ();
double resolution = widget.Screen.Resolution;
if (resolution != -1) {
Pango.Context context = PangoCairoHelper.LayoutGetContext (layout);
PangoCairoHelper.ContextSetResolution (context, resolution);
context.Dispose ();
}
Log.Debug ("Creating Pango.Layout, configuring Cairo.Context");
return layout;
}
public static Surface CreateSurfaceForPixbuf (Cairo.Context cr, Gdk.Pixbuf pixbuf)
{
Surface surface = cr.Target.CreateSimilar (cr.Target.Content, pixbuf.Width, pixbuf.Height);
Cairo.Context surface_cr = new Context (surface);
Gdk.CairoHelper.SetSourcePixbuf (surface_cr, pixbuf, 0, 0);
surface_cr.Paint ();
((IDisposable)surface_cr).Dispose ();
return surface;
}
public static Cairo.Color AlphaBlend (Cairo.Color ca, Cairo.Color cb, double alpha)
{
return new Cairo.Color (
(1.0 - alpha) * ca.R + alpha * cb.R,
(1.0 - alpha) * ca.G + alpha * cb.G,
(1.0 - alpha) * ca.B + alpha * cb.B);
}
public static Cairo.Color GdkColorToCairoColor(Gdk.Color color)
{
return GdkColorToCairoColor(color, 1.0);
}
public static Cairo.Color GdkColorToCairoColor(Gdk.Color color, double alpha)
{
return new Cairo.Color(
(double)(color.Red >> 8) / 255.0,
(double)(color.Green >> 8) / 255.0,
(double)(color.Blue >> 8) / 255.0,
alpha);
}
public static Cairo.Color RgbToColor (uint rgbColor)
{
return RgbaToColor ((rgbColor << 8) | 0x000000ff);
}
public static Cairo.Color RgbaToColor (uint rgbaColor)
{
return new Cairo.Color (
(byte)(rgbaColor >> 24) / 255.0,
(byte)(rgbaColor >> 16) / 255.0,
(byte)(rgbaColor >> 8) / 255.0,
(byte)(rgbaColor & 0x000000ff) / 255.0);
}
public static bool ColorIsDark (Cairo.Color color)
{
double h, s, b;
HsbFromColor (color, out h, out s, out b);
return b < 0.5;
}
public static void HsbFromColor(Cairo.Color color, out double hue,
out double saturation, out double brightness)
{
double min, max, delta;
double red = color.R;
double green = color.G;
double blue = color.B;
hue = 0;
saturation = 0;
brightness = 0;
if(red > green) {
max = Math.Max(red, blue);
min = Math.Min(green, blue);
} else {
max = Math.Max(green, blue);
min = Math.Min(red, blue);
}
brightness = (max + min) / 2;
if(Math.Abs(max - min) < 0.0001) {
hue = 0;
saturation = 0;
} else {
saturation = brightness <= 0.5
? (max - min) / (max + min)
: (max - min) / (2 - max - min);
delta = max - min;
if(red == max) {
hue = (green - blue) / delta;
} else if(green == max) {
hue = 2 + (blue - red) / delta;
} else if(blue == max) {
hue = 4 + (red - green) / delta;
}
hue *= 60;
if(hue < 0) {
hue += 360;
}
}
}
private static double Modula(double number, double divisor)
{
return ((int)number % divisor) + (number - (int)number);
}
public static Cairo.Color ColorFromHsb(double hue, double saturation, double brightness)
{
int i;
double [] hue_shift = { 0, 0, 0 };
double [] color_shift = { 0, 0, 0 };
double m1, m2, m3;
m2 = brightness <= 0.5
? brightness * (1 + saturation)
: brightness + saturation - brightness * saturation;
m1 = 2 * brightness - m2;
hue_shift[0] = hue + 120;
hue_shift[1] = hue;
hue_shift[2] = hue - 120;
color_shift[0] = color_shift[1] = color_shift[2] = brightness;
i = saturation == 0 ? 3 : 0;
for(; i < 3; i++) {
m3 = hue_shift[i];
if(m3 > 360) {
m3 = Modula(m3, 360);
} else if(m3 < 0) {
m3 = 360 - Modula(Math.Abs(m3), 360);
}
if(m3 < 60) {
color_shift[i] = m1 + (m2 - m1) * m3 / 60;
} else if(m3 < 180) {
color_shift[i] = m2;
} else if(m3 < 240) {
color_shift[i] = m1 + (m2 - m1) * (240 - m3) / 60;
} else {
color_shift[i] = m1;
}
}
return new Cairo.Color(color_shift[0], color_shift[1], color_shift[2]);
}
public static Cairo.Color ColorShade (Cairo.Color @base, double ratio)
{
double h, s, b;
HsbFromColor (@base, out h, out s, out b);
b = Math.Max (Math.Min (b * ratio, 1), 0);
s = Math.Max (Math.Min (s * ratio, 1), 0);
Cairo.Color color = ColorFromHsb (h, s, b);
color.A = @base.A;
return color;
}
public static Cairo.Color ColorAdjustBrightness(Cairo.Color @base, double br)
{
double h, s, b;
HsbFromColor(@base, out h, out s, out b);
b = Math.Max(Math.Min(br, 1), 0);
return ColorFromHsb(h, s, b);
}
public static string ColorGetHex (Cairo.Color color, bool withAlpha)
{
if (withAlpha) {
return String.Format("#{0:x2}{1:x2}{2:x2}{3:x2}", (byte)(color.R * 255), (byte)(color.G * 255),
(byte)(color.B * 255), (byte)(color.A * 255));
} else {
return String.Format("#{0:x2}{1:x2}{2:x2}", (byte)(color.R * 255), (byte)(color.G * 255),
(byte)(color.B * 255));
}
}
public static void RoundedRectangle(Cairo.Context cr, double x, double y, double w, double h, double r)
{
RoundedRectangle(cr, x, y, w, h, r, CairoCorners.All, false);
}
public static void RoundedRectangle(Cairo.Context cr, double x, double y, double w, double h,
double r, CairoCorners corners)
{
RoundedRectangle(cr, x, y, w, h, r, corners, false);
}
public static void RoundedRectangle(Cairo.Context cr, double x, double y, double w, double h,
double r, CairoCorners corners, bool topBottomFallsThrough)
{
if(topBottomFallsThrough && corners == CairoCorners.None) {
cr.MoveTo(x, y - r);
cr.LineTo(x, y + h + r);
cr.MoveTo(x + w, y - r);
cr.LineTo(x + w, y + h + r);
return;
} else if(r < 0.0001 || corners == CairoCorners.None) {
cr.Rectangle(x, y, w, h);
return;
}
if((corners & (CairoCorners.TopLeft | CairoCorners.TopRight)) == 0 && topBottomFallsThrough) {
y -= r;
h += r;
cr.MoveTo(x + w, y);
} else {
if((corners & CairoCorners.TopLeft) != 0) {
cr.MoveTo(x + r, y);
} else {
cr.MoveTo(x, y);
}
if((corners & CairoCorners.TopRight) != 0) {
cr.Arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
} else {
cr.LineTo(x + w, y);
}
}
if((corners & (CairoCorners.BottomLeft | CairoCorners.BottomRight)) == 0 && topBottomFallsThrough) {
h += r;
cr.LineTo(x + w, y + h);
cr.MoveTo(x, y + h);
cr.LineTo(x, y + r);
cr.Arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
} else {
if((corners & CairoCorners.BottomRight) != 0) {
cr.Arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
} else {
cr.LineTo(x + w, y + h);
}
if((corners & CairoCorners.BottomLeft) != 0) {
cr.Arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
} else {
cr.LineTo(x, y + h);
}
if((corners & CairoCorners.TopLeft) != 0) {
cr.Arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
} else {
cr.LineTo(x, y);
}
}
}
public static void DisposeContext (Cairo.Context cr)
{
((IDisposable)cr.Target).Dispose ();
((IDisposable)cr).Dispose ();
}
private struct CairoInteropCall
{
public string Name;
public MethodInfo ManagedMethod;
public bool CallNative;
public CairoInteropCall (string name)
{
Name = name;
ManagedMethod = null;
CallNative = false;
}
}
private static bool CallCairoMethod (Cairo.Context cr, ref CairoInteropCall call)
{
if (call.ManagedMethod == null && !call.CallNative) {
MemberInfo [] members = typeof (Cairo.Context).GetMember (call.Name, MemberTypes.Method,
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public);
if (members != null && members.Length > 0 && members[0] is MethodInfo) {
call.ManagedMethod = (MethodInfo)members[0];
} else {
call.CallNative = true;
}
}
if (call.ManagedMethod != null) {
call.ManagedMethod.Invoke (cr, null);
return true;
}
return false;
}
private static bool native_push_pop_exists = true;
[DllImport ("libcairo-2.dll")]
private static extern void cairo_push_group (IntPtr ptr);
private static CairoInteropCall cairo_push_group_call = new CairoInteropCall ("PushGroup");
public static void PushGroup (Cairo.Context cr)
{
if (!native_push_pop_exists) {
return;
}
try {
if (!CallCairoMethod (cr, ref cairo_push_group_call)) {
cairo_push_group (cr.Handle);
}
} catch {
native_push_pop_exists = false;
}
}
[DllImport ("libcairo-2.dll")]
private static extern void cairo_pop_group_to_source (IntPtr ptr);
private static CairoInteropCall cairo_pop_group_to_source_call = new CairoInteropCall ("PopGroupToSource");
public static void PopGroupToSource (Cairo.Context cr)
{
if (!native_push_pop_exists) {
return;
}
try {
if (!CallCairoMethod (cr, ref cairo_pop_group_to_source_call)) {
cairo_pop_group_to_source (cr.Handle);
}
} catch (EntryPointNotFoundException) {
native_push_pop_exists = false;
}
}
}
}
| |
using Lucene.Net.Support;
using System;
using System.Diagnostics;
namespace Lucene.Net.Util
{
/*
* 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.
*/
/// <summary>
/// BitSet of fixed length (numBits), backed by accessible (<seealso cref="#getBits"/>)
/// long[], accessed with a long index. Use it only if you intend to store more
/// than 2.1B bits, otherwise you should use <seealso cref="FixedBitSet"/>.
///
/// @lucene.internal
/// </summary>
public sealed class LongBitSet
{
private readonly long[] bits;
private readonly long NumBits;
private readonly int NumWords;
/// <summary>
/// If the given <seealso cref="LongBitSet"/> is large enough to hold
/// {@code numBits}, returns the given bits, otherwise returns a new
/// <seealso cref="LongBitSet"/> which can hold the requested number of bits.
///
/// <p>
/// <b>NOTE:</b> the returned bitset reuses the underlying {@code long[]} of
/// the given {@code bits} if possible. Also, calling <seealso cref="#length()"/> on the
/// returned bits may return a value greater than {@code numBits}.
/// </summary>
public static LongBitSet EnsureCapacity(LongBitSet bits, long numBits)
{
if (numBits < bits.Length())
{
return bits;
}
else
{
int numWords = Bits2words(numBits);
long[] arr = bits.Bits;
if (numWords >= arr.Length)
{
arr = ArrayUtil.Grow(arr, numWords + 1);
}
return new LongBitSet(arr, arr.Length << 6);
}
}
/// <summary>
/// returns the number of 64 bit words it would take to hold numBits </summary>
public static int Bits2words(long numBits)
{
int numLong = (int)((long)((ulong)numBits >> 6));
if ((numBits & 63) != 0)
{
numLong++;
}
return numLong;
}
public LongBitSet(long numBits)
{
this.NumBits = numBits;
bits = new long[Bits2words(numBits)];
NumWords = bits.Length;
}
public LongBitSet(long[] storedBits, long numBits)
{
this.NumWords = Bits2words(numBits);
if (NumWords > storedBits.Length)
{
throw new System.ArgumentException("The given long array is too small to hold " + numBits + " bits");
}
this.NumBits = numBits;
this.bits = storedBits;
}
/// <summary>
/// Returns the number of bits stored in this bitset. </summary>
public long Length()
{
return NumBits;
}
/// <summary>
/// Expert. </summary>
public long[] Bits
{
get
{
return bits;
}
}
/// <summary>
/// Returns number of set bits. NOTE: this visits every
/// long in the backing bits array, and the result is not
/// internally cached!
/// </summary>
public long Cardinality()
{
return BitUtil.Pop_array(bits, 0, bits.Length);
}
public bool Get(long index)
{
Debug.Assert(index >= 0 && index < NumBits, "index=" + index);
int i = (int)(index >> 6); // div 64
// signed shift will keep a negative index and force an
// array-index-out-of-bounds-exception, removing the need for an explicit check.
int bit = (int)(index & 0x3f); // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
public void Set(long index)
{
Debug.Assert(index >= 0 && index < NumBits, "index=" + index + " numBits=" + NumBits);
int wordNum = (int)(index >> 6); // div 64
int bit = (int)(index & 0x3f); // mod 64
long bitmask = 1L << bit;
bits[wordNum] |= bitmask;
}
public bool GetAndSet(long index)
{
Debug.Assert(index >= 0 && index < NumBits);
int wordNum = (int)(index >> 6); // div 64
int bit = (int)(index & 0x3f); // mod 64
long bitmask = 1L << bit;
bool val = (bits[wordNum] & bitmask) != 0;
bits[wordNum] |= bitmask;
return val;
}
public void Clear(long index)
{
Debug.Assert(index >= 0 && index < NumBits);
int wordNum = (int)(index >> 6);
int bit = (int)(index & 0x03f);
long bitmask = 1L << bit;
bits[wordNum] &= ~bitmask;
}
public bool GetAndClear(long index)
{
Debug.Assert(index >= 0 && index < NumBits);
int wordNum = (int)(index >> 6); // div 64
int bit = (int)(index & 0x3f); // mod 64
long bitmask = 1L << bit;
bool val = (bits[wordNum] & bitmask) != 0;
bits[wordNum] &= ~bitmask;
return val;
}
/// <summary>
/// Returns the index of the first set bit starting at the index specified.
/// -1 is returned if there are no more set bits.
/// </summary>
public long NextSetBit(long index)
{
Debug.Assert(index >= 0 && index < NumBits);
int i = (int)(index >> 6);
int subIndex = (int)(index & 0x3f); // index within the word
long word = bits[i] >> subIndex; // skip all the bits to the right of index
if (word != 0)
{
return index + Number.NumberOfTrailingZeros(word);
}
while (++i < NumWords)
{
word = bits[i];
if (word != 0)
{
return (i << 6) + Number.NumberOfTrailingZeros(word);
}
}
return -1;
}
/// <summary>
/// Returns the index of the last set bit before or on the index specified.
/// -1 is returned if there are no more set bits.
/// </summary>
public long PrevSetBit(long index)
{
Debug.Assert(index >= 0 && index < NumBits, "index=" + index + " numBits=" + NumBits);
int i = (int)(index >> 6);
int subIndex = (int)(index & 0x3f); // index within the word
long word = (bits[i] << (63 - subIndex)); // skip all the bits to the left of index
if (word != 0)
{
return (i << 6) + subIndex - Number.NumberOfLeadingZeros(word); // See LUCENE-3197
}
while (--i >= 0)
{
word = bits[i];
if (word != 0)
{
return (i << 6) + 63 - Number.NumberOfLeadingZeros(word);
}
}
return -1;
}
/// <summary>
/// this = this OR other </summary>
public void Or(LongBitSet other)
{
Debug.Assert(other.NumWords <= NumWords, "numWords=" + NumWords + ", other.numWords=" + other.NumWords);
int pos = Math.Min(NumWords, other.NumWords);
while (--pos >= 0)
{
bits[pos] |= other.bits[pos];
}
}
/// <summary>
/// this = this XOR other </summary>
public void Xor(LongBitSet other)
{
Debug.Assert(other.NumWords <= NumWords, "numWords=" + NumWords + ", other.numWords=" + other.NumWords);
int pos = Math.Min(NumWords, other.NumWords);
while (--pos >= 0)
{
bits[pos] ^= other.bits[pos];
}
}
/// <summary>
/// returns true if the sets have any elements in common </summary>
public bool Intersects(LongBitSet other)
{
int pos = Math.Min(NumWords, other.NumWords);
while (--pos >= 0)
{
if ((bits[pos] & other.bits[pos]) != 0)
{
return true;
}
}
return false;
}
/// <summary>
/// this = this AND other </summary>
public void And(LongBitSet other)
{
int pos = Math.Min(NumWords, other.NumWords);
while (--pos >= 0)
{
bits[pos] &= other.bits[pos];
}
if (NumWords > other.NumWords)
{
Arrays.Fill(bits, other.NumWords, NumWords, 0L);
}
}
/// <summary>
/// this = this AND NOT other </summary>
public void AndNot(LongBitSet other)
{
int pos = Math.Min(NumWords, other.bits.Length);
while (--pos >= 0)
{
bits[pos] &= ~other.bits[pos];
}
}
// NOTE: no .isEmpty() here because that's trappy (ie,
// typically isEmpty is low cost, but this one wouldn't
// be)
/// <summary>
/// Flips a range of bits
/// </summary>
/// <param name="startIndex"> lower index </param>
/// <param name="endIndex"> one-past the last bit to flip </param>
public void Flip(long startIndex, long endIndex)
{
Debug.Assert(startIndex >= 0 && startIndex < NumBits);
Debug.Assert(endIndex >= 0 && endIndex <= NumBits);
if (endIndex <= startIndex)
{
return;
}
int startWord = (int)(startIndex >> 6);
int endWord = (int)((endIndex - 1) >> 6);
/*
///* Grrr, java shifting wraps around so -1L>>>64 == -1
/// for that reason, make sure not to use endmask if the bits to flip will
/// be zero in the last word (redefine endWord to be the last changed...)
/// long startmask = -1L << (startIndex & 0x3f); // example: 11111...111000
/// long endmask = -1L >>> (64-(endIndex & 0x3f)); // example: 00111...111111
/// **
*/
//LUCENE TO-DO
long startmask = -1L << (int)startIndex;
long endmask = (long)(unchecked(((ulong)-1L)) >> (int)-endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
if (startWord == endWord)
{
bits[startWord] ^= (startmask & endmask);
return;
}
bits[startWord] ^= startmask;
for (int i = startWord + 1; i < endWord; i++)
{
bits[i] = ~bits[i];
}
bits[endWord] ^= endmask;
}
/// <summary>
/// Sets a range of bits
/// </summary>
/// <param name="startIndex"> lower index </param>
/// <param name="endIndex"> one-past the last bit to set </param>
public void Set(long startIndex, long endIndex)
{
Debug.Assert(startIndex >= 0 && startIndex < NumBits);
Debug.Assert(endIndex >= 0 && endIndex <= NumBits);
if (endIndex <= startIndex)
{
return;
}
int startWord = (int)(startIndex >> 6);
int endWord = (int)((endIndex - 1) >> 6);
//LUCENE TO-DO
long startmask = -1L << (int)startIndex;
long endmask = (long)(0xffffffffffffffffUL >> (int)-endIndex);//-(int)((uint)1L >> (int)-endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
if (startWord == endWord)
{
bits[startWord] |= (startmask & endmask);
return;
}
bits[startWord] |= startmask;
Arrays.Fill(bits, startWord + 1, endWord, -1L);
bits[endWord] |= endmask;
}
/// <summary>
/// Clears a range of bits.
/// </summary>
/// <param name="startIndex"> lower index </param>
/// <param name="endIndex"> one-past the last bit to clear </param>
public void Clear(long startIndex, long endIndex)
{
Debug.Assert(startIndex >= 0 && startIndex < NumBits);
Debug.Assert(endIndex >= 0 && endIndex <= NumBits);
if (endIndex <= startIndex)
{
return;
}
int startWord = (int)(startIndex >> 6);
int endWord = (int)((endIndex - 1) >> 6);
// Casting long to int discards MSBs, so it is no problem because we are taking mod 64.
long startmask = (-1L) << (int)startIndex; // -1 << (startIndex mod 64)
long endmask = (-1L) << (int)endIndex; // -1 << (endIndex mod 64)
if ((endIndex & 0x3f) == 0)
{
endmask = 0;
}
startmask = ~startmask;
if (startWord == endWord)
{
bits[startWord] &= (startmask | endmask);
return;
}
bits[startWord] &= startmask;
Arrays.Fill(bits, startWord + 1, endWord, 0L);
bits[endWord] &= endmask;
}
public LongBitSet Clone()
{
long[] bits = new long[this.bits.Length];
Array.Copy(this.bits, 0, bits, 0, bits.Length);
return new LongBitSet(bits, NumBits);
}
/// <summary>
/// returns true if both sets have the same bits set </summary>
public override bool Equals(object o)
{
if (this == o)
{
return true;
}
if (!(o is LongBitSet))
{
return false;
}
LongBitSet other = (LongBitSet)o;
if (NumBits != other.Length())
{
return false;
}
return Arrays.Equals(bits, other.bits);
}
public override int GetHashCode()
{
long h = 0;
for (int i = NumWords; --i >= 0; )
{
h ^= bits[i];
h = (h << 1) | ((long)((ulong)h >> 63)); // rotate left
}
// fold leftmost bits into right and add a constant to prevent
// empty sets from returning 0, which is too common.
return (int)((h >> 32) ^ h) + unchecked((int)0x98761234);
}
}
}
| |
using System;
using Orleans.Runtime;
namespace Orleans
{
/// <summary>
/// Extension methods for grains.
/// </summary>
public static class GrainExtensions
{
private const string WRONG_GRAIN_ERROR_MSG = "Passing a half baked grain as an argument. It is possible that you instantiated a grain class explicitly, as a regular object and not via Orleans runtime or via proper test mocking";
internal static GrainReference AsReference(this IAddressable grain)
{
ThrowIfNullGrain(grain);
// When called against an instance of a grain reference class, do nothing
var reference = grain as GrainReference;
if (reference != null) return reference;
var grainBase = grain as Grain;
if (grainBase != null)
{
if (grainBase.Data?.GrainReference is GrainReference grainRef)
{
return grainRef;
}
else
{
throw new ArgumentException(WRONG_GRAIN_ERROR_MSG, nameof(grain));
}
}
var systemTarget = grain as ISystemTargetBase;
if (systemTarget != null) return systemTarget.GrainReference;
throw new ArgumentException(
$"AsWeaklyTypedReference has been called on an unexpected type: {grain.GetType().FullName}.",
nameof(grain));
}
/// <summary>
/// Converts this grain to a specific grain interface.
/// </summary>
/// <typeparam name="TGrainInterface">The type of the grain interface.</typeparam>
/// <param name="grain">The grain to convert.</param>
/// <returns>A strongly typed <c>GrainReference</c> of grain interface type TGrainInterface.</returns>
public static TGrainInterface AsReference<TGrainInterface>(this IAddressable grain)
{
ThrowIfNullGrain(grain);
var grainReference = grain.AsReference();
return (TGrainInterface)grainReference.Runtime.Cast(grain, typeof(TGrainInterface));
}
/// <summary>
/// Casts a grain to a specific grain interface.
/// </summary>
/// <typeparam name="TGrainInterface">The type of the grain interface.</typeparam>
/// <param name="grain">The grain to cast.</param>
public static TGrainInterface Cast<TGrainInterface>(this IAddressable grain)
{
return grain.AsReference<TGrainInterface>();
}
/// <summary>
/// Casts the provided <paramref name="grain"/> to the provided <paramref name="interfaceType"/>.
/// </summary>
/// <param name="grain">The grain.</param>
/// <param name="interfaceType">The resulting interface type.</param>
/// <returns>A reference to <paramref name="grain"/> which implements <paramref name="interfaceType"/>.</returns>
public static object Cast(this IAddressable grain, Type interfaceType)
{
return grain.AsReference().Runtime.Cast(grain, interfaceType);
}
public static GrainId GetGrainId(this IAddressable grain)
{
switch (grain)
{
case Grain grainBase:
if (grainBase.GrainId.IsDefault)
{
throw new ArgumentException(WRONG_GRAIN_ERROR_MSG, "grain");
}
return grainBase.GrainId;
case GrainReference grainReference:
if (grainReference.GrainId.IsDefault)
{
throw new ArgumentException(WRONG_GRAIN_ERROR_MSG, "grain");
}
return grainReference.GrainId;
case ISystemTargetBase systemTarget:
return systemTarget.GrainId;
default:
throw new ArgumentException(String.Format("GetGrainIdentity has been called on an unexpected type: {0}.", grain.GetType().FullName), "grain");
}
}
/// <summary>
/// Returns whether part of the primary key is of type long.
/// </summary>
/// <param name="grain">The target grain.</param>
public static bool IsPrimaryKeyBasedOnLong(this IAddressable grain)
{
var grainId = GetGrainId(grain);
if (GrainIdKeyExtensions.TryGetIntegerKey(grainId, out var primaryKey, out _))
{
return true;
}
if (LegacyGrainId.TryConvertFromGrainId(grainId, out var legacyId))
{
return legacyId.IsLongKey;
}
throw new InvalidOperationException($"Unable to extract integer key from grain id {grainId}");
}
/// <summary>
/// Returns the long representation of a grain primary key.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <param name="keyExt">The output parameter to return the extended key part of the grain primary key, if extended primary key was provided for that grain.</param>
/// <returns>A long representing the primary key for this grain.</returns>
public static long GetPrimaryKeyLong(this IAddressable grain, out string keyExt)
{
var grainId = GetGrainId(grain);
if (GrainIdKeyExtensions.TryGetIntegerKey(grainId, out var primaryKey, out keyExt))
{
return primaryKey;
}
if (LegacyGrainId.TryConvertFromGrainId(grainId, out var legacyId))
{
return legacyId.GetPrimaryKeyLong(out keyExt);
}
throw new InvalidOperationException($"Unable to extract integer key from grain id {grainId}");
}
/// <summary>
/// Returns the long representation of a grain primary key.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <returns>A long representing the primary key for this grain.</returns>
public static long GetPrimaryKeyLong(this IAddressable grain)
{
var grainId = GetGrainId(grain);
if (GrainIdKeyExtensions.TryGetIntegerKey(grainId, out var primaryKey, out _))
{
return primaryKey;
}
if (LegacyGrainId.TryConvertFromGrainId(grainId, out var legacyId))
{
return legacyId.GetPrimaryKeyLong();
}
throw new InvalidOperationException($"Unable to extract integer key from grain id {grainId}");
}
/// <summary>
/// Returns the Guid representation of a grain primary key.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <param name="keyExt">The output parameter to return the extended key part of the grain primary key, if extended primary key was provided for that grain.</param>
/// <returns>A Guid representing the primary key for this grain.</returns>
public static Guid GetPrimaryKey(this IAddressable grain, out string keyExt)
{
var grainId = GetGrainId(grain);
if (GrainIdKeyExtensions.TryGetGuidKey(grainId, out var guid, out keyExt))
{
return guid;
}
if (LegacyGrainId.TryConvertFromGrainId(grainId, out var legacyId))
{
return legacyId.GetPrimaryKey(out keyExt);
}
if (GrainIdKeyExtensions.TryGetIntegerKey(grainId, out var integerKey, out keyExt))
{
var N0 = 0L;
var N1 = integerKey;
return new Guid((uint)(N0 & 0xffffffff), (ushort)(N0 >> 32), (ushort)(N0 >> 48), (byte)N1, (byte)(N1 >> 8), (byte)(N1 >> 16), (byte)(N1 >> 24), (byte)(N1 >> 32), (byte)(N1 >> 40), (byte)(N1 >> 48), (byte)(N1 >> 56));
}
throw new InvalidOperationException($"Unable to extract GUID key from grain id {grainId}");
}
/// <summary>
/// Returns the Guid representation of a grain primary key.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <returns>A Guid representing the primary key for this grain.</returns>
public static Guid GetPrimaryKey(this IAddressable grain) => grain.GetPrimaryKey(out _);
/// <summary>
/// Returns the string primary key of the grain.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <returns>A string representing the primary key for this grain.</returns>
public static string GetPrimaryKeyString(this IAddressable grain)
{
var grainId = GetGrainId(grain);
if (LegacyGrainId.TryConvertFromGrainId(grainId, out var legacyId))
{
return legacyId.GetPrimaryKeyString();
}
return grainId.Key.ToStringUtf8();
}
private static void ThrowIfNullGrain(IAddressable grain)
{
if (grain == null)
{
throw new ArgumentNullException(nameof(grain));
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Billing
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for InvoicesOperations.
/// </summary>
public static partial class InvoicesOperationsExtensions
{
/// <summary>
/// Lists the available invoices for a subscription in reverse chronological
/// order beginning with the most recent invoice. In preview, invoices are
/// available via this API only for invoice periods which end December 1, 2016
/// or later
/// <see href="https://go.microsoft.com/fwlink/?linkid=842057" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='expand'>
/// May be used to expand the downloadUrl property within a list of invoices.
/// This enables download links to be generated for multiple invoices at once.
/// By default, downloadURLs are not included when listing invoices.
/// </param>
/// <param name='filter'>
/// May be used to filter invoices by invoicePeriodEndDate. The filter supports
/// 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support
/// 'ne', 'or', or 'not'
/// </param>
/// <param name='skiptoken'>
/// Skiptoken is only used if a previous operation returned a partial result.
/// If a previous response contains a nextLink element, the value of the
/// nextLink element will include a skiptoken parameter that specifies a
/// starting point to use for subsequent calls.
/// </param>
/// <param name='top'>
/// May be used to limit the number of results to the most recent N invoices.
/// </param>
public static IPage<Invoice> List(this IInvoicesOperations operations, string expand = default(string), string filter = default(string), string skiptoken = default(string), int? top = default(int?))
{
return operations.ListAsync(expand, filter, skiptoken, top).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the available invoices for a subscription in reverse chronological
/// order beginning with the most recent invoice. In preview, invoices are
/// available via this API only for invoice periods which end December 1, 2016
/// or later
/// <see href="https://go.microsoft.com/fwlink/?linkid=842057" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='expand'>
/// May be used to expand the downloadUrl property within a list of invoices.
/// This enables download links to be generated for multiple invoices at once.
/// By default, downloadURLs are not included when listing invoices.
/// </param>
/// <param name='filter'>
/// May be used to filter invoices by invoicePeriodEndDate. The filter supports
/// 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently support
/// 'ne', 'or', or 'not'
/// </param>
/// <param name='skiptoken'>
/// Skiptoken is only used if a previous operation returned a partial result.
/// If a previous response contains a nextLink element, the value of the
/// nextLink element will include a skiptoken parameter that specifies a
/// starting point to use for subsequent calls.
/// </param>
/// <param name='top'>
/// May be used to limit the number of results to the most recent N invoices.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Invoice>> ListAsync(this IInvoicesOperations operations, string expand = default(string), string filter = default(string), string skiptoken = default(string), int? top = default(int?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(expand, filter, skiptoken, top, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a named invoice resource. When getting a single invoice, the
/// downloadUrl property is expanded automatically.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='invoiceName'>
/// The name of an invoice resource.
/// </param>
public static Invoice Get(this IInvoicesOperations operations, string invoiceName)
{
return operations.GetAsync(invoiceName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a named invoice resource. When getting a single invoice, the
/// downloadUrl property is expanded automatically.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='invoiceName'>
/// The name of an invoice resource.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Invoice> GetAsync(this IInvoicesOperations operations, string invoiceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(invoiceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the most recent invoice. When getting a single invoice, the
/// downloadUrl property is expanded automatically.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Invoice GetLatest(this IInvoicesOperations operations)
{
return operations.GetLatestAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the most recent invoice. When getting a single invoice, the
/// downloadUrl property is expanded automatically.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Invoice> GetLatestAsync(this IInvoicesOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetLatestWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the available invoices for a subscription in reverse chronological
/// order beginning with the most recent invoice. In preview, invoices are
/// available via this API only for invoice periods which end December 1, 2016
/// or later
/// <see href="https://go.microsoft.com/fwlink/?linkid=842057" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Invoice> ListNext(this IInvoicesOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the available invoices for a subscription in reverse chronological
/// order beginning with the most recent invoice. In preview, invoices are
/// available via this API only for invoice periods which end December 1, 2016
/// or later
/// <see href="https://go.microsoft.com/fwlink/?linkid=842057" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Invoice>> ListNextAsync(this IInvoicesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using VSConstants = Microsoft.VisualStudio.VSConstants;
namespace Microsoft.VisualStudioTools.Navigation
{
/// <summary>
/// Implements a simple library that tracks project symbols, objects etc.
/// </summary>
internal class Library : IVsSimpleLibrary2
{
private Guid _guid;
private _LIB_FLAGS2 _capabilities;
private LibraryNode _root;
private uint _updateCount;
public Library(Guid libraryGuid)
{
this._guid = libraryGuid;
this._root = new LibraryNode(null, string.Empty, string.Empty, LibraryNodeType.Package);
}
public _LIB_FLAGS2 LibraryCapabilities
{
get { return this._capabilities; }
set { this._capabilities = value; }
}
internal void AddNode(LibraryNode node)
{
lock (this)
{
// re-create root node here because we may have handed out the node before and don't want to mutate it's list.
this._root = this._root.Clone();
this._root.AddNode(node);
this._updateCount++;
}
}
internal void RemoveNode(LibraryNode node)
{
lock (this)
{
this._root = this._root.Clone();
this._root.RemoveNode(node);
this._updateCount++;
}
}
#region IVsSimpleLibrary2 Members
public int AddBrowseContainer(VSCOMPONENTSELECTORDATA[] pcdComponent, ref uint pgrfOptions, out string pbstrComponentAdded)
{
pbstrComponentAdded = null;
return VSConstants.E_NOTIMPL;
}
public int CreateNavInfo(SYMBOL_DESCRIPTION_NODE[] rgSymbolNodes, uint ulcNodes, out IVsNavInfo ppNavInfo)
{
ppNavInfo = null;
return VSConstants.E_NOTIMPL;
}
public int GetBrowseContainersForHierarchy(IVsHierarchy pHierarchy, uint celt, VSBROWSECONTAINER[] rgBrowseContainers, uint[] pcActual)
{
return VSConstants.E_NOTIMPL;
}
public int GetGuid(out Guid pguidLib)
{
pguidLib = this._guid;
return VSConstants.S_OK;
}
public int GetLibFlags2(out uint pgrfFlags)
{
pgrfFlags = (uint)this.LibraryCapabilities;
return VSConstants.S_OK;
}
public int GetList2(uint ListType, uint flags, VSOBSEARCHCRITERIA2[] pobSrch, out IVsSimpleObjectList2 ppIVsSimpleObjectList2)
{
if ((flags & (uint)_LIB_LISTFLAGS.LLF_RESOURCEVIEW) != 0)
{
ppIVsSimpleObjectList2 = null;
return VSConstants.E_NOTIMPL;
}
ICustomSearchListProvider listProvider;
if (pobSrch != null &&
pobSrch.Length > 0)
{
if ((listProvider = pobSrch[0].pIVsNavInfo as ICustomSearchListProvider) != null)
{
switch ((_LIB_LISTTYPE)ListType)
{
case _LIB_LISTTYPE.LLT_NAMESPACES:
ppIVsSimpleObjectList2 = listProvider.GetSearchList();
break;
default:
ppIVsSimpleObjectList2 = null;
return VSConstants.E_FAIL;
}
}
else
{
if (pobSrch[0].eSrchType == VSOBSEARCHTYPE.SO_ENTIREWORD && ListType == (uint)_LIB_LISTTYPE.LLT_MEMBERS)
{
var srchText = pobSrch[0].szName;
int colonIndex;
if ((colonIndex = srchText.LastIndexOf(':')) != -1)
{
var filename = srchText.Substring(0, srchText.LastIndexOf(':'));
foreach (var project in this._root.Children)
{
foreach (var item in project.Children)
{
if (item.FullName == filename)
{
ppIVsSimpleObjectList2 = item.DoSearch(pobSrch[0]);
if (ppIVsSimpleObjectList2 != null)
{
return VSConstants.S_OK;
}
}
}
}
}
ppIVsSimpleObjectList2 = null;
return VSConstants.E_FAIL;
}
else if (pobSrch[0].eSrchType == VSOBSEARCHTYPE.SO_SUBSTRING && ListType == (uint)_LIB_LISTTYPE.LLT_NAMESPACES)
{
var lib = new LibraryNode(null, "Search results " + pobSrch[0].szName, "Search results " + pobSrch[0].szName, LibraryNodeType.Package);
foreach (var item in SearchNodes(pobSrch[0], new SimpleObjectList<LibraryNode>(), this._root).Children)
{
lib.Children.Add(item);
}
ppIVsSimpleObjectList2 = lib;
return VSConstants.S_OK;
}
else
{
ppIVsSimpleObjectList2 = null;
return VSConstants.E_FAIL;
}
}
}
else
{
ppIVsSimpleObjectList2 = this._root as IVsSimpleObjectList2;
}
return VSConstants.S_OK;
}
private static SimpleObjectList<LibraryNode> SearchNodes(VSOBSEARCHCRITERIA2 srch, SimpleObjectList<LibraryNode> list, LibraryNode curNode)
{
foreach (var child in curNode.Children)
{
if (child.Name.IndexOf(srch.szName, StringComparison.OrdinalIgnoreCase) != -1)
{
list.Children.Add(child.Clone(child.Name));
}
SearchNodes(srch, list, child);
}
return list;
}
public void VisitNodes(ILibraryNodeVisitor visitor, CancellationToken ct = default(CancellationToken))
{
lock (this)
{
this._root.Visit(visitor, ct);
}
}
public int GetSeparatorStringWithOwnership(out string pbstrSeparator)
{
pbstrSeparator = ".";
return VSConstants.S_OK;
}
public int GetSupportedCategoryFields2(int Category, out uint pgrfCatField)
{
pgrfCatField = (uint)_LIB_CATEGORY2.LC_HIERARCHYTYPE | (uint)_LIB_CATEGORY2.LC_PHYSICALCONTAINERTYPE;
return VSConstants.S_OK;
}
public int LoadState(IStream pIStream, LIB_PERSISTTYPE lptType)
{
return VSConstants.S_OK;
}
public int RemoveBrowseContainer(uint dwReserved, string pszLibName)
{
return VSConstants.E_NOTIMPL;
}
public int SaveState(IStream pIStream, LIB_PERSISTTYPE lptType)
{
return VSConstants.S_OK;
}
public int UpdateCounter(out uint pCurUpdate)
{
pCurUpdate = this._updateCount;
return VSConstants.S_OK;
}
public void Update()
{
this._updateCount++;
this._root.Update();
}
#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 ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex001.complex001
{
// <Title>Derived generic types</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public class MyClass<T>
where T : List<object>
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<List<object>> mc = new MyClass<List<dynamic>>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex002.complex002
{
// <Title>Derived generic types</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public class MyClass<T>
where T : List<object>
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<List<dynamic>> mc = new MyClass<List<dynamic>>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex008.complex008
{
// <Title>Generic constraints</Title>
// <Description> Trying to pass in int and dynamic as type parameters used to give an error saying that there is no boxing conversion from int to dynamic
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class M
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int rez = M1<int, dynamic>();
rez += M2<int, dynamic>();
int i = 4;
dynamic d = 4;
// Simple call let Runtime decide d's type which is 'int' instead of 'object'
rez += M3(i, d);
return rez > 0 ? 1 : 0;
}
public static int M3<T, S>(T t, S s) where T : S
{
// if (typeof(T) != typeof(int) || typeof(S) != typeof(object)) return 1;
if (typeof(T) != typeof(int) || typeof(S) != typeof(int))
return 1;
return 0;
}
public static int M2<T, S>() where T : struct, S
{
if (typeof(T) != typeof(int) || typeof(S) != typeof(object))
return 1;
return 0;
}
public static int M1<T, S>() where T : S
{
if (typeof(T) != typeof(int) || typeof(S) != typeof(object))
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex009.complex009
{
// <Title>Derived generic types</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new C();
c.NakedGen1<GenDerClass<int>, GenBaseClass<int>>();
c.NakedGen1<GenDerClass<Struct>, GenBaseClass<Struct>>();
return 0;
}
}
public class C
{
public void NakedGen1<T, U>() where T : U
{
}
}
public struct Struct
{
}
public class GenBaseClass<T>
{
}
public class GenDerClass<T> : GenBaseClass<T>
{
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex010.complex010
{
// <Title>Derived generic types</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class Base<T>
{
public virtual void Foo<G>() where G : T, new()
{
}
}
public class DerivedNullableOfInt : Base<int?>
{
public override void Foo<G>()
{
dynamic d = new G();
d = 4;
d.ToString();
Program.Status = 1;
}
}
public class Program
{
public static int Status = 0;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic d = new DerivedNullableOfInt();
d.Foo<int?>();
if (Program.Status == 1)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex011.complex011
{
// <Title>Derived generic types</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public class Base<T>
{
public virtual IEnumerable<G> Foo<G>() where G : T, new()
{
return null;
}
}
public class DerivedNullableOfInt : Base<int?>
{
public override IEnumerable<G> Foo<G>()
{
yield return new G();
}
}
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic d = new DerivedNullableOfInt();
var x = d.Foo<int?>();
return x != null ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex012.complex012
{
// <Title>Derived generic types</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Base<T>
{
public virtual int Foo<G>() where G : T, new()
{
return -1;
}
}
public class DerivedNullableOfInt : Base<int?>
{
public override int Foo<G>()
{
int i = 3;
Func<G, int> f = x => i;
return f(new G());
}
}
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic d = new DerivedNullableOfInt();
var x = d.Foo<int?>();
if (x != null)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple001.simple001
{
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class MyClass<T>
where T : class
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<object> mc = new MyClass<dynamic>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple002.simple002
{
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class MyClass<T>
where T : class
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<dynamic> mc = new MyClass<object>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple006.simple006
{
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class MyClass<T>
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<object> mc = new MyClass<dynamic>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple008.simple008
{
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class MyClass<T, U>
where T : U
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<dynamic, object> mc = new MyClass<dynamic, object>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple009.simple009
{
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class MyClass<T>
where T : class
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<dynamic> mc = new MyClass<dynamic>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple012.simple012
{
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class MyClass<T, U>
where T : U
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<object, object> mc = new MyClass<dynamic, dynamic>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple013.simple013
{
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class MyClass<T, U>
where T : U
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<dynamic, object> mc = new MyClass<object, dynamic>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple015.simple015
{
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class MyClass<T>
where T : new()
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<dynamic> mc = new MyClass<dynamic>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple016.simple016
{
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class MyClass<T>
where T : new()
{
public void Foo()
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
MyClass<object> mc = new MyClass<dynamic>();
mc.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple018.simple018
{
// <Title>Generic constraints</Title>
// <Description></Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic x = new Test();
x.Bar<string, dynamic>();
var y = new Test();
y.Bar<string, dynamic>(); // used to be error CS0311:
// The type 'string' cannot be used as type parameter 'T' in the generic type or method 'A.Foo<T,S>()'.
// There is no implicit reference conversion from 'string' to '::dynamic'.
return 0;
}
public void Bar<T, S>() where T : S
{
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple019.simple019
{
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class B
{
public static int Status = 1;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic x = new B();
x.Foo<int>();
return B.Status;
}
public void Foo<T, S>() where T : S
{
B.Status = 1;
}
public void Foo<T>()
{
B.Status = 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple020.simple020
{
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class B
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic x = new B();
try
{
x.Foo(); // Unexpected NullReferenceException
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "B.Foo<T>()"))
return 0;
}
return 1;
}
public void Foo<T>()
{
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple021.simple021
{
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class B
{
public static int Status = 1;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic x = new B();
x.Foo<int, int>();
return B.Status;
}
public void Foo<T, S>() where T : S // The constraint is important part
{
B.Status = 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple022.simple022
{
// <Title>Generic constraints</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class B
{
public static int Status = 1;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic x = new B();
try
{
x.Foo<int>(); // Unexpected NullReferenceException
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArity, e.Message, "B.Foo<T,S>()", ErrorVerifier.GetErrorElement(ErrorElementId.SK_METHOD), "2"))
B.Status = 0;
}
return B.Status;
}
public void Foo<T, S>() where T : S
{
B.Status = 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference001.typeinference001
{
// <Title>Generic Type Inference</Title>
// <Description> Runtime type inference succeeds in cases where it should fail
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class C
{
public static void M<T>(T x, T y)
{
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
string x = "string";
dynamic y = 7;
try
{
C.M(x, y);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "C.M<T>(T, T)"))
return 0;
}
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference002.typeinference002
{
// <Title>Generic Type Inference</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class A
{
public void M<T>(T x, T y)
{
}
}
public class TestClass
{
[Fact]
public void RunTest()
{
Test.DynamicCSharpRunTest();
}
}
public struct Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var vv = new A();
dynamic vd = new A();
int ret = 0;
// dyn (null) & string -> string
dynamic dynPara = null;
string str = "QC";
try
{
vv.M(dynPara, str);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("1)" + ex);
ret++; // Fail
}
try
{
vd.M(dynPara, str);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("2)" + ex);
ret++; // Fail
}
// dyn (null) & class
dynPara = null;
var a = new A();
try
{
vv.M(dynPara, a);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("3)" + ex);
ret++; // Fail
}
try
{
vd.M(a, dynPara);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("4)" + ex);
ret++; // Fail
}
// dyn (class), dyn (null)
dynPara = new A();
dynamic dynP2 = null;
try
{
vv.M(dynPara, dynP2);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("5)" + ex);
ret++; // Fail
}
try
{
vd.M(dynP2, dynPara);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("6)" + ex);
ret++; // Fail
}
return 0 == ret ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference003.typeinference003
{
// <Title>Generic Type Inference</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public struct S
{
public void M<T>(T x, T y)
{
}
}
public struct Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var vv = new S();
dynamic vd = new S();
int ret = 6;
// dyn (int), string (null)
dynamic dynPara = 100;
string str = null;
try
{
vv.M(str, dynPara);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "S.M<T>(T, T)"))
ret--; // Pass
}
try
{
vd.M(dynPara, str);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "S.M<T>(T, T)"))
ret--; // Pass
}
// dyn (null), int -\-> int?
dynPara = null;
int n = 0;
try
{
vv.M(dynPara, n);
System.Console.WriteLine("3) no ex");
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "S.M<int>(int, int)"))
ret--; // Pass
}
try
{
vd.M(n, dynPara);
System.Console.WriteLine("4) no ex");
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "S.M<int>(int, int)"))
ret--; // Pass
}
// dyn->struct, dyn->null
dynPara = new Test();
dynamic dynP2 = null;
try
{
vv.M(dynPara, dynP2);
System.Console.WriteLine("5) no ex");
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "S.M<Test>(Test, Test)"))
ret--; // Pass
}
try
{
vd.M(dynPara, dynP2);
System.Console.WriteLine("6) no ex");
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "S.M<Test>(Test, Test)"))
ret--; // Pass
}
return 0 == ret ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference004.typeinference004
{
// <Title>Generic Type Inference</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public void M<T>(T x, T y, T z)
{
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var obj = new Test();
dynamic dobj = new Test();
int ret = 0;
// -> object
dynamic d = 11;
string str = "string";
object o = null;
try
{
obj.M(d, str, o);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("1)" + ex);
ret++; // Fail
}
try
{
dobj.M(o, d, str);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("2)" + ex);
ret++; // Fail
}
// -> int?
d = null;
int n1 = 111111;
int? n2 = 11;
try
{
obj.M(n1, d, n2);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("3)" + ex);
ret++; // Fail
}
try
{
dobj.M(n1, n2, d);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("4)" + ex);
ret++; // Fail
}
// -> long
d = 0;
var v = -50000000000; // long
byte b = 1;
try
{
obj.M(d, v, b);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("5)" + ex);
ret++; // Fail
}
try
{
dobj.M(b, d, v);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("6)" + ex);
ret++; // Fail
}
// ->
d = null;
dynamic d2 = 0;
long? sb = null; // failed for (s)byte, (u)short, etc.
try
{
obj.M<long?>(d, sb, d2);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("7)" + ex);
ret++; // Fail
}
try
{
dobj.M<long?>(sb, d2, d);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex
{
System.Console.WriteLine("8)" + ex);
ret++; // Fail
}
return 0 == ret ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference005.typeinference005
{
// <Title>Generic Type Inference</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public struct Test
{
public void M<T>(T x, T y, T z)
{
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var vv = new Test();
dynamic vd = new Test();
int ret = 6;
string x = "string";
int? y = null;
dynamic z = 7;
try
{
vv.M(x, y, z);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "Test.M<T>(T, T, T)"))
ret--; // Pass
}
try
{
vd.M(x, z, y);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "Test.M<T>(T, T, T)"))
ret--; // Pass
}
Test? o1 = null;
char ch = '\0';
z = "";
try
{
vv.M(z, o1, ch);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "Test.M<T>(T, T, T)"))
ret--; // Pass
}
try
{
vd.M(ch, z, o1);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "Test.M<T>(T, T, T)"))
ret--; // Pass
}
dynamic z2 = 100;
z = null;
try
{
vv.M(z2, ch, z);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Test.M<int>(int, int, int)"))
ret--; // Pass
}
try
{
vd.M(z, z2, ch);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Test.M<int>(int, int, int)"))
ret--; // Pass
}
return 0 == ret ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference006.typeinference006
{
// <Title>Generic Type Inference</Title>
// <Description> We used to give compiler errors in these cases
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class A
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int rez = 0;
dynamic x = 1;
rez += Bar1(1, x);
rez += Bar1((dynamic)1, x);
dynamic d = new List<List<int>>();
rez += Bar2(d, 1);
rez += Bar2(d, (dynamic)1);
var l = new List<List<int>>();
rez += Bar2(l, x);
rez += Bar3(1, x, x);
rez += Bar3(1, 1, x);
var cls = new C<int>();
rez += cls.Foo(1, x);
rez += cls.Foo(x, 1);
rez += Bar4(x, 1);
rez += Bar4(1, x);
return rez;
}
public static int Bar1<T, S>(T x, S y) where T : IComparable<S>
{
return 0;
}
public static int Bar2<T, S>(T t, S s) where T : IList<List<S>>
{
return 0;
}
public static int Bar3<T, U, V>(T t, U u, V v) where T : U where U : IComparable<V>
{
return 0;
}
public static int Bar4<T, U>(T t, IComparable<U> u) where T : IComparable<U>
{
return 0;
}
}
public class C<T>
{
public int Foo<U>(T t, U u) where U : IComparable<T>
{
return 0;
}
}
// </Code>
}
| |
//------------------------------------------------------------------------------
// <copyright file="ConfigurationLockCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Configuration.Internal;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Security.Permissions;
using System.Xml;
using System.Globalization;
using System.ComponentModel;
using System.Security;
using System.Text;
namespace System.Configuration {
public sealed class ConfigurationLockCollection : IEnumerable, ICollection {
private HybridDictionary internalDictionary;
private ArrayList internalArraylist;
private bool _bModified = false;
private bool _bExceptionList = false;
private string _ignoreName = String.Empty;
private ConfigurationElement _thisElement = null;
private ConfigurationLockCollectionType _lockType;
private string SeedList = String.Empty;
private const string LockAll = "*";
internal ConfigurationLockCollection(ConfigurationElement thisElement)
: this(thisElement, ConfigurationLockCollectionType.LockedAttributes) {
}
internal ConfigurationLockCollection(ConfigurationElement thisElement, ConfigurationLockCollectionType lockType)
: this(thisElement, lockType, String.Empty) {
}
internal ConfigurationLockCollection(ConfigurationElement thisElement, ConfigurationLockCollectionType lockType, string ignoreName)
: this(thisElement, lockType, ignoreName, null) {
}
internal ConfigurationLockCollection(ConfigurationElement thisElement, ConfigurationLockCollectionType lockType,
string ignoreName, ConfigurationLockCollection parentCollection) {
_thisElement = thisElement;
_lockType = lockType;
internalDictionary = new HybridDictionary();
internalArraylist = new ArrayList();
_bModified = false;
_bExceptionList = _lockType == ConfigurationLockCollectionType.LockedExceptionList ||
_lockType == ConfigurationLockCollectionType.LockedElementsExceptionList;
_ignoreName = ignoreName;
if (parentCollection != null) {
foreach (string key in parentCollection) // seed the new collection
{
Add(key, ConfigurationValueFlags.Inherited); // add the local copy
if (_bExceptionList) {
if (SeedList.Length != 0)
SeedList += ",";
SeedList += key;
}
}
}
}
internal void ClearSeedList()
{
SeedList = String.Empty;
}
internal ConfigurationLockCollectionType LockType {
get { return _lockType; }
}
public void Add(string name) {
if (((_thisElement.ItemLocked & ConfigurationValueFlags.Locked) != 0) &&
((_thisElement.ItemLocked & ConfigurationValueFlags.Inherited) != 0)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_attribute_locked, name));
}
ConfigurationValueFlags flags = ConfigurationValueFlags.Modified;
string attribToLockTrim = name.Trim();
ConfigurationProperty propToLock = _thisElement.Properties[attribToLockTrim];
if (propToLock == null && attribToLockTrim != LockAll) {
ConfigurationElementCollection collection = _thisElement as ConfigurationElementCollection;
if (collection == null && _thisElement.Properties.DefaultCollectionProperty != null) { // this is not a collection but it may contain a default collection
collection = _thisElement[_thisElement.Properties.DefaultCollectionProperty] as ConfigurationElementCollection;
}
if (collection == null ||
_lockType == ConfigurationLockCollectionType.LockedAttributes || // If the collection type is not element then the lock is bogus
_lockType == ConfigurationLockCollectionType.LockedExceptionList) {
_thisElement.ReportInvalidLock(attribToLockTrim, _lockType, null, null);
}
else if (!collection.IsLockableElement(attribToLockTrim)) {
_thisElement.ReportInvalidLock(attribToLockTrim, _lockType, null, collection.LockableElements);
}
}
else { // the lock is in the property bag but is it the correct type?
if (propToLock != null && propToLock.IsRequired)
throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_required_attribute_lock_attempt, propToLock.Name));
if (attribToLockTrim != LockAll) {
if ((_lockType == ConfigurationLockCollectionType.LockedElements) ||
(_lockType == ConfigurationLockCollectionType.LockedElementsExceptionList)) {
// If it is an element then it must be derived from ConfigurationElement
if (!typeof(ConfigurationElement).IsAssignableFrom(propToLock.Type)) {
_thisElement.ReportInvalidLock(attribToLockTrim, _lockType, null, null);
}
}
else {
// if it is a property then it cannot be derived from ConfigurationElement
if (typeof(ConfigurationElement).IsAssignableFrom(propToLock.Type)) {
_thisElement.ReportInvalidLock(attribToLockTrim, _lockType, null, null);
}
}
}
}
if (internalDictionary.Contains(name)) {
flags = ConfigurationValueFlags.Modified | (ConfigurationValueFlags)internalDictionary[name];
internalDictionary.Remove(name); // not from parent
internalArraylist.Remove(name);
}
internalDictionary.Add(name, flags); // not from parent
internalArraylist.Add(name);
_bModified = true;
}
internal void Add(string name, ConfigurationValueFlags flags) {
if ((flags != ConfigurationValueFlags.Inherited) && (internalDictionary.Contains(name))) {
// the user has an item declared as locked below a level where it is already locked
// keep enough info so we can write out the lock if they save in modified mode
flags = ConfigurationValueFlags.Modified | (ConfigurationValueFlags)internalDictionary[name];
internalDictionary.Remove(name);
internalArraylist.Remove(name);
}
internalDictionary.Add(name, flags); // not from parent
internalArraylist.Add(name);
}
internal bool DefinedInParent(string name) {
if (name == null)
return false;
if (_bExceptionList)
{
string ParentListEnclosed = "," + SeedList + ",";
if (name.Equals(_ignoreName) || ParentListEnclosed.IndexOf("," + name + ",", StringComparison.Ordinal) >= 0) {
return true;
}
}
return (internalDictionary.Contains(name) &&
((ConfigurationValueFlags)internalDictionary[name] & ConfigurationValueFlags.Inherited) != 0);
}
internal bool IsValueModified(string name) {
return (internalDictionary.Contains(name) &&
((ConfigurationValueFlags)internalDictionary[name] & ConfigurationValueFlags.Modified) != 0);
}
internal void RemoveInheritedLocks() {
StringCollection removeList = new StringCollection();
foreach (string key in this) {
if (DefinedInParent(key)) {
removeList.Add(key);
}
}
foreach (string key in removeList) {
internalDictionary.Remove(key);
internalArraylist.Remove(key);
}
}
public void Remove(string name) {
if (!internalDictionary.Contains(name)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_collection_entry_not_found, name));
}
// in a locked list you cannot remove items that were locked in the parent
// in an exception list this is legal because it makes the list more restrictive
if (_bExceptionList == false &&
((ConfigurationValueFlags)internalDictionary[name] & ConfigurationValueFlags.Inherited) != 0) {
if (((ConfigurationValueFlags)internalDictionary[name] & ConfigurationValueFlags.Modified) != 0) {
// allow the local one to be "removed" so it won't write out but throw if they try and remove
// one that is only inherited
ConfigurationValueFlags flags = (ConfigurationValueFlags)internalDictionary[name];
flags &= ~ConfigurationValueFlags.Modified;
internalDictionary[name] = flags;
_bModified = true;
return;
}
else {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_attribute_locked, name));
}
}
internalDictionary.Remove(name);
internalArraylist.Remove(name);
_bModified = true;
}
public IEnumerator GetEnumerator() {
return internalArraylist.GetEnumerator();
}
internal void ClearInternal(bool useSeedIfAvailble) {
ArrayList removeList = new ArrayList();
foreach (DictionaryEntry de in internalDictionary) {
if ((((ConfigurationValueFlags)de.Value & ConfigurationValueFlags.Inherited) == 0)
|| _bExceptionList == true) {
removeList.Add(de.Key);
}
}
foreach (object removeKey in removeList) {
internalDictionary.Remove(removeKey);
internalArraylist.Remove(removeKey);
}
// Clearing an Exception list really means revert to parent
if (useSeedIfAvailble && !String.IsNullOrEmpty(SeedList)) {
string[] Keys = SeedList.Split(new char[] { ',' });
foreach (string key in Keys) {
Add(key, ConfigurationValueFlags.Inherited); //
}
}
_bModified = true;
}
public void Clear() {
ClearInternal(true);
}
public bool Contains(string name) {
if (_bExceptionList && name.Equals(_ignoreName)) {
return true;
}
return internalDictionary.Contains(name);
}
public int Count {
get {
return internalDictionary.Count;
}
}
public bool IsSynchronized {
get {
return false;
}
}
public object SyncRoot {
get {
return this;
}
}
public void CopyTo(string[] array, int index) {
((ICollection)this).CopyTo(array, index);
}
void ICollection.CopyTo(Array array, int index) {
internalArraylist.CopyTo(array, index);
}
public bool IsModified {
get {
return _bModified;
}
}
internal void ResetModified() {
_bModified = false;
}
public bool IsReadOnly(string name) {
if (!internalDictionary.Contains(name)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_collection_entry_not_found, name));
}
return (bool)(((ConfigurationValueFlags)internalDictionary[name] & ConfigurationValueFlags.Inherited) != 0);
}
internal bool ExceptionList {
get {
return _bExceptionList;
}
}
public string AttributeList {
get {
StringBuilder sb;
sb = new StringBuilder();
foreach (DictionaryEntry de in internalDictionary) {
if (sb.Length != 0) {
sb.Append(',');
}
sb.Append(de.Key);
}
return sb.ToString();
}
}
public void SetFromList(string attributeList) {
string[] splits = attributeList.Split(new char[] { ',', ';', ':' });
Clear();
foreach (string name in splits) {
string attribTrim = name.Trim();
if (!Contains(attribTrim)) {
Add(attribTrim);
}
}
}
public bool HasParentElements {
get {
// return true if there is at least one element that was defined in the parent
bool result = false;
// Check to see if the exception list is empty as a result of a merge from config
// If so the there were some parent elements because empty string is invalid in config.
// and the only way to get an empty list is for the merged config to have no elements
// in common.
if (ExceptionList && internalDictionary.Count == 0 && !String.IsNullOrEmpty(SeedList))
return true;
foreach (DictionaryEntry de in internalDictionary) {
if ((bool)(((ConfigurationValueFlags)de.Value & ConfigurationValueFlags.Inherited) != 0)) {
result = true;
break;
}
}
return result;
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Rulesets.Osu.Edit;
using osu.Game.Screens.Edit;
using osu.Game.Tests.Visual;
namespace osu.Game.Tests.Editing
{
[HeadlessTest]
public class TestSceneHitObjectComposerDistanceSnapping : EditorClockTestScene
{
private TestHitObjectComposer composer;
[Cached(typeof(EditorBeatmap))]
[Cached(typeof(IBeatSnapProvider))]
private readonly EditorBeatmap editorBeatmap;
protected override Container<Drawable> Content { get; }
public TestSceneHitObjectComposerDistanceSnapping()
{
base.Content.Add(new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
editorBeatmap = new EditorBeatmap(new OsuBeatmap()),
Content = new Container
{
RelativeSizeAxes = Axes.Both,
}
},
});
}
[SetUp]
public void Setup() => Schedule(() =>
{
Children = new Drawable[]
{
composer = new TestHitObjectComposer()
};
BeatDivisor.Value = 1;
composer.EditorBeatmap.Difficulty.SliderMultiplier = 1;
composer.EditorBeatmap.ControlPointInfo.Clear();
composer.EditorBeatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = 1000 });
});
[TestCase(1)]
[TestCase(2)]
public void TestSliderMultiplier(float multiplier)
{
AddStep($"set multiplier = {multiplier}", () => composer.EditorBeatmap.Difficulty.SliderMultiplier = multiplier);
assertSnapDistance(100 * multiplier);
}
[TestCase(1)]
[TestCase(2)]
public void TestSpeedMultiplier(float multiplier)
{
assertSnapDistance(100 * multiplier, new HitObject
{
DifficultyControlPoint = new DifficultyControlPoint
{
SliderVelocity = multiplier
}
});
}
[TestCase(1)]
[TestCase(2)]
public void TestBeatDivisor(int divisor)
{
AddStep($"set divisor = {divisor}", () => BeatDivisor.Value = divisor);
assertSnapDistance(100f / divisor);
}
[Test]
public void TestConvertDurationToDistance()
{
assertDurationToDistance(500, 50);
assertDurationToDistance(1000, 100);
AddStep("set slider multiplier = 2", () => composer.EditorBeatmap.Difficulty.SliderMultiplier = 2);
assertDurationToDistance(500, 100);
assertDurationToDistance(1000, 200);
AddStep("set beat length = 500", () =>
{
composer.EditorBeatmap.ControlPointInfo.Clear();
composer.EditorBeatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = 500 });
});
assertDurationToDistance(500, 200);
assertDurationToDistance(1000, 400);
}
[Test]
public void TestConvertDistanceToDuration()
{
assertDistanceToDuration(50, 500);
assertDistanceToDuration(100, 1000);
AddStep("set slider multiplier = 2", () => composer.EditorBeatmap.Difficulty.SliderMultiplier = 2);
assertDistanceToDuration(100, 500);
assertDistanceToDuration(200, 1000);
AddStep("set beat length = 500", () =>
{
composer.EditorBeatmap.ControlPointInfo.Clear();
composer.EditorBeatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = 500 });
});
assertDistanceToDuration(200, 500);
assertDistanceToDuration(400, 1000);
}
[Test]
public void TestGetSnappedDurationFromDistance()
{
assertSnappedDuration(0, 0);
assertSnappedDuration(50, 1000);
assertSnappedDuration(100, 1000);
assertSnappedDuration(150, 2000);
assertSnappedDuration(200, 2000);
assertSnappedDuration(250, 3000);
AddStep("set slider multiplier = 2", () => composer.EditorBeatmap.Difficulty.SliderMultiplier = 2);
assertSnappedDuration(0, 0);
assertSnappedDuration(50, 0);
assertSnappedDuration(100, 1000);
assertSnappedDuration(150, 1000);
assertSnappedDuration(200, 1000);
assertSnappedDuration(250, 1000);
AddStep("set beat length = 500", () =>
{
composer.EditorBeatmap.ControlPointInfo.Clear();
composer.EditorBeatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = 500 });
});
assertSnappedDuration(50, 0);
assertSnappedDuration(100, 500);
assertSnappedDuration(150, 500);
assertSnappedDuration(200, 500);
assertSnappedDuration(250, 500);
assertSnappedDuration(400, 1000);
}
[Test]
public void GetSnappedDistanceFromDistance()
{
assertSnappedDistance(50, 0);
assertSnappedDistance(100, 100);
assertSnappedDistance(150, 100);
assertSnappedDistance(200, 200);
assertSnappedDistance(250, 200);
AddStep("set slider multiplier = 2", () => composer.EditorBeatmap.Difficulty.SliderMultiplier = 2);
assertSnappedDistance(50, 0);
assertSnappedDistance(100, 0);
assertSnappedDistance(150, 0);
assertSnappedDistance(200, 200);
assertSnappedDistance(250, 200);
AddStep("set beat length = 500", () =>
{
composer.EditorBeatmap.ControlPointInfo.Clear();
composer.EditorBeatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = 500 });
});
assertSnappedDistance(50, 0);
assertSnappedDistance(100, 0);
assertSnappedDistance(150, 0);
assertSnappedDistance(200, 200);
assertSnappedDistance(250, 200);
assertSnappedDistance(400, 400);
}
private void assertSnapDistance(float expectedDistance, HitObject hitObject = null)
=> AddAssert($"distance is {expectedDistance}", () => composer.GetBeatSnapDistanceAt(hitObject ?? new HitObject()) == expectedDistance);
private void assertDurationToDistance(double duration, float expectedDistance)
=> AddAssert($"duration = {duration} -> distance = {expectedDistance}", () => composer.DurationToDistance(new HitObject(), duration) == expectedDistance);
private void assertDistanceToDuration(float distance, double expectedDuration)
=> AddAssert($"distance = {distance} -> duration = {expectedDuration}", () => composer.DistanceToDuration(new HitObject(), distance) == expectedDuration);
private void assertSnappedDuration(float distance, double expectedDuration)
=> AddAssert($"distance = {distance} -> duration = {expectedDuration} (snapped)", () => composer.GetSnappedDurationFromDistance(new HitObject(), distance) == expectedDuration);
private void assertSnappedDistance(float distance, float expectedDistance)
=> AddAssert($"distance = {distance} -> distance = {expectedDistance} (snapped)", () => composer.GetSnappedDistanceFromDistance(new HitObject(), distance) == expectedDistance);
private class TestHitObjectComposer : OsuHitObjectComposer
{
public new EditorBeatmap EditorBeatmap => base.EditorBeatmap;
public TestHitObjectComposer()
: base(new OsuRuleset())
{
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using SIL.i18n;
using SIL.Windows.Forms.Widgets;
namespace SIL.Windows.Forms.i18n
{
[Designer("LocalizationHelperDesigner, PalsoUIWindowsFormsDesign")]
[ToolboxItem(true)]
[ProvideProperty("ParentFo", typeof (Form))]
public partial class LocalizationHelper: Component, ISupportInitialize, IExtenderProvider
{
private readonly Dictionary<Control, TextFontPair> _originalControlProperties =
new Dictionary<Control, TextFontPair>();
private bool _alreadyChanging;
private bool _wiredToParent;
private Control _parent;
#if DEBUG
private string _nameOfParentContainer;
private StackTrace _constructionStackTrace;
#endif
public LocalizationHelper()
{
InitializeComponent();
}
public LocalizationHelper(IContainer container)
{
if (container != null)
{
container.Add(this);
}
InitializeComponent();
#if DEBUG
_constructionStackTrace = new StackTrace();
#endif
}
public Control Parent
{
get { return _parent; }
set
{
if (_parent == value)
{
return;
}
if (_wiredToParent && _parent != null)
{
UnwireFromControl(_parent);
UnwireFromChildren(_parent);
}
_parent = value;
if (_wiredToParent && _parent != null)
{
WireToControl(_parent);
WireToChildren(_parent);
}
}
}
private void OnFontChanged(object sender, EventArgs e)
{
if (_alreadyChanging)
{
return;
}
Control control = (Control) sender;
_alreadyChanging = true;
_originalControlProperties[control].Font = control.Font;
var hints = control as ILocalizableControl;
if (hints==null || hints.ShouldModifyFont)
{
if (control is LinkLabel && ((LinkLabel)control).UseMnemonic == false)
{
//then that link is for user data, and shouldn't be localized (this came up in Chorus AnnotationEditorView)
}
else
{
var font = StringCatalog.ModifyFontForLocalization(control.Font);
control.Font = font;
}
}
_alreadyChanging = false;
}
private void OnTextChanged(object sender, EventArgs e)
{
if (_alreadyChanging)
{
return;
}
Control control = (Control) sender;
if (control.Text.Contains("{0}"))
{
return;
//they're going to have to format it anyways, so we can't fix it automatically
}
_alreadyChanging = true;
_originalControlProperties[control].Text = control.Text;
if (!String.IsNullOrEmpty(control.Text))
//don't try to translation, for example, buttons with no label
{
control.Text = StringCatalog.Get(control.Text);
}
_alreadyChanging = false;
}
private void OnControlAdded(object sender, ControlEventArgs e)
{
WireToControlAndChildren(e.Control);
}
private void WireToControlAndChildren(Control control)
{
if (control is ILocalizableControl)
{
((ILocalizableControl) control).BeginWiring();
}
WireToControl(control);
WireToChildren(control);
if (control is ILocalizableControl)
{
((ILocalizableControl) control).EndWiring();
}
}
private void OnControlRemoved(object sender, ControlEventArgs e)
{
UnwireFromControl(e.Control);
UnwireFromChildren(e.Control);
}
private void OnControlDisposed(object sender, EventArgs e)
{
Control control = (Control) sender;
if (control != Parent)
{
UnwireFromControl(control);
}
UnwireFromChildren(control);
}
private void WireToChildren(Control control)
{
control.SuspendLayout();
Debug.Assert(control != null);
//Debug.WriteLine("Wiring to children of " + control.Name);
control.ControlAdded += OnControlAdded;
control.ControlRemoved += OnControlRemoved;
control.Disposed += OnControlDisposed;
foreach (Control child in control.Controls)
{
WireToControlAndChildren(child);
}
control.ResumeLayout();
}
private void WireToControl(Control control)
{
#if DEBUG
_nameOfParentContainer = control.Name;
#endif
Debug.Assert(control != null);
if (IsAllowedControl(control))
{
// Debug.WriteLine("Wiring to " + control.Name);
control.TextChanged += OnTextChanged;
control.FontChanged += OnFontChanged;
_originalControlProperties.Add(control, new TextFontPair(control.Text, control.Font));
OnTextChanged(control, null);
OnFontChanged(control, null);
}
}
private void UnwireFromChildren(Control control)
{
control.SuspendLayout();
Debug.Assert(control != null);
control.ControlAdded -= OnControlAdded;
control.ControlRemoved -= OnControlRemoved;
control.Disposed -= OnControlDisposed;
//Debug.WriteLine("Unwiring from children of " + control.Name);
foreach (Control child in control.Controls)
{
UnwireFromControl(child);
UnwireFromChildren(child);
}
control.ResumeLayout();
}
private void UnwireFromControl(Control control)
{
Debug.Assert(control != null);
// In modal forms mono can call Dispose twice, resulting in two attempts to unwire
// the control.
if (IsAllowedControl(control) && _originalControlProperties.ContainsKey(control))//Added because once, on mono (WS-14891) somehow this wasn't true (probably not this control's fault, but still...))
{
control.TextChanged -= OnTextChanged;
control.FontChanged -= OnFontChanged;
control.Text = _originalControlProperties[control].Text;
control.Font = _originalControlProperties[control].Font;
_originalControlProperties.Remove(control);
}
}
private static bool IsAllowedControl(Control control)
{
return control is Label ||
control is BetterLabel ||
control is GroupBox ||
control is ButtonBase ||
control is IButtonControl ||
control is TabControl ||
control is TabPage ||
control is Form ||
control is BetterLabel ||
control is ILocalizableControl;
}
#region ISupportInitialize Members
///<summary>
///Signals the object that initialization is starting.
///</summary>
///
public void BeginInit() {}
///<summary>
///Signals the object that initialization is complete.
///</summary>
///
public void EndInit()
{
if (DesignMode)
return;
if (!_wiredToParent && Parent != null)
{
_wiredToParent = true;
WireToControl(_parent);
WireToChildren(Parent);
}
}
#endregion
#region IExtenderProvider Members
///<summary>
///Specifies whether this object can provide its extender properties to the specified object.
///</summary>
///
///<returns>
///true if this object can provide extender properties to the specified object; otherwise, false.
///</returns>
///
///<param name="extendee">The <see cref="T:System.Object"></see> to receive the extender properties. </param>
public bool CanExtend(object extendee)
{
return (extendee is UserControl);
}
#endregion
private class TextFontPair
{
private string _text;
private Font _font;
public TextFontPair(string text, Font font)
{
_text = text;
_font = font;
}
public string Text
{
get { return _text; }
set { _text = value; }
}
public Font Font
{
get { return _font; }
set { _font = value; }
}
}
~LocalizationHelper()
{
if (Parent !=null)
{
#if DEBUG
throw new InvalidOperationException("Disposed not explicitly called on " + GetType().FullName +
". Parent container name was '" + _nameOfParentContainer + "'." + Environment.NewLine + _constructionStackTrace);
#else
;
#endif
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal partial class MethodDebugInfo<TTypeSymbol, TLocalSymbol>
{
private struct LocalNameAndScope : IEquatable<LocalNameAndScope>
{
internal readonly string LocalName;
internal readonly int ScopeStart;
internal readonly int ScopeEnd;
internal LocalNameAndScope(string localName, int scopeStart, int scopeEnd)
{
LocalName = localName;
ScopeStart = scopeStart;
ScopeEnd = scopeEnd;
}
public bool Equals(LocalNameAndScope other)
{
return ScopeStart == other.ScopeStart &&
ScopeEnd == other.ScopeEnd &&
string.Equals(LocalName, other.LocalName, StringComparison.Ordinal);
}
public override bool Equals(object obj)
{
throw new NotImplementedException();
}
public override int GetHashCode()
{
return Hash.Combine(
Hash.Combine(ScopeStart, ScopeEnd),
LocalName.GetHashCode());
}
}
public unsafe static MethodDebugInfo<TTypeSymbol, TLocalSymbol> ReadMethodDebugInfo(
ISymUnmanagedReader3 symReader,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProviderOpt, // TODO: only null in DTEE case where we looking for default namesapace
int methodToken,
int methodVersion,
int ilOffset,
bool isVisualBasicMethod)
{
// no symbols
if (symReader == null)
{
return None;
}
var symReader4 = symReader as ISymUnmanagedReader4;
if (symReader4 != null) // TODO: VB Portable PDBs
{
byte* metadata;
int size;
// TODO: version
int hr = symReader4.GetPortableDebugMetadata(out metadata, out size);
SymUnmanagedReaderExtensions.ThrowExceptionForHR(hr);
if (metadata != null)
{
var mdReader = new MetadataReader(metadata, size);
try
{
return ReadFromPortable(mdReader, methodToken, ilOffset, symbolProviderOpt, isVisualBasicMethod);
}
catch (BadImageFormatException)
{
// bad CDI, ignore
return None;
}
}
}
var allScopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
var containingScopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance();
try
{
var symMethod = symReader.GetMethodByVersion(methodToken, methodVersion);
if (symMethod != null)
{
symMethod.GetAllScopes(allScopes, containingScopes, ilOffset, isScopeEndInclusive: isVisualBasicMethod);
}
ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups;
ImmutableArray<ExternAliasRecord> externAliasRecords;
string defaultNamespaceName;
if (isVisualBasicMethod)
{
ReadVisualBasicImportsDebugInfo(
symReader,
methodToken,
methodVersion,
out importRecordGroups,
out defaultNamespaceName);
externAliasRecords = ImmutableArray<ExternAliasRecord>.Empty;
}
else
{
Debug.Assert(symbolProviderOpt != null);
ReadCSharpNativeImportsInfo(
symReader,
symbolProviderOpt,
methodToken,
methodVersion,
out importRecordGroups,
out externAliasRecords);
defaultNamespaceName = "";
}
ImmutableArray<HoistedLocalScopeRecord> hoistedLocalScopeRecords = ImmutableArray<HoistedLocalScopeRecord>.Empty;
ImmutableDictionary<int, ImmutableArray<bool>> dynamicLocalMap = null;
ImmutableDictionary<string, ImmutableArray<bool>> dynamicLocalConstantMap = null;
ImmutableDictionary<int, ImmutableArray<string>> tupleLocalMap = null;
ImmutableDictionary<LocalNameAndScope, ImmutableArray<string>> tupleLocalConstantMap = null;
byte[] customDebugInfo = symReader.GetCustomDebugInfoBytes(methodToken, methodVersion);
if (customDebugInfo != null)
{
if (!isVisualBasicMethod)
{
var customDebugInfoRecord = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(customDebugInfo, CustomDebugInfoKind.StateMachineHoistedLocalScopes);
if (!customDebugInfoRecord.IsDefault)
{
hoistedLocalScopeRecords = CustomDebugInfoReader.DecodeStateMachineHoistedLocalScopesRecord(customDebugInfoRecord)
.SelectAsArray(s => new HoistedLocalScopeRecord(s.StartOffset, s.EndOffset - s.StartOffset + 1));
}
GetCSharpDynamicLocalInfo(
customDebugInfo,
allScopes,
out dynamicLocalMap,
out dynamicLocalConstantMap);
}
GetTupleElementNamesLocalInfo(
customDebugInfo,
out tupleLocalMap,
out tupleLocalConstantMap);
}
var constantsBuilder = ArrayBuilder<TLocalSymbol>.GetInstance();
if (symbolProviderOpt != null) // TODO
{
GetConstants(constantsBuilder, symbolProviderOpt, containingScopes, dynamicLocalConstantMap, tupleLocalConstantMap);
}
var reuseSpan = GetReuseSpan(allScopes, ilOffset, isVisualBasicMethod);
return new MethodDebugInfo<TTypeSymbol, TLocalSymbol>(
hoistedLocalScopeRecords,
importRecordGroups,
externAliasRecords,
dynamicLocalMap,
tupleLocalMap,
defaultNamespaceName,
containingScopes.GetLocalNames(),
constantsBuilder.ToImmutableAndFree(),
reuseSpan);
}
catch (InvalidOperationException)
{
// bad CDI, ignore
return None;
}
finally
{
allScopes.Free();
containingScopes.Free();
}
}
/// <summary>
/// Get the (unprocessed) import strings for a given method.
/// </summary>
/// <remarks>
/// Doesn't consider forwarding.
///
/// CONSIDER: Dev12 doesn't just check the root scope - it digs around to find the best
/// match based on the IL offset and then walks up to the root scope (see PdbUtil::GetScopeFromOffset).
/// However, it's not clear that this matters, since imports can't be scoped in VB. This is probably
/// just based on the way they were extracting locals and constants based on a specific scope.
///
/// Returns empty array if there are no import strings for the specified method.
/// </remarks>
private static ImmutableArray<string> GetImportStrings(ISymUnmanagedReader reader, int methodToken, int methodVersion)
{
var method = reader.GetMethodByVersion(methodToken, methodVersion);
if (method == null)
{
// In rare circumstances (only bad PDBs?) GetMethodByVersion can return null.
// If there's no debug info for the method, then no import strings are available.
return ImmutableArray<string>.Empty;
}
ISymUnmanagedScope rootScope = method.GetRootScope();
if (rootScope == null)
{
Debug.Assert(false, "Expected a root scope.");
return ImmutableArray<string>.Empty;
}
var childScopes = rootScope.GetChildren();
if (childScopes.Length == 0)
{
// It seems like there should always be at least one child scope, but we've
// seen PDBs where that is not the case.
return ImmutableArray<string>.Empty;
}
// As in NamespaceListWrapper::Init, we only consider namespaces in the first
// child of the root scope.
ISymUnmanagedScope firstChildScope = childScopes[0];
var namespaces = firstChildScope.GetNamespaces();
if (namespaces.Length == 0)
{
// It seems like there should always be at least one namespace (i.e. the global
// namespace), but we've seen PDBs where that is not the case.
return ImmutableArray<string>.Empty;
}
return ImmutableArray.CreateRange(namespaces.Select(n => n.GetName()));
}
private static void ReadCSharpNativeImportsInfo(
ISymUnmanagedReader3 reader,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider,
int methodToken,
int methodVersion,
out ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups,
out ImmutableArray<ExternAliasRecord> externAliasRecords)
{
ImmutableArray<string> externAliasStrings;
var importStringGroups = CustomDebugInfoReader.GetCSharpGroupedImportStrings(
methodToken,
KeyValuePair.Create(reader, methodVersion),
getMethodCustomDebugInfo: (token, arg) => arg.Key.GetCustomDebugInfoBytes(token, arg.Value),
getMethodImportStrings: (token, arg) => GetImportStrings(arg.Key, token, arg.Value),
externAliasStrings: out externAliasStrings);
Debug.Assert(importStringGroups.IsDefault == externAliasStrings.IsDefault);
ArrayBuilder<ImmutableArray<ImportRecord>> importRecordGroupBuilder = null;
ArrayBuilder<ExternAliasRecord> externAliasRecordBuilder = null;
if (!importStringGroups.IsDefault)
{
importRecordGroupBuilder = ArrayBuilder<ImmutableArray<ImportRecord>>.GetInstance(importStringGroups.Length);
foreach (var importStringGroup in importStringGroups)
{
var groupBuilder = ArrayBuilder<ImportRecord>.GetInstance(importStringGroup.Length);
foreach (var importString in importStringGroup)
{
ImportRecord record;
if (TryCreateImportRecordFromCSharpImportString(symbolProvider, importString, out record))
{
groupBuilder.Add(record);
}
else
{
Debug.WriteLine($"Failed to parse import string {importString}");
}
}
importRecordGroupBuilder.Add(groupBuilder.ToImmutableAndFree());
}
if (!externAliasStrings.IsDefault)
{
externAliasRecordBuilder = ArrayBuilder<ExternAliasRecord>.GetInstance(externAliasStrings.Length);
foreach (string externAliasString in externAliasStrings)
{
string alias;
string externAlias;
string target;
ImportTargetKind kind;
if (!CustomDebugInfoReader.TryParseCSharpImportString(externAliasString, out alias, out externAlias, out target, out kind))
{
Debug.WriteLine($"Unable to parse extern alias '{externAliasString}'");
continue;
}
Debug.Assert(kind == ImportTargetKind.Assembly, "Programmer error: How did a non-assembly get in the extern alias list?");
Debug.Assert(alias != null); // Name of the extern alias.
Debug.Assert(externAlias == null); // Not used.
Debug.Assert(target != null); // Name of the target assembly.
AssemblyIdentity targetIdentity;
if (!AssemblyIdentity.TryParseDisplayName(target, out targetIdentity))
{
Debug.WriteLine($"Unable to parse target of extern alias '{externAliasString}'");
continue;
}
externAliasRecordBuilder.Add(new ExternAliasRecord(alias, targetIdentity));
}
}
}
importRecordGroups = importRecordGroupBuilder?.ToImmutableAndFree() ?? ImmutableArray<ImmutableArray<ImportRecord>>.Empty;
externAliasRecords = externAliasRecordBuilder?.ToImmutableAndFree() ?? ImmutableArray<ExternAliasRecord>.Empty;
}
private static bool TryCreateImportRecordFromCSharpImportString(EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider, string importString, out ImportRecord record)
{
ImportTargetKind targetKind;
string externAlias;
string alias;
string targetString;
if (CustomDebugInfoReader.TryParseCSharpImportString(importString, out alias, out externAlias, out targetString, out targetKind))
{
ITypeSymbol type = null;
if (targetKind == ImportTargetKind.Type)
{
type = symbolProvider.GetTypeSymbolForSerializedType(targetString);
targetString = null;
}
record = new ImportRecord(
targetKind: targetKind,
alias: alias,
targetType: type,
targetString: targetString,
targetAssembly: null,
targetAssemblyAlias: externAlias);
return true;
}
record = default(ImportRecord);
return false;
}
/// <exception cref="InvalidOperationException">Bad data.</exception>
private static void GetCSharpDynamicLocalInfo(
byte[] customDebugInfo,
IEnumerable<ISymUnmanagedScope> scopes,
out ImmutableDictionary<int, ImmutableArray<bool>> dynamicLocalMap,
out ImmutableDictionary<string, ImmutableArray<bool>> dynamicLocalConstantMap)
{
dynamicLocalMap = null;
dynamicLocalConstantMap = null;
var record = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(customDebugInfo, CustomDebugInfoKind.DynamicLocals);
if (record.IsDefault)
{
return;
}
var localKindsByName = PooledDictionary<string, LocalKind>.GetInstance();
GetLocalKindByName(localKindsByName, scopes);
ImmutableDictionary<int, ImmutableArray<bool>>.Builder localBuilder = null;
ImmutableDictionary<string, ImmutableArray<bool>>.Builder constantBuilder = null;
var dynamicLocals = CustomDebugInfoReader.DecodeDynamicLocalsRecord(record);
foreach (var dynamicLocal in dynamicLocals)
{
int slot = dynamicLocal.SlotId;
var flags = GetFlags(dynamicLocal);
if (slot == 0)
{
LocalKind kind;
var name = dynamicLocal.LocalName;
localKindsByName.TryGetValue(name, out kind);
switch (kind)
{
case LocalKind.DuplicateName:
// Drop locals with ambiguous names.
continue;
case LocalKind.ConstantName:
constantBuilder = constantBuilder ?? ImmutableDictionary.CreateBuilder<string, ImmutableArray<bool>>();
constantBuilder[name] = flags;
continue;
}
}
localBuilder = localBuilder ?? ImmutableDictionary.CreateBuilder<int, ImmutableArray<bool>>();
localBuilder[slot] = flags;
}
if (localBuilder != null)
{
dynamicLocalMap = localBuilder.ToImmutable();
}
if (constantBuilder != null)
{
dynamicLocalConstantMap = constantBuilder.ToImmutable();
}
localKindsByName.Free();
}
private static ImmutableArray<bool> GetFlags(DynamicLocalInfo bucket)
{
int flagCount = bucket.FlagCount;
ulong flags = bucket.Flags;
var builder = ArrayBuilder<bool>.GetInstance(flagCount);
for (int i = 0; i < flagCount; i++)
{
builder.Add((flags & (1u << i)) != 0);
}
return builder.ToImmutableAndFree();
}
private enum LocalKind { DuplicateName, VariableName, ConstantName }
/// <summary>
/// Dynamic CDI encodes slot id and name for each dynamic local variable, but only name for a constant.
/// Constants have slot id set to 0. As a result there is a potential for ambiguity. If a variable in a slot 0
/// and a constant defined anywhere in the method body have the same name we can't say which one
/// the dynamic flags belong to (if there is a dynamic record for at least one of them).
///
/// This method returns the local kind (variable, constant, or duplicate) based on name.
/// </summary>
private static void GetLocalKindByName(Dictionary<string, LocalKind> localNames, IEnumerable<ISymUnmanagedScope> scopes)
{
Debug.Assert(localNames.Count == 0);
var localSlot0 = scopes.SelectMany(scope => scope.GetLocals()).FirstOrDefault(variable => variable.GetSlot() == 0);
if (localSlot0 != null)
{
localNames.Add(localSlot0.GetName(), LocalKind.VariableName);
}
foreach (var scope in scopes)
{
foreach (var constant in scope.GetConstants())
{
string name = constant.GetName();
localNames[name] = localNames.ContainsKey(name) ? LocalKind.DuplicateName : LocalKind.ConstantName;
}
}
}
private static void GetTupleElementNamesLocalInfo(
byte[] customDebugInfo,
out ImmutableDictionary<int, ImmutableArray<string>> tupleLocalMap,
out ImmutableDictionary<LocalNameAndScope, ImmutableArray<string>> tupleLocalConstantMap)
{
tupleLocalMap = null;
tupleLocalConstantMap = null;
var record = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(customDebugInfo, CustomDebugInfoKind.TupleElementNames);
if (record.IsDefault)
{
return;
}
ImmutableDictionary<int, ImmutableArray<string>>.Builder localBuilder = null;
ImmutableDictionary<LocalNameAndScope, ImmutableArray<string>>.Builder constantBuilder = null;
var tuples = CustomDebugInfoReader.DecodeTupleElementNamesRecord(record);
foreach (var tuple in tuples)
{
var slotIndex = tuple.SlotIndex;
var elementNames = tuple.ElementNames;
if (slotIndex < 0)
{
constantBuilder = constantBuilder ?? ImmutableDictionary.CreateBuilder<LocalNameAndScope, ImmutableArray<string>>();
var localAndScope = new LocalNameAndScope(tuple.LocalName, tuple.ScopeStart, tuple.ScopeEnd);
constantBuilder[localAndScope] = elementNames;
}
else
{
localBuilder = localBuilder ?? ImmutableDictionary.CreateBuilder<int, ImmutableArray<string>>();
localBuilder[slotIndex] = elementNames;
}
}
if (localBuilder != null)
{
tupleLocalMap = localBuilder.ToImmutable();
}
if (constantBuilder != null)
{
tupleLocalConstantMap = constantBuilder.ToImmutable();
}
}
private static void ReadVisualBasicImportsDebugInfo(
ISymUnmanagedReader reader,
int methodToken,
int methodVersion,
out ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups,
out string defaultNamespaceName)
{
importRecordGroups = ImmutableArray<ImmutableArray<ImportRecord>>.Empty;
var importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(
methodToken,
KeyValuePair.Create(reader, methodVersion),
(token, arg) => GetImportStrings(arg.Key, token, arg.Value));
if (importStrings.IsDefault)
{
defaultNamespaceName = "";
return;
}
defaultNamespaceName = null;
var projectLevelImportRecords = ArrayBuilder<ImportRecord>.GetInstance();
var fileLevelImportRecords = ArrayBuilder<ImportRecord>.GetInstance();
foreach (string importString in importStrings)
{
Debug.Assert(importString != null);
if (importString.Length > 0 && importString[0] == '*')
{
string alias = null;
string target = null;
ImportTargetKind kind = 0;
VBImportScopeKind scope = 0;
if (!CustomDebugInfoReader.TryParseVisualBasicImportString(importString, out alias, out target, out kind, out scope))
{
Debug.WriteLine($"Unable to parse import string '{importString}'");
continue;
}
else if (kind == ImportTargetKind.Defunct)
{
continue;
}
Debug.Assert(alias == null); // The default namespace is never aliased.
Debug.Assert(target != null);
Debug.Assert(kind == ImportTargetKind.DefaultNamespace);
// We only expect to see one of these, but it looks like ProcedureContext::LoadImportsAndDefaultNamespaceNormal
// implicitly uses the last one if there are multiple.
Debug.Assert(defaultNamespaceName == null);
defaultNamespaceName = target;
}
else
{
ImportRecord importRecord;
VBImportScopeKind scope = 0;
if (TryCreateImportRecordFromVisualBasicImportString(importString, out importRecord, out scope))
{
if (scope == VBImportScopeKind.Project)
{
projectLevelImportRecords.Add(importRecord);
}
else
{
Debug.Assert(scope == VBImportScopeKind.File || scope == VBImportScopeKind.Unspecified);
fileLevelImportRecords.Add(importRecord);
}
}
else
{
Debug.WriteLine($"Failed to parse import string {importString}");
}
}
}
importRecordGroups = ImmutableArray.Create(
fileLevelImportRecords.ToImmutableAndFree(),
projectLevelImportRecords.ToImmutableAndFree());
defaultNamespaceName = defaultNamespaceName ?? "";
}
private static bool TryCreateImportRecordFromVisualBasicImportString(string importString, out ImportRecord record, out VBImportScopeKind scope)
{
ImportTargetKind targetKind;
string alias;
string targetString;
if (CustomDebugInfoReader.TryParseVisualBasicImportString(importString, out alias, out targetString, out targetKind, out scope))
{
record = new ImportRecord(
targetKind: targetKind,
alias: alias,
targetType: null,
targetString: targetString,
targetAssembly: null,
targetAssemblyAlias: null);
return true;
}
record = default(ImportRecord);
return false;
}
private static ILSpan GetReuseSpan(ArrayBuilder<ISymUnmanagedScope> scopes, int ilOffset, bool isEndInclusive)
{
return MethodContextReuseConstraints.CalculateReuseSpan(
ilOffset,
ILSpan.MaxValue,
scopes.Select(scope => new ILSpan((uint)scope.GetStartOffset(), (uint)(scope.GetEndOffset() + (isEndInclusive ? 1 : 0)))));
}
private static void GetConstants(
ArrayBuilder<TLocalSymbol> builder,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider,
ArrayBuilder<ISymUnmanagedScope> scopes,
ImmutableDictionary<string, ImmutableArray<bool>> dynamicLocalConstantMapOpt,
ImmutableDictionary<LocalNameAndScope, ImmutableArray<string>> tupleLocalConstantMapOpt)
{
foreach (var scope in scopes)
{
foreach (var constant in scope.GetConstants())
{
string name = constant.GetName();
object rawValue = constant.GetValue();
var signature = constant.GetSignature().ToImmutableArray();
TTypeSymbol type;
try
{
type = symbolProvider.DecodeLocalVariableType(signature);
}
catch (Exception e) when (e is UnsupportedSignatureContent || e is BadImageFormatException)
{
// ignore
continue;
}
if (type.Kind == SymbolKind.ErrorType)
{
continue;
}
ConstantValue constantValue = PdbHelpers.GetSymConstantValue(type, rawValue);
// TODO (https://github.com/dotnet/roslyn/issues/1815): report error properly when the symbol is used
if (constantValue.IsBad)
{
continue;
}
var dynamicFlags = default(ImmutableArray<bool>);
if (dynamicLocalConstantMapOpt != null)
{
dynamicLocalConstantMapOpt.TryGetValue(name, out dynamicFlags);
}
var tupleElementNames = default(ImmutableArray<string>);
if (tupleLocalConstantMapOpt != null)
{
int scopeStart = scope.GetStartOffset();
int scopeEnd = scope.GetEndOffset();
tupleLocalConstantMapOpt.TryGetValue(new LocalNameAndScope(name, scopeStart, scopeEnd), out tupleElementNames);
}
builder.Add(symbolProvider.GetLocalConstant(name, type, constantValue, dynamicFlags, tupleElementNames));
}
}
}
/// <summary>
/// Returns symbols for the locals emitted in the original method,
/// based on the local signatures from the IL and the names and
/// slots from the PDB. The actual locals are needed to ensure the
/// local slots in the generated method match the original.
/// </summary>
public static void GetLocals(
ArrayBuilder<TLocalSymbol> builder,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider,
ImmutableArray<string> names,
ImmutableArray<LocalInfo<TTypeSymbol>> localInfo,
ImmutableDictionary<int, ImmutableArray<bool>> dynamicLocalMapOpt,
ImmutableDictionary<int, ImmutableArray<string>> tupleLocalConstantMapOpt)
{
if (localInfo.Length == 0)
{
// When debugging a .dmp without a heap, localInfo will be empty although
// names may be non-empty if there is a PDB. Since there's no type info, the
// locals are dropped. Note this means the local signature of any generated
// method will not match the original signature, so new locals will overlap
// original locals. That is ok since there is no live process for the debugger
// to update (any modified values exist in the debugger only).
return;
}
Debug.Assert(localInfo.Length >= names.Length);
for (int i = 0; i < localInfo.Length; i++)
{
string name = (i < names.Length) ? names[i] : null;
var dynamicFlags = default(ImmutableArray<bool>);
dynamicLocalMapOpt?.TryGetValue(i, out dynamicFlags);
var tupleElementNames = default(ImmutableArray<string>);
tupleLocalConstantMapOpt?.TryGetValue(i, out tupleElementNames);
builder.Add(symbolProvider.GetLocalVariable(name, i, localInfo[i], dynamicFlags, tupleElementNames));
}
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 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.Collections.Generic;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
namespace XenAPI
{
internal abstract class CustomJsonConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
}
internal class XenRefConverter<T> : CustomJsonConverter<XenRef<T>> where T : XenObject<T>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var str = jToken.ToObject<string>();
return string.IsNullOrEmpty(str) ? null : new XenRef<T>(str);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var reference = JObject.FromObject(value).GetValue("opaque_ref");
writer.WriteValue(reference);
}
}
internal class XenRefListConverter<T> : CustomJsonConverter<List<XenRef<T>>> where T : XenObject<T>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var refList = new List<XenRef<T>>();
foreach (JToken token in jToken.ToArray())
{
var str = token.ToObject<string>();
refList.Add(new XenRef<T>(str));
}
return refList;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var list = value as List<XenRef<T>>;
writer.WriteStartArray();
if (list != null)
list.ForEach(v => writer.WriteValue(v.opaque_ref));
writer.WriteEndArray();
}
}
internal class XenRefXenObjectMapConverter<T> : CustomJsonConverter<Dictionary<XenRef<T>, T>> where T : XenObject<T>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var dict = new Dictionary<XenRef<T>, T>();
foreach (JProperty property in jToken)
dict.Add(new XenRef<T>(property.Name), property.Value.ToObject<T>());
return dict;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
internal class XenRefLongMapConverter<T> : CustomJsonConverter<Dictionary<XenRef<T>, long>> where T : XenObject<T>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var dict = new Dictionary<XenRef<T>, long>();
foreach (JProperty property in jToken)
dict.Add(new XenRef<T>(property.Name), property.Value.ToObject<long>());
return dict;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dict = value as Dictionary<XenRef<T>, long>;
writer.WriteStartObject();
if (dict != null)
{
foreach (var kvp in dict)
{
writer.WritePropertyName(kvp.Key.opaque_ref);
writer.WriteValue(kvp.Value);
}
}
writer.WriteEndObject();
}
}
internal class XenRefStringMapConverter<T> : CustomJsonConverter<Dictionary<XenRef<T>, string>> where T : XenObject<T>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var dict = new Dictionary<XenRef<T>, string>();
foreach (JProperty property in jToken)
dict.Add(new XenRef<T>(property.Name), property.Value.ToString());
return dict;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dict = value as Dictionary<XenRef<T>, string>;
writer.WriteStartObject();
if (dict != null)
{
foreach (var kvp in dict)
{
writer.WritePropertyName(kvp.Key.opaque_ref);
writer.WriteValue(kvp.Value);
}
}
writer.WriteEndObject();
}
}
internal class XenRefStringStringMapMapConverter<T> : CustomJsonConverter<Dictionary<XenRef<T>, Dictionary<string, string>>> where T : XenObject<T>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var dict = new Dictionary<XenRef<T>, Dictionary<string, string>>();
foreach (JProperty property in jToken)
dict.Add(new XenRef<T>(property.Name), property.Value.ToObject<Dictionary<string, string>>());
return dict;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dict = value as Dictionary<XenRef<T>, Dictionary<string, string>>;
writer.WriteStartObject();
if (dict != null)
{
foreach (var kvp in dict)
{
writer.WritePropertyName(kvp.Key.opaque_ref);
writer.WriteStartObject();
foreach (var valKvp in kvp.Value)
{
writer.WritePropertyName(valKvp.Key);
writer.WriteValue(valKvp.Value);
}
writer.WriteEndObject();
}
}
writer.WriteEndObject();
}
}
internal class XenRefXenRefMapConverter<TK, TV> : CustomJsonConverter<Dictionary<XenRef<TK>, XenRef<TV>>> where TK : XenObject<TK> where TV : XenObject<TV>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var dict = new Dictionary<XenRef<TK>, XenRef<TV>>();
foreach (JProperty property in jToken)
dict.Add(new XenRef<TK>(property.Name), new XenRef<TV>(property.Value.ToString()));
return dict;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dict = value as Dictionary<XenRef<TK>, XenRef<TV>>;
writer.WriteStartObject();
if (dict != null)
{
foreach (var kvp in dict)
{
writer.WritePropertyName(kvp.Key.opaque_ref);
writer.WriteValue(kvp.Value.opaque_ref);
}
}
writer.WriteEndObject();
}
}
internal class XenRefStringSetMapConverter<T> : CustomJsonConverter<Dictionary<XenRef<T>, string[]>> where T : XenObject<T>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var dict = new Dictionary<XenRef<T>, string[]>();
foreach (JProperty property in jToken)
dict.Add(new XenRef<T>(property.Name), property.Value.ToObject<string[]>());
return dict;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dict = value as Dictionary<XenRef<T>, string[]>;
writer.WriteStartObject();
if (dict != null)
{
foreach (var kvp in dict)
{
writer.WritePropertyName(kvp.Key.opaque_ref);
writer.WriteStartArray();
foreach (var v in kvp.Value)
writer.WriteValue(v);
writer.WriteEndArray();
}
}
writer.WriteEndObject();
}
}
internal class StringXenRefMapConverter<T> : CustomJsonConverter<Dictionary<string, XenRef<T>>> where T : XenObject<T>
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var dict = new Dictionary<string, XenRef<T>>();
foreach (JProperty property in jToken)
dict.Add(property.Name, new XenRef<T>(property.Value.ToString()));
return dict;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dict = value as Dictionary<string, XenRef<T>>;
writer.WriteStartObject();
if (dict != null)
{
foreach (var kvp in dict)
{
writer.WritePropertyName(kvp.Key);
writer.WriteValue(kvp.Value.opaque_ref);
}
}
writer.WriteEndObject();
}
}
internal class StringStringMapConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var dict = new Dictionary<string, string>();
foreach (JProperty property in jToken)
dict.Add(property.Name, property.Value == null ? null : property.Value.ToString());
return dict;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Dictionary<string, string>);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dict = value as Dictionary<string, string>;
writer.WriteStartObject();
if (dict != null)
{
foreach (var kvp in dict)
{
writer.WritePropertyName(kvp.Key);
writer.WriteValue(kvp.Value ?? "");
}
}
writer.WriteEndObject();
}
}
internal class XenEventConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(Event).IsAssignableFrom(objectType);
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
var id = jToken["id"];
var timestamp = jToken["timestamp"];
var operation = jToken["operation"];
var opaqueRef = jToken["ref"];
var class_ = jToken["class"];
var snapshot = jToken["snapshot"];
var newEvent = new Event
{
id = id == null ? 0 : id.ToObject<long>(),
timestamp = timestamp == null ? null : timestamp.ToObject<string>(),
operation = operation == null ? null : operation.ToObject<string>(),
opaqueRef = opaqueRef == null ? null : opaqueRef.ToObject<string>(),
class_ = class_ == null ? null : class_.ToObject<string>()
};
Type typ = Type.GetType(string.Format("XenAPI.{0}", newEvent.class_), false, true);
newEvent.snapshot = snapshot == null ? null : snapshot.ToObject(typ, serializer);
return newEvent;
}
}
internal class XenDateTimeConverter : IsoDateTimeConverter
{
private static readonly string[] DateFormatsUniversal =
{
"yyyyMMddTHH:mm:ssZ"
};
private static readonly string[] DateFormatsOther =
{
"yyyyMMddTHH:mm:ss",
"yyyyMMddTHHmmsszzz",
"yyyyMMddTHHmmsszz"
};
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
string str = JToken.Load(reader).ToString();
DateTime result;
if (DateTime.TryParseExact(str, DateFormatsUniversal, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out result))
return result;
if (DateTime.TryParseExact(str, DateFormatsOther, CultureInfo.InvariantCulture,
DateTimeStyles.None, out result))
return result;
return DateTime.MinValue;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is DateTime)
{
var dateTime = (DateTime)value;
dateTime = dateTime.ToUniversalTime();
var text = dateTime.ToString(DateFormatsUniversal[0], CultureInfo.InvariantCulture);
writer.WriteValue(text);
return;
}
base.WriteJson(writer, value, serializer);
}
}
internal class XenEnumConverter : StringEnumConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken jToken = JToken.Load(reader);
return Helper.EnumParseDefault(objectType, jToken.ToObject<string>());
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A furniture store.
/// </summary>
public class FurnitureStore_Core : TypeCore, IStore
{
public FurnitureStore_Core()
{
this._TypeId = 108;
this._Id = "FurnitureStore";
this._Schema_Org_Url = "http://schema.org/FurnitureStore";
string label = "";
GetLabel(out label, "FurnitureStore", typeof(FurnitureStore_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155,252};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{252};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
// CRC32.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2011 Dino Chiesa.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// Last Saved: <2011-August-02 18:25:54>
//
// ------------------------------------------------------------------
//
// This module defines the CRC32 class, which can do the CRC32 algorithm, using
// arbitrary starting polynomials, and bit reversal. The bit reversal is what
// distinguishes this CRC-32 used in BZip2 from the CRC-32 that is used in PKZIP
// files, or GZIP files. This class does both.
//
// ------------------------------------------------------------------
using System;
using Interop = System.Runtime.InteropServices;
namespace Ionic2.Crc
{
/// <summary>
/// Computes a CRC-32. The CRC-32 algorithm is parameterized - you
/// can set the polynomial and enable or disable bit
/// reversal. This can be used for GZIP, BZip2, or ZIP.
/// </summary>
/// <remarks>
/// This type is used internally by DotNetZip; it is generally not used
/// directly by applications wishing to create, read, or manipulate zip
/// archive files.
/// </remarks>
[Interop.GuidAttribute("ebc25cf6-9120-4283-b972-0e5520d0000C")]
[Interop.ComVisible(true)]
#if !NETCF
[Interop.ClassInterface(Interop.ClassInterfaceType.AutoDispatch)]
#endif
public class CRC32
{
/// <summary>
/// Indicates the total number of bytes applied to the CRC.
/// </summary>
public Int64 TotalBytesRead
{
get
{
return _TotalBytesRead;
}
}
/// <summary>
/// Indicates the current CRC for all blocks slurped in.
/// </summary>
public Int32 Crc32Result
{
get
{
return unchecked((Int32)(~_register));
}
}
/// <summary>
/// Returns the CRC32 for the specified stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <returns>the CRC32 calculation</returns>
public Int32 GetCrc32(System.IO.Stream input)
{
return GetCrc32AndCopy(input, null);
}
/// <summary>
/// Returns the CRC32 for the specified stream, and writes the input into the
/// output stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <param name="output">The stream into which to deflate the input</param>
/// <returns>the CRC32 calculation</returns>
public Int32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output)
{
if (input == null)
throw new Exception("The input stream must not be null.");
unchecked
{
byte[] buffer = new byte[BUFFER_SIZE];
int readSize = BUFFER_SIZE;
_TotalBytesRead = 0;
int count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
_TotalBytesRead += count;
while (count > 0)
{
SlurpBlock(buffer, 0, count);
count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
_TotalBytesRead += count;
}
return (Int32)(~_register);
}
}
/// <summary>
/// Get the CRC32 for the given (word,byte) combo. This is a
/// computation defined by PKzip for PKZIP 2.0 (weak) encryption.
/// </summary>
/// <param name="W">The word to start with.</param>
/// <param name="B">The byte to combine it with.</param>
/// <returns>The CRC-ized result.</returns>
public Int32 ComputeCrc32(Int32 W, byte B)
{
return _InternalComputeCrc32((UInt32)W, B);
}
internal Int32 _InternalComputeCrc32(UInt32 W, byte B)
{
return (Int32)(crc32Table[(W ^ B) & 0xFF] ^ (W >> 8));
}
/// <summary>
/// Update the value for the running CRC32 using the given block of bytes.
/// This is useful when using the CRC32() class in a Stream.
/// </summary>
/// <param name="block">block of bytes to slurp</param>
/// <param name="offset">starting point in the block</param>
/// <param name="count">how many bytes within the block to slurp</param>
public void SlurpBlock(byte[] block, int offset, int count)
{
if (block == null)
throw new Exception("The data buffer must not be null.");
// bzip algorithm
for (int i = 0; i < count; i++)
{
int x = offset + i;
byte b = block[x];
if (this.reverseBits)
{
UInt32 temp = (_register >> 24) ^ b;
_register = (_register << 8) ^ crc32Table[temp];
}
else
{
UInt32 temp = (_register & 0x000000FF) ^ b;
_register = (_register >> 8) ^ crc32Table[temp];
}
}
_TotalBytesRead += count;
}
/// <summary>
/// Process one byte in the CRC.
/// </summary>
/// <param name = "b">the byte to include into the CRC . </param>
public void UpdateCRC(byte b)
{
if (this.reverseBits)
{
UInt32 temp = (_register >> 24) ^ b;
_register = (_register << 8) ^ crc32Table[temp];
}
else
{
UInt32 temp = (_register & 0x000000FF) ^ b;
_register = (_register >> 8) ^ crc32Table[temp];
}
}
/// <summary>
/// Process a run of N identical bytes into the CRC.
/// </summary>
/// <remarks>
/// <para>
/// This method serves as an optimization for updating the CRC when a
/// run of identical bytes is found. Rather than passing in a buffer of
/// length n, containing all identical bytes b, this method accepts the
/// byte value and the length of the (virtual) buffer - the length of
/// the run.
/// </para>
/// </remarks>
/// <param name = "b">the byte to include into the CRC. </param>
/// <param name = "n">the number of times that byte should be repeated. </param>
public void UpdateCRC(byte b, int n)
{
while (n-- > 0)
{
if (this.reverseBits)
{
uint temp = (_register >> 24) ^ b;
_register = (_register << 8) ^ crc32Table[(temp >= 0)
? temp
: (temp + 256)];
}
else
{
UInt32 temp = (_register & 0x000000FF) ^ b;
_register = (_register >> 8) ^ crc32Table[(temp >= 0)
? temp
: (temp + 256)];
}
}
}
private static uint ReverseBits(uint data)
{
unchecked
{
uint ret = data;
ret = (ret & 0x55555555) << 1 | (ret >> 1) & 0x55555555;
ret = (ret & 0x33333333) << 2 | (ret >> 2) & 0x33333333;
ret = (ret & 0x0F0F0F0F) << 4 | (ret >> 4) & 0x0F0F0F0F;
ret = (ret << 24) | ((ret & 0xFF00) << 8) | ((ret >> 8) & 0xFF00) | (ret >> 24);
return ret;
}
}
private static byte ReverseBits(byte data)
{
unchecked
{
uint u = (uint)data * 0x00020202;
uint m = 0x01044010;
uint s = u & m;
uint t = (u << 2) & (m << 1);
return (byte)((0x01001001 * (s + t)) >> 24);
}
}
private void GenerateLookupTable()
{
crc32Table = new UInt32[256];
unchecked
{
UInt32 dwCrc;
byte i = 0;
do
{
dwCrc = i;
for (byte j = 8; j > 0; j--)
{
if ((dwCrc & 1) == 1)
{
dwCrc = (dwCrc >> 1) ^ dwPolynomial;
}
else
{
dwCrc >>= 1;
}
}
if (reverseBits)
{
crc32Table[ReverseBits(i)] = ReverseBits(dwCrc);
}
else
{
crc32Table[i] = dwCrc;
}
i++;
} while (i!=0);
}
#if VERBOSE
Console.WriteLine();
Console.WriteLine("private static readonly UInt32[] crc32Table = {");
for (int i = 0; i < crc32Table.Length; i+=4)
{
Console.Write(" ");
for (int j=0; j < 4; j++)
{
Console.Write(" 0x{0:X8}U,", crc32Table[i+j]);
}
Console.WriteLine();
}
Console.WriteLine("};");
Console.WriteLine();
#endif
}
private uint gf2_matrix_times(uint[] matrix, uint vec)
{
uint sum = 0;
int i=0;
while (vec != 0)
{
if ((vec & 0x01)== 0x01)
sum ^= matrix[i];
vec >>= 1;
i++;
}
return sum;
}
private void gf2_matrix_square(uint[] square, uint[] mat)
{
for (int i = 0; i < 32; i++)
square[i] = gf2_matrix_times(mat, mat[i]);
}
/// <summary>
/// Combines the given CRC32 value with the current running total.
/// </summary>
/// <remarks>
/// This is useful when using a divide-and-conquer approach to
/// calculating a CRC. Multiple threads can each calculate a
/// CRC32 on a segment of the data, and then combine the
/// individual CRC32 values at the end.
/// </remarks>
/// <param name="crc">the crc value to be combined with this one</param>
/// <param name="length">the length of data the CRC value was calculated on</param>
public void Combine(int crc, int length)
{
uint[] even = new uint[32]; // even-power-of-two zeros operator
uint[] odd = new uint[32]; // odd-power-of-two zeros operator
if (length == 0)
return;
uint crc1= ~_register;
uint crc2= (uint) crc;
// put operator for one zero bit in odd
odd[0] = this.dwPolynomial; // the CRC-32 polynomial
uint row = 1;
for (int i = 1; i < 32; i++)
{
odd[i] = row;
row <<= 1;
}
// put operator for two zero bits in even
gf2_matrix_square(even, odd);
// put operator for four zero bits in odd
gf2_matrix_square(odd, even);
uint len2 = (uint) length;
// apply len2 zeros to crc1 (first square will put the operator for one
// zero byte, eight zero bits, in even)
do {
// apply zeros operator for this bit of len2
gf2_matrix_square(even, odd);
if ((len2 & 1)== 1)
crc1 = gf2_matrix_times(even, crc1);
len2 >>= 1;
if (len2 == 0)
break;
// another iteration of the loop with odd and even swapped
gf2_matrix_square(odd, even);
if ((len2 & 1)==1)
crc1 = gf2_matrix_times(odd, crc1);
len2 >>= 1;
} while (len2 != 0);
crc1 ^= crc2;
_register= ~crc1;
//return (int) crc1;
return;
}
/// <summary>
/// Create an instance of the CRC32 class using the default settings: no
/// bit reversal, and a polynomial of 0xEDB88320.
/// </summary>
public CRC32() : this(false)
{
}
/// <summary>
/// Create an instance of the CRC32 class, specifying whether to reverse
/// data bits or not.
/// </summary>
/// <param name='reverseBits'>
/// specify true if the instance should reverse data bits.
/// </param>
/// <remarks>
/// <para>
/// In the CRC-32 used by BZip2, the bits are reversed. Therefore if you
/// want a CRC32 with compatibility with BZip2, you should pass true
/// here. In the CRC-32 used by GZIP and PKZIP, the bits are not
/// reversed; Therefore if you want a CRC32 with compatibility with
/// those, you should pass false.
/// </para>
/// </remarks>
public CRC32(bool reverseBits) :
this( unchecked((int)0xEDB88320), reverseBits)
{
}
/// <summary>
/// Create an instance of the CRC32 class, specifying the polynomial and
/// whether to reverse data bits or not.
/// </summary>
/// <param name='polynomial'>
/// The polynomial to use for the CRC, expressed in the reversed (LSB)
/// format: the highest ordered bit in the polynomial value is the
/// coefficient of the 0th power; the second-highest order bit is the
/// coefficient of the 1 power, and so on. Expressed this way, the
/// polynomial for the CRC-32C used in IEEE 802.3, is 0xEDB88320.
/// </param>
/// <param name='reverseBits'>
/// specify true if the instance should reverse data bits.
/// </param>
///
/// <remarks>
/// <para>
/// In the CRC-32 used by BZip2, the bits are reversed. Therefore if you
/// want a CRC32 with compatibility with BZip2, you should pass true
/// here for the <c>reverseBits</c> parameter. In the CRC-32 used by
/// GZIP and PKZIP, the bits are not reversed; Therefore if you want a
/// CRC32 with compatibility with those, you should pass false for the
/// <c>reverseBits</c> parameter.
/// </para>
/// </remarks>
public CRC32(int polynomial, bool reverseBits)
{
this.reverseBits = reverseBits;
this.dwPolynomial = (uint) polynomial;
this.GenerateLookupTable();
}
/// <summary>
/// Reset the CRC-32 class - clear the CRC "remainder register."
/// </summary>
/// <remarks>
/// <para>
/// Use this when employing a single instance of this class to compute
/// multiple, distinct CRCs on multiple, distinct data blocks.
/// </para>
/// </remarks>
public void Reset()
{
_register = 0xFFFFFFFFU;
}
// private member vars
private UInt32 dwPolynomial;
private Int64 _TotalBytesRead;
private bool reverseBits;
private UInt32[] crc32Table;
private const int BUFFER_SIZE = 8192;
private UInt32 _register = 0xFFFFFFFFU;
}
/// <summary>
/// A Stream that calculates a CRC32 (a checksum) on all bytes read,
/// or on all bytes written.
/// </summary>
///
/// <remarks>
/// <para>
/// This class can be used to verify the CRC of a ZipEntry when
/// reading from a stream, or to calculate a CRC when writing to a
/// stream. The stream should be used to either read, or write, but
/// not both. If you intermix reads and writes, the results are not
/// defined.
/// </para>
///
/// <para>
/// This class is intended primarily for use internally by the
/// DotNetZip library.
/// </para>
/// </remarks>
public class CrcCalculatorStream : System.IO.Stream, System.IDisposable
{
private static readonly Int64 UnsetLengthLimit = -99;
internal System.IO.Stream _innerStream;
private CRC32 _Crc32;
private Int64 _lengthLimit = -99;
private bool _leaveOpen;
/// <summary>
/// The default constructor.
/// </summary>
/// <remarks>
/// <para>
/// Instances returned from this constructor will leave the underlying
/// stream open upon Close(). The stream uses the default CRC32
/// algorithm, which implies a polynomial of 0xEDB88320.
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
public CrcCalculatorStream(System.IO.Stream stream)
: this(true, CrcCalculatorStream.UnsetLengthLimit, stream, null)
{
}
/// <summary>
/// The constructor allows the caller to specify how to handle the
/// underlying stream at close.
/// </summary>
/// <remarks>
/// <para>
/// The stream uses the default CRC32 algorithm, which implies a
/// polynomial of 0xEDB88320.
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="leaveOpen">true to leave the underlying stream
/// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param>
public CrcCalculatorStream(System.IO.Stream stream, bool leaveOpen)
: this(leaveOpen, CrcCalculatorStream.UnsetLengthLimit, stream, null)
{
}
/// <summary>
/// A constructor allowing the specification of the length of the stream
/// to read.
/// </summary>
/// <remarks>
/// <para>
/// The stream uses the default CRC32 algorithm, which implies a
/// polynomial of 0xEDB88320.
/// </para>
/// <para>
/// Instances returned from this constructor will leave the underlying
/// stream open upon Close().
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="length">The length of the stream to slurp</param>
public CrcCalculatorStream(System.IO.Stream stream, Int64 length)
: this(true, length, stream, null)
{
if (length < 0)
throw new ArgumentException("length");
}
/// <summary>
/// A constructor allowing the specification of the length of the stream
/// to read, as well as whether to keep the underlying stream open upon
/// Close().
/// </summary>
/// <remarks>
/// <para>
/// The stream uses the default CRC32 algorithm, which implies a
/// polynomial of 0xEDB88320.
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="length">The length of the stream to slurp</param>
/// <param name="leaveOpen">true to leave the underlying stream
/// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param>
public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen)
: this(leaveOpen, length, stream, null)
{
if (length < 0)
throw new ArgumentException("length");
}
/// <summary>
/// A constructor allowing the specification of the length of the stream
/// to read, as well as whether to keep the underlying stream open upon
/// Close(), and the CRC32 instance to use.
/// </summary>
/// <remarks>
/// <para>
/// The stream uses the specified CRC32 instance, which allows the
/// application to specify how the CRC gets calculated.
/// </para>
/// </remarks>
/// <param name="stream">The underlying stream</param>
/// <param name="length">The length of the stream to slurp</param>
/// <param name="leaveOpen">true to leave the underlying stream
/// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param>
/// <param name="crc32">the CRC32 instance to use to calculate the CRC32</param>
public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen,
CRC32 crc32)
: this(leaveOpen, length, stream, crc32)
{
if (length < 0)
throw new ArgumentException("length");
}
// This ctor is private - no validation is done here. This is to allow the use
// of a (specific) negative value for the _lengthLimit, to indicate that there
// is no length set. So we validate the length limit in those ctors that use an
// explicit param, otherwise we don't validate, because it could be our special
// value.
private CrcCalculatorStream
(bool leaveOpen, Int64 length, System.IO.Stream stream, CRC32 crc32)
: base()
{
_innerStream = stream;
_Crc32 = crc32 ?? new CRC32();
_lengthLimit = length;
_leaveOpen = leaveOpen;
}
/// <summary>
/// Gets the total number of bytes run through the CRC32 calculator.
/// </summary>
///
/// <remarks>
/// This is either the total number of bytes read, or the total number of
/// bytes written, depending on the direction of this stream.
/// </remarks>
public Int64 TotalBytesSlurped
{
get { return _Crc32.TotalBytesRead; }
}
/// <summary>
/// Provides the current CRC for all blocks slurped in.
/// </summary>
/// <remarks>
/// <para>
/// The running total of the CRC is kept as data is written or read
/// through the stream. read this property after all reads or writes to
/// get an accurate CRC for the entire stream.
/// </para>
/// </remarks>
public Int32 Crc
{
get { return _Crc32.Crc32Result; }
}
/// <summary>
/// Indicates whether the underlying stream will be left open when the
/// <c>CrcCalculatorStream</c> is Closed.
/// </summary>
/// <remarks>
/// <para>
/// Set this at any point before calling <see cref="Close()"/>.
/// </para>
/// </remarks>
public bool LeaveOpen
{
get { return _leaveOpen; }
set { _leaveOpen = value; }
}
/// <summary>
/// Read from the stream
/// </summary>
/// <param name="buffer">the buffer to read</param>
/// <param name="offset">the offset at which to start</param>
/// <param name="count">the number of bytes to read</param>
/// <returns>the number of bytes actually read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
int bytesToRead = count;
// Need to limit the # of bytes returned, if the stream is intended to have
// a definite length. This is especially useful when returning a stream for
// the uncompressed data directly to the application. The app won't
// necessarily read only the UncompressedSize number of bytes. For example
// wrapping the stream returned from OpenReader() into a StreadReader() and
// calling ReadToEnd() on it, We can "over-read" the zip data and get a
// corrupt string. The length limits that, prevents that problem.
if (_lengthLimit != CrcCalculatorStream.UnsetLengthLimit)
{
if (_Crc32.TotalBytesRead >= _lengthLimit) return 0; // EOF
Int64 bytesRemaining = _lengthLimit - _Crc32.TotalBytesRead;
if (bytesRemaining < count) bytesToRead = (int)bytesRemaining;
}
int n = _innerStream.Read(buffer, offset, bytesToRead);
if (n > 0) _Crc32.SlurpBlock(buffer, offset, n);
return n;
}
/// <summary>
/// Write to the stream.
/// </summary>
/// <param name="buffer">the buffer from which to write</param>
/// <param name="offset">the offset at which to start writing</param>
/// <param name="count">the number of bytes to write</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (count > 0) _Crc32.SlurpBlock(buffer, offset, count);
_innerStream.Write(buffer, offset, count);
}
/// <summary>
/// Indicates whether the stream supports reading.
/// </summary>
public override bool CanRead
{
get { return _innerStream.CanRead; }
}
/// <summary>
/// Indicates whether the stream supports seeking.
/// </summary>
/// <remarks>
/// <para>
/// Always returns false.
/// </para>
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream supports writing.
/// </summary>
public override bool CanWrite
{
get { return _innerStream.CanWrite; }
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
_innerStream.Flush();
}
/// <summary>
/// Returns the length of the underlying stream.
/// </summary>
public override long Length
{
get
{
if (_lengthLimit == CrcCalculatorStream.UnsetLengthLimit)
return _innerStream.Length;
else return _lengthLimit;
}
}
/// <summary>
/// The getter for this property returns the total bytes read.
/// If you use the setter, it will throw
/// <see cref="NotSupportedException"/>.
/// </summary>
public override long Position
{
get { return _Crc32.TotalBytesRead; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Seeking is not supported on this stream. This method always throws
/// <see cref="NotSupportedException"/>
/// </summary>
/// <param name="offset">N/A</param>
/// <param name="origin">N/A</param>
/// <returns>N/A</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// This method always throws
/// <see cref="NotSupportedException"/>
/// </summary>
/// <param name="value">N/A</param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
Close();
}
/// <summary>
/// Closes the stream.
/// </summary>
public override void Close()
{
base.Close();
if (!_leaveOpen)
_innerStream.Close();
}
}
}
| |
using CoCoL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace PerfTester
{
public struct StatRequest
{
public TaskCompletionSource<ResultStats> Result;
}
public struct RequestResult
{
public DateTime Started;
public DateTime Finished;
public bool Failed;
public Exception Exception;
}
public struct ResultStats
{
public TimeSpan Duration;
public long Requests;
public long Failures;
public TimeSpan Min;
public TimeSpan Mean;
public TimeSpan Max;
public TimeSpan StdDeviation;
public TimeSpan Pct90;
public TimeSpan Pct95;
public TimeSpan Pct99;
}
public static class Processes
{
private const bool D = false;
public static Task RunGranterAsync(IWriteChannel<bool> channel, long count, CancellationToken token)
{
var canceltask = new TaskCompletionSource<bool>();
token.Register(() => canceltask.TrySetCanceled());
var total = count;
return AutomationExtensions.RunTask(
new { channel },
async self => {
while(count > 0)
{
DebugWriteLine($"Emitting task {total - count} of {total}");
if (await Task.WhenAny(new [] { canceltask.Task, channel.WriteAsync(true) }) == canceltask.Task)
throw new TaskCanceledException();
count--;
DebugWriteLine($"Emitted task {total - count} of {total}");
}
DebugWriteLine("Stopping task granter");
}
);
}
public static Task RunStatPrinterAsync(IWriteChannel<StatRequest> channel, TimeSpan period, long total, CancellationToken token)
{
return AutomationExtensions.RunTask(
new { channel },
async _ => {
while(true)
{
await Task.Delay(period, token);
var tcs = new TaskCompletionSource<ResultStats>();
await channel.WriteAsync(new StatRequest() {
Result = tcs
});
var res = await tcs.Task;
var pg = (res.Requests / (double)total) * 100;
Console.WriteLine($" {pg:0.00}% ({res.Requests} of {total}) {(res.Failures == 0 ? "" : $"{res.Failures} {(res.Failures == 1 ? "failure" : "failures")}")}");
}
}
);
}
public static async Task RunWorkersAsync(IReadChannel<bool> requests, int workers, Func<RunnerBase> starter)
{
var active = new List<RunnerBase>();
while(!await requests.IsRetiredAsync)
{
while (active.Count < workers)
{
DebugWriteLine($"Starting worker {active.Count + 1} of {workers}");
active.Add(starter());
}
DebugWriteLine("Waiting for workers to complete");
await Task.WhenAny(active.Select(x => x.Result));
DebugWriteLine("One or more workers completed");
for (var i = active.Count - 1; i >= 0; i--)
if (active[i].Result.IsCompleted)
active.RemoveAt(i);
DebugWriteLine($"{workers - active.Count} workers completed");
}
DebugWriteLine("No more requests, waiting for all workers to complete");
await Task.WhenAll(active.Select(x => x.Result));
}
public static async Task<ResultStats> RunCollectorAsync(IReadChannel<RequestResult> channel, IReadChannel<StatRequest> stats, CancellationToken token)
{
var canceltask = new TaskCompletionSource<bool>();
token.Register(() => canceltask.TrySetCanceled());
var durations = new List<long>();
var started = 0L;
var finished = 0L;
var count = 0L;
var failures = 0L;
var chans = new IMultisetRequestUntyped[] {channel.RequestRead(), stats.RequestRead()};
try
{
using(channel.AsReadOnly())
{
while(true)
{
var res = await chans.ReadFromAnyAsync();
DebugWriteLine($"Got message of type {res.Value.GetType()}");
if (res.Value is RequestResult a)
{
started = started == 0 ? a.Started.Ticks : Math.Min(a.Started.Ticks, started);
finished = finished == 0 ? a.Finished.Ticks : Math.Max(a.Finished.Ticks, finished);
count++;
if (a.Failed)
failures++;
else
durations.Add((a.Finished - a.Started).Ticks);
}
else if(res.Value is StatRequest s)
{
s.Result.TrySetResult(new ResultStats() {
Duration = new TimeSpan(finished - started),
Requests = count,
Failures = failures,
});
}
}
}
}
catch
{
}
if (durations.LongCount() == 0)
return new ResultStats();
DebugWriteLine($"All requests performed, computing stats");
var mean = durations.Sum() / durations.LongCount();
var sqdev = durations.Select(x => Math.Pow(x - mean, 2)).Sum();
var avgdev = sqdev / durations.LongCount();
var sqr = Math.Sqrt(Math.Abs(avgdev));
var sorted = durations.Select(x => x).OrderBy(x => x);
var n99 = (int)Math.Ceiling(0.99 * (durations.Count - 1));
var n95 = (int)Math.Ceiling(0.95 * (durations.Count - 1));
var n90 = (int)Math.Ceiling(0.90 * (durations.Count - 1));
var min = sorted.FirstOrDefault();
var t0 = sorted.Skip(n90);
var t90 = t0.FirstOrDefault();
t0 = t0.Skip(n95 - n90);
var t95 = t0.FirstOrDefault();
t0 = t0.Skip(n99 - n95);
var t99 = t0.FirstOrDefault();
var max = t0.LastOrDefault();
DebugWriteLine($"All requests performed, returning stats");
return new ResultStats()
{
Duration = new TimeSpan(finished - started),
Requests = count,
Failures = failures,
Min = new TimeSpan(min),
Mean = new TimeSpan(mean),
Max = new TimeSpan(max),
StdDeviation = new TimeSpan((long)sqr),
Pct90 = new TimeSpan(t90),
Pct95 = new TimeSpan(t95),
Pct99 = new TimeSpan(t99)
};
}
private static void DebugWriteLine(string msg)
{
//Console.WriteLine(msg);
}
}
}
| |
/* Copyright (c) 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Xml;
using System.IO;
using System.Collections;
using Google.GData.Apps;
using Google.GData.Client;
using Google.GData.Extensions.Apps;
namespace Google.GData.Apps.AdminSettings
{
/// <summary>
/// A Google Apps Google Admin Settings entry.
/// </summary>
public class AdminSettingsEntry : AppsExtendedEntry
{
/// <summary>
/// Constructs a new <code>AdminSettingsEntry</code> object.
/// </summary>
public AdminSettingsEntry()
: base()
{
}
/// <summary>
/// typed override of the Update method
/// </summary>
/// <returns>AdminSettingsEntry</returns>
public new AdminSettingsEntry Update()
{
return base.Update() as AdminSettingsEntry;
}
/// <summary>
/// DefaultLanguage Property accessor
/// </summary>
public string DefaultLanguage
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.DefaultLanguage);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.DefaultLanguage).Value = value; }
}
/// <summary>
/// OrganizationName Property accessor
/// </summary>
public string OrganizationName
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.OrganizationName);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.OrganizationName).Value = value; }
}
/// <summary>
/// MaximumNumberOfUsers Property accessor
/// </summary>
public string MaximumNumberOfUsers
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.MaximumNumberOfUsers);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.MaximumNumberOfUsers).Value = value; }
}
/// <summary>
/// MaximumNumberOfUsers Property accessor
/// </summary>
public string CurrentNumberOfUsers
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.CurrentNumberOfUsers);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.CurrentNumberOfUsers).Value = value; }
}
/// <summary>
/// IsVerified Property accessor
/// </summary>
public string IsVerified
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.IsVerified);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.IsVerified).Value = value; }
}
/// <summary>
/// SupportPIN Property accessor
/// </summary>
public string SupportPIN
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.SupportPIN);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.SupportPIN).Value = value; }
}
/// <summary>
/// Edition Property accessor
/// </summary>
public string Edition
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.Edition);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.Edition).Value = value; }
}
/// <summary>
/// CustomerPIN Property accessor
/// </summary>
public string CustomerPIN
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.CustomerPIN);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.CustomerPIN).Value = value; }
}
/// <summary>
/// CreationTime Property accessor
/// </summary>
public string CreationTime
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.CreationTime);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.CreationTime).Value = value; }
}
/// <summary>
/// CountryCode Property accessor
/// </summary>
public string CountryCode
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.CountryCode);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.CountryCode).Value = value; }
}
/// <summary>
/// AdminSecondaryEmail Property accessor
/// </summary>
public string AdminSecondaryEmail
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.AdminSecondaryEmail);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.AdminSecondaryEmail).Value = value; }
}
/// <summary>
/// LogoImage Property accessor
/// </summary>
public string LogoImage
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.LogoImage);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.LogoImage).Value = value; }
}
/// <summary>
/// RecordName Property accessor
/// </summary>
public string RecordName
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.RecordName);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.RecordName).Value = value; }
}
/// <summary>
/// Verified Property accessor
/// </summary>
public string Verified
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.Verified);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.Verified).Value = value; }
}
/// <summary>
/// VerifiedMethod Property accessor
/// </summary>
public string VerifiedMethod
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.VerifiedMethod);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.VerifiedMethod).Value = value; }
}
/// <summary>
/// MaximumNumberOfUsers Property accessor
/// </summary>
public string SamlSignonUri
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.SamlSignonUri);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.SamlSignonUri).Value = value; }
}
/// <summary>
/// SamlLogoutUri Property accessor
/// </summary>
public string SamlLogoutUri
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.SamlLogoutUri);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.SamlLogoutUri).Value = value; }
}
/// <summary>
/// ChangePasswordUri Property accessor
/// </summary>
public string ChangePasswordUri
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.ChangePasswordUri);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.ChangePasswordUri).Value = value; }
}
/// <summary>
/// EnableSSO Property accessor
/// </summary>
public string EnableSSO
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.EnableSSO);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.EnableSSO).Value = value; }
}
/// <summary>
/// SsoWhitelist Property accessor
/// </summary>
public string SsoWhitelist
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.SsoWhitelist);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.SsoWhitelist).Value = value; }
}
/// <summary>
/// UseDomainSpecificIssuer Property accessor
/// </summary>
public string UseDomainSpecificIssuer
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.UseDomainSpecificIssuer);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.UseDomainSpecificIssuer).Value = value; }
}
/// <summary>
/// SigningKey Property accessor
/// </summary>
public string SigningKey
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.SigningKey);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.SigningKey).Value = value; }
}
/// <summary>
/// EnableUserMigration Property accessor
/// </summary>
public string EnableUserMigration
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.EnableUserMigration);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.EnableUserMigration).Value = value; }
}
/// <summary>
/// SmartHost Property accessor
/// </summary>
public string SmartHost
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.SmartHost);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.SmartHost).Value = value; }
}
/// <summary>
/// SmtpMode Property accessor
/// </summary>
public string SmtpMode
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.SmtpMode);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.SmtpMode).Value = value; }
}
/// <summary>
/// RouteDestination Property accessor
/// </summary>
public string RouteDestination
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.RouteDestination);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.RouteDestination).Value = value; }
}
/// <summary>
/// RouteRewriteTo Property accessor
/// </summary>
public string RouteRewriteTo
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.RouteRewriteTo);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.RouteRewriteTo).Value = value; }
}
/// <summary>
/// RouteEnabled Property accessor
/// </summary>
public string RouteEnabled
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.RouteEnabled);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.RouteEnabled).Value = value; }
}
/// <summary>
/// BounceNotifications Property accessor
/// </summary>
public string BounceNotifications
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.BounceNotifications);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.BounceNotifications).Value = value; }
}
/// <summary>
/// AccountHandling Property accessor
/// </summary>
public string AccountHandling
{
get
{
PropertyElement property =
this.getPropertyByName(AppsDomainSettingsNameTable.AccountHandling);
return property != null ? property.Value : null;
}
set { this.getPropertyByName(AppsDomainSettingsNameTable.AccountHandling).Value = value; }
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.