context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using Orleans.Serialization.Buffers;
using Orleans.Serialization.Cloning;
using Orleans.Serialization.Utilities;
using Orleans.Serialization.WireProtocol;
using System;
using System.Buffers;
using System.Runtime.CompilerServices;
namespace Orleans.Serialization.Codecs
{
[RegisterSerializer]
[RegisterCopier]
public sealed class BoolCodec : TypedCodecBase<bool, BoolCodec>, IFieldCodec<bool>, IDeepCopier<bool>
{
private static readonly Type CodecFieldType = typeof(bool);
void IFieldCodec<bool>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer,
uint fieldIdDelta,
Type expectedType,
bool value) => WriteField(ref writer, fieldIdDelta, expectedType, value);
public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, bool value) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.VarInt);
writer.WriteVarUInt32(value ? 1U : 0U);
}
bool IFieldCodec<bool>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) => ReadValue(ref reader, field);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool ReadValue<TInput>(ref Reader<TInput> reader, Field field)
{
ReferenceCodec.MarkValueField(reader.Session);
return reader.ReadUInt8(field.WireType) == 1;
}
public bool DeepCopy(bool input, CopyContext _) => input;
}
[RegisterSerializer]
[RegisterCopier]
public sealed class CharCodec : TypedCodecBase<char, CharCodec>, IFieldCodec<char>, IDeepCopier<char>
{
private static readonly Type CodecFieldType = typeof(char);
void IFieldCodec<char>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer,
uint fieldIdDelta,
Type expectedType,
char value) => WriteField(ref writer, fieldIdDelta, expectedType, value);
public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, char value) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.VarInt);
writer.WriteVarUInt32(value);
}
char IFieldCodec<char>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) => ReadValue(ref reader, field);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static char ReadValue<TInput>(ref Reader<TInput> reader, Field field)
{
ReferenceCodec.MarkValueField(reader.Session);
return (char)reader.ReadUInt16(field.WireType);
}
public char DeepCopy(char input, CopyContext _) => input;
}
[RegisterSerializer]
[RegisterCopier]
public sealed class ByteCodec : TypedCodecBase<byte, ByteCodec>, IFieldCodec<byte>, IDeepCopier<byte>
{
private static readonly Type CodecFieldType = typeof(byte);
void IFieldCodec<byte>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer,
uint fieldIdDelta,
Type expectedType,
byte value) => WriteField(ref writer, fieldIdDelta, expectedType, value);
public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, byte value) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.VarInt);
writer.WriteVarUInt32(value);
}
public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, byte value, Type actualType) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
writer.WriteFieldHeader(fieldIdDelta, expectedType, actualType, WireType.VarInt);
writer.WriteVarUInt32(value);
}
byte IFieldCodec<byte>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) => ReadValue(ref reader, field);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte ReadValue<TInput>(ref Reader<TInput> reader, Field field)
{
ReferenceCodec.MarkValueField(reader.Session);
return reader.ReadUInt8(field.WireType);
}
public byte DeepCopy(byte input, CopyContext _) => input;
}
[RegisterSerializer]
[RegisterCopier]
public sealed class SByteCodec : TypedCodecBase<sbyte, SByteCodec>, IFieldCodec<sbyte>, IDeepCopier<sbyte>
{
private static readonly Type CodecFieldType = typeof(sbyte);
void IFieldCodec<sbyte>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer,
uint fieldIdDelta,
Type expectedType,
sbyte value) => WriteField(ref writer, fieldIdDelta, expectedType, value);
public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, sbyte value) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.VarInt);
writer.WriteVarInt8(value);
}
public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, sbyte value, Type actualType) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
writer.WriteFieldHeader(fieldIdDelta, expectedType, actualType, WireType.VarInt);
writer.WriteVarInt8(value);
}
sbyte IFieldCodec<sbyte>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) => ReadValue(ref reader, field);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static sbyte ReadValue<TInput>(ref Reader<TInput> reader, Field field)
{
ReferenceCodec.MarkValueField(reader.Session);
return reader.ReadInt8(field.WireType);
}
public sbyte DeepCopy(sbyte input, CopyContext _) => input;
}
[RegisterSerializer]
[RegisterCopier]
public sealed class UInt16Codec : TypedCodecBase<ushort, UInt16Codec>, IFieldCodec<ushort>, IDeepCopier<ushort>
{
public static readonly Type CodecFieldType = typeof(ushort);
ushort IFieldCodec<ushort>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) => ReadValue(ref reader, field);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ushort ReadValue<TInput>(ref Reader<TInput> reader, Field field)
{
ReferenceCodec.MarkValueField(reader.Session);
return reader.ReadUInt16(field.WireType);
}
void IFieldCodec<ushort>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer,
uint fieldIdDelta,
Type expectedType,
ushort value) => WriteField(ref writer, fieldIdDelta, expectedType, value);
public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, ushort value) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.VarInt);
writer.WriteVarUInt32(value);
}
public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, ushort value, Type actualType) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
writer.WriteFieldHeader(fieldIdDelta, expectedType, actualType, WireType.VarInt);
writer.WriteVarUInt32(value);
}
public ushort DeepCopy(ushort input, CopyContext _) => input;
}
[RegisterSerializer]
[RegisterCopier]
public sealed class Int16Codec : TypedCodecBase<short, Int16Codec>, IFieldCodec<short>, IDeepCopier<short>
{
private static readonly Type CodecFieldType = typeof(short);
void IFieldCodec<short>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer,
uint fieldIdDelta,
Type expectedType,
short value) => WriteField(ref writer, fieldIdDelta, expectedType, value);
public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, short value) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.VarInt);
writer.WriteVarInt16(value);
}
public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, short value, Type actualType) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
writer.WriteFieldHeader(fieldIdDelta, expectedType, actualType, WireType.VarInt);
writer.WriteVarInt16(value);
}
short IFieldCodec<short>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) => ReadValue(ref reader, field);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static short ReadValue<TInput>(ref Reader<TInput> reader, Field field)
{
ReferenceCodec.MarkValueField(reader.Session);
return reader.ReadInt16(field.WireType);
}
public short DeepCopy(short input, CopyContext _) => input;
}
[RegisterSerializer]
[RegisterCopier]
public sealed class UInt32Codec : TypedCodecBase<uint, UInt32Codec>, IFieldCodec<uint>, IDeepCopier<uint>
{
private static readonly Type CodecFieldType = typeof(uint);
void IFieldCodec<uint>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer,
uint fieldIdDelta,
Type expectedType,
uint value) => WriteField(ref writer, fieldIdDelta, expectedType, value);
public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, uint value) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
if (value > 1 << 20)
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.Fixed32);
writer.WriteUInt32(value);
}
else
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.VarInt);
writer.WriteVarUInt32(value);
}
}
public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, uint value, Type actualType) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
if (value > 1 << 20)
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, actualType, WireType.Fixed32);
writer.WriteUInt32(value);
}
else
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, actualType, WireType.VarInt);
writer.WriteVarUInt32(value);
}
}
uint IFieldCodec<uint>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) => ReadValue(ref reader, field);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint ReadValue<TInput>(ref Reader<TInput> reader, Field field)
{
ReferenceCodec.MarkValueField(reader.Session);
return reader.ReadUInt32(field.WireType);
}
public uint DeepCopy(uint input, CopyContext _) => input;
}
[RegisterSerializer]
[RegisterCopier]
public sealed class Int32Codec : TypedCodecBase<int, Int32Codec>, IFieldCodec<int>, IDeepCopier<int>
{
public static readonly Type CodecFieldType = typeof(int);
void IFieldCodec<int>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer,
uint fieldIdDelta,
Type expectedType,
int value)
{
ReferenceCodec.MarkValueField(writer.Session);
if (value > 1 << 20 || -value > 1 << 20)
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.Fixed32);
writer.WriteInt32(value);
}
else
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.VarInt);
writer.WriteVarInt32(value);
}
}
public static void WriteField<TBufferWriter>(
ref Writer<TBufferWriter> writer,
uint fieldIdDelta,
Type expectedType,
int value) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
if (value > 1 << 20 || -value > 1 << 20)
{
writer.WriteFieldHeaderExpected(fieldIdDelta, WireType.Fixed32);
writer.WriteInt32(value);
}
else
{
writer.WriteFieldHeaderExpected(fieldIdDelta, WireType.VarInt);
writer.WriteVarInt32(value);
}
}
public static void WriteField<TBufferWriter>(
ref Writer<TBufferWriter> writer,
uint fieldIdDelta,
Type expectedType,
int value,
Type actualType) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
if (value > 1 << 20 || -value > 1 << 20)
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, actualType, WireType.Fixed32);
writer.WriteInt32(value);
}
else
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, actualType, WireType.VarInt);
writer.WriteVarInt32(value);
}
}
int IFieldCodec<int>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) => ReadValue(ref reader, field);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int ReadValue<TInput>(ref Reader<TInput> reader, Field field)
{
ReferenceCodec.MarkValueField(reader.Session);
return reader.ReadInt32(field.WireType);
}
public int DeepCopy(int input, CopyContext _) => input;
}
[RegisterSerializer]
[RegisterCopier]
public sealed class Int64Codec : TypedCodecBase<long, Int64Codec>, IFieldCodec<long>, IDeepCopier<long>
{
private static readonly Type CodecFieldType = typeof(long);
void IFieldCodec<long>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, long value) => WriteField(ref writer, fieldIdDelta, expectedType, value);
public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, long value) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
if (value <= int.MaxValue && value >= int.MinValue)
{
if (value > 1 << 20 || -value > 1 << 20)
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.Fixed32);
writer.WriteInt32((int)value);
}
else
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.VarInt);
writer.WriteVarInt64(value);
}
}
else if (value > 1 << 41 || -value > 1 << 41)
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.Fixed64);
writer.WriteInt64(value);
}
else
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.VarInt);
writer.WriteVarInt64(value);
}
}
public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, long value, Type actualType) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
if (value <= int.MaxValue && value >= int.MinValue)
{
if (value > 1 << 20 || -value > 1 << 20)
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, actualType, WireType.Fixed32);
writer.WriteInt32((int)value);
}
else
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, actualType, WireType.VarInt);
writer.WriteVarInt64(value);
}
}
else if (value > 1 << 41 || -value > 1 << 41)
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, actualType, WireType.Fixed64);
writer.WriteInt64(value);
}
else
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, actualType, WireType.VarInt);
writer.WriteVarInt64(value);
}
}
long IFieldCodec<long>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) => ReadValue(ref reader, field);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static long ReadValue<TInput>(ref Reader<TInput> reader, Field field)
{
ReferenceCodec.MarkValueField(reader.Session);
return reader.ReadInt64(field.WireType);
}
public long DeepCopy(long input, CopyContext _) => input;
}
[RegisterSerializer]
[RegisterCopier]
public sealed class UInt64Codec : TypedCodecBase<ulong, UInt64Codec>, IFieldCodec<ulong>, IDeepCopier<ulong>
{
private static readonly Type CodecFieldType = typeof(ulong);
void IFieldCodec<ulong>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer,
uint fieldIdDelta,
Type expectedType,
ulong value) => WriteField(ref writer, fieldIdDelta, expectedType, value);
public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, ulong value) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
if (value <= int.MaxValue)
{
if (value > 1 << 20)
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.Fixed32);
writer.WriteUInt32((uint)value);
}
else
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.VarInt);
writer.WriteVarUInt64(value);
}
}
else if (value > 1 << 41)
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.Fixed64);
writer.WriteUInt64(value);
}
else
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecFieldType, WireType.VarInt);
writer.WriteVarUInt64(value);
}
}
public static void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, ulong value, Type actualType) where TBufferWriter : IBufferWriter<byte>
{
ReferenceCodec.MarkValueField(writer.Session);
if (value <= int.MaxValue)
{
if (value > 1 << 20)
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, actualType, WireType.Fixed32);
writer.WriteUInt32((uint)value);
}
else
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, actualType, WireType.VarInt);
writer.WriteVarUInt64(value);
}
}
else if (value > 1 << 41)
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, actualType, WireType.Fixed64);
writer.WriteUInt64(value);
}
else
{
writer.WriteFieldHeader(fieldIdDelta, expectedType, actualType, WireType.VarInt);
writer.WriteVarUInt64(value);
}
}
ulong IFieldCodec<ulong>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) => ReadValue(ref reader, field);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong ReadValue<TInput>(ref Reader<TInput> reader, Field field)
{
ReferenceCodec.MarkValueField(reader.Session);
return reader.ReadUInt64(field.WireType);
}
public ulong DeepCopy(ulong input, CopyContext _) => input;
}
}
| |
/*
* Copyright (c) 2006-2016, openmetaverse.co
* 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.
* - Neither the name of the openmetaverse.co nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.IO;
using System.Xml;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenMetaverse.Http;
using OpenMetaverse.Interfaces;
using OpenMetaverse.Messages.Linden;
namespace OpenMetaverse.Utilities
{
public enum VoiceStatus
{
StatusLoginRetry,
StatusLoggedIn,
StatusJoining,
StatusJoined,
StatusLeftChannel,
BeginErrorStatus,
ErrorChannelFull,
ErrorChannelLocked,
ErrorNotAvailable,
ErrorUnknown
}
public enum VoiceServiceType
{
/// <summary>Unknown voice service level</summary>
Unknown,
/// <summary>Spatialized local chat</summary>
TypeA,
/// <summary>Remote multi-party chat</summary>
TypeB,
/// <summary>One-to-one and small group chat</summary>
TypeC
}
public partial class VoiceManager
{
public const int VOICE_MAJOR_VERSION = 1;
public const string DAEMON_ARGS = " -p tcp -h -c -ll ";
public const int DAEMON_LOG_LEVEL = 1;
public const int DAEMON_PORT = 44124;
public const string VOICE_RELEASE_SERVER = "bhr.vivox.com";
public const string VOICE_DEBUG_SERVER = "bhd.vivox.com";
public const string REQUEST_TERMINATOR = "\n\n\n";
public delegate void LoginStateChangeCallback(int cookie, string accountHandle, int statusCode, string statusString, int state);
public delegate void NewSessionCallback(int cookie, string accountHandle, string eventSessionHandle, int state, string nameString, string uriString);
public delegate void SessionStateChangeCallback(int cookie, string uriString, int statusCode, string statusString, string eventSessionHandle, int state, bool isChannel, string nameString);
public delegate void ParticipantStateChangeCallback(int cookie, string uriString, int statusCode, string statusString, int state, string nameString, string displayNameString, int participantType);
public delegate void ParticipantPropertiesCallback(int cookie, string uriString, int statusCode, string statusString, bool isLocallyMuted, bool isModeratorMuted, bool isSpeaking, int volume, float energy);
public delegate void AuxAudioPropertiesCallback(int cookie, float energy);
public delegate void BasicActionCallback(int cookie, int statusCode, string statusString);
public delegate void ConnectorCreatedCallback(int cookie, int statusCode, string statusString, string connectorHandle);
public delegate void LoginCallback(int cookie, int statusCode, string statusString, string accountHandle);
public delegate void SessionCreatedCallback(int cookie, int statusCode, string statusString, string sessionHandle);
public delegate void DevicesCallback(int cookie, int statusCode, string statusString, string currentDevice);
public delegate void ProvisionAccountCallback(string username, string password);
public delegate void ParcelVoiceInfoCallback(string regionName, int localID, string channelURI);
public event LoginStateChangeCallback OnLoginStateChange;
public event NewSessionCallback OnNewSession;
public event SessionStateChangeCallback OnSessionStateChange;
public event ParticipantStateChangeCallback OnParticipantStateChange;
public event ParticipantPropertiesCallback OnParticipantProperties;
public event AuxAudioPropertiesCallback OnAuxAudioProperties;
public event ConnectorCreatedCallback OnConnectorCreated;
public event LoginCallback OnLogin;
public event SessionCreatedCallback OnSessionCreated;
public event BasicActionCallback OnSessionConnected;
public event BasicActionCallback OnAccountLogout;
public event BasicActionCallback OnConnectorInitiateShutdown;
public event BasicActionCallback OnAccountChannelGetList;
public event BasicActionCallback OnSessionTerminated;
public event DevicesCallback OnCaptureDevices;
public event DevicesCallback OnRenderDevices;
public event ProvisionAccountCallback OnProvisionAccount;
public event ParcelVoiceInfoCallback OnParcelVoiceInfo;
public GridClient Client;
public string VoiceServer = VOICE_RELEASE_SERVER;
public bool Enabled;
protected Voice.TCPPipe _DaemonPipe;
protected VoiceStatus _Status;
protected int _CommandCookie = 0;
protected string _TuningSoundFile = String.Empty;
protected Dictionary<string, string> _ChannelMap = new Dictionary<string, string>();
protected List<string> _CaptureDevices = new List<string>();
protected List<string> _RenderDevices = new List<string>();
#region Response Processing Variables
private bool isEvent = false;
private bool isChannel = false;
private bool isLocallyMuted = false;
private bool isModeratorMuted = false;
private bool isSpeaking = false;
private int cookie = 0;
//private int returnCode = 0;
private int statusCode = 0;
private int volume = 0;
private int state = 0;
private int participantType = 0;
private float energy = 0f;
private string statusString = String.Empty;
//private string uuidString = String.Empty;
private string actionString = String.Empty;
private string connectorHandle = String.Empty;
private string accountHandle = String.Empty;
private string sessionHandle = String.Empty;
private string eventSessionHandle = String.Empty;
private string eventTypeString = String.Empty;
private string uriString = String.Empty;
private string nameString = String.Empty;
//private string audioMediaString = String.Empty;
private string displayNameString = String.Empty;
#endregion Response Processing Variables
public VoiceManager(GridClient client)
{
Client = client;
Client.Network.RegisterEventCallback("RequiredVoiceVersion", new Caps.EventQueueCallback(RequiredVoiceVersionEventHandler));
// Register callback handlers for the blocking functions
RegisterCallbacks();
Enabled = true;
}
public bool IsDaemonRunning()
{
throw new NotImplementedException();
}
public bool StartDaemon()
{
throw new NotImplementedException();
}
public void StopDaemon()
{
throw new NotImplementedException();
}
public bool ConnectToDaemon()
{
if (!Enabled) return false;
return ConnectToDaemon("127.0.0.1", DAEMON_PORT);
}
public bool ConnectToDaemon(string address, int port)
{
if (!Enabled) return false;
_DaemonPipe = new Voice.TCPPipe();
_DaemonPipe.OnDisconnected += new Voice.TCPPipe.OnDisconnectedCallback(_DaemonPipe_OnDisconnected);
_DaemonPipe.OnReceiveLine += new Voice.TCPPipe.OnReceiveLineCallback(_DaemonPipe_OnReceiveLine);
SocketException se = _DaemonPipe.Connect(address, port);
if (se == null)
{
return true;
}
else
{
Console.WriteLine("Connection failed: " + se.Message);
return false;
}
}
public Dictionary<string, string> GetChannelMap()
{
return new Dictionary<string, string>(_ChannelMap);
}
public List<string> CurrentCaptureDevices()
{
return new List<string>(_CaptureDevices);
}
public List<string> CurrentRenderDevices()
{
return new List<string>(_RenderDevices);
}
public string VoiceAccountFromUUID(UUID id)
{
string result = "x" + Convert.ToBase64String(id.GetBytes());
return result.Replace('+', '-').Replace('/', '_');
}
public UUID UUIDFromVoiceAccount(string accountName)
{
if (accountName.Length == 25 && accountName[0] == 'x' && accountName[23] == '=' && accountName[24] == '=')
{
accountName = accountName.Replace('/', '_').Replace('+', '-');
byte[] idBytes = Convert.FromBase64String(accountName);
if (idBytes.Length == 16)
return new UUID(idBytes, 0);
else
return UUID.Zero;
}
else
{
return UUID.Zero;
}
}
public string SIPURIFromVoiceAccount(string account)
{
return String.Format("sip:{0}@{1}", account, VoiceServer);
}
public int RequestCaptureDevices()
{
if (_DaemonPipe.Connected)
{
_DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format(
"<Request requestId=\"{0}\" action=\"Aux.GetCaptureDevices.1\"></Request>{1}",
_CommandCookie++,
REQUEST_TERMINATOR)));
return _CommandCookie - 1;
}
else
{
Logger.Log("VoiceManager.RequestCaptureDevices() called when the daemon pipe is disconnected", Helpers.LogLevel.Error, Client);
return -1;
}
}
public int RequestRenderDevices()
{
if (_DaemonPipe.Connected)
{
_DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format(
"<Request requestId=\"{0}\" action=\"Aux.GetRenderDevices.1\"></Request>{1}",
_CommandCookie++,
REQUEST_TERMINATOR)));
return _CommandCookie - 1;
}
else
{
Logger.Log("VoiceManager.RequestRenderDevices() called when the daemon pipe is disconnected", Helpers.LogLevel.Error, Client);
return -1;
}
}
public int RequestCreateConnector()
{
return RequestCreateConnector(VoiceServer);
}
public int RequestCreateConnector(string voiceServer)
{
if (_DaemonPipe.Connected)
{
VoiceServer = voiceServer;
string accountServer = String.Format("https://www.{0}/api2/", VoiceServer);
string logPath = ".";
StringBuilder request = new StringBuilder();
request.Append(String.Format("<Request requestId=\"{0}\" action=\"Connector.Create.1\">", _CommandCookie++));
request.Append("<ClientName>V2 SDK</ClientName>");
request.Append(String.Format("<AccountManagementServer>{0}</AccountManagementServer>", accountServer));
request.Append("<Logging>");
request.Append("<Enabled>false</Enabled>");
request.Append(String.Format("<Folder>{0}</Folder>", logPath));
request.Append("<FileNamePrefix>vivox-gateway</FileNamePrefix>");
request.Append("<FileNameSuffix>.log</FileNameSuffix>");
request.Append("<LogLevel>0</LogLevel>");
request.Append("</Logging>");
request.Append("</Request>");
request.Append(REQUEST_TERMINATOR);
_DaemonPipe.SendData(Encoding.ASCII.GetBytes(request.ToString()));
return _CommandCookie - 1;
}
else
{
Logger.Log("VoiceManager.CreateConnector() called when the daemon pipe is disconnected", Helpers.LogLevel.Error, Client);
return -1;
}
}
private bool RequestVoiceInternal(string me, CapsClient.CompleteCallback callback, string capsName)
{
if (Enabled && Client.Network.Connected)
{
if (Client.Network.CurrentSim != null && Client.Network.CurrentSim.Caps != null)
{
Uri url = Client.Network.CurrentSim.Caps.CapabilityURI(capsName);
if (url != null)
{
CapsClient request = new CapsClient(url);
OSDMap body = new OSDMap();
request.OnComplete += new CapsClient.CompleteCallback(callback);
request.BeginGetResponse(body, OSDFormat.Xml, Client.Settings.CAPS_TIMEOUT);
return true;
}
else
{
Logger.Log("VoiceManager." + me + "(): " + capsName + " capability is missing",
Helpers.LogLevel.Info, Client);
return false;
}
}
}
Logger.Log("VoiceManager.RequestVoiceInternal(): Voice system is currently disabled",
Helpers.LogLevel.Info, Client);
return false;
}
public bool RequestProvisionAccount()
{
return RequestVoiceInternal("RequestProvisionAccount", ProvisionCapsResponse, "ProvisionVoiceAccountRequest");
}
public bool RequestParcelVoiceInfo()
{
return RequestVoiceInternal("RequestParcelVoiceInfo", ParcelVoiceInfoResponse, "ParcelVoiceInfoRequest");
}
public int RequestLogin(string accountName, string password, string connectorHandle)
{
if (_DaemonPipe.Connected)
{
StringBuilder request = new StringBuilder();
request.Append(String.Format("<Request requestId=\"{0}\" action=\"Account.Login.1\">", _CommandCookie++));
request.Append(String.Format("<ConnectorHandle>{0}</ConnectorHandle>", connectorHandle));
request.Append(String.Format("<AccountName>{0}</AccountName>", accountName));
request.Append(String.Format("<AccountPassword>{0}</AccountPassword>", password));
request.Append("<AudioSessionAnswerMode>VerifyAnswer</AudioSessionAnswerMode>");
request.Append("<AccountURI />");
request.Append("<ParticipantPropertyFrequency>10</ParticipantPropertyFrequency>");
request.Append("<EnableBuddiesAndPresence>false</EnableBuddiesAndPresence>");
request.Append("</Request>");
request.Append(REQUEST_TERMINATOR);
_DaemonPipe.SendData(Encoding.ASCII.GetBytes(request.ToString()));
return _CommandCookie - 1;
}
else
{
Logger.Log("VoiceManager.Login() called when the daemon pipe is disconnected", Helpers.LogLevel.Error, Client);
return -1;
}
}
public int RequestSetRenderDevice(string deviceName)
{
if (_DaemonPipe.Connected)
{
_DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format(
"<Request requestId=\"{0}\" action=\"Aux.SetRenderDevice.1\"><RenderDeviceSpecifier>{1}</RenderDeviceSpecifier></Request>{2}",
_CommandCookie, deviceName, REQUEST_TERMINATOR)));
return _CommandCookie - 1;
}
else
{
Logger.Log("VoiceManager.RequestSetRenderDevice() called when the daemon pipe is disconnected", Helpers.LogLevel.Error, Client);
return -1;
}
}
public int RequestStartTuningMode(int duration)
{
if (_DaemonPipe.Connected)
{
_DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format(
"<Request requestId=\"{0}\" action=\"Aux.CaptureAudioStart.1\"><Duration>{1}</Duration></Request>{2}",
_CommandCookie, duration, REQUEST_TERMINATOR)));
return _CommandCookie - 1;
}
else
{
Logger.Log("VoiceManager.RequestStartTuningMode() called when the daemon pipe is disconnected", Helpers.LogLevel.Error, Client);
return -1;
}
}
public int RequestStopTuningMode()
{
if (_DaemonPipe.Connected)
{
_DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format(
"<Request requestId=\"{0}\" action=\"Aux.CaptureAudioStop.1\"></Request>{1}",
_CommandCookie, REQUEST_TERMINATOR)));
return _CommandCookie - 1;
}
else
{
Logger.Log("VoiceManager.RequestStopTuningMode() called when the daemon pipe is disconnected", Helpers.LogLevel.Error, Client);
return _CommandCookie - 1;
}
}
public int RequestSetSpeakerVolume(int volume)
{
if (volume < 0 || volume > 100)
throw new ArgumentException("volume must be between 0 and 100", "volume");
if (_DaemonPipe.Connected)
{
_DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format(
"<Request requestId=\"{0}\" action=\"Aux.SetSpeakerLevel.1\"><Level>{1}</Level></Request>{2}",
_CommandCookie, volume, REQUEST_TERMINATOR)));
return _CommandCookie - 1;
}
else
{
Logger.Log("VoiceManager.RequestSetSpeakerVolume() called when the daemon pipe is disconnected", Helpers.LogLevel.Error, Client);
return -1;
}
}
public int RequestSetCaptureVolume(int volume)
{
if (volume < 0 || volume > 100)
throw new ArgumentException("volume must be between 0 and 100", "volume");
if (_DaemonPipe.Connected)
{
_DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format(
"<Request requestId=\"{0}\" action=\"Aux.SetMicLevel.1\"><Level>{1}</Level></Request>{2}",
_CommandCookie, volume, REQUEST_TERMINATOR)));
return _CommandCookie - 1;
}
else
{
Logger.Log("VoiceManager.RequestSetCaptureVolume() called when the daemon pipe is disconnected", Helpers.LogLevel.Error, Client);
return -1;
}
}
/// <summary>
/// Does not appear to be working
/// </summary>
/// <param name="fileName"></param>
/// <param name="loop"></param>
public int RequestRenderAudioStart(string fileName, bool loop)
{
if (_DaemonPipe.Connected)
{
_TuningSoundFile = fileName;
_DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format(
"<Request requestId=\"{0}\" action=\"Aux.RenderAudioStart.1\"><SoundFilePath>{1}</SoundFilePath><Loop>{2}</Loop></Request>{3}",
_CommandCookie++, _TuningSoundFile, (loop ? "1" : "0"), REQUEST_TERMINATOR)));
return _CommandCookie - 1;
}
else
{
Logger.Log("VoiceManager.RequestRenderAudioStart() called when the daemon pipe is disconnected", Helpers.LogLevel.Error, Client);
return -1;
}
}
public int RequestRenderAudioStop()
{
if (_DaemonPipe.Connected)
{
_DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format(
"<Request requestId=\"{0}\" action=\"Aux.RenderAudioStop.1\"><SoundFilePath>{1}</SoundFilePath></Request>{2}",
_CommandCookie++, _TuningSoundFile, REQUEST_TERMINATOR)));
return _CommandCookie - 1;
}
else
{
Logger.Log("VoiceManager.RequestRenderAudioStop() called when the daemon pipe is disconnected", Helpers.LogLevel.Error, Client);
return -1;
}
}
#region Callbacks
private void RequiredVoiceVersionEventHandler(string capsKey, IMessage message, Simulator simulator)
{
RequiredVoiceVersionMessage msg = (RequiredVoiceVersionMessage)message;
if (VOICE_MAJOR_VERSION != msg.MajorVersion)
{
Logger.Log(String.Format("Voice version mismatch! Got {0}, expecting {1}. Disabling the voice manager",
msg.MajorVersion, VOICE_MAJOR_VERSION), Helpers.LogLevel.Error, Client);
Enabled = false;
}
else
{
Logger.DebugLog("Voice version " + msg.MajorVersion + " verified", Client);
}
}
private void ProvisionCapsResponse(CapsClient client, OSD response, Exception error)
{
if (response is OSDMap)
{
OSDMap respTable = (OSDMap)response;
if (OnProvisionAccount != null)
{
try { OnProvisionAccount(respTable["username"].AsString(), respTable["password"].AsString()); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
}
private void ParcelVoiceInfoResponse(CapsClient client, OSD response, Exception error)
{
if (response is OSDMap)
{
OSDMap respTable = (OSDMap)response;
string regionName = respTable["region_name"].AsString();
int localID = (int)respTable["parcel_local_id"].AsInteger();
string channelURI = null;
if (respTable["voice_credentials"] is OSDMap)
{
OSDMap creds = (OSDMap)respTable["voice_credentials"];
channelURI = creds["channel_uri"].AsString();
}
if (OnParcelVoiceInfo != null) OnParcelVoiceInfo(regionName, localID, channelURI);
}
}
private void _DaemonPipe_OnDisconnected(SocketException se)
{
if (se != null) Console.WriteLine("Disconnected! " + se.Message);
else Console.WriteLine("Disconnected!");
}
private void _DaemonPipe_OnReceiveLine(string line)
{
XmlTextReader reader = new XmlTextReader(new StringReader(line));
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
{
if (reader.Depth == 0)
{
isEvent = (reader.Name == "Event");
if (isEvent || reader.Name == "Response")
{
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
switch (reader.Name)
{
// case "requestId":
// uuidString = reader.Value;
// break;
case "action":
actionString = reader.Value;
break;
case "type":
eventTypeString = reader.Value;
break;
}
}
}
}
else
{
switch (reader.Name)
{
case "InputXml":
cookie = -1;
// Parse through here to get the cookie value
reader.Read();
if (reader.Name == "Request")
{
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
if (reader.Name == "requestId")
{
Int32.TryParse(reader.Value, out cookie);
break;
}
}
}
if (cookie == -1)
{
Logger.Log("VoiceManager._DaemonPipe_OnReceiveLine(): Failed to parse InputXml for the cookie",
Helpers.LogLevel.Warning, Client);
}
break;
case "CaptureDevices":
_CaptureDevices.Clear();
break;
case "RenderDevices":
_RenderDevices.Clear();
break;
// case "ReturnCode":
// returnCode = reader.ReadElementContentAsInt();
// break;
case "StatusCode":
statusCode = reader.ReadElementContentAsInt();
break;
case "StatusString":
statusString = reader.ReadElementContentAsString();
break;
case "State":
state = reader.ReadElementContentAsInt();
break;
case "ConnectorHandle":
connectorHandle = reader.ReadElementContentAsString();
break;
case "AccountHandle":
accountHandle = reader.ReadElementContentAsString();
break;
case "SessionHandle":
sessionHandle = reader.ReadElementContentAsString();
break;
case "URI":
uriString = reader.ReadElementContentAsString();
break;
case "IsChannel":
isChannel = reader.ReadElementContentAsBoolean();
break;
case "Name":
nameString = reader.ReadElementContentAsString();
break;
// case "AudioMedia":
// audioMediaString = reader.ReadElementContentAsString();
// break;
case "ChannelName":
nameString = reader.ReadElementContentAsString();
break;
case "ParticipantURI":
uriString = reader.ReadElementContentAsString();
break;
case "DisplayName":
displayNameString = reader.ReadElementContentAsString();
break;
case "AccountName":
nameString = reader.ReadElementContentAsString();
break;
case "ParticipantType":
participantType = reader.ReadElementContentAsInt();
break;
case "IsLocallyMuted":
isLocallyMuted = reader.ReadElementContentAsBoolean();
break;
case "IsModeratorMuted":
isModeratorMuted = reader.ReadElementContentAsBoolean();
break;
case "IsSpeaking":
isSpeaking = reader.ReadElementContentAsBoolean();
break;
case "Volume":
volume = reader.ReadElementContentAsInt();
break;
case "Energy":
energy = reader.ReadElementContentAsFloat();
break;
case "MicEnergy":
energy = reader.ReadElementContentAsFloat();
break;
case "ChannelURI":
uriString = reader.ReadElementContentAsString();
break;
case "ChannelListResult":
_ChannelMap[nameString] = uriString;
break;
case "CaptureDevice":
reader.Read();
_CaptureDevices.Add(reader.ReadElementContentAsString());
break;
case "CurrentCaptureDevice":
reader.Read();
nameString = reader.ReadElementContentAsString();
break;
case "RenderDevice":
reader.Read();
_RenderDevices.Add(reader.ReadElementContentAsString());
break;
case "CurrentRenderDevice":
reader.Read();
nameString = reader.ReadElementContentAsString();
break;
}
}
break;
}
case XmlNodeType.EndElement:
if (reader.Depth == 0)
ProcessEvent();
break;
}
}
if (isEvent)
{
}
//Client.DebugLog("VOICE: " + line);
}
private void ProcessEvent()
{
if (isEvent)
{
switch (eventTypeString)
{
case "LoginStateChangeEvent":
if (OnLoginStateChange != null) OnLoginStateChange(cookie, accountHandle, statusCode, statusString, state);
break;
case "SessionNewEvent":
if (OnNewSession != null) OnNewSession(cookie, accountHandle, eventSessionHandle, state, nameString, uriString);
break;
case "SessionStateChangeEvent":
if (OnSessionStateChange != null) OnSessionStateChange(cookie, uriString, statusCode, statusString, eventSessionHandle, state, isChannel, nameString);
break;
case "ParticipantStateChangeEvent":
if (OnParticipantStateChange != null) OnParticipantStateChange(cookie, uriString, statusCode, statusString, state, nameString, displayNameString, participantType);
break;
case "ParticipantPropertiesEvent":
if (OnParticipantProperties != null) OnParticipantProperties(cookie, uriString, statusCode, statusString, isLocallyMuted, isModeratorMuted, isSpeaking, volume, energy);
break;
case "AuxAudioPropertiesEvent":
if (OnAuxAudioProperties != null) OnAuxAudioProperties(cookie, energy);
break;
}
}
else
{
switch (actionString)
{
case "Connector.Create.1":
if (OnConnectorCreated != null) OnConnectorCreated(cookie, statusCode, statusString, connectorHandle);
break;
case "Account.Login.1":
if (OnLogin != null) OnLogin(cookie, statusCode, statusString, accountHandle);
break;
case "Session.Create.1":
if (OnSessionCreated != null) OnSessionCreated(cookie, statusCode, statusString, sessionHandle);
break;
case "Session.Connect.1":
if (OnSessionConnected != null) OnSessionConnected(cookie, statusCode, statusString);
break;
case "Session.Terminate.1":
if (OnSessionTerminated != null) OnSessionTerminated(cookie, statusCode, statusString);
break;
case "Account.Logout.1":
if (OnAccountLogout != null) OnAccountLogout(cookie, statusCode, statusString);
break;
case "Connector.InitiateShutdown.1":
if (OnConnectorInitiateShutdown != null) OnConnectorInitiateShutdown(cookie, statusCode, statusString);
break;
case "Account.ChannelGetList.1":
if (OnAccountChannelGetList != null) OnAccountChannelGetList(cookie, statusCode, statusString);
break;
case "Aux.GetCaptureDevices.1":
if (OnCaptureDevices != null) OnCaptureDevices(cookie, statusCode, statusString, nameString);
break;
case "Aux.GetRenderDevices.1":
if (OnRenderDevices != null) OnRenderDevices(cookie, statusCode, statusString, nameString);
break;
}
}
}
#endregion Callbacks
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A quaternion of type T.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct gquat<T> : IEnumerable<T>, IEquatable<gquat<T>>
{
#region Fields
/// <summary>
/// x-component
/// </summary>
public T x;
/// <summary>
/// y-component
/// </summary>
public T y;
/// <summary>
/// z-component
/// </summary>
public T z;
/// <summary>
/// w-component
/// </summary>
public T w;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public gquat(T x, T y, T z, T w)
{
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/// <summary>
/// all-same-value constructor
/// </summary>
public gquat(T v)
{
this.x = v;
this.y = v;
this.z = v;
this.w = v;
}
/// <summary>
/// copy constructor
/// </summary>
public gquat(gquat<T> q)
{
this.x = q.x;
this.y = q.y;
this.z = q.z;
this.w = q.w;
}
/// <summary>
/// vector-and-scalar constructor (CAUTION: not angle-axis, use FromAngleAxis instead)
/// </summary>
public gquat(gvec3<T> v, T s)
{
this.x = v.x;
this.y = v.y;
this.z = v.z;
this.w = s;
}
#endregion
#region Explicit Operators
/// <summary>
/// Explicitly converts this to a gvec4.
/// </summary>
public static explicit operator gvec4<T>(gquat<T> v) => new gvec4<T>((T)v.x, (T)v.y, (T)v.z, (T)v.w);
#endregion
#region Indexer
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public T this[int index]
{
get
{
switch (index)
{
case 0: return x;
case 1: return y;
case 2: return z;
case 3: return w;
default: throw new ArgumentOutOfRangeException("index");
}
}
set
{
switch (index)
{
case 0: x = value; break;
case 1: y = value; break;
case 2: z = value; break;
case 3: w = value; break;
default: throw new ArgumentOutOfRangeException("index");
}
}
}
#endregion
#region Properties
/// <summary>
/// Returns an array with all values
/// </summary>
public T[] Values => new[] { x, y, z, w };
/// <summary>
/// Returns the number of components (4).
/// </summary>
public int Count => 4;
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero quaternion
/// </summary>
public static gquat<T> Zero { get; } = new gquat<T>(default(T), default(T), default(T), default(T));
#endregion
#region Operators
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator==(gquat<T> lhs, gquat<T> rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator!=(gquat<T> lhs, gquat<T> rhs) => !lhs.Equals(rhs);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all components.
/// </summary>
public IEnumerator<T> GetEnumerator()
{
yield return x;
yield return y;
yield return z;
yield return w;
}
/// <summary>
/// Returns an enumerator that iterates through all components.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <summary>
/// Returns a string representation of this quaternion using ', ' as a seperator.
/// </summary>
public override string ToString() => ToString(", ");
/// <summary>
/// Returns a string representation of this quaternion using a provided seperator.
/// </summary>
public string ToString(string sep) => ((x + sep + y) + sep + (z + sep + w));
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(gquat<T> rhs) => ((EqualityComparer<T>.Default.Equals(x, rhs.x) && EqualityComparer<T>.Default.Equals(y, rhs.y)) && (EqualityComparer<T>.Default.Equals(z, rhs.z) && EqualityComparer<T>.Default.Equals(w, rhs.w)));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is gquat<T> && Equals((gquat<T>) obj);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((EqualityComparer<T>.Default.GetHashCode(x)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(y)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(z)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(w);
}
}
#endregion
#region Component-Wise Static Functions
/// <summary>
/// Returns a bvec4 from component-wise application of Equal (EqualityComparer<T>.Default.Equals(lhs, rhs)).
/// </summary>
public static bvec4 Equal(gquat<T> lhs, gquat<T> rhs) => new bvec4(EqualityComparer<T>.Default.Equals(lhs.x, rhs.x), EqualityComparer<T>.Default.Equals(lhs.y, rhs.y), EqualityComparer<T>.Default.Equals(lhs.z, rhs.z), EqualityComparer<T>.Default.Equals(lhs.w, rhs.w));
/// <summary>
/// Returns a bvec4 from component-wise application of Equal (EqualityComparer<T>.Default.Equals(lhs, rhs)).
/// </summary>
public static bvec4 Equal(gquat<T> lhs, T rhs) => new bvec4(EqualityComparer<T>.Default.Equals(lhs.x, rhs), EqualityComparer<T>.Default.Equals(lhs.y, rhs), EqualityComparer<T>.Default.Equals(lhs.z, rhs), EqualityComparer<T>.Default.Equals(lhs.w, rhs));
/// <summary>
/// Returns a bvec4 from component-wise application of Equal (EqualityComparer<T>.Default.Equals(lhs, rhs)).
/// </summary>
public static bvec4 Equal(T lhs, gquat<T> rhs) => new bvec4(EqualityComparer<T>.Default.Equals(lhs, rhs.x), EqualityComparer<T>.Default.Equals(lhs, rhs.y), EqualityComparer<T>.Default.Equals(lhs, rhs.z), EqualityComparer<T>.Default.Equals(lhs, rhs.w));
/// <summary>
/// Returns a bvec from the application of Equal (EqualityComparer<T>.Default.Equals(lhs, rhs)).
/// </summary>
public static bvec4 Equal(T lhs, T rhs) => new bvec4(EqualityComparer<T>.Default.Equals(lhs, rhs));
/// <summary>
/// Returns a bvec4 from component-wise application of NotEqual (!EqualityComparer<T>.Default.Equals(lhs, rhs)).
/// </summary>
public static bvec4 NotEqual(gquat<T> lhs, gquat<T> rhs) => new bvec4(!EqualityComparer<T>.Default.Equals(lhs.x, rhs.x), !EqualityComparer<T>.Default.Equals(lhs.y, rhs.y), !EqualityComparer<T>.Default.Equals(lhs.z, rhs.z), !EqualityComparer<T>.Default.Equals(lhs.w, rhs.w));
/// <summary>
/// Returns a bvec4 from component-wise application of NotEqual (!EqualityComparer<T>.Default.Equals(lhs, rhs)).
/// </summary>
public static bvec4 NotEqual(gquat<T> lhs, T rhs) => new bvec4(!EqualityComparer<T>.Default.Equals(lhs.x, rhs), !EqualityComparer<T>.Default.Equals(lhs.y, rhs), !EqualityComparer<T>.Default.Equals(lhs.z, rhs), !EqualityComparer<T>.Default.Equals(lhs.w, rhs));
/// <summary>
/// Returns a bvec4 from component-wise application of NotEqual (!EqualityComparer<T>.Default.Equals(lhs, rhs)).
/// </summary>
public static bvec4 NotEqual(T lhs, gquat<T> rhs) => new bvec4(!EqualityComparer<T>.Default.Equals(lhs, rhs.x), !EqualityComparer<T>.Default.Equals(lhs, rhs.y), !EqualityComparer<T>.Default.Equals(lhs, rhs.z), !EqualityComparer<T>.Default.Equals(lhs, rhs.w));
/// <summary>
/// Returns a bvec from the application of NotEqual (!EqualityComparer<T>.Default.Equals(lhs, rhs)).
/// </summary>
public static bvec4 NotEqual(T lhs, T rhs) => new bvec4(!EqualityComparer<T>.Default.Equals(lhs, rhs));
#endregion
}
}
| |
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Globalization;
using Sitecore.StringExtensions;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using Revolver.Core.Formatting;
namespace Revolver.Core
{
[Serializable]
public class Context
{
private ItemUri _currentItemUri = null;
private string _lastGoodPath = string.Empty;
private StringDictionary _envVars = null;
private Dictionary<string, string> _customCommands = null;
private Dictionary<string, CommandArgs> _commandAliases;
[NonSerialized]
private CommandHandler _commandHandler = null;
private Stack<ItemUri> _pathStack = new Stack<ItemUri>();
public Item CurrentItem
{
get
{
Item item = null;
if (_currentItemUri != null)
{
// todo: check performance of below with lots of versions.
item = Database.GetItem(_currentItemUri);
if (item == null || !item.Versions.GetVersionNumbers().Select(x => x.Number).Contains(item.Version.Number))
// The version may have been deleted, try to get the latest version
item = CurrentDatabase.GetItem(_currentItemUri.ItemID, _currentItemUri.Language);
if (item == null)
// The item may have been deleted, try to get the parent
item = CurrentDatabase.GetItem(_lastGoodPath.Substring(0, _lastGoodPath.LastIndexOf("/")));
}
return item;
}
set
{
if (value != null)
{
_lastGoodPath = value.Paths.FullPath;
_currentItemUri = value.Uri;
}
}
}
public Database CurrentDatabase
{
get
{
if (_currentItemUri != null)
return Factory.GetDatabase(_currentItemUri.DatabaseName);
return null;
}
set
{
if (value == null)
return;
var language = Sitecore.Context.Language;
if (_currentItemUri != null)
language = _currentItemUri.Language;
_currentItemUri = value.GetRootItem(language).Uri;
}
}
public Language CurrentLanguage
{
get
{
if (_currentItemUri != null)
return _currentItemUri.Language;
return null;
}
set
{
_currentItemUri = new ItemUri(_currentItemUri.ItemID, value, Sitecore.Data.Version.Latest, _currentItemUri.DatabaseName);
}
}
/// <summary>
/// Gets the last path that was valid that the context was on
/// </summary>
public string LastGoodPath
{
get { return _lastGoodPath; }
}
public CommandHandler CommandHandler
{
get { return _commandHandler; }
set { _commandHandler = value; }
}
public StringDictionary EnvironmentVariables
{
get { return _envVars; }
}
public Dictionary<string, string> CustomCommands
{
get { return _customCommands; }
set { _customCommands = value; }
}
public Dictionary<string, CommandArgs> CommandAliases
{
get { return _commandAliases; }
}
public Context()
{
if (Sitecore.Context.Site == null)
Sitecore.Context.SetActiveSite(Sitecore.Constants.ShellSiteName);
var db = Sitecore.Context.ContentDatabase ?? Sitecore.Context.Database;
_currentItemUri = db.GetRootItem(Sitecore.Context.Language).Uri;
// Initialise environment variables dictionary
_envVars = new StringDictionary();
_envVars.Add("prompt", "sc >");
_envVars.Add("outputbuffer", "1000000");
_customCommands = new Dictionary<string, string>();
_commandAliases = new Dictionary<string, CommandArgs>();
}
/// <summary>
/// Create a copy of this context
/// </summary>
/// <returns></returns>
public Context Clone()
{
return new Context()
{
_commandHandler = _commandHandler,
_currentItemUri = _currentItemUri,
_envVars = _envVars,
_lastGoodPath = _lastGoodPath,
_pathStack = _pathStack,
_customCommands = _customCommands,
_commandAliases = _commandAliases
};
}
/// <summary>
/// Save the current context (database and item) onto the stack.
/// </summary>
public void PushContext()
{
_pathStack.Push(_currentItemUri);
}
/// <summary>
/// Revert the context back to the previous database and item
/// </summary>
public void Revert()
{
if (_pathStack.Count > 0)
{
_currentItemUri = _pathStack.Pop();
}
}
public CommandResult ExecuteCommand(string commandLine, ICommandFormatter formatter)
{
if (_commandHandler == null)
_commandHandler = new CommandHandler(this, formatter);
return _commandHandler.Execute(commandLine);
}
/// <summary>
/// Set the given context to the given path
/// </summary>
/// <param name="path">The path to set the context from</param>
/// <param name="dbName">The databse to change to</param>
/// <param name="language">The language to change context to</param>
/// <param name="versionNumber">The version number to change context to</param>
/// <returns>A CommandResult indicating the status of the command</returns>
public CommandResult SetContext(string path, string dbName = null, Language language = null, int? versionNumber = null)
{
PushContext();
string workingPath = path;
// Determine if we're changing dbs.
if (string.IsNullOrEmpty(dbName))
dbName = CurrentDatabase.Name;
if (path.StartsWith("/") && path.Length > 1)
{
int ind = path.IndexOf('/', 2);
string pathDBName = string.Empty;
if (ind > 0)
pathDBName = path.Substring(1, ind - 1);
else
pathDBName = path.Substring(1);
// Loop through available dbs and see if we have a name match
string[] avNames = Factory.GetDatabaseNames();
for (int i = 0; i < avNames.Length; i++)
{
if (string.Compare(avNames[i], pathDBName, true) == 0)
{
dbName = avNames[i];
}
}
}
Database db = null;
if (CurrentDatabase.Name != dbName)
{
try
{
db = Factory.GetDatabase(dbName, true);
}
catch(InvalidOperationException)
{
// Couldn't find DB
db = null;
}
if (db == null)
{
Revert();
return new CommandResult(CommandStatus.Failure, "Failed to find database '{0}'".FormatWith(dbName));
}
else
CurrentDatabase = db;
}
if (workingPath.StartsWith("/" + dbName))
{
int ind = path.IndexOf('/', 2);
if (ind >= 0)
workingPath = path.Substring(ind);
else
workingPath = "/";
}
string itemPath = string.Empty;
int index = -1;
if (workingPath.StartsWith("{"))
itemPath = workingPath;
else
{
itemPath = PathParser.EvaluatePath(this, workingPath);
// Extract indexer if present
if (itemPath.Contains("["))
{
int startIndex = itemPath.IndexOf("[");
int endIndex = itemPath.LastIndexOf("]");
if ((endIndex > startIndex) && (endIndex < itemPath.Length))
{
string indexerString = itemPath.Substring(startIndex + 1, itemPath.Length - endIndex);
if (int.TryParse(indexerString, out index))
{
itemPath = itemPath.Substring(0, startIndex);
}
if (index < 0)
{
Revert();
return new CommandResult(CommandStatus.Failure, "Index must be non-negative");
}
}
}
}
string parsedLanguage = PathParser.ParseLanguageFromPath(workingPath);
if (string.IsNullOrEmpty(parsedLanguage))
{
if (language != null)
parsedLanguage = language.Name;
}
string version = PathParser.ParseVersionFromPath(workingPath);
if (string.IsNullOrEmpty(version))
{
if (versionNumber != null)
version = versionNumber.ToString();
}
Sitecore.Globalization.Language targetLanguage = null;
Sitecore.Data.Version targetVersion = null;
if (parsedLanguage != string.Empty)
{
if (!Sitecore.Globalization.Language.TryParse(parsedLanguage, out targetLanguage))
{
Revert();
return new CommandResult(CommandStatus.Failure, "Failed to parse language '{0}'".FormatWith(language));
}
}
else
targetLanguage = CurrentLanguage;
if (!string.IsNullOrEmpty(version))
{
// if version contains a negative number, take it as latest version minus that number
var parsedVersion = Sitecore.Data.Version.Latest.Number;
if (int.TryParse(version, out parsedVersion))
{
if (parsedVersion < 0)
{
var versionedItem = CurrentDatabase.GetItem(itemPath, targetLanguage);
if (versionedItem != null)
{
var versions = versionedItem.Versions.GetVersionNumbers();
var targetVersionIndex = versions.Length + parsedVersion - 1;
if (targetVersionIndex < 0 || targetVersionIndex > versions.Length - 1)
{
Revert();
return new CommandResult(CommandStatus.Failure, "Version index greater than number of versions.");
}
targetVersion = versions[targetVersionIndex];
}
}
else
targetVersion = Sitecore.Data.Version.Parse(parsedVersion);
}
else
{
Revert();
return new CommandResult(CommandStatus.Failure, "Failed to parse version '{0}'".FormatWith(version));
}
}
else
targetVersion = Sitecore.Data.Version.Latest;
var item = CurrentDatabase.GetItem(itemPath, targetLanguage, targetVersion);
if (item == null)
{
Revert();
return new CommandResult(CommandStatus.Failure, "Failed to find item '{0}'".FormatWith(itemPath));
}
else
{
// If indexer was specified, swap to indexed item
if (index >= 0)
{
if (itemPath.EndsWith("/"))
{
Sitecore.Collections.ChildList children = item.GetChildren();
if (index < children.Count)
item = children[index];
else
{
Revert();
return new CommandResult(CommandStatus.Failure, "Index greater than child count");
}
}
else
{
Sitecore.Collections.ChildList children = item.Parent.GetChildren();
int count = 0;
foreach (Item child in children)
{
if (child.Name == item.Name)
count++;
if (count == (index + 1))
{
item = child;
break;
}
}
if (count <= index)
{
Revert();
return new CommandResult(CommandStatus.Failure, "Index greater than named child count");
}
}
}
CurrentItem = item;
}
return new CommandResult(CommandStatus.Success, string.Empty);
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// NetworkInterfacesOperations operations.
/// </summary>
public partial interface INetworkInterfacesOperations
{
/// <summary>
/// Deletes the specified network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about the specified network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkInterface>> GetWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network interface
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkInterface>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route tables applied to a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EffectiveRouteListResult>> GetEffectiveRouteTableWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network security groups applied to a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EffectiveNetworkSecurityGroupListResult>> ListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about all network interfaces in a virtual machine
/// in a virtual machine scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetVMNetworkInterfacesWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a virtual machine scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetNetworkInterfacesWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the specified network interface in a virtual machine scale set.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualMachineScaleSetName'>
/// The name of the virtual machine scale set.
/// </param>
/// <param name='virtualmachineIndex'>
/// The virtual machine index.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkInterface>> GetVirtualMachineScaleSetNetworkInterfaceWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network interface
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkInterface>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all route tables applied to a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EffectiveRouteListResult>> BeginGetEffectiveRouteTableWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network security groups applied to a network interface.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkInterfaceName'>
/// The name of the network interface.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EffectiveNetworkSecurityGroupListResult>> BeginListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about all network interfaces in a virtual machine
/// in a virtual machine scale set.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetVMNetworkInterfacesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network interfaces in a virtual machine scale set.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetNetworkInterfacesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using ChainUtils.BouncyCastle.Crypto.Modes;
using ChainUtils.BouncyCastle.Crypto.Parameters;
namespace ChainUtils.BouncyCastle.Crypto
{
/**
* The AEAD block ciphers already handle buffering internally, so this class
* just takes care of implementing IBufferedCipher methods.
*/
public class BufferedAeadBlockCipher
: BufferedCipherBase
{
private readonly IAeadBlockCipher cipher;
public BufferedAeadBlockCipher(
IAeadBlockCipher cipher)
{
if (cipher == null)
throw new ArgumentNullException("cipher");
this.cipher = cipher;
}
public override string AlgorithmName
{
get { return cipher.AlgorithmName; }
}
/**
* initialise the cipher.
*
* @param forEncryption if true the cipher is initialised for
* encryption, if false for decryption.
* @param param the key and other data required by the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public override void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (parameters is ParametersWithRandom)
{
parameters = ((ParametersWithRandom) parameters).Parameters;
}
cipher.Init(forEncryption, parameters);
}
/**
* return the blocksize for the underlying cipher.
*
* @return the blocksize for the underlying cipher.
*/
public override int GetBlockSize()
{
return cipher.GetBlockSize();
}
/**
* return the size of the output buffer required for an update
* an input of len bytes.
*
* @param len the length of the input.
* @return the space required to accommodate a call to update
* with len bytes of input.
*/
public override int GetUpdateOutputSize(
int length)
{
return cipher.GetUpdateOutputSize(length);
}
/**
* return the size of the output buffer required for an update plus a
* doFinal with an input of len bytes.
*
* @param len the length of the input.
* @return the space required to accommodate a call to update and doFinal
* with len bytes of input.
*/
public override int GetOutputSize(
int length)
{
return cipher.GetOutputSize(length);
}
/**
* process a single byte, producing an output block if neccessary.
*
* @param in the input byte.
* @param out the space for any output that might be produced.
* @param outOff the offset from which the output will be copied.
* @return the number of output bytes copied to out.
* @exception DataLengthException if there isn't enough space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
*/
public override int ProcessByte(
byte input,
byte[] output,
int outOff)
{
return cipher.ProcessByte(input, output, outOff);
}
public override byte[] ProcessByte(
byte input)
{
var outLength = GetUpdateOutputSize(1);
var outBytes = outLength > 0 ? new byte[outLength] : null;
var pos = ProcessByte(input, outBytes, 0);
if (outLength > 0 && pos < outLength)
{
var tmp = new byte[pos];
Array.Copy(outBytes, 0, tmp, 0, pos);
outBytes = tmp;
}
return outBytes;
}
public override byte[] ProcessBytes(
byte[] input,
int inOff,
int length)
{
if (input == null)
throw new ArgumentNullException("input");
if (length < 1)
return null;
var outLength = GetUpdateOutputSize(length);
var outBytes = outLength > 0 ? new byte[outLength] : null;
var pos = ProcessBytes(input, inOff, length, outBytes, 0);
if (outLength > 0 && pos < outLength)
{
var tmp = new byte[pos];
Array.Copy(outBytes, 0, tmp, 0, pos);
outBytes = tmp;
}
return outBytes;
}
/**
* process an array of bytes, producing output if necessary.
*
* @param in the input byte array.
* @param inOff the offset at which the input data starts.
* @param len the number of bytes to be copied out of the input array.
* @param out the space for any output that might be produced.
* @param outOff the offset from which the output will be copied.
* @return the number of output bytes copied to out.
* @exception DataLengthException if there isn't enough space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
*/
public override int ProcessBytes(
byte[] input,
int inOff,
int length,
byte[] output,
int outOff)
{
return cipher.ProcessBytes(input, inOff, length, output, outOff);
}
public override byte[] DoFinal()
{
var outBytes = new byte[GetOutputSize(0)];
var pos = DoFinal(outBytes, 0);
if (pos < outBytes.Length)
{
var tmp = new byte[pos];
Array.Copy(outBytes, 0, tmp, 0, pos);
outBytes = tmp;
}
return outBytes;
}
public override byte[] DoFinal(
byte[] input,
int inOff,
int inLen)
{
if (input == null)
throw new ArgumentNullException("input");
var outBytes = new byte[GetOutputSize(inLen)];
var pos = (inLen > 0)
? ProcessBytes(input, inOff, inLen, outBytes, 0)
: 0;
pos += DoFinal(outBytes, pos);
if (pos < outBytes.Length)
{
var tmp = new byte[pos];
Array.Copy(outBytes, 0, tmp, 0, pos);
outBytes = tmp;
}
return outBytes;
}
/**
* Process the last block in the buffer.
*
* @param out the array the block currently being held is copied into.
* @param outOff the offset at which the copying starts.
* @return the number of output bytes copied to out.
* @exception DataLengthException if there is insufficient space in out for
* the output, or the input is not block size aligned and should be.
* @exception InvalidOperationException if the underlying cipher is not
* initialised.
* @exception InvalidCipherTextException if padding is expected and not found.
* @exception DataLengthException if the input is not block size
* aligned.
*/
public override int DoFinal(
byte[] output,
int outOff)
{
return cipher.DoFinal(output, outOff);
}
/**
* Reset the buffer and cipher. After resetting the object is in the same
* state as it was after the last init (if there was one).
*/
public override void Reset()
{
cipher.Reset();
}
}
}
| |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at subtext@googlegroups.com
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using log4net;
using Subtext.Framework.Logging;
using Subtext.Web.Properties;
namespace Subtext.Web.Controls.Captcha
{
/// <summary>
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Captcha")]
public abstract class CaptchaBase : BaseValidator
{
static readonly SymmetricAlgorithm EncryptionAlgorithm = InitializeEncryptionAlgorithm();
private readonly static ILog Log = new Log();
/// <summary>
/// Gets the name of the hidden form field in which the encrypted answer
/// is located. The answer is sent encrypted to the browser, which must
/// send the answer back.
/// </summary>
/// <value>The name of the hidden encrypted answer field.</value>
protected string HiddenEncryptedAnswerFieldName
{
get { return ClientID + "_encrypted"; }
}
/// <summary>
/// The input field (possibly hidden) in which the client
/// will specify the answer.
/// </summary>
protected string AnswerFormFieldName
{
get { return ClientID + "_answer"; }
}
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Captcha")]
[DefaultValue(0)]
[Description("Number of seconds this CAPTCHA is valid after it is generated. Zero means valid forever.")]
[Category("Captcha")]
public int CaptchaTimeout { get; set; }
static SymmetricAlgorithm InitializeEncryptionAlgorithm()
{
SymmetricAlgorithm rijaendel = Rijndael.Create();
//TODO: We should set these values in the db the very first time this code is called and load them from the db every other time.
rijaendel.GenerateKey();
rijaendel.GenerateIV();
return rijaendel;
}
/// <summary>
/// Encrypts the string and returns a base64 encoded encrypted string.
/// </summary>
/// <param name="clearText">The clear text.</param>
/// <returns></returns>
public static string EncryptString(string clearText)
{
byte[] clearTextBytes = Encoding.UTF8.GetBytes(clearText);
byte[] encrypted = EncryptionAlgorithm.CreateEncryptor().TransformFinalBlock(clearTextBytes, 0,
clearTextBytes.Length);
return Convert.ToBase64String(encrypted);
}
/// <summary>
/// Decrypts the base64 encrypted string and returns the cleartext.
/// </summary>
/// <param name="encryptedEncodedText">The clear text.</param>
/// <exception type="System.Security.Cryptography.CryptographicException">Thrown the string to be decrypted
/// was encrypted using a different encryptor (for example, if we recompile and
/// receive an old string).</exception>
/// <returns></returns>
public static string DecryptString(string encryptedEncodedText)
{
try
{
byte[] encryptedBytes = Convert.FromBase64String(encryptedEncodedText);
byte[] decryptedBytes = EncryptionAlgorithm.CreateDecryptor().TransformFinalBlock(encryptedBytes, 0,
encryptedBytes.Length);
return Encoding.UTF8.GetString(decryptedBytes);
}
catch(FormatException fe)
{
throw new CaptchaExpiredException(
String.Format(CultureInfo.InvariantCulture, Resources.CaptchaExpired_EncryptedTextNotValid,
encryptedEncodedText), fe);
}
catch(CryptographicException e)
{
throw new CaptchaExpiredException(Resources.CaptchaExpired_KeyOutOfSynch, e);
}
}
/// <summary>Checks the properties of the control for valid values.</summary>
/// <returns>true if the control properties are valid; otherwise, false.</returns>
protected override bool ControlPropertiesValid()
{
if(!String.IsNullOrEmpty(ControlToValidate))
{
CheckControlValidationProperty(ControlToValidate, "ControlToValidate");
}
return true;
}
/// <summary>
/// Encrypts the answer along with the current datetime.
/// </summary>
/// <param name="answer">The answer.</param>
/// <returns></returns>
protected virtual string EncryptAnswer(string answer)
{
return EncryptString(answer + "|" + DateTime.Now.ToString("yyyy/MM/dd HH:mm", CultureInfo.InvariantCulture));
}
///<summary>
///When overridden in a derived class, this method contains the code to determine whether the value in the input control is valid.
///</summary>
///<returns>
///true if the value in the input control is valid; otherwise, false.
///</returns>
///
protected override bool EvaluateIsValid()
{
try
{
return ValidateCaptcha();
}
catch(CaptchaExpiredException e)
{
if(e.InnerException != null)
{
string warning = Resources.Warning_CaptchaExpired;
if(HttpContext.Current != null && HttpContext.Current.Request != null)
{
warning += " User Agent: " + HttpContext.Current.Request.UserAgent;
}
Log.Warn(warning, e.InnerException);
}
ErrorMessage = Resources.Message_FormExpired;
return false;
}
}
private bool ValidateCaptcha()
{
string answer = GetClientSpecifiedAnswer();
AnswerAndDate answerAndDate = GetEncryptedAnswerFromForm();
string expectedAnswer = answerAndDate.Answer;
bool isValid = !String.IsNullOrEmpty(answer)
&& String.Equals(answer, expectedAnswer, StringComparison.OrdinalIgnoreCase);
return isValid;
}
// Gets the answer from the client, whether entered by
// javascript or by the user.
protected virtual string GetClientSpecifiedAnswer()
{
return Page.Request.Form[AnswerFormFieldName];
}
/// <summary>
/// Gets the encrypted answer from form.
/// </summary>
/// <returns></returns>
/// <exception type="CaptchaExpiredException">Thrown when the user takes too long to submit a captcha answer.</exception>
protected virtual AnswerAndDate GetEncryptedAnswerFromForm()
{
string formValue = Page.Request.Form[HiddenEncryptedAnswerFieldName];
AnswerAndDate answerAndDate = AnswerAndDate.ParseAnswerAndDate(formValue, CaptchaTimeout);
if(answerAndDate.Expired)
{
throw new CaptchaExpiredException(Resources.CaptchaExpired_WaitedTooLong);
}
return answerAndDate;
}
}
/// <summary>
/// Represents the answer and date returned by the
/// client.
/// </summary>
public struct AnswerAndDate
{
public string Answer
{
get { return _answer; }
}
string _answer;
public DateTime Date
{
get { return _date; }
}
DateTime _date;
public bool Expired
{
get { return _expired; }
}
bool _expired;
public static AnswerAndDate ParseAnswerAndDate(string encryptedAnswer, int timeoutInSeconds)
{
AnswerAndDate answerAndDate;
answerAndDate._expired = false;
answerAndDate._answer = string.Empty;
answerAndDate._date = DateTime.MinValue;
if(String.IsNullOrEmpty(encryptedAnswer))
{
return answerAndDate;
}
string decryptedAnswer = CaptchaBase.DecryptString(encryptedAnswer);
string[] answerParts = decryptedAnswer.Split('|');
if(answerParts.Length < 2)
{
return answerAndDate;
}
answerAndDate._answer = answerParts[0];
answerAndDate._date = DateTime.ParseExact(answerParts[1], "yyyy/MM/dd HH:mm", CultureInfo.InvariantCulture);
if(timeoutInSeconds != 0 && (DateTime.Now - answerAndDate._date).TotalSeconds >= timeoutInSeconds)
{
throw new CaptchaExpiredException(Resources.CaptchaExpired_WaitedTooLong);
}
return answerAndDate;
}
}
}
| |
// <copyright file="Term.cs" company="Basho Technologies, Inc.">
// Copyright 2011 - OJ Reeves & Jeremiah Peschka
// Copyright 2014 - Basho Technologies, Inc.
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// </copyright>
namespace RiakClient.Models.Search
{
using System;
/// <summary>
/// Represents an abstract Lucene search term.
/// </summary>
public abstract class Term
{
private readonly string field;
private readonly RiakFluentSearch search;
private double? boost;
private bool not;
protected Term(RiakFluentSearch search, string field)
{
this.search = search;
this.field = field;
}
internal Term Owner { get; set; }
/// <summary>
/// Returns a new <see cref="RiakFluentSearch"/> object based on this Term.
/// </summary>
/// <returns>A configured <see cref="RiakFluentSearch"/> object.</returns>
protected RiakFluentSearch Search
{
get { return search; }
}
/// <summary>
/// Builds the Term into a new <see cref="RiakFluentSearch"/> object.
/// </summary>
/// <returns>A configured <see cref="RiakFluentSearch"/> object.</returns>
public RiakFluentSearch Build()
{
return search;
}
/// <summary>
/// Boosts the relevance level of the this Term when matches are found.
/// </summary>
/// <param name="boost">The amount to set this Term's boost value to.</param>
/// <returns>A boosted <see cref="Term"/>.</returns>
/// <remarks>The default boost value is 1.0.</remarks>
public Term Boost(double boost)
{
this.boost = boost;
return this;
}
/// <summary>
/// Inverts any matches so that the documents found by this Term are excluded from the result set.
/// </summary>
/// <returns>An inverted Term.</returns>
public Term Not()
{
not = true;
return this;
}
/// <summary>
/// Combines this Term, using a logical OR, with a new one
/// searching this Term's field for the provided <paramref name="value"/> string.
/// </summary>
/// <param name="value">The other value to match.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided <paramref name="value"/>.
/// </returns>
public BinaryTerm Or(string value)
{
return Or(field, Token.Is(value));
}
/// <summary>
/// Combines this Term, using a logical OR, with a new one searching
/// this Term's field for the provided <paramref name="value"/> Token.
/// </summary>
/// <param name="value">The other value to match.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided <paramref name="value"/>.
/// </returns>
public BinaryTerm Or(Token value)
{
return Or(field, value);
}
/// <summary>
/// Combines this Term, using a logical OR, with a new one searching the <paramref name="field"/>
/// field for <paramref name="value"/> string.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="value">The other value to match.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided <paramref name="value"/>.
/// </returns>
public BinaryTerm Or(string field, string value)
{
return new BinaryTerm(search, field, BinaryTerm.Op.Or, this, Token.Is(value));
}
/// <summary>
/// Combines this Term, using a logical OR, with a new one searching
/// the <paramref name="field"/> field for the <paramref name="value"/> Token.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="value">The other value to match.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided <paramref name="value"/>.
/// </returns>
public BinaryTerm Or(string field, Token value)
{
return new BinaryTerm(search, field, BinaryTerm.Op.Or, this, value);
}
/// <summary>
/// Combines this Term, using a logical OR, with a new Range Term
/// searching the current field for values between <paramref name="from"/>
/// and <paramref name="to"/>.
/// </summary>
/// <param name="from">The lower bound of values to search for.</param>
/// <param name="to">The upper bound of values to search for.</param>
/// <param name="inclusive">The option to include the bounds in the range or not.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided parameters.
/// </returns>
public BinaryTerm OrBetween(string from, string to, bool inclusive = true)
{
return OrBetween(field, Token.Is(from), Token.Is(to), inclusive);
}
/// <summary>
/// Combine this Term, using a logical OR, with a new Range Term
/// searching the current field for values between <paramref name="from"/>
/// and <paramref name="to"/>.
/// </summary>
/// <param name="from">The lower bound of values to search for.</param>
/// <param name="to">The upper bound of values to search for.</param>
/// <param name="inclusive">The option to include the bounds in the range or not.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided parameters.
/// </returns>
public BinaryTerm OrBetween(string from, Token to, bool inclusive = true)
{
return OrBetween(field, Token.Is(from), to, inclusive);
}
/// <summary>
/// Combine this Term, using a logical OR, with a new Range Term
/// searching the current field for values between <paramref name="from"/>
/// and <paramref name="to"/>.
/// </summary>
/// <param name="from">The lower bound of values to search for.</param>
/// <param name="to">The upper bound of values to search for.</param>
/// <param name="inclusive">The option to include the bounds in the range or not.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided parameters.
/// </returns>
public BinaryTerm OrBetween(Token from, string to, bool inclusive = true)
{
return OrBetween(field, from, Token.Is(to), inclusive);
}
/// <summary>
/// Combine this Term, using a logical Or, with a new Range Term
/// searching the current field for values between <paramref name="from"/>
/// and <paramref name="to"/>.
/// </summary>
/// <param name="from">The lower bound of values to search for.</param>
/// <param name="to">The upper bound of values to search for.</param>
/// <param name="inclusive">The option to include the bounds in the range or not.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided parameters.
/// </returns>
public BinaryTerm OrBetween(Token from, Token to, bool inclusive = true)
{
return OrBetween(field, from, to, inclusive);
}
/// <summary>
/// Combine this Term, using a logical OR, with a new Range Term
/// searching <paramref name="field"/> for values between <paramref name="from"/>
/// and <paramref name="to"/>.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="from">The lower bound of values to search for.</param>
/// <param name="to">The upper bound of values to search for.</param>
/// <param name="inclusive">The option to include the bounds in the range or not.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided parameters.
/// </returns>
public BinaryTerm OrBetween(string field, string from, string to, bool inclusive = true)
{
return OrBetween(field, Token.Is(from), Token.Is(to), inclusive);
}
/// <summary>
/// Combine this Term, using a logical OR, with a new Range Term
/// searching <paramref name="field"/> for values between <paramref name="from"/>
/// and <paramref name="to"/>.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="from">The lower bound of values to search for.</param>
/// <param name="to">The upper bound of values to search for.</param>
/// <param name="inclusive">The option to include the bounds in the range or not.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided parameters.
/// </returns>
public BinaryTerm OrBetween(string field, string from, Token to, bool inclusive = true)
{
return OrBetween(field, Token.Is(from), to, inclusive);
}
/// <summary>
/// Combine this Term, using a logical OR, with a new Range Term
/// searching <paramref name="field"/> for values between <paramref name="from"/>
/// and <paramref name="to"/>.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="from">The lower bound of values to search for.</param>
/// <param name="to">The upper bound of values to search for.</param>
/// <param name="inclusive">The option to include the bounds in the range or not.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided parameters.
/// </returns>
public BinaryTerm OrBetween(string field, Token from, string to, bool inclusive = true)
{
return OrBetween(field, from, Token.Is(to), inclusive);
}
/// <summary>
/// Combine this Term, using a logical OR, with a new Range Term
/// searching <paramref name="field"/> for values between <paramref name="from"/>
/// and <paramref name="to"/>.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="from">The lower bound of values to search for.</param>
/// <param name="to">The upper bound of values to search for.</param>
/// <param name="inclusive">The option to include the bounds in the range or not.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided parameters.
/// </returns>
public BinaryTerm OrBetween(string field, Token from, Token to, bool inclusive = true)
{
var range = new RangeTerm(search, field, from, to, inclusive);
return new BinaryTerm(search, field, BinaryTerm.Op.Or, this, range);
}
/// <summary>
/// Combines a Term searching this field for the <paramref name="value"/> string, using a logical OR,
/// with another Term generated by the <paramref name="groupSetup"/> Func.
/// </summary>
/// <param name="value">The value to match using the current field.</param>
/// <param name="groupSetup">
/// A <see cref="Func{T1,T2}"/> that accepts a <see cref="Term"/> for fluent configuration,
/// and returns a configured <see cref="Term"/>.
/// </param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on the two created <see cref="Term"/>s.
/// </returns>
public BinaryTerm Or(string value, Func<Term, Term> groupSetup)
{
return Or(field, Token.Is(value), groupSetup);
}
/// <summary>
/// Combines a Term searching this field for the <paramref name="value"/> Token, using a logical OR,
/// with another Term generated by the <paramref name="groupSetup"/> Func.
/// </summary>
/// <param name="value">The value to match using the current field.</param>
/// <param name="groupSetup">
/// A <see cref="Func{T1,T2}"/> that accepts a <see cref="Term"/> for fluent configuration,
/// and returns a configured <see cref="Term"/>.
/// </param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on the two created <see cref="Term"/>s.
/// </returns>
public BinaryTerm Or(Token value, Func<Term, Term> groupSetup)
{
return Or(field, value, groupSetup);
}
/// <summary>
/// Combines a Term searching the <paramref name="field"/> field for the <paramref name="value"/> string,
/// using a logical OR, with another Term generated by the <paramref name="groupSetup"/> Func.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="value">The other value to match.</param>
/// <param name="groupSetup">
/// A <see cref="Func{T1,T2}"/> that accepts a <see cref="Term"/> for fluent configuration,
/// and returns a configured <see cref="Term"/>.
/// </param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on the two created <see cref="Term"/>s.
/// </returns>
public BinaryTerm Or(string field, string value, Func<Term, Term> groupSetup)
{
return Or(field, Token.Is(value), groupSetup);
}
/// <summary>
/// Combines a Term searching the <paramref name="field"/> field for the <paramref name="value"/> Token,
/// using a logical OR, with another Term generated by the <paramref name="groupSetup"/> Func.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="value">The other value to match.</param>
/// <param name="groupSetup">
/// A <see cref="Func{T1,T2}"/> that accepts a <see cref="Term"/> for fluent configuration,
/// and returns a configured <see cref="Term"/>.
/// </param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on the two created <see cref="Term"/>s.
/// </returns>
public BinaryTerm Or(string field, Token value, Func<Term, Term> groupSetup)
{
var groupedTerm = groupSetup(new UnaryTerm(search, field, value));
var groupTerm = new GroupTerm(search, field, groupedTerm);
return new BinaryTerm(search, field, BinaryTerm.Op.Or, this, groupTerm);
}
/// <summary>
/// Combines this Term, using a logical AND, with a new one searching this
/// Term's field for the provided <paramref name="value"/> string.
/// </summary>
/// <param name="value">The other value to match.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided <paramref name="value"/>.
/// </returns>
public BinaryTerm And(string value)
{
return And(field, Token.Is(value));
}
/// <summary>
/// Combines this Term, using a logical AND, with a new one searching this
/// Term's field for the provided <paramref name="value"/> Token.
/// </summary>
/// <param name="value">The other value to match.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided <paramref name="value"/>.
/// </returns>
public BinaryTerm And(Token value)
{
return And(field, value);
}
/// <summary>
/// Combines this Term, using a logical AND, with a new one searching the
/// <paramref name="field"/> field for the provided <paramref name="value"/> string.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="value">The other value to match.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided <paramref name="value"/>.
/// </returns>
public BinaryTerm And(string field, string value)
{
return And(field, Token.Is(value));
}
/// <summary>
/// Combines this Term, using a logical AND, with a new one searching the
/// <paramref name="field"/> field for the provided <paramref name="value"/> Token.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="value">The other value to match.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided <paramref name="value"/>.
/// </returns>
public BinaryTerm And(string field, Token value)
{
return new BinaryTerm(search, field, BinaryTerm.Op.And, this, value);
}
/// <summary>
/// Combine this Term, using a logical AND, with a new Range Term
/// searching the current field for values between <paramref name="from"/>
/// and <paramref name="to"/>.
/// </summary>
/// <param name="from">The lower bound of values to search for.</param>
/// <param name="to">The upper bound of values to search for.</param>
/// <param name="inclusive">The option to include the bounds in the range or not.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided parameters.
/// </returns>
public BinaryTerm AndBetween(string from, string to, bool inclusive = true)
{
return AndBetween(field, from, to, inclusive);
}
/// <summary>
/// Combine this Term, using a logical AND, with a new Range Term
/// searching the current field for values between <paramref name="from"/>
/// and <paramref name="to"/>.
/// </summary>
/// <param name="from">The lower bound of values to search for.</param>
/// <param name="to">The upper bound of values to search for.</param>
/// <param name="inclusive">The option to include the bounds in the range or not.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided parameters.
/// </returns>
public BinaryTerm AndBetween(string from, Token to, bool inclusive = true)
{
return AndBetween(field, Token.Is(from), to, inclusive);
}
/// <summary>
/// Combine this Term, using a logical AND, with a new Range Term
/// searching the current field for values between <paramref name="from"/>
/// and <paramref name="to"/>.
/// </summary>
/// <param name="from">The lower bound of values to search for.</param>
/// <param name="to">The upper bound of values to search for.</param>
/// <param name="inclusive">The option to include the bounds in the range or not.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided parameters.
/// </returns>
public BinaryTerm AndBetween(Token from, string to, bool inclusive = true)
{
return AndBetween(field, from, Token.Is(to), inclusive);
}
/// <summary>
/// Combine this Term, using a logical AND, with a new Range Term
/// searching the current field for values between <paramref name="from"/>
/// and <paramref name="to"/>.
/// </summary>
/// <param name="from">The lower bound of values to search for.</param>
/// <param name="to">The upper bound of values to search for.</param>
/// <param name="inclusive">The option to include the bounds in the range or not.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided parameters.
/// </returns>
public BinaryTerm AndBetween(Token from, Token to, bool inclusive = true)
{
return AndBetween(field, from, to, inclusive);
}
/// <summary>
/// Combine this Term, using a logical AND, with a new Range Term
/// searching <paramref name="field"/> for values between <paramref name="from"/>
/// and <paramref name="to"/>.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="from">The lower bound of values to search for.</param>
/// <param name="to">The upper bound of values to search for.</param>
/// <param name="inclusive">The option to include the bounds in the range or not.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided parameters.
/// </returns>
public BinaryTerm AndBetween(string field, string from, string to, bool inclusive = true)
{
return AndBetween(field, Token.Is(from), Token.Is(to), inclusive);
}
/// <summary>
/// Combine this Term, using a logical AND, with a new Range Term
/// searching <paramref name="field"/> for values between <paramref name="from"/>
/// and <paramref name="to"/>.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="from">The lower bound of values to search for.</param>
/// <param name="to">The upper bound of values to search for.</param>
/// <param name="inclusive">The option to include the bounds in the range or not.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided parameters.
/// </returns>
public BinaryTerm AndBetween(string field, string from, Token to, bool inclusive = true)
{
return AndBetween(field, Token.Is(from), to, inclusive);
}
/// <summary>
/// Combine this Term, using a logical AND, with a new Range Term
/// searching <paramref name="field"/> for values between <paramref name="from"/>
/// and <paramref name="to"/>.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="from">The lower bound of values to search for.</param>
/// <param name="to">The upper bound of values to search for.</param>
/// <param name="inclusive">The option to include the bounds in the range or not.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided parameters.
/// </returns>
public BinaryTerm AndBetween(string field, Token from, string to, bool inclusive = true)
{
return AndBetween(field, from, Token.Is(to), inclusive);
}
/// <summary>
/// Combine this Term, using a logical AND, with a new Range Term
/// searching <paramref name="field"/> for values between <paramref name="from"/>
/// and <paramref name="to"/>.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="from">The lower bound of values to search for.</param>
/// <param name="to">The upper bound of values to search for.</param>
/// <param name="inclusive">The option to include the bounds in the range or not.</param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on this Term and the provided parameters.
/// </returns>
public BinaryTerm AndBetween(string field, Token from, Token to, bool inclusive = true)
{
var range = new RangeTerm(search, field, from, to, inclusive);
return new BinaryTerm(search, field, BinaryTerm.Op.And, this, range);
}
/// <summary>
/// Combines a Term searching this field for the <paramref name="value"/> string, using a logical AND,
/// with another Term generated by the <paramref name="groupSetup"/> Func.
/// </summary>
/// <param name="value">The value to match using the current field.</param>
/// <param name="groupSetup">
/// A <see cref="Func{T1,T2}"/> that accepts a <see cref="Term"/> for fluent configuration,
/// and returns a configured <see cref="Term"/>.
/// </param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on the two created <see cref="Term"/>s.
/// </returns>
public BinaryTerm And(string value, Func<Term, Term> groupSetup)
{
return And(Token.Is(value), groupSetup);
}
/// <summary>
/// Combines a Term searching this field for the <paramref name="value"/> Token, using a logical AND,
/// with another Term generated by the <paramref name="groupSetup"/> Func.
/// </summary>
/// <param name="value">The value to match using the current field.</param>
/// <param name="groupSetup">
/// A <see cref="Func{T1,T2}"/> that accepts a <see cref="Term"/> for fluent configuration,
/// and returns a configured <see cref="Term"/>.
/// </param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on the two created <see cref="Term"/>s.
/// </returns>
public BinaryTerm And(Token value, Func<Term, Term> groupSetup)
{
return And(field, value, groupSetup);
}
/// <summary>
/// Combines a Term searching the <paramref name="field"/> field for the <paramref name="value"/> string,
/// using a logical AND, with another Term generated by the <paramref name="groupSetup"/> Func.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="value">The other value to match.</param>
/// <param name="groupSetup">
/// A <see cref="Func{T1,T2}"/> that accepts a <see cref="Term"/> for fluent configuration,
/// and returns a configured <see cref="Term"/>.
/// </param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on the two created <see cref="Term"/>s.
/// </returns>
public BinaryTerm And(string field, string value, Func<Term, Term> groupSetup)
{
return And(field, Token.Is(value), groupSetup);
}
/// <summary>
/// Combines a Term searching the <paramref name="field"/> field for the <paramref name="value"/> Token,
/// using a logical AND, with another Term generated by the <paramref name="groupSetup"/> Func.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="value">The other value to match.</param>
/// <param name="groupSetup">
/// A <see cref="Func{T1,T2}"/> that accepts a <see cref="Term"/> for fluent configuration,
/// and returns a configured <see cref="Term"/>.
/// </param>
/// <returns>
/// A new <see cref="BinaryTerm"/> based on the two created <see cref="Term"/>s.
/// </returns>
public BinaryTerm And(string field, Token value, Func<Term, Term> groupSetup)
{
var groupedTerm = groupSetup(new UnaryTerm(search, field, value));
var groupTerm = new GroupTerm(search, field, groupedTerm);
return new BinaryTerm(search, field, BinaryTerm.Op.And, this, groupTerm);
}
/// <summary>
/// Combine this Term, using a logical AND, with a new one that searches the current field
/// for a set of <paramref name="words"/> that are within a certain distance
/// (<paramref name="proximity"/>) of each other.
/// </summary>
/// <param name="proximity">The maximum distance the words can be from each other.</param>
/// <param name="words">The set of words to find within a certain distance of each other.</param>
/// <returns>A constructed search <see cref="Term"/>.</returns>
public Term AndProximity(double proximity, params string[] words)
{
return AndProximity(field, proximity, words);
}
/// <summary>
/// Combine this Term, using a logical AND, with a new one that searches the <paramref name="field"/>
/// field for a set of <paramref name="words"/> that are within a certain distance
/// (<paramref name="proximity"/>) of each other.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="proximity">The maximum distance the words can be from each other.</param>
/// <param name="words">The set of words to find within a certain distance of each other.</param>
/// <returns>A constructed search <see cref="Term"/>.</returns>
public Term AndProximity(string field, double proximity, params string[] words)
{
var term = new ProximityTerm(search, field, proximity, words);
return new BinaryTerm(search, field, BinaryTerm.Op.And, this, term);
}
/// <summary>
/// Combine this Term, using a logical OR, with a new one that searches the current field
/// for a set of <paramref name="words"/> that are within a certain distance
/// (<paramref name="proximity"/>) of each other.
/// </summary>
/// <param name="proximity">The maximum distance the words can be from each other.</param>
/// <param name="words">The set of words to find within a certain distance of each other.</param>
/// <returns>A constructed search <see cref="Term"/>.</returns>
public Term OrProximity(double proximity, params string[] words)
{
return OrProximity(field, proximity, words);
}
/// <summary>
/// Combine this Term, using a logical OR, with a new one that searches the <paramref name="field"/>
/// field for a set of <paramref name="words"/> that are within a certain distance
/// (<paramref name="proximity"/>) of each other.
/// </summary>
/// <param name="field">The other field to search.</param>
/// <param name="proximity">The maximum distance the words can be from each other.</param>
/// <param name="words">The set of words to find within a certain distance of each other.</param>
/// <returns>A constructed search <see cref="Term"/>.</returns>
public Term OrProximity(string field, double proximity, params string[] words)
{
var term = new ProximityTerm(search, field, proximity, words);
return new BinaryTerm(search, field, BinaryTerm.Op.Or, this, term);
}
internal string Suffix()
{
return boost.HasValue ? "^" + boost.Value : string.Empty;
}
internal string Prefix()
{
return not ? "NOT " : string.Empty;
}
internal string Field()
{
return string.IsNullOrWhiteSpace(field) ? string.Empty : field + ":";
}
}
}
| |
/*
* Copyright (c) 2010, www.wojilu.com. All rights reserved.
*/
using System;
using System.Collections.Generic;
using wojilu.Members.Interface;
using wojilu.Members.Users.Domain;
using wojilu.Members.Sites.Domain;
using wojilu.Common.Menus.Interface;
using wojilu.Common.MemberApp.Interface;
using wojilu.Data;
using wojilu.Web.Mvc.Routes;
using wojilu.Common.AppBase.Interface;
namespace wojilu.Members.Sites.Service {
public class SiteMenuService : IMenuService {
public IMenu New() {
return new SiteMenu();
}
public Type GetMemberType() {
return typeof( Site );
}
public Result Delete( IMenu menu ) {
if (hasSubMenus( menu )) {
return new Result( lang.get( "deleteSubMenuFirst" ) );
}
((SiteMenu)menu).delete();
updateDefaultMenu( menu );
return new Result();
}
private bool hasSubMenus( IMenu menu ) {
List<IMenu> subMenus = GetByParent( menu );
return subMenus.Count > 0;
}
public List<IMenu> GetByParent( IMenu m ) {
List<IMenu> list = new List<IMenu>();
List<SiteMenu> menus = cdb.findAll<SiteMenu>();
foreach (SiteMenu menu in menus) {
if (menu.ParentId == m.Id) list.Add( menu );
}
return list;
}
public IMenu FindById( int ownerId, int menuId ) {
List<SiteMenu> menus = cdb.findAll<SiteMenu>();
foreach (SiteMenu menu in menus) {
if (menu.OwnerId == ownerId && menu.Id == menuId)
return menu;
}
return null;
}
public List<IMenu> GetRootList( IMember owner ) {
List<IMenu> results = new List<IMenu>();
List<SiteMenu> menus = cdb.findAll<SiteMenu>();
foreach (SiteMenu menu in menus) {
if (menu.OwnerId == owner.Id && menu.ParentId==0)
results.Add( menu );
}
results.Sort();
return results;
}
public List<IMenu> GetList( IMember owner ) {
List<IMenu> results = new List<IMenu>();
List<SiteMenu> menus = cdb.findAll<SiteMenu>();
foreach (SiteMenu menu in menus) {
if (menu.OwnerId == owner.Id )
results.Add( menu );
}
results.Sort();
return results;
}
public Result Insert( IMenu menu, User creator, IMember owner ) {
menu.OwnerId = owner.Id;
menu.Creator = creator;
menu.Created = DateTime.Now;
clearDefaultMenu( menu );
if (strUtil.HasText( menu.Url ) && strUtil.EqualsIgnoreCase( "default", menu.Url ) == false) {
RouteTable.UpdateFriendUrl( menu.Url );
}
return Insert( menu );
}
private Result Insert( IMenu menu ) {
((SiteMenu)menu).insert();
return new Result();
}
public Result Update( IMenu menu ) {
((SiteMenu)menu).update();
clearDefaultMenu( menu );
if (strUtil.HasText( menu.Url ) && strUtil.EqualsIgnoreCase( "default", menu.Url ) == false) {
RouteTable.UpdateFriendUrl( menu.Url );
}
return new Result();
}
private void clearDefaultMenu( IMenu menu ) {
if ("default".Equals( menu.Url ) == false) return;
List<SiteMenu> list = cdb.findAll<SiteMenu>();
foreach (SiteMenu smenu in list) {
if ((smenu.Id != menu.Id) && "default".Equals( smenu.Url )) {
smenu.Url = "";
smenu.update();
break;
}
}
}
//----------------------------------------------------------------------
public IMenu FindByApp( String rawAppUrl ) {
List<SiteMenu> menus = cdb.findAll<SiteMenu>();
foreach (SiteMenu menu in menus) {
if (strUtil.IsNullOrEmpty( menu.RawUrl )) continue;
if (PathHelper.CompareUrlWithoutExt( menu.RawUrl, rawAppUrl )) return menu;
}
return null;
}
public IMenu AddMenuByApp( IMemberApp app, String name, String friendUrl, String rawAppUrl ) {
Boolean isFirst = this.GetList(Site.Instance).Count == 0;
IMenu menu = new SiteMenu();
menu.OwnerId = app.OwnerId;
menu.OwnerUrl = app.OwnerUrl;
menu.OwnerType = app.OwnerType;
menu.Creator = app.Creator;
menu.Name = name;
menu.Url = friendUrl;
if (isFirst) menu.Url = "default";
menu.RawUrl = rawAppUrl;
menu.Created = DateTime.Now;
Insert( menu );
return menu;
}
public void RemoveMenuByApp( IMemberApp app, String rawAppUrl ) {
IMenu menu = FindByApp( rawAppUrl );
if (menu != null) {
((SiteMenu)menu).delete();
updateDefaultMenu( menu );
}
}
public void UpdateMenuByApp( IMemberApp app, String rawAppUrl ) {
IMenu menu = FindByApp( rawAppUrl );
if (menu != null) {
UpdateName( menu, app.Name );
}
}
private void UpdateName( IMenu menu, String appName ) {
menu.Name = appName;
((SiteMenu)menu).update();
}
private void updateDefaultMenu( IMenu menu ) {
if (strUtil.EqualsIgnoreCase( menu.Url, "default" )) {
List<IMenu> menus = this.GetList( Site.Instance );
if (menus.Count > 0) {
IMenu defaultMenu = menus[0];
defaultMenu.Url = "default";
cdb.update( (SiteMenu)defaultMenu );
}
}
}
}
}
| |
// 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.InteropServices;
using Xunit;
namespace Tests.System.Runtime.InteropServices
{
public class StringBufferTests
{
private const string TestString = ".NET Core is awesome.";
[Fact]
public void CanIndexChar()
{
using (var buffer = new StringBuffer())
{
buffer.Length = 1;
buffer[0] = 'Q';
Assert.Equal(buffer[0], 'Q');
}
}
[Fact]
public unsafe void CreateFromString()
{
string testString = "Test";
using (var buffer = new StringBuffer(testString))
{
Assert.Equal((ulong)testString.Length, buffer.Length);
Assert.Equal((ulong)testString.Length + 1, buffer.CharCapacity);
for (int i = 0; i < testString.Length; i++)
{
Assert.Equal(testString[i], buffer[(ulong)i]);
}
// Check the null termination
Assert.Equal('\0', buffer.CharPointer[testString.Length]);
Assert.Equal(testString, buffer.ToString());
}
}
[Fact]
public void ReduceLength()
{
using (var buffer = new StringBuffer("Food"))
{
Assert.Equal((ulong)5, buffer.CharCapacity);
buffer.Length = 3;
Assert.Equal("Foo", buffer.ToString());
// Shouldn't reduce capacity when dropping length
Assert.Equal((ulong)5, buffer.CharCapacity);
}
}
[Fact]
public void GetOverIndexThrowsArgumentOutOfRange()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentOutOfRangeException>(() => { char c = buffer[0]; });
}
}
[Fact]
public void SetOverIndexThrowsArgumentOutOfRange()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentOutOfRangeException>(() => { buffer[0] = 'Q'; });
}
}
[Theory,
InlineData(@"Foo", @"Foo", true),
InlineData(@"Foo", @"foo", false),
InlineData(@"Foobar", @"Foo", true),
InlineData(@"Foobar", @"foo", false),
InlineData(@"Fo", @"Foo", false),
InlineData(@"Fo", @"foo", false),
InlineData(@"", @"", true),
InlineData(@"", @"f", false),
InlineData(@"f", @"", true),
]
public void StartsWith(string source, string value, bool expected)
{
using (var buffer = new StringBuffer(source))
{
Assert.Equal(expected, buffer.StartsWith(value));
}
}
[Fact]
public void StartsWithNullThrows()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentNullException>(() => buffer.StartsWith(null));
}
}
[Fact]
public void SubstringEqualsNegativeCountThrows()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.SubstringEquals("", startIndex: 0, count: -2));
}
}
[Fact]
public void SubstringEqualsOverSizeCountThrows()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.SubstringEquals("", startIndex: 0, count: 1));
}
}
[Fact]
public void SubstringEqualsOverSizeCountWithIndexThrows()
{
using (var buffer = new StringBuffer("A"))
{
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.SubstringEquals("", startIndex: 1, count: 1));
}
}
[Theory,
InlineData(@"", null, 0, 0, false),
InlineData(@"", @"", 0, 0, true),
InlineData(@"", @"", 0, -1, true),
InlineData(@"A", @"", 0, -1, false),
InlineData(@"", @"A", 0, -1, false),
InlineData(@"Foo", @"Foo", 0, -1, true),
InlineData(@"Foo", @"foo", 0, -1, false),
InlineData(@"Foo", @"Foo", 1, -1, false),
InlineData(@"Foo", @"Food", 0, -1, false),
InlineData(@"Food", @"Foo", 0, -1, false),
InlineData(@"Food", @"Foo", 0, 3, true),
InlineData(@"Food", @"ood", 1, 3, true),
InlineData(@"Food", @"ooD", 1, 3, false),
InlineData(@"Food", @"ood", 1, 2, false),
InlineData(@"Food", @"Food", 0, 3, false),
]
public void SubstringEquals(string source, string value, int startIndex, int count, bool expected)
{
using (var buffer = new StringBuffer(source))
{
Assert.Equal(expected, buffer.SubstringEquals(value, startIndex: (ulong)startIndex, count: count));
}
}
[Theory,
InlineData(@"", @"", 0, -1, @""),
InlineData(@"", @"", 0, 0, @""),
InlineData(@"", @"A", 0, -1, @"A"),
InlineData(@"", @"A", 0, 0, @""),
InlineData(@"", @"Aa", 0, -1, @"Aa"),
InlineData(@"", @"Aa", 0, 0, @""),
InlineData(@"", "Aa\0", 0, -1, "Aa\0"),
InlineData(@"", "Aa\0", 0, 3, "Aa\0"),
InlineData(@"", @"AB", 0, -1, @"AB"),
InlineData(@"", @"AB", 0, 1, @"A"),
InlineData(@"", @"AB", 1, 1, @"B"),
InlineData(@"", @"AB", 1, -1, @"B"),
InlineData(@"", @"ABC", 1, -1, @"BC"),
InlineData(null, @"", 0, -1, @""),
InlineData(null, @"", 0, 0, @""),
InlineData(null, @"A", 0, -1, @"A"),
InlineData(null, @"A", 0, 0, @""),
InlineData(null, @"Aa", 0, -1, @"Aa"),
InlineData(null, @"Aa", 0, 0, @""),
InlineData(null, "Aa\0", 0, -1, "Aa\0"),
InlineData(null, "Aa\0", 0, 3, "Aa\0"),
InlineData(null, @"AB", 0, -1, @"AB"),
InlineData(null, @"AB", 0, 1, @"A"),
InlineData(null, @"AB", 1, 1, @"B"),
InlineData(null, @"AB", 1, -1, @"B"),
InlineData(null, @"ABC", 1, -1, @"BC"),
InlineData(@"Q", @"", 0, -1, @"Q"),
InlineData(@"Q", @"", 0, 0, @"Q"),
InlineData(@"Q", @"A", 0, -1, @"QA"),
InlineData(@"Q", @"A", 0, 0, @"Q"),
InlineData(@"Q", @"Aa", 0, -1, @"QAa"),
InlineData(@"Q", @"Aa", 0, 0, @"Q"),
InlineData(@"Q", "Aa\0", 0, -1, "QAa\0"),
InlineData(@"Q", "Aa\0", 0, 3, "QAa\0"),
InlineData(@"Q", @"AB", 0, -1, @"QAB"),
InlineData(@"Q", @"AB", 0, 1, @"QA"),
InlineData(@"Q", @"AB", 1, 1, @"QB"),
InlineData(@"Q", @"AB", 1, -1, @"QB"),
InlineData(@"Q", @"ABC", 1, -1, @"QBC"),
]
public void AppendTests(string source, string value, int startIndex, int count, string expected)
{
// From string
using (var buffer = new StringBuffer(source))
{
buffer.Append(value, startIndex, count);
Assert.Equal(expected, buffer.ToString());
}
// From buffer
using (var buffer = new StringBuffer(source))
using (var valueBuffer = new StringBuffer(value))
{
if (count == -1)
buffer.Append(valueBuffer, (ulong)startIndex, valueBuffer.Length - (ulong)startIndex);
else
buffer.Append(valueBuffer, (ulong)startIndex, (ulong)count);
Assert.Equal(expected, buffer.ToString());
}
}
[Fact]
public void AppendNullStringThrows()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentNullException>(() => buffer.Append((string)null));
}
}
[Fact]
public void AppendNullStringBufferThrows()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentNullException>(() => buffer.Append((StringBuffer)null));
}
}
[Fact]
public void AppendNegativeIndexThrows()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.Append("a", startIndex: -1));
}
}
[Fact]
public void AppendOverIndexThrows()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.Append("", startIndex: 1));
}
}
[Fact]
public void AppendOverCountThrows()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.Append("", startIndex: 0, count: 1));
}
}
[Fact]
public void AppendOverCountWithIndexThrows()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.Append("A", startIndex: 1, count: 1));
}
}
[Fact]
public void ToStringIndexOverLengthThrows()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.Substring(startIndex: 1));
}
}
[Fact]
public void ToStringNegativeCountThrows()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.Substring(startIndex: 0, count: -2));
}
}
[Fact]
public void ToStringCountOverLengthThrows()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.Substring(startIndex: 0, count: 1));
}
}
[Theory,
InlineData(@"", 0, -1, @""),
InlineData(@"A", 0, -1, @"A"),
InlineData(@"AB", 0, -1, @"AB"),
InlineData(@"AB", 0, 1, @"A"),
InlineData(@"AB", 1, 1, @"B"),
InlineData(@"AB", 1, -1, @"B"),
InlineData(@"", 0, 0, @""),
InlineData(@"A", 0, 0, @""),
]
public void ToStringTest(string source, int startIndex, int count, string expected)
{
using (var buffer = new StringBuffer(source))
{
Assert.Equal(expected, buffer.Substring(startIndex: (ulong)startIndex, count: count));
}
}
[Fact]
public unsafe void SetLengthToFirstNullNoNull()
{
using (var buffer = new StringBuffer("A"))
{
// Wipe out the last null
buffer.CharPointer[buffer.Length] = 'B';
buffer.SetLengthToFirstNull();
Assert.Equal((ulong)1, buffer.Length);
}
}
[Fact]
public unsafe void SetLengthToFirstNullEmptyBuffer()
{
using (var buffer = new StringBuffer())
{
buffer.SetLengthToFirstNull();
Assert.Equal((ulong)0, buffer.Length);
}
}
[Theory,
InlineData(@"", 0, 0),
InlineData(@"Foo", 3, 3),
InlineData("\0", 1, 0),
InlineData("Foo\0Bar", 7, 3),
]
public unsafe void SetLengthToFirstNullTests(string content, ulong startLength, ulong endLength)
{
using (var buffer = new StringBuffer(content))
{
// With existing content
Assert.Equal(startLength, buffer.Length);
buffer.SetLengthToFirstNull();
Assert.Equal(endLength, buffer.Length);
// Clear the buffer & manually copy in
buffer.Length = 0;
fixed (char* contentPointer = content)
{
Buffer.MemoryCopy(contentPointer, buffer.CharPointer, (long)buffer.CharCapacity * 2, content.Length * sizeof(char));
}
Assert.Equal((ulong)0, buffer.Length);
buffer.SetLengthToFirstNull();
Assert.Equal(endLength, buffer.Length);
}
}
[Theory,
InlineData("foo", new char[] { }, "foo"),
InlineData("foo", null, "foo"),
InlineData("foo", new char[] { 'b' }, "foo"),
InlineData("", new char[] { }, ""),
InlineData("", null, ""),
InlineData("", new char[] { 'b' }, ""),
InlineData("foo", new char[] { 'o' }, "f"),
InlineData("foo", new char[] { 'o', 'f' }, ""),
// Add a couple cases to try and get the trim to walk off the front of the buffer.
InlineData("foo", new char[] { 'o', 'f', '\0' }, ""),
InlineData("foo", new char[] { 'o', 'f', '\u9000' }, "")
]
public void TrimEnd(string content, char[] trimChars, string expected)
{
// We want equivalence with built-in string behavior
using (var buffer = new StringBuffer(content))
{
buffer.TrimEnd(trimChars);
Assert.Equal(expected, buffer.ToString());
}
}
[Theory,
InlineData(@"Foo", @"Bar", 0, 0, 3, "Bar"),
InlineData(@"Foo", @"Bar", 0, 0, -1, "Bar"),
InlineData(@"Foo", @"Bar", 3, 0, 3, "FooBar"),
InlineData(@"", @"Bar", 0, 0, 3, "Bar"),
InlineData(@"Foo", @"Bar", 1, 0, 3, "FBar"),
InlineData(@"Foo", @"Bar", 1, 1, 2, "Far"),
]
public void CopyFromString(string content, string source, ulong bufferIndex, int sourceIndex, int count, string expected)
{
using (var buffer = new StringBuffer(content))
{
buffer.CopyFrom(bufferIndex, source, sourceIndex, count);
Assert.Equal(expected, buffer.ToString());
}
}
[Fact]
public void CopyFromStringThrowsOnNull()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentNullException>(() => { buffer.CopyFrom(0, null); });
}
}
[Fact]
public void CopyFromStringThrowsIndexingBeyondBufferLength()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentOutOfRangeException>(() => { buffer.CopyFrom(1, ""); });
}
}
[Theory,
InlineData("", 0, 1),
InlineData("", 1, 0),
InlineData("", 1, -1),
InlineData("", 2, 0),
InlineData("Foo", 3, 1),
InlineData("Foo", 4, 0),
]
public void CopyFromStringThrowsIndexingBeyondStringLength(string value, int index, int count)
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentOutOfRangeException>(() => { buffer.CopyFrom(0, value, index, count); });
}
}
[Theory,
InlineData(@"Foo", @"Bar", 0, 0, 3, "Bar"),
InlineData(@"Foo", @"Bar", 3, 0, 3, "FooBar"),
InlineData(@"", @"Bar", 0, 0, 3, "Bar"),
InlineData(@"Foo", @"Bar", 1, 0, 3, "FBar"),
InlineData(@"Foo", @"Bar", 1, 1, 2, "Far"),
]
public void CopyToBufferString(string destination, string content, ulong destinationIndex, ulong bufferIndex, ulong count, string expected)
{
using (var buffer = new StringBuffer(content))
using (var destinationBuffer = new StringBuffer(destination))
{
buffer.CopyTo(bufferIndex, destinationBuffer, destinationIndex, count);
Assert.Equal(expected, destinationBuffer.ToString());
}
}
[Fact]
public void CopyToBufferThrowsOnNull()
{
using (var buffer = new StringBuffer())
{
Assert.Throws<ArgumentNullException>(() => { buffer.CopyTo(0, null, 0, 0); });
}
}
[Theory,
InlineData("", 0, 1),
InlineData("", 1, 0),
InlineData("", 2, 0),
InlineData("Foo", 3, 1),
InlineData("Foo", 4, 0),
]
public void CopyToBufferThrowsIndexingBeyondSourceBufferLength(string source, ulong index, ulong count)
{
using (var buffer = new StringBuffer(source))
using (var targetBuffer = new StringBuffer())
{
Assert.Throws<ArgumentOutOfRangeException>(() => { buffer.CopyTo(index, targetBuffer, 0, count); });
}
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Data;
using System.Linq.Expressions;
namespace NServiceKit.OrmLite
{
/// <summary>A read extensions.</summary>
public static class ReadExtensions
{
/// <summary>Creates the expression.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <returns>The new expression.</returns>
public static SqlExpressionVisitor<T> CreateExpression<T>()
{
return OrmLiteConfig.DialectProvider.ExpressionVisitor<T>();
}
/// <summary>An IDbCommand extension method that selects.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>A List<T></returns>
public static List<T> Select<T>(this IDbCommand dbCmd, Expression<Func<T, bool>> predicate)
{
var ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<T>();
string sql = ev.Where(predicate).ToSelectStatement();
using (var reader = dbCmd.ExecReader(sql))
{
return ConvertToList<T>(reader);
}
}
/// <summary>An IDbCommand extension method that selects.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="expression">The expression.</param>
/// <returns>A List<T></returns>
public static List<T> Select<T>(this IDbCommand dbCmd, Func<SqlExpressionVisitor<T>, SqlExpressionVisitor<T>> expression)
{
var ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<T>();
string sql = expression(ev).ToSelectStatement();
using (var reader = dbCmd.ExecReader(sql))
{
return ConvertToList<T>(reader);
}
}
/// <summary>An IDbCommand extension method that selects.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="expression">The expression.</param>
/// <returns>A List<T></returns>
public static List<T> Select<T>(this IDbCommand dbCmd, SqlExpressionVisitor<T> expression)
{
string sql = expression.ToSelectStatement();
using (var reader = dbCmd.ExecReader(sql))
{
return ConvertToList<T>(reader);
}
}
/// <summary>An IDbCommand extension method that select parameter.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>A List<T></returns>
public static List<T> SelectParam<T>(this IDbCommand dbCmd, Expression<Func<T, bool>> predicate)
{
var ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<T>();
ev.IsParameterized = true;
string sql = ev.Where(predicate).ToSelectStatement();
dbCmd.Parameters.Clear();
List<IDataParameter> paramsToInsert = new List<IDataParameter>();
foreach (var param in ev.Params)
{
var cmdParam = dbCmd.CreateParameter();
cmdParam.ParameterName = param.Key;
cmdParam.Value = param.Value ?? DBNull.Value;
paramsToInsert.Add(cmdParam);
}
using (var reader = dbCmd.ExecReader(sql, paramsToInsert))
{
return ConvertToList<T>(reader);
}
}
/// <summary>An IDbCommand extension method that firsts.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>A T.</returns>
public static T First<T>(this IDbCommand dbCmd, Expression<Func<T, bool>> predicate)
{
var ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<T>();
return First(dbCmd, ev.Where(predicate).Limit(1));
}
/// <summary>An IDbCommand extension method that firsts.</summary>
/// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="expression">The expression.</param>
/// <returns>A T.</returns>
public static T First<T>(this IDbCommand dbCmd, SqlExpressionVisitor<T> expression)
{
var result = FirstOrDefault(dbCmd, expression);
if (Equals(result, default(T)))
{
throw new ArgumentNullException(string.Format(
"{0}: '{1}' does not exist", typeof(T).Name, expression.WhereExpression));
}
return result;
}
/// <summary>An IDbCommand extension method that first or default.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>A T.</returns>
public static T FirstOrDefault<T>(this IDbCommand dbCmd, Expression<Func<T, bool>> predicate)
{
var ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<T>();
return FirstOrDefault(dbCmd, ev.Where(predicate).Limit(1));
}
/// <summary>An IDbCommand extension method that first or default.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="expression">The expression.</param>
/// <returns>A T.</returns>
public static T FirstOrDefault<T>(this IDbCommand dbCmd, SqlExpressionVisitor<T> expression)
{
string sql= expression.ToSelectStatement();
using (var dbReader = dbCmd.ExecReader(sql))
{
return ConvertTo<T>(dbReader);
}
}
/// <summary>
/// e.g. dbCmd.GetScalar<MyClass, DateTime>(myClass => Sql.Max(myClass.Timestamp));
/// </summary>
/// <typeparam name="T"> Generic type parameter.</typeparam>
/// <typeparam name="TKey">Type of the key.</typeparam>
/// <param name="dbCmd">The dbCmd to act on.</param>
/// <param name="field">The field.</param>
/// <returns>The scalar.</returns>
public static TKey GetScalar<T, TKey>(this IDbCommand dbCmd, Expression<Func<T, TKey>> field)
{
var ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<T>();
ev.Select(field);
var sql = ev.ToSelectStatement();
return dbCmd.GetScalar<TKey>(sql);
}
/// <summary>
/// dbCmd.GetScalar<MyClass, DateTime>(MyClass=>Sql.Max(myClass.Timestamp),
/// MyClass=> MyClass.SomeProp== someValue);
/// </summary>
/// <typeparam name="T"> Generic type parameter.</typeparam>
/// <typeparam name="TKey">Type of the key.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="field"> The field.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>The scalar.</returns>
public static TKey GetScalar<T,TKey>(this IDbCommand dbCmd,Expression<Func<T, TKey>> field,
Expression<Func<T, bool>> predicate)
{
var ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<T>();
ev.Select(field).Where(predicate);
string sql = ev.ToSelectStatement();
return dbCmd.GetScalar<TKey>(sql);
}
/// <summary>An IDbCommand extension method that counts.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd">The dbCmd to act on.</param>
/// <returns>A long.</returns>
public static long Count<T>(this IDbCommand dbCmd)
{
SqlExpressionVisitor<T> expression = OrmLiteConfig.DialectProvider.ExpressionVisitor<T>();
string sql = expression.ToCountStatement();
return dbCmd.GetScalar<long>(sql);
}
/// <summary>An IDbCommand extension method that counts.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="expression">The expression.</param>
/// <returns>A long.</returns>
public static long Count<T>(this IDbCommand dbCmd, SqlExpressionVisitor<T> expression)
{
string sql = expression.ToCountStatement();
return dbCmd.GetScalar<long>(sql);
}
/// <summary>An IDbCommand extension method that counts.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dbCmd"> The dbCmd to act on.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>A long.</returns>
public static long Count<T>(this IDbCommand dbCmd, Expression<Func<T, bool>> predicate)
{
var ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<T>();
ev.Where(predicate);
string sql = ev.ToCountStatement();
return dbCmd.GetScalar<long>(sql);
}
/// <summary>Convert to.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dataReader">The data reader.</param>
/// <returns>to converted.</returns>
private static T ConvertTo<T>(IDataReader dataReader)
{
var fieldDefs = ModelDefinition<T>.Definition.AllFieldDefinitionsArray;
using (dataReader)
{
if (dataReader.Read())
{
var row = OrmLiteUtilExtensions.CreateInstance<T>();
var namingStrategy = OrmLiteConfig.DialectProvider.NamingStrategy;
for (int i = 0; i<dataReader.FieldCount; i++)
{
var fieldDef = fieldDefs.FirstOrDefault(
x =>
namingStrategy.GetColumnName(x.FieldName).ToUpper() ==
dataReader.GetName(i).ToUpper());
if (fieldDef == null) continue;
var value = dataReader.GetValue(i);
fieldDef.SetValue(row, value);
}
return row;
}
return default(T);
}
}
/// <summary>Converts a dataReader to a list.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="dataReader">The data reader.</param>
/// <returns>The given data converted to a list.</returns>
private static List<T> ConvertToList<T>(IDataReader dataReader)
{
var fieldDefs = ModelDefinition<T>.Definition.AllFieldDefinitionsArray;
var fieldDefCache = new Dictionary<int, FieldDefinition>();
var to = new List<T>();
using (dataReader)
{
while (dataReader.Read())
{
var row = OrmLiteUtilExtensions.CreateInstance<T>();
var namingStrategy = OrmLiteConfig.DialectProvider.NamingStrategy;
for (int i = 0; i<dataReader.FieldCount; i++)
{
FieldDefinition fieldDef;
if (!fieldDefCache.TryGetValue(i, out fieldDef))
{
fieldDef = fieldDefs.FirstOrDefault(
x =>
namingStrategy.GetColumnName(x.FieldName).ToUpper() ==
dataReader.GetName(i).ToUpper());
fieldDefCache[i] = fieldDef;
}
if (fieldDef == null) continue;
var value = dataReader.GetValue(i);
fieldDef.SetValue(row, value);
}
to.Add(row);
}
}
return to;
}
/*
private static T PopulateWithSqlReader<T>( T objWithProperties, IDataReader dataReader, FieldDefinition[] fieldDefs)
{
foreach (var fieldDef in fieldDefs)
{
try{
// NOTE: this is a nasty ineffeciency here when we're calling this for multiple rows!
// we should only call GetOrdinal once per column per result set
// and one could only wish for a -1 return instead of an IndexOutOfRangeException...
// how to get -1 ?
//If the index of the named field is not found, an IndexOutOfRangeException is thrown.
//http://msdn.microsoft.com/en-us/library/system.data.idatarecord.getordinal(v=vs.100).aspx
var index = dataReader.GetColumnIndex(fieldDef.FieldName);
var value = dataReader.GetValue(index);
fieldDef.SetValue(objWithProperties, value);
}
catch(IndexOutOfRangeException){
// just ignore not retrived fields
}
}
return objWithProperties;
}
*/
// First FirstOrDefault // Use LIMIT to retrive only one row ! someone did it
}
}
| |
// 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,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System.Collections.Generic;
using System.Linq;
using Microsoft.PythonTools.Analysis.Analyzer;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Parsing.Ast;
namespace Microsoft.PythonTools.Analysis.Values {
/// <summary>
/// Represents an instance of a class implemented in Python
/// </summary>
internal class InstanceInfo : AnalysisValue, IReferenceableContainer {
private readonly ClassInfo _classInfo;
private Dictionary<string, VariableDef> _instanceAttrs;
public InstanceInfo(ClassInfo classInfo) {
_classInfo = classInfo;
}
public override IDictionary<string, IAnalysisSet> GetAllMembers(IModuleContext moduleContext) {
var res = new Dictionary<string, IAnalysisSet>();
if (_instanceAttrs != null) {
foreach (var kvp in _instanceAttrs) {
var types = kvp.Value.TypesNoCopy;
var key = kvp.Key;
kvp.Value.ClearOldValues();
if (kvp.Value.VariableStillExists) {
MergeTypes(res, key, types);
}
}
}
// check and see if it's defined in a base class instance as well...
foreach (var b in _classInfo.Bases) {
foreach (var ns in b) {
if (ns.Push()) {
try {
ClassInfo baseClass = ns as ClassInfo;
if (baseClass != null &&
baseClass.Instance._instanceAttrs != null) {
foreach (var kvp in baseClass.Instance._instanceAttrs) {
kvp.Value.ClearOldValues();
if (kvp.Value.VariableStillExists) {
MergeTypes(res, kvp.Key, kvp.Value.TypesNoCopy);
}
}
}
} finally {
ns.Pop();
}
}
}
}
foreach (var classMem in _classInfo.GetAllMembers(moduleContext)) {
MergeTypes(res, classMem.Key, classMem.Value);
}
return res;
}
private static void MergeTypes(Dictionary<string, IAnalysisSet> res, string key, IEnumerable<AnalysisValue> types) {
IAnalysisSet set;
if (!res.TryGetValue(key, out set)) {
res[key] = set = AnalysisSet.Create(types);
} else {
res[key] = set.Union(types);
}
}
public Dictionary<string, VariableDef> InstanceAttributes {
get {
return _instanceAttrs;
}
}
public PythonAnalyzer ProjectState {
get {
return _classInfo.AnalysisUnit.ProjectState;
}
}
public override IEnumerable<OverloadResult> Overloads {
get {
IAnalysisSet callRes;
if (_classInfo.GetAllMembers(ProjectState._defaultContext).TryGetValue("__call__", out callRes)) {
foreach (var overload in callRes.SelectMany(av => av.Overloads)) {
yield return overload.WithNewParameters(
overload.Parameters.Skip(1).ToArray()
);
}
}
foreach (var overload in base.Overloads) {
yield return overload;
}
}
}
public override IAnalysisSet Call(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
var res = base.Call(node, unit, args, keywordArgNames);
if (Push()) {
try {
var callRes = GetTypeMember(node, unit, "__call__");
if (callRes.Any()) {
res = res.Union(callRes.Call(node, unit, args, keywordArgNames));
}
} finally {
Pop();
}
}
return res;
}
internal IAnalysisSet GetTypeMember(Node node, AnalysisUnit unit, string name) {
var result = AnalysisSet.Empty;
var classMem = _classInfo.GetMemberNoReferences(node, unit, name);
if (classMem.Count > 0) {
result = classMem.GetDescriptor(node, this, _classInfo, unit);
if (result.Count > 0) {
// TODO: Check if it's a data descriptor...
}
return result;
} else {
// if the class gets a value later we need to be re-analyzed
_classInfo.Scope.CreateEphemeralVariable(node, unit, name, false).AddDependency(unit);
}
return result;
}
public override IAnalysisSet GetMember(Node node, AnalysisUnit unit, string name) {
// Must unconditionally call the base implementation of GetMember
var ignored = base.GetMember(node, unit, name);
// __getattribute__ takes precedence over everything.
IAnalysisSet getattrRes = AnalysisSet.Empty;
var getAttribute = _classInfo.GetMemberNoReferences(node, unit.CopyForEval(), "__getattribute__");
if (getAttribute.Count > 0) {
foreach (var getAttrFunc in getAttribute) {
var func = getAttrFunc as BuiltinMethodInfo;
if (func != null && func.Function.DeclaringType.TypeId == BuiltinTypeId.Object) {
continue;
}
// TODO: We should really do a get descriptor / call here
getattrRes = getattrRes.Union(getAttrFunc.Call(node, unit, new[] { SelfSet, ProjectState.ClassInfos[BuiltinTypeId.Str].Instance.SelfSet }, ExpressionEvaluator.EmptyNames));
}
}
// ok, it must be an instance member, or it will become one later
VariableDef def;
if (_instanceAttrs == null) {
_instanceAttrs = new Dictionary<string, VariableDef>();
}
if (!_instanceAttrs.TryGetValue(name, out def)) {
_instanceAttrs[name] = def = new EphemeralVariableDef();
}
def.AddReference(node, unit);
def.AddDependency(unit);
// now check class members
var res = GetTypeMember(node, unit, name);
res = res.Union(def.Types);
// check and see if it's defined in a base class instance as well...
foreach (var b in _classInfo.Bases) {
foreach (var ns in b) {
if (ns.Push()) {
try {
ClassInfo baseClass = ns as ClassInfo;
if (baseClass != null &&
baseClass.Instance._instanceAttrs != null &&
baseClass.Instance._instanceAttrs.TryGetValue(name, out def)) {
res = res.Union(def.TypesNoCopy);
}
} finally {
ns.Pop();
}
}
}
}
if (res.Count == 0) {
// and if that doesn't exist fall back to __getattr__
var getAttr = _classInfo.GetMemberNoReferences(node, unit, "__getattr__");
if (getAttr.Count > 0) {
foreach (var getAttrFunc in getAttr) {
getattrRes = getattrRes.Union(getAttr.Call(node, unit, new[] { SelfSet, _classInfo.AnalysisUnit.ProjectState.ClassInfos[BuiltinTypeId.Str].Instance.SelfSet }, ExpressionEvaluator.EmptyNames));
}
}
return getattrRes;
}
return res;
}
public override IAnalysisSet GetDescriptor(Node node, AnalysisValue instance, AnalysisValue context, AnalysisUnit unit) {
if (Push()) {
try {
var getter = GetTypeMember(node, unit, "__get__");
if (getter.Count > 0) {
var get = getter.GetDescriptor(node, this, _classInfo, unit);
return get.Call(node, unit, new[] { instance, context }, ExpressionEvaluator.EmptyNames);
}
} finally {
Pop();
}
}
return SelfSet;
}
public override void SetMember(Node node, AnalysisUnit unit, string name, IAnalysisSet value) {
if (_instanceAttrs == null) {
_instanceAttrs = new Dictionary<string, VariableDef>();
}
VariableDef instMember;
if (!_instanceAttrs.TryGetValue(name, out instMember) || instMember == null) {
_instanceAttrs[name] = instMember = new VariableDef();
}
instMember.AddAssignment(node, unit);
instMember.MakeUnionStrongerIfMoreThan(ProjectState.Limits.InstanceMembers, value);
instMember.AddTypes(unit, value);
}
public override void DeleteMember(Node node, AnalysisUnit unit, string name) {
if (_instanceAttrs == null) {
_instanceAttrs = new Dictionary<string, VariableDef>();
}
VariableDef instMember;
if (!_instanceAttrs.TryGetValue(name, out instMember) || instMember == null) {
_instanceAttrs[name] = instMember = new VariableDef();
}
instMember.AddReference(node, unit);
_classInfo.GetMember(node, unit, name);
}
public override IAnalysisSet UnaryOperation(Node node, AnalysisUnit unit, PythonOperator operation) {
if (operation == PythonOperator.Not) {
return unit.ProjectState.ClassInfos[BuiltinTypeId.Bool].Instance;
}
string methodName = UnaryOpToString(unit.ProjectState, operation);
if (methodName != null) {
var method = GetTypeMember(node, unit, methodName);
if (method.Count > 0) {
var res = method.Call(
node,
unit,
new[] { this },
ExpressionEvaluator.EmptyNames
);
return res;
}
}
return base.UnaryOperation(node, unit, operation);
}
internal static string UnaryOpToString(PythonAnalyzer state, PythonOperator operation) {
string op = null;
switch (operation) {
case PythonOperator.Not: op = state.LanguageVersion.Is3x() ? "__bool__" : "__nonzero__"; break;
case PythonOperator.Pos: op = "__pos__"; break;
case PythonOperator.Invert: op = "__invert__"; break;
case PythonOperator.Negate: op = "__neg__"; break;
}
return op;
}
public override IAnalysisSet BinaryOperation(Node node, AnalysisUnit unit, PythonOperator operation, IAnalysisSet rhs) {
string op = BinaryOpToString(operation);
if (op != null) {
var invokeMem = GetTypeMember(node, unit, op);
if (invokeMem.Count > 0) {
// call __*__ method
return invokeMem.Call(node, unit, new[] { rhs }, ExpressionEvaluator.EmptyNames);
}
}
return base.BinaryOperation(node, unit, operation, rhs);
}
internal static string BinaryOpToString(PythonOperator operation) {
string op = null;
switch (operation) {
case PythonOperator.Multiply: op = "__mul__"; break;
case PythonOperator.MatMultiply: op = "__matmul__"; break;
case PythonOperator.Add: op = "__add__"; break;
case PythonOperator.Subtract: op = "__sub__"; break;
case PythonOperator.Xor: op = "__xor__"; break;
case PythonOperator.BitwiseAnd: op = "__and__"; break;
case PythonOperator.BitwiseOr: op = "__or__"; break;
case PythonOperator.Divide: op = "__div__"; break;
case PythonOperator.FloorDivide: op = "__floordiv__"; break;
case PythonOperator.LeftShift: op = "__lshift__"; break;
case PythonOperator.Mod: op = "__mod__"; break;
case PythonOperator.Power: op = "__pow__"; break;
case PythonOperator.RightShift: op = "__rshift__"; break;
case PythonOperator.TrueDivide: op = "__truediv__"; break;
}
return op;
}
public override IAnalysisSet ReverseBinaryOperation(Node node, AnalysisUnit unit, PythonOperator operation, IAnalysisSet rhs) {
string op = ReverseBinaryOpToString(operation);
if (op != null) {
var invokeMem = GetTypeMember(node, unit, op);
if (invokeMem.Count > 0) {
// call __r*__ method
return invokeMem.Call(node, unit, new[] { rhs }, ExpressionEvaluator.EmptyNames);
}
}
return base.ReverseBinaryOperation(node, unit, operation, rhs);
}
private static string ReverseBinaryOpToString(PythonOperator operation) {
string op = null;
switch (operation) {
case PythonOperator.Multiply: op = "__rmul__"; break;
case PythonOperator.MatMultiply: op = "__rmatmul__"; break;
case PythonOperator.Add: op = "__radd__"; break;
case PythonOperator.Subtract: op = "__rsub__"; break;
case PythonOperator.Xor: op = "__rxor__"; break;
case PythonOperator.BitwiseAnd: op = "__rand__"; break;
case PythonOperator.BitwiseOr: op = "__ror__"; break;
case PythonOperator.Divide: op = "__rdiv__"; break;
case PythonOperator.FloorDivide: op = "__rfloordiv__"; break;
case PythonOperator.LeftShift: op = "__rlshift__"; break;
case PythonOperator.Mod: op = "__rmod__"; break;
case PythonOperator.Power: op = "__rpow__"; break;
case PythonOperator.RightShift: op = "__rrshift__"; break;
case PythonOperator.TrueDivide: op = "__rtruediv__"; break;
}
return op;
}
public override IAnalysisSet GetEnumeratorTypes(Node node, AnalysisUnit unit) {
if (Push()) {
try {
var iter = GetIterator(node, unit);
if (iter.Any()) {
return iter
.GetMember(node, unit, unit.ProjectState.LanguageVersion.Is3x() ? "__next__" : "next")
.Call(node, unit, ExpressionEvaluator.EmptySets, ExpressionEvaluator.EmptyNames);
}
} finally {
Pop();
}
}
return base.GetEnumeratorTypes(node, unit);
}
public override IAnalysisSet GetAsyncEnumeratorTypes(Node node, AnalysisUnit unit) {
if (unit.ProjectState.LanguageVersion.Is3x() && Push()) {
try {
var iter = GetAsyncIterator(node, unit);
if (iter.Any()) {
return iter
.GetMember(node, unit, "__anext__")
.Call(node, unit, ExpressionEvaluator.EmptySets, ExpressionEvaluator.EmptyNames)
.Await(node, unit);
}
} finally {
Pop();
}
}
return base.GetAsyncEnumeratorTypes(node, unit);
}
public override IPythonProjectEntry DeclaringModule {
get {
return _classInfo.DeclaringModule;
}
}
public override int DeclaringVersion {
get {
return _classInfo.DeclaringVersion;
}
}
public override string Description {
get {
return ClassInfo.ClassDefinition.Name + " instance";
}
}
public override string Documentation {
get {
return ClassInfo.Documentation;
}
}
public override PythonMemberType MemberType {
get {
return PythonMemberType.Instance;
}
}
internal override bool IsOfType(IAnalysisSet klass) {
return klass.Contains(ClassInfo) || klass.Contains(ProjectState.ClassInfos[BuiltinTypeId.Object]);
}
public ClassInfo ClassInfo {
get { return _classInfo; }
}
public override string ToString() {
return ClassInfo.AnalysisUnit.FullName + " instance";
}
internal override bool UnionEquals(AnalysisValue ns, int strength) {
if (strength >= MergeStrength.ToObject) {
if (ns.TypeId == BuiltinTypeId.NoneType) {
// II + BII(None) => do not merge
return false;
}
// II + II => BII(object)
// II + BII => BII(object)
var obj = ProjectState.ClassInfos[BuiltinTypeId.Object];
return ns is InstanceInfo ||
(ns is BuiltinInstanceInfo && ns.TypeId != BuiltinTypeId.Type && ns.TypeId != BuiltinTypeId.Function) ||
ns == obj.Instance;
} else if (strength >= MergeStrength.ToBaseClass) {
var ii = ns as InstanceInfo;
if (ii != null) {
return ii.ClassInfo.UnionEquals(ClassInfo, strength);
}
var bii = ns as BuiltinInstanceInfo;
if (bii != null) {
return bii.ClassInfo.UnionEquals(ClassInfo, strength);
}
}
return base.UnionEquals(ns, strength);
}
internal override int UnionHashCode(int strength) {
if (strength >= MergeStrength.ToObject) {
return ProjectState.ClassInfos[BuiltinTypeId.Object].Instance.UnionHashCode(strength);
} else if (strength >= MergeStrength.ToBaseClass) {
return ClassInfo.UnionHashCode(strength);
}
return base.UnionHashCode(strength);
}
internal override AnalysisValue UnionMergeTypes(AnalysisValue ns, int strength) {
if (strength >= MergeStrength.ToObject) {
// II + II => BII(object)
// II + BII => BII(object)
return ProjectState.ClassInfos[BuiltinTypeId.Object].Instance;
} else if (strength >= MergeStrength.ToBaseClass) {
var ii = ns as InstanceInfo;
if (ii != null) {
return ii.ClassInfo.UnionMergeTypes(ClassInfo, strength).GetInstanceType().Single();
}
var bii = ns as BuiltinInstanceInfo;
if (bii != null) {
return bii.ClassInfo.UnionMergeTypes(ClassInfo, strength).GetInstanceType().Single();
}
}
return base.UnionMergeTypes(ns, strength);
}
#region IVariableDefContainer Members
public IEnumerable<IReferenceable> GetDefinitions(string name) {
VariableDef def;
if (_instanceAttrs != null && _instanceAttrs.TryGetValue(name, out def)) {
yield return def;
}
foreach (var classDef in _classInfo.GetDefinitions(name)) {
yield return classDef;
}
}
#endregion
}
}
| |
namespace android.content.res
{
[global::MonoJavaBridge.JavaInterface(typeof(global::android.content.res.XmlResourceParser_))]
public partial interface XmlResourceParser : org.xmlpull.v1.XmlPullParser, android.util.AttributeSet
{
void close();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.content.res.XmlResourceParser))]
internal sealed partial class XmlResourceParser_ : java.lang.Object, XmlResourceParser
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal XmlResourceParser_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.content.res.XmlResourceParser.close()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "close", "()V", ref global::android.content.res.XmlResourceParser_._m0);
}
private static global::MonoJavaBridge.MethodId _m1;
void org.xmlpull.v1.XmlPullParser.setProperty(java.lang.String arg0, java.lang.Object arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "setProperty", "(Ljava/lang/String;Ljava/lang/Object;)V", ref global::android.content.res.XmlResourceParser_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m2;
global::java.lang.Object org.xmlpull.v1.XmlPullParser.getProperty(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getProperty", "(Ljava/lang/String;)Ljava/lang/Object;", ref global::android.content.res.XmlResourceParser_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m3;
global::java.lang.String org.xmlpull.v1.XmlPullParser.getName()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getName", "()Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m3) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m4;
int org.xmlpull.v1.XmlPullParser.next()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "next", "()I", ref global::android.content.res.XmlResourceParser_._m4);
}
private static global::MonoJavaBridge.MethodId _m5;
int org.xmlpull.v1.XmlPullParser.getLineNumber()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getLineNumber", "()I", ref global::android.content.res.XmlResourceParser_._m5);
}
private static global::MonoJavaBridge.MethodId _m6;
bool org.xmlpull.v1.XmlPullParser.isWhitespace()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "isWhitespace", "()Z", ref global::android.content.res.XmlResourceParser_._m6);
}
private static global::MonoJavaBridge.MethodId _m7;
int org.xmlpull.v1.XmlPullParser.nextToken()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "nextToken", "()I", ref global::android.content.res.XmlResourceParser_._m7);
}
private static global::MonoJavaBridge.MethodId _m8;
void org.xmlpull.v1.XmlPullParser.setInput(java.io.InputStream arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "setInput", "(Ljava/io/InputStream;Ljava/lang/String;)V", ref global::android.content.res.XmlResourceParser_._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m9;
void org.xmlpull.v1.XmlPullParser.setInput(java.io.Reader arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "setInput", "(Ljava/io/Reader;)V", ref global::android.content.res.XmlResourceParser_._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m10;
global::java.lang.String org.xmlpull.v1.XmlPullParser.getPrefix()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getPrefix", "()Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m10) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m11;
global::java.lang.String org.xmlpull.v1.XmlPullParser.getAttributeValue(java.lang.String arg0, java.lang.String arg1)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeValue", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m12;
global::java.lang.String org.xmlpull.v1.XmlPullParser.getAttributeValue(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeValue", "(I)Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m13;
int org.xmlpull.v1.XmlPullParser.getColumnNumber()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getColumnNumber", "()I", ref global::android.content.res.XmlResourceParser_._m13);
}
private static global::MonoJavaBridge.MethodId _m14;
global::java.lang.String org.xmlpull.v1.XmlPullParser.getText()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getText", "()Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m14) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m15;
int org.xmlpull.v1.XmlPullParser.getEventType()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getEventType", "()I", ref global::android.content.res.XmlResourceParser_._m15);
}
private static global::MonoJavaBridge.MethodId _m16;
int org.xmlpull.v1.XmlPullParser.getAttributeCount()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeCount", "()I", ref global::android.content.res.XmlResourceParser_._m16);
}
private static global::MonoJavaBridge.MethodId _m17;
global::java.lang.String org.xmlpull.v1.XmlPullParser.getAttributeName(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeName", "(I)Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m18;
global::java.lang.String org.xmlpull.v1.XmlPullParser.getPositionDescription()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getPositionDescription", "()Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m18) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m19;
void org.xmlpull.v1.XmlPullParser.setFeature(java.lang.String arg0, bool arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "setFeature", "(Ljava/lang/String;Z)V", ref global::android.content.res.XmlResourceParser_._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m20;
bool org.xmlpull.v1.XmlPullParser.getFeature(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getFeature", "(Ljava/lang/String;)Z", ref global::android.content.res.XmlResourceParser_._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m21;
global::java.lang.String org.xmlpull.v1.XmlPullParser.getInputEncoding()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getInputEncoding", "()Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m21) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m22;
void org.xmlpull.v1.XmlPullParser.defineEntityReplacementText(java.lang.String arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "defineEntityReplacementText", "(Ljava/lang/String;Ljava/lang/String;)V", ref global::android.content.res.XmlResourceParser_._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m23;
int org.xmlpull.v1.XmlPullParser.getNamespaceCount(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getNamespaceCount", "(I)I", ref global::android.content.res.XmlResourceParser_._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m24;
global::java.lang.String org.xmlpull.v1.XmlPullParser.getNamespacePrefix(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getNamespacePrefix", "(I)Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m25;
global::java.lang.String org.xmlpull.v1.XmlPullParser.getNamespaceUri(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getNamespaceUri", "(I)Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m26;
global::java.lang.String org.xmlpull.v1.XmlPullParser.getNamespace()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getNamespace", "()Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m26) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m27;
global::java.lang.String org.xmlpull.v1.XmlPullParser.getNamespace(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getNamespace", "(Ljava/lang/String;)Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m28;
int org.xmlpull.v1.XmlPullParser.getDepth()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getDepth", "()I", ref global::android.content.res.XmlResourceParser_._m28);
}
private static global::MonoJavaBridge.MethodId _m29;
char[] org.xmlpull.v1.XmlPullParser.getTextCharacters(int[] arg0)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<char>(this, global::android.content.res.XmlResourceParser_.staticClass, "getTextCharacters", "([I)[C", ref global::android.content.res.XmlResourceParser_._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as char[];
}
private static global::MonoJavaBridge.MethodId _m30;
bool org.xmlpull.v1.XmlPullParser.isEmptyElementTag()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "isEmptyElementTag", "()Z", ref global::android.content.res.XmlResourceParser_._m30);
}
private static global::MonoJavaBridge.MethodId _m31;
global::java.lang.String org.xmlpull.v1.XmlPullParser.getAttributeNamespace(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeNamespace", "(I)Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m32;
global::java.lang.String org.xmlpull.v1.XmlPullParser.getAttributePrefix(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributePrefix", "(I)Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m33;
global::java.lang.String org.xmlpull.v1.XmlPullParser.getAttributeType(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeType", "(I)Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m34;
bool org.xmlpull.v1.XmlPullParser.isAttributeDefault(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "isAttributeDefault", "(I)Z", ref global::android.content.res.XmlResourceParser_._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m35;
void org.xmlpull.v1.XmlPullParser.require(int arg0, java.lang.String arg1, java.lang.String arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "require", "(ILjava/lang/String;Ljava/lang/String;)V", ref global::android.content.res.XmlResourceParser_._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m36;
global::java.lang.String org.xmlpull.v1.XmlPullParser.nextText()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "nextText", "()Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m36) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m37;
int org.xmlpull.v1.XmlPullParser.nextTag()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "nextTag", "()I", ref global::android.content.res.XmlResourceParser_._m37);
}
private static global::MonoJavaBridge.MethodId _m38;
global::java.lang.String android.util.AttributeSet.getAttributeValue(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeValue", "(I)Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m39;
global::java.lang.String android.util.AttributeSet.getAttributeValue(java.lang.String arg0, java.lang.String arg1)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeValue", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m40;
int android.util.AttributeSet.getAttributeCount()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeCount", "()I", ref global::android.content.res.XmlResourceParser_._m40);
}
private static global::MonoJavaBridge.MethodId _m41;
global::java.lang.String android.util.AttributeSet.getAttributeName(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeName", "(I)Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m41, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m42;
global::java.lang.String android.util.AttributeSet.getPositionDescription()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getPositionDescription", "()Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m42) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m43;
int android.util.AttributeSet.getAttributeNameResource(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeNameResource", "(I)I", ref global::android.content.res.XmlResourceParser_._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m44;
int android.util.AttributeSet.getAttributeListValue(java.lang.String arg0, java.lang.String arg1, java.lang.String[] arg2, int arg3)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeListValue", "(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;I)I", ref global::android.content.res.XmlResourceParser_._m44, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m45;
int android.util.AttributeSet.getAttributeListValue(int arg0, java.lang.String[] arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeListValue", "(I[Ljava/lang/String;I)I", ref global::android.content.res.XmlResourceParser_._m45, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m46;
bool android.util.AttributeSet.getAttributeBooleanValue(java.lang.String arg0, java.lang.String arg1, bool arg2)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeBooleanValue", "(Ljava/lang/String;Ljava/lang/String;Z)Z", ref global::android.content.res.XmlResourceParser_._m46, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m47;
bool android.util.AttributeSet.getAttributeBooleanValue(int arg0, bool arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeBooleanValue", "(IZ)Z", ref global::android.content.res.XmlResourceParser_._m47, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m48;
int android.util.AttributeSet.getAttributeResourceValue(java.lang.String arg0, java.lang.String arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeResourceValue", "(Ljava/lang/String;Ljava/lang/String;I)I", ref global::android.content.res.XmlResourceParser_._m48, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m49;
int android.util.AttributeSet.getAttributeResourceValue(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeResourceValue", "(II)I", ref global::android.content.res.XmlResourceParser_._m49, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m50;
int android.util.AttributeSet.getAttributeIntValue(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeIntValue", "(II)I", ref global::android.content.res.XmlResourceParser_._m50, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m51;
int android.util.AttributeSet.getAttributeIntValue(java.lang.String arg0, java.lang.String arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeIntValue", "(Ljava/lang/String;Ljava/lang/String;I)I", ref global::android.content.res.XmlResourceParser_._m51, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m52;
int android.util.AttributeSet.getAttributeUnsignedIntValue(java.lang.String arg0, java.lang.String arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeUnsignedIntValue", "(Ljava/lang/String;Ljava/lang/String;I)I", ref global::android.content.res.XmlResourceParser_._m52, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m53;
int android.util.AttributeSet.getAttributeUnsignedIntValue(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeUnsignedIntValue", "(II)I", ref global::android.content.res.XmlResourceParser_._m53, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m54;
float android.util.AttributeSet.getAttributeFloatValue(java.lang.String arg0, java.lang.String arg1, float arg2)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeFloatValue", "(Ljava/lang/String;Ljava/lang/String;F)F", ref global::android.content.res.XmlResourceParser_._m54, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m55;
float android.util.AttributeSet.getAttributeFloatValue(int arg0, float arg1)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getAttributeFloatValue", "(IF)F", ref global::android.content.res.XmlResourceParser_._m55, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m56;
global::java.lang.String android.util.AttributeSet.getIdAttribute()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getIdAttribute", "()Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m56) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m57;
global::java.lang.String android.util.AttributeSet.getClassAttribute()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.content.res.XmlResourceParser_.staticClass, "getClassAttribute", "()Ljava/lang/String;", ref global::android.content.res.XmlResourceParser_._m57) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m58;
int android.util.AttributeSet.getIdAttributeResourceValue(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getIdAttributeResourceValue", "(I)I", ref global::android.content.res.XmlResourceParser_._m58, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m59;
int android.util.AttributeSet.getStyleAttribute()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.res.XmlResourceParser_.staticClass, "getStyleAttribute", "()I", ref global::android.content.res.XmlResourceParser_._m59);
}
static XmlResourceParser_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.content.res.XmlResourceParser_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/res/XmlResourceParser"));
}
}
}
| |
using System;
using System.Threading.Tasks;
namespace Bridge.jQuery2
{
public partial class jQuery
{
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <returns></returns>
public virtual jQuery FadeIn()
{
return null;
}
//[Template("Bridge.Task.fromCallbackOptions({this}, 'fadeIn', 'complete')")]
[Template("Bridge.Task.fromPromise({this}.fadeIn())")]
public virtual Task FadeInTask()
{
return null;
}
[Template("Bridge.Task.fromPromise({this}.fadeIn({0}))")]
public virtual Task FadeInTask(int duration)
{
return null;
}
[Template("Bridge.Task.fromPromise({this}.fadeIn({0}, {1}))")]
public virtual Task FadeInTask(int duration, string easing)
{
return null;
}
[Template("Bridge.Task.fromPromise({this}.fadeIn({0}))")]
public virtual Task FadeInTask(EffectOptions options)
{
return null;
}
//[Template("Bridge.Task.fromCallbackOptions({this}, 'fadeOut', 'complete')")]
[Template("Bridge.Task.fromPromise({this}.fadeOut())")]
public virtual Task FadeOutTask()
{
return null;
}
[Template("Bridge.Task.fromPromise({this}.fadeOut({0}))")]
public virtual Task FadeOutTask(int duration)
{
return null;
}
[Template("Bridge.Task.fromPromise({this}.fadeOut({0}, {1}))")]
public virtual Task FadeOutTask(int duration, string easing)
{
return null;
}
[Template("Bridge.Task.fromPromise({this}.fadeOut({0}))")]
public virtual Task FadeOutTask(EffectOptions options)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <returns></returns>
public virtual jQuery FadeIn(int duration)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeIn(int duration, Delegate complete)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeIn(int duration, Action complete)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <returns></returns>
public virtual jQuery FadeIn(string duration)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeIn(string duration, Delegate complete)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeIn(string duration, Action complete)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="options">A map of additional options to pass to the method.</param>
/// <returns></returns>
public virtual jQuery FadeIn(EffectOptions options)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <returns></returns>
public virtual jQuery FadeIn(int duration, string easing)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <returns></returns>
public virtual jQuery FadeIn(string duration, string easing)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeIn(int duration, string easing, Delegate complete)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeIn(int duration, string easing, Action complete)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeIn(string duration, string easing, Delegate complete)
{
return null;
}
/// <summary>
/// Display the matched elements by fading them to opaque.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeIn(string duration, string easing, Action complete)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <returns></returns>
public virtual jQuery FadeOut()
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <returns></returns>
public virtual jQuery FadeOut(int duration)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeOut(int duration, Delegate complete)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeOut(int duration, Action complete)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <returns></returns>
public virtual jQuery FadeOut(string duration)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeOut(string duration, Delegate complete)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeOut(string duration, Action complete)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="options">A map of additional options to pass to the method.</param>
/// <returns></returns>
public virtual jQuery FadeOut(EffectOptions options)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <returns></returns>
public virtual jQuery FadeOut(int duration, string easing)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <returns></returns>
public virtual jQuery FadeOut(string duration, string easing)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeOut(int duration, string easing, Delegate complete)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeOut(int duration, string easing, Action complete)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeOut(string duration, string easing, Delegate complete)
{
return null;
}
/// <summary>
/// Hide the matched elements by fading them to transparent.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeOut(string duration, string easing, Action complete)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <returns></returns>
public virtual jQuery FadeTo(int duration)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <returns></returns>
public virtual jQuery FadeTo(string duration)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <returns></returns>
public virtual jQuery FadeTo(int duration, int opacity)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <returns></returns>
public virtual jQuery FadeTo(string duration, int opacity)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeTo(int duration, int opacity, Delegate complete)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeTo(int duration, int opacity, Action complete)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeTo(string duration, int opacity, Delegate complete)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeTo(string duration, int opacity, Action complete)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <returns></returns>
public virtual jQuery FadeTo(int duration, int opacity, string easing)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <returns></returns>
public virtual jQuery FadeTo(string duration, int opacity, string easing)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeTo(int duration, int opacity, string easing, Delegate complete)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeTo(int duration, int opacity, string easing, Action complete)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeTo(string duration, int opacity, string easing, Delegate complete)
{
return null;
}
/// <summary>
/// Adjust the opacity of the matched elements.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="opacity">A number between 0 and 1 denoting the target opacity.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeTo(string duration, int opacity, string easing, Action complete)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(int duration)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(string duration)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(int duration, string easing)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(string duration, string easing)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(int duration, string easing, Delegate complete)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(int duration, string easing, Action complete)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(string duration, string easing, Delegate complete)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="duration">A string or number determining how long the animation will run.</param>
/// <param name="easing">A string indicating which easing function to use for the transition.</param>
/// <param name="complete">A function to call once the animation is complete.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(string duration, string easing, Action complete)
{
return null;
}
/// <summary>
/// Display or hide the matched elements by animating their opacity.
/// </summary>
/// <param name="options">A map of additional options to pass to the method.</param>
/// <returns></returns>
public virtual jQuery FadeToggle(EffectOptions options)
{
return null;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;
using System.Globalization;
using System.Diagnostics;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
internal class SerialConsoleLogger : BaseConsoleLogger
{
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
/// <owner>SumedhK</owner>
public SerialConsoleLogger()
: this(LoggerVerbosity.Normal)
{
// do nothing
}
/// <summary>
/// Create a logger instance with a specific verbosity. This logs to
/// the default console.
/// </summary>
/// <owner>SumedhK</owner>
/// <param name="verbosity">Verbosity level.</param>
public SerialConsoleLogger(LoggerVerbosity verbosity)
:
this
(
verbosity,
new WriteHandler(Console.Out.Write),
new ColorSetter(SetColor),
new ColorResetter(Console.ResetColor)
)
{
// do nothing
}
/// <summary>
/// Initializes the logger, with alternate output handlers.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
/// <param name="verbosity"></param>
/// <param name="write"></param>
/// <param name="colorSet"></param>
/// <param name="colorReset"></param>
public SerialConsoleLogger
(
LoggerVerbosity verbosity,
WriteHandler write,
ColorSetter colorSet,
ColorResetter colorReset
)
{
InitializeConsoleMethods(verbosity, write, colorSet, colorReset);
}
#endregion
#region Methods
/// <summary>
/// Reset the states of per-build member variables
/// VSW#516376
/// </summary>
internal override void ResetConsoleLoggerState()
{
if (ShowSummary)
{
errorList = new ArrayList();
warningList = new ArrayList();
}
else
{
errorList = null;
warningList = null;
}
errorCount = 0;
warningCount = 0;
projectPerformanceCounters = null;
targetPerformanceCounters = null;
taskPerformanceCounters = null;
}
/// <summary>
/// Handler for build started events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
/// <owner>t-jeffv, sumedhk</owner>
public override void BuildStartedHandler(object sender, BuildStartedEventArgs e)
{
buildStarted = e.Timestamp;
// if verbosity is detailed or diagnostic
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
WriteLinePrettyFromResource("BuildStartedWithTime", e.Timestamp);
}
}
/// <summary>
/// Handler for build finished events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
/// <owner>t-jeffv, sumedhk</owner>
public override void BuildFinishedHandler(object sender, BuildFinishedEventArgs e)
{
// Show the performance summary iff the verbosity is diagnostic or the user specifically asked for it
// with a logger parameter.
if (this.showPerfSummary)
{
ShowPerfSummary();
}
// if verbosity is normal, detailed or diagnostic
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
if (e.Succeeded)
{
setColor(ConsoleColor.Green);
}
// Write the "Build Finished" event.
WriteNewLine();
WriteLinePretty(e.Message);
resetColor();
}
// The decision whether or not to show a summary at this verbosity
// was made during initalization. We just do what we're told.
if (ShowSummary)
{
ShowErrorWarningSummary();
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
// Emit text like:
// 1 Warning(s)
// 0 Error(s)
// Don't color the line if it's zero. (Per Whidbey behavior.)
if (warningCount > 0)
{
setColor(ConsoleColor.Yellow);
}
WriteLinePrettyFromResource(2, "WarningCount", warningCount);
resetColor();
if (errorCount > 0)
{
setColor(ConsoleColor.Red);
}
WriteLinePrettyFromResource(2, "ErrorCount", errorCount);
resetColor();
}
}
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
string timeElapsed = LogFormatter.FormatTimeSpan(e.Timestamp - buildStarted);
WriteNewLine();
WriteLinePrettyFromResource("TimeElapsed", timeElapsed);
}
ResetConsoleLoggerState();
}
/// <summary>
/// At the end of the build, repeats the errors and warnings that occurred
/// during the build, and displays the error count and warning count.
/// </summary>
private void ShowErrorWarningSummary()
{
if (warningCount == 0 && errorCount == 0) return;
// Make some effort to distinguish the summary from the previous output
WriteNewLine();
if (warningCount > 0)
{
setColor(ConsoleColor.Yellow);
foreach(BuildWarningEventArgs warningEventArgs in warningList)
{
WriteLinePretty(EventArgsFormatting.FormatEventMessage(warningEventArgs, runningWithCharacterFileType));
}
}
if (errorCount > 0)
{
setColor(ConsoleColor.Red);
foreach (BuildErrorEventArgs errorEventArgs in errorList)
{
WriteLinePretty(EventArgsFormatting.FormatEventMessage(errorEventArgs, runningWithCharacterFileType));
}
}
resetColor();
}
/// <summary>
/// Handler for project started events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
/// <owner>t-jeffv, sumedhk</owner>
public override void ProjectStartedHandler(object sender, ProjectStartedEventArgs e)
{
if (!contextStack.IsEmpty())
{
this.VerifyStack(contextStack.Peek().type == FrameType.Target, "Bad stack -- Top is project {0}", contextStack.Peek().ID);
}
// if verbosity is normal, detailed or diagnostic
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
ShowDeferredMessages();
// check for stack corruption
if (!contextStack.IsEmpty())
{
this.VerifyStack(contextStack.Peek().type == FrameType.Target, "Bad stack -- Top is target {0}", contextStack.Peek().ID);
}
contextStack.Push(new Frame(FrameType.Project,
false, // message not yet displayed
this.currentIndentLevel,
e.ProjectFile,
e.TargetNames,
null,
GetCurrentlyBuildingProjectFile()));
WriteProjectStarted();
}
else
{
contextStack.Push(new Frame(FrameType.Project,
false, // message not yet displayed
this.currentIndentLevel,
e.ProjectFile,
e.TargetNames,
null,
GetCurrentlyBuildingProjectFile()));
}
if (this.showPerfSummary)
{
PerformanceCounter counter = GetPerformanceCounter(e.ProjectFile, ref projectPerformanceCounters);
// Place the counter "in scope" meaning the project is executing right now.
counter.InScope = true;
}
if (Verbosity == LoggerVerbosity.Diagnostic && showItemAndPropertyList)
{
if (null != e.Properties)
{
ArrayList propertyList = ExtractPropertyList(e.Properties);
WriteProperties(propertyList);
}
if (null != e.Items)
{
SortedList itemList = ExtractItemList(e.Items);
WriteItems(itemList);
}
}
}
/// <summary>
/// Handler for project finished events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
/// <owner>t-jeffv, sumedhk</owner>
public override void ProjectFinishedHandler(object sender, ProjectFinishedEventArgs e)
{
if (this.showPerfSummary)
{
PerformanceCounter counter = GetPerformanceCounter(e.ProjectFile, ref projectPerformanceCounters);
// Place the counter "in scope" meaning the project is done executing right now.
counter.InScope = false;
}
// if verbosity is detailed or diagnostic,
// or there was an error or warning
if (contextStack.Peek().hasErrorsOrWarnings
|| (IsVerbosityAtLeast(LoggerVerbosity.Detailed)))
{
setColor(ConsoleColor.Cyan);
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
WriteNewLine();
}
WriteLinePretty(e.Message);
resetColor();
}
Frame top = contextStack.Pop();
this.VerifyStack(top.type == FrameType.Project, "Unexpected project frame {0}", top.ID);
this.VerifyStack(top.ID == e.ProjectFile, "Project frame {0} expected, but was {1}.", e.ProjectFile, top.ID);
}
/// <summary>
/// Handler for target started events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
/// <owner>t-jeffv, sumedhk</owner>
public override void TargetStartedHandler(object sender, TargetStartedEventArgs e)
{
contextStack.Push(new Frame(FrameType.Target,
false,
this.currentIndentLevel,
e.TargetName,
null,
e.TargetFile,
GetCurrentlyBuildingProjectFile()));
// if verbosity is detailed or diagnostic
if (IsVerbosityAtLeast(LoggerVerbosity.Detailed))
{
WriteTargetStarted();
}
if (this.showPerfSummary)
{
PerformanceCounter counter = GetPerformanceCounter(e.TargetName, ref targetPerformanceCounters);
// Place the counter "in scope" meaning the target is executing right now.
counter.InScope = true;
}
// Bump up the overall number of indents, so that anything within this target will show up
// indented.
this.currentIndentLevel++;
}
/// <summary>
/// Handler for target finished events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
/// <owner>t-jeffv, sumedhk</owner>
public override void TargetFinishedHandler(object sender, TargetFinishedEventArgs e)
{
// Done with the target, so shift everything left again.
this.currentIndentLevel--;
if (this.showPerfSummary)
{
PerformanceCounter counter = GetPerformanceCounter(e.TargetName, ref targetPerformanceCounters);
// Place the counter "in scope" meaning the target is done executing right now.
counter.InScope = false;
}
bool targetHasErrorsOrWarnings = contextStack.Peek().hasErrorsOrWarnings;
// if verbosity is diagnostic,
// or there was an error or warning and verbosity is normal or detailed
if ((targetHasErrorsOrWarnings && (IsVerbosityAtLeast(LoggerVerbosity.Normal)))
|| Verbosity == LoggerVerbosity.Diagnostic)
{
setColor(ConsoleColor.Cyan);
WriteLinePretty(e.Message);
resetColor();
}
Frame top = contextStack.Pop();
this.VerifyStack(top.type == FrameType.Target, "bad stack frame type");
this.VerifyStack(top.ID == e.TargetName, "bad stack frame id");
// set the value on the Project frame, for the ProjectFinished handler
if (targetHasErrorsOrWarnings)
{
SetErrorsOrWarningsOnCurrentFrame();
}
}
/// <summary>
/// Handler for task started events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
/// <owner>t-jeffv, sumedhk</owner>
public override void TaskStartedHandler(object sender, TaskStartedEventArgs e)
{
// if verbosity is detailed or diagnostic
if (IsVerbosityAtLeast(LoggerVerbosity.Detailed))
{
setColor(ConsoleColor.Cyan);
WriteLinePretty(e.Message);
resetColor();
}
if (this.showPerfSummary)
{
PerformanceCounter counter = GetPerformanceCounter(e.TaskName, ref taskPerformanceCounters);
// Place the counter "in scope" meaning the task is executing right now.
counter.InScope = true;
}
// Bump up the overall number of indents, so that anything within this task will show up
// indented.
this.currentIndentLevel++;
}
/// <summary>
/// Handler for task finished events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
/// <owner>t-jeffv, sumedhk</owner>
public override void TaskFinishedHandler(object sender, TaskFinishedEventArgs e)
{
// Done with the task, so shift everything left again.
this.currentIndentLevel--;
if (this.showPerfSummary)
{
PerformanceCounter counter = GetPerformanceCounter(e.TaskName, ref taskPerformanceCounters);
// Place the counter "in scope" meaning the task is done executing.
counter.InScope = false;
}
// if verbosity is detailed or diagnostic
if (IsVerbosityAtLeast(LoggerVerbosity.Detailed))
{
setColor(ConsoleColor.Cyan);
WriteLinePretty(e.Message);
resetColor();
}
}
/// <summary>
/// Prints an error event
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
public override void ErrorHandler(object sender, BuildErrorEventArgs e)
{
errorCount++;
SetErrorsOrWarningsOnCurrentFrame();
ShowDeferredMessages();
setColor(ConsoleColor.Red);
WriteLinePretty(EventArgsFormatting.FormatEventMessage(e, runningWithCharacterFileType));
if (ShowSummary)
{
errorList.Add(e);
}
resetColor();
}
/// <summary>
/// Prints a warning event
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
public override void WarningHandler(object sender, BuildWarningEventArgs e)
{
warningCount++;
SetErrorsOrWarningsOnCurrentFrame();
ShowDeferredMessages();
setColor(ConsoleColor.Yellow);
WriteLinePretty(EventArgsFormatting.FormatEventMessage(e, runningWithCharacterFileType));
if (ShowSummary)
{
warningList.Add(e);
}
resetColor();
}
/// <summary>
/// Prints a message event
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
public override void MessageHandler(object sender, BuildMessageEventArgs e)
{
bool print = false;
bool lightenText = false;
switch (e.Importance)
{
case MessageImportance.High:
print = IsVerbosityAtLeast(LoggerVerbosity.Minimal);
break;
case MessageImportance.Normal:
print = IsVerbosityAtLeast(LoggerVerbosity.Normal);
lightenText = true;
break;
case MessageImportance.Low:
print = IsVerbosityAtLeast(LoggerVerbosity.Detailed);
lightenText = true;
break;
default:
ErrorUtilities.VerifyThrow(false, "Impossible");
break;
}
if (print)
{
ShowDeferredMessages();
if (lightenText)
{
setColor(ConsoleColor.DarkGray);
}
// null messages are ok -- treat as blank line
string nonNullMessage = (e.Message == null) ? String.Empty : e.Message;
WriteLinePretty(nonNullMessage);
if (lightenText)
{
resetColor();
}
}
}
/// <summary>
/// Prints a custom event
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
public override void CustomEventHandler(object sender, CustomBuildEventArgs e)
{
// if verbosity is detailed or diagnostic
if (IsVerbosityAtLeast(LoggerVerbosity.Detailed))
{
// ignore custom events with null messages -- some other
// logger will handle them appropriately
if (e.Message != null)
{
ShowDeferredMessages();
WriteLinePretty(e.Message);
}
}
}
/// <summary>
/// Writes project started messages.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal void WriteProjectStarted()
{
this.VerifyStack(!contextStack.IsEmpty(), "Bad project stack");
//Pop the current project
Frame outerMost = contextStack.Pop();
this.VerifyStack(!outerMost.displayed, "Bad project stack on {0}", outerMost.ID);
this.VerifyStack(outerMost.type == FrameType.Project, "Bad project stack");
outerMost.displayed = true;
contextStack.Push(outerMost);
WriteProjectStartedText(outerMost.ID, outerMost.targetNames, outerMost.parentProjectFile,
this.IsVerbosityAtLeast(LoggerVerbosity.Normal) ? outerMost.indentLevel : 0);
}
/// <summary>
/// Displays the text for a project started message.
/// </summary>
/// <param name ="current">current project file</param>
/// <param name ="previous">previous project file</param>
/// <param name="targetNames">targets that are being invoked</param>
/// <param name="indentLevel">indentation level</param>
/// <owner>t-jeffv, sumedhk</owner>
private void WriteProjectStartedText(string current, string targetNames, string previous, int indentLevel)
{
if (!SkipProjectStartedText)
{
setColor(ConsoleColor.Cyan);
this.VerifyStack((current != null), "Unexpected null project stack");
WriteLinePretty(projectSeparatorLine);
if (previous == null)
{
if ((targetNames == null) || (targetNames.Length == 0))
{
WriteLinePrettyFromResource(indentLevel, "ProjectStartedPrefixForTopLevelProjectWithDefaultTargets", current);
}
else
{
WriteLinePrettyFromResource(indentLevel, "ProjectStartedPrefixForTopLevelProjectWithTargetNames", current, targetNames);
}
}
else
{
if ((targetNames == null) || (targetNames.Length == 0))
{
WriteLinePrettyFromResource(indentLevel, "ProjectStartedPrefixForNestedProjectWithDefaultTargets", previous, current);
}
else
{
WriteLinePrettyFromResource(indentLevel, "ProjectStartedPrefixForNestedProjectWithTargetNames", previous, current, targetNames);
}
}
// add a little bit of extra space
WriteNewLine();
resetColor();
}
}
/// <summary>
/// Writes target started messages.
/// </summary>
/// <owner>SumedhK</owner>
private void WriteTargetStarted()
{
Frame f = contextStack.Pop();
f.displayed = true;
contextStack.Push(f);
setColor(ConsoleColor.Cyan);
if (this.Verbosity == LoggerVerbosity.Diagnostic)
{
WriteLinePrettyFromResource(f.indentLevel, "TargetStartedFromFile", f.ID, f.file);
}
else
{
WriteLinePrettyFromResource(this.IsVerbosityAtLeast(LoggerVerbosity.Normal) ? f.indentLevel : 0,
"TargetStartedPrefix", f.ID);
}
resetColor();
}
/// <summary>
/// Determines the currently building project file.
/// </summary>
/// <returns>name of project file currently being built</returns>
/// <owner>RGoel</owner>
private string GetCurrentlyBuildingProjectFile()
{
if (contextStack.IsEmpty())
{
return null;
}
Frame topOfStack = contextStack.Peek();
// If the top of the stack is a TargetStarted event, then its parent project
// file is the one we want.
if (topOfStack.type == FrameType.Target)
{
return topOfStack.parentProjectFile;
}
// If the top of the stack is a ProjectStarted event, then its ID is the project
// file we want.
else if (topOfStack.type == FrameType.Project)
{
return topOfStack.ID;
}
else
{
ErrorUtilities.VerifyThrow(false, "Unexpected frame type.");
return null;
}
}
/// <summary>
/// Displays project started and target started messages that
/// are shown only when the associated project or target produces
/// output.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
private void ShowDeferredMessages()
{
if (contextStack.IsEmpty())
{
return;
}
if (!contextStack.Peek().displayed)
{
Frame f = contextStack.Pop();
ShowDeferredMessages();
//push now, so that the stack is in a good state
//for WriteProjectStarted() and WriteLinePretty()
//because we use the stack to control indenting
contextStack.Push(f);
switch (f.type)
{
case FrameType.Project:
WriteProjectStarted();
break;
case FrameType.Target:
// Only do things if we're at normal verbosity. If
// we're at a higher verbosity, we can assume that all
// targets have already be printed. If we're at lower
// verbosity we don't need to print at all.
ErrorUtilities.VerifyThrow(this.Verbosity < LoggerVerbosity.Detailed,
"This target should have already been printed at a higher verbosity.");
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
WriteTargetStarted();
}
break;
default:
ErrorUtilities.VerifyThrow(false, "Unexpected frame type.");
break;
}
}
}
/// <summary>
/// Marks the current frame to indicate that an error or warning
/// occurred during it.
/// </summary>
/// <owner>danmose</owner>
private void SetErrorsOrWarningsOnCurrentFrame()
{
// under unit test, there may not be frames on the stack
if (contextStack.Count == 0)
{
return;
}
Frame frame = contextStack.Pop();
frame.hasErrorsOrWarnings = true;
contextStack.Push(frame);
}
/// <summary>
/// Checks the condition passed in. If it's false, it emits an error message to the console
/// indicating that there's a problem with the console logger. These "problems" should
/// never occur in the real world after we ship, unless there's a bug in the MSBuild
/// engine such that events aren't getting paired up properly. So the messages don't
/// really need to be localized here, since they're only for our own benefit, and have
/// zero value to a customer.
/// </summary>
/// <param name="condition"></param>
/// <param name="unformattedMessage"></param>
/// <param name="args"></param>
/// <owner>RGoel</owner>
private void VerifyStack
(
bool condition,
string unformattedMessage,
params object[] args
)
{
if (!condition && !ignoreLoggerErrors)
{
string errorMessage = "INTERNAL CONSOLE LOGGER ERROR. " + ResourceUtilities.FormatString(unformattedMessage, args);
BuildErrorEventArgs errorEvent = new BuildErrorEventArgs(null, null, null, 0, 0, 0, 0,
errorMessage, null, null);
Debug.Assert(false, errorMessage);
ErrorHandler(null, errorEvent);
}
}
#endregion
#region Supporting classes
/// <summary>
/// This enumeration represents the kinds of context that can be
/// stored in the context stack.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal enum FrameType
{
Project,
Target
}
/// <summary>
/// This struct represents context information about a single
/// target or project.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal struct Frame
{
/// <summary>
/// Creates a new instance of frame with all fields specified.
/// </summary>
/// <param name="t">the type of the this frame</param>
/// <param name="d">display state. true indicates this frame has been displayed to the user</param>
/// <param name="indent">indentation level for this frame</param>
/// <param name="s">frame id</param>
/// <param name="targets">targets to execute, in the case of a project frame</param>
/// <param name="fileOfTarget">the file name where the target is defined</param>
/// <param name="parent">parent project file</param>
/// <owner>t-jeffv, sumedhk</owner>
internal Frame
(
FrameType t,
bool d,
int indent,
string s,
string targets,
string fileOfTarget,
string parent
)
{
type = t;
displayed = d;
indentLevel = indent;
ID = s;
targetNames = targets;
file = fileOfTarget;
hasErrorsOrWarnings = false;
parentProjectFile = parent;
}
/// <summary>
/// Indicates if project or target frame.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal FrameType type;
/// <summary>
/// Set to true to indicate the user has seen a message about this frame.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal bool displayed;
/// <summary>
/// The number of tabstops to indent this event when it is eventually displayed.
/// </summary>
/// <owner>RGoel</owner>
internal int indentLevel;
/// <summary>
/// A string associated with this frame -- should be a target name
/// or a project file.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal string ID;
/// <summary>
/// For a TargetStarted or a ProjectStarted event, this field tells us
/// the name of the *parent* project file that was responsible.
/// </summary>
internal string parentProjectFile;
/// <summary>
/// Stores the TargetNames from the ProjectStarted event. Null for Target frames.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal string targetNames;
/// <summary>
/// For TargetStarted events, this stores the filename where the Target is defined
/// (e.g., Microsoft.Common.targets). This is different than the project that is
/// being built.
/// For ProjectStarted events, this is null.
/// </summary>
internal string file;
/// <summary>
/// True if there were errors/warnings during the project or target frame.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal bool hasErrorsOrWarnings;
}
/// <summary>
/// The FrameStack class represents a (lifo) stack of Frames.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal class FrameStack
{
/// <summary>
/// The frames member is contained by FrameStack and does
/// all the heavy lifting for FrameStack.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
private System.Collections.Stack frames;
/// <summary>
/// Create a new, empty, FrameStack.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal FrameStack()
{
frames = new System.Collections.Stack();
}
/// <summary>
/// Remove and return the top element in the stack.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
/// <exception cref="InvalidOperationException">Thrown when stack is empty.</exception>
internal Frame Pop()
{
return (Frame)(frames.Pop());
}
/// <summary>
/// Returns, but does not remove, the top of the stack.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal Frame Peek()
{
return (Frame)(frames.Peek());
}
/// <summary>
/// Push(f) adds f to the top of the stack.
/// </summary>
/// <param name="f">a frame to push</param>
/// <owner>t-jeffv, sumedhk</owner>
internal void Push(Frame f)
{
frames.Push(f);
}
/// <summary>
/// Constant property that indicates the number of elements
/// in the stack.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal int Count
{
get
{
return frames.Count;
}
}
/// <summary>
/// s.IsEmpty() is true iff s.Count == 0
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal bool IsEmpty()
{
return (frames.Count == 0);
}
}
#endregion
#region Private member data
/// <summary>
/// contextStack is the only interesting state in the console
/// logger. The context stack contains a sequence of frames
/// denoting current and previous containing projects and targets
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal FrameStack contextStack = new FrameStack();
#endregion
}
}
| |
/* ====================================================================
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.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
namespace TestCases.POIFS.FileSystem
{
using System;
using System.Collections;
using System.IO;
using NUnit.Framework;
using NPOI.POIFS.FileSystem;
using NPOI.Util;
using NPOI.POIFS.Storage;
using NPOI.POIFS.Properties;
using TestCases.HSSF;
using NPOI.POIFS.Common;
using System.Collections.Generic;
/**
* Tests for POIFSFileSystem
*
* @author Josh Micich
*/
[TestFixture]
public class TestPOIFSFileSystem
{
private POIDataSamples _samples = POIDataSamples.GetPOIFSInstance();
/**
* Mock exception used to ensure correct error handling
*/
private class MyEx : Exception
{
public MyEx()
{
// no fields to initialise
}
}
/**
* Helps facilitate Testing. Keeps track of whether close() was called.
* Also can throw an exception at a specific point in the stream.
*/
private class TestIS : Stream
{
private Stream _is;
private int _FailIndex;
private int _currentIx;
private bool _isClosed;
public TestIS(Stream is1, int FailIndex)
{
_is = is1;
_FailIndex = FailIndex;
_currentIx = 0;
_isClosed = false;
}
public int Read()
{
int result = _is.ReadByte();
if (result >= 0)
{
CheckRead(1);
}
return result;
}
public override int Read(byte[] b, int off, int len)
{
int result = _is.Read(b, off, len);
CheckRead(result);
return result;
}
private void CheckRead(int nBytes)
{
_currentIx += nBytes;
if (_FailIndex > 0 && _currentIx > _FailIndex)
{
throw new MyEx();
}
}
public override void Close()
{
_isClosed = true;
_is.Close();
}
public bool IsClosed()
{
return _isClosed;
}
public override void Flush()
{
_is.Flush();
}
public override long Seek(long offset, SeekOrigin origin)
{
return _is.Seek(offset, origin);
}
public override void SetLength(long value)
{
_is.SetLength(value);
}
// Properties
public override bool CanRead
{
get
{
return _is.CanRead;
}
}
public override bool CanSeek
{
get
{
return _is.CanSeek;
}
}
public override bool CanWrite
{
get
{
return _is.CanWrite;
}
}
public override long Length
{
get
{
return _is.Length;
}
}
public override long Position
{
get
{
return _is.Position;
}
set
{
_is.Position = value;
}
}
public override void Write(byte[] buffer, int offset, int count)
{
}
}
/**
* Test for undesired behaviour observable as of svn revision 618865 (5-Feb-2008).
* POIFSFileSystem was not closing the input stream.
*/
[Test]
public void TestAlwaysClose()
{
TestIS testIS;
// Normal case - Read until EOF and close
testIS = new TestIS(OpenSampleStream("13224.xls"), -1);
try
{
new POIFSFileSystem(testIS);
}
catch (IOException)
{
throw;
}
Assert.IsTrue(testIS.IsClosed(), "input stream was not closed");
// intended to crash after Reading 10000 bytes
testIS = new TestIS(OpenSampleStream("13224.xls"), 10000);
try
{
new POIFSFileSystem(testIS);
Assert.Fail("ex Should have been thrown");
}
catch (IOException)
{
throw;
}
catch (MyEx)
{
// expected
}
Assert.IsTrue(testIS.IsClosed(), "input stream was not closed"); // but still Should close
}
/**
* Test for bug # 48898 - problem opening an OLE2
* file where the last block is short (i.e. not a full
* multiple of 512 bytes)
*
* As yet, this problem remains. One school of thought is
* not not issue an EOF when we discover the last block
* is short, but this seems a bit wrong.
* The other is to fix the handling of the last block in
* POIFS, since it seems to be slight wrong
*/
[Test]
public void TestShortLastBlock()
{
String[] files = new String[] { "ShortLastBlock.qwp", "ShortLastBlock.wps" };
for (int i = 0; i < files.Length; i++)
{
// Open the file up
POIFSFileSystem fs = new POIFSFileSystem(
_samples.OpenResourceAsStream(files[i])
);
// Write it into a temp output array
MemoryStream baos = new MemoryStream();
fs.WriteFileSystem(baos);
// Check sizes
}
}
[Test]
public void TestFATandDIFATsectors()
{
// Open the file up
try
{
Stream stream = _samples.OpenResourceAsStream("ReferencesInvalidSectors.mpp");
try
{
POIFSFileSystem fs = new POIFSFileSystem(stream);
Assert.Fail("File is corrupt and shouldn't have been opened");
}
finally
{
stream.Close();
}
}
catch (IOException e)
{
String msg = e.Message;
Assert.IsTrue(msg.StartsWith("Your file contains 695 sectors"));
}
}
[Test]
public void TestBATandXBAT()
{
byte[] hugeStream = new byte[8 * 1024 * 1024];
POIFSFileSystem fs = new POIFSFileSystem();
fs.Root.CreateDocument("BIG", new MemoryStream(hugeStream));
MemoryStream baos = new MemoryStream();
fs.WriteFileSystem(baos);
byte[] fsData = baos.ToArray();
// Check the header was written properly
Stream inp = new MemoryStream(fsData);
HeaderBlock header = new HeaderBlock(inp);
Assert.AreEqual(109 + 21, header.BATCount);
Assert.AreEqual(1, header.XBATCount);
ByteBuffer xbatData = ByteBuffer.CreateBuffer(512);
xbatData.Write(fsData, (1 + header.XBATIndex) * 512, 512);
xbatData.Position = 0;
BATBlock xbat = BATBlock.CreateBATBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, xbatData);
for (int i = 0; i < 21; i++)
{
Assert.IsTrue(xbat.GetValueAt(i) != POIFSConstants.UNUSED_BLOCK);
}
for (int i = 21; i < 127; i++)
Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, xbat.GetValueAt(i));
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, xbat.GetValueAt(127));
RawDataBlockList blockList = new RawDataBlockList(inp, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS);
Assert.AreEqual(fsData.Length / 512, blockList.BlockCount() + 1);
new BlockAllocationTableReader(header.BigBlockSize,
header.BATCount,
header.BATArray,
header.XBATCount,
header.XBATIndex,
blockList);
Assert.AreEqual(fsData.Length / 512, blockList.BlockCount() + 1);
//fs = null;
//fs = new POIFSFileSystem(new MemoryStream(fsData));
//DirectoryNode root = fs.Root;
//Assert.AreEqual(1, root.EntryCount);
//DocumentNode big = (DocumentNode)root.GetEntry("BIG");
//Assert.AreEqual(hugeStream.Length, big.Size);
}
[Test]
public void Test4KBlocks()
{
Stream inp = _samples.OpenResourceAsStream("BlockSize4096.zvi");
try
{
// First up, check that we can process the header properly
HeaderBlock header_block = new HeaderBlock(inp);
POIFSBigBlockSize bigBlockSize = header_block.BigBlockSize;
Assert.AreEqual(4096, bigBlockSize.GetBigBlockSize());
// Check the fat info looks sane
Assert.AreEqual(1, header_block.BATArray.Length);
Assert.AreEqual(1, header_block.BATCount);
Assert.AreEqual(0, header_block.XBATCount);
// Now check we can get the basic fat
RawDataBlockList data_blocks = new RawDataBlockList(inp, bigBlockSize);
Assert.AreEqual(15, data_blocks.BlockCount());
// Now try and open properly
POIFSFileSystem fs = new POIFSFileSystem(
_samples.OpenResourceAsStream("BlockSize4096.zvi")
);
Assert.IsTrue(fs.Root.EntryCount > 3);
// Check we can get at all the contents
CheckAllDirectoryContents(fs.Root);
// Finally, check we can do a similar 512byte one too
fs = new POIFSFileSystem(
_samples.OpenResourceAsStream("BlockSize512.zvi")
);
Assert.IsTrue(fs.Root.EntryCount > 3);
CheckAllDirectoryContents(fs.Root);
}
finally
{
inp.Close();
}
}
private void CheckAllDirectoryContents(DirectoryEntry dir)
{
IEnumerator<Entry> it = dir.Entries;
//foreach (Entry entry in dir)
while (it.MoveNext())
{
Entry entry = it.Current;
if (entry is DirectoryEntry)
{
CheckAllDirectoryContents((DirectoryEntry)entry);
}
else
{
DocumentNode doc = (DocumentNode)entry;
DocumentInputStream dis = new DocumentInputStream(doc);
try
{
int numBytes = dis.Available();
byte[] data = new byte[numBytes];
dis.Read(data);
}
finally
{
dis.Close();
}
}
}
}
private static Stream OpenSampleStream(String sampleFileName)
{
return HSSFTestDataSamples.OpenSampleFileStream(sampleFileName);
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !WINDOWS_UWP
namespace NLog.Targets
{
using System;
using System.IO;
using System.Text;
using System.ComponentModel;
using NLog.Common;
/// <summary>
/// Writes log messages to the console.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/Console-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/Console/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/Console/Simple/Example.cs" />
/// </example>
[Target("Console")]
public sealed class ConsoleTarget : TargetWithLayoutHeaderAndFooter
{
/// <summary>
/// Should logging being paused/stopped because of the race condition bug in Console.Writeline?
/// </summary>
/// <remarks>
/// Console.Out.Writeline / Console.Error.Writeline could throw 'IndexOutOfRangeException', which is a bug.
/// See http://stackoverflow.com/questions/33915790/console-out-and-console-error-race-condition-error-in-a-windows-service-written
/// and https://connect.microsoft.com/VisualStudio/feedback/details/2057284/console-out-probable-i-o-race-condition-issue-in-multi-threaded-windows-service
///
/// Full error:
/// Error during session close: System.IndexOutOfRangeException: Probable I/ O race condition detected while copying memory.
/// The I/ O package is not thread safe by default.In multithreaded applications,
/// a stream must be accessed in a thread-safe way, such as a thread - safe wrapper returned by TextReader's or
/// TextWriter's Synchronized methods.This also applies to classes like StreamWriter and StreamReader.
///
/// </remarks>
private bool _pauseLogging;
/// <summary>
/// Gets or sets a value indicating whether to send the log messages to the standard error instead of the standard output.
/// </summary>
/// <docgen category='Console Options' order='10' />
[DefaultValue(false)]
public bool Error { get; set; }
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
/// <summary>
/// The encoding for writing messages to the <see cref="Console"/>.
/// </summary>
/// <remarks>Has side effect</remarks>
public Encoding Encoding
{
get => ConsoleTargetHelper.GetConsoleOutputEncoding(_encoding, IsInitialized, _pauseLogging);
set
{
if (ConsoleTargetHelper.SetConsoleOutputEncoding(value, IsInitialized, _pauseLogging))
_encoding = value;
}
}
private Encoding _encoding;
#endif
/// <summary>
/// Gets or sets a value indicating whether to auto-check if the console is available
/// - Disables console writing if Environment.UserInteractive = False (Windows Service)
/// - Disables console writing if Console Standard Input is not available (Non-Console-App)
/// </summary>
[DefaultValue(false)]
public bool DetectConsoleAvailable { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ConsoleTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
public ConsoleTarget() : base()
{
_pauseLogging = false;
DetectConsoleAvailable = false;
OptimizeBufferReuse = true;
}
/// <summary>
///
/// Initializes a new instance of the <see cref="ConsoleTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
/// <param name="name">Name of the target.</param>
public ConsoleTarget(string name) : this()
{
Name = name;
}
/// <summary>
/// Initializes the target.
/// </summary>
protected override void InitializeTarget()
{
_pauseLogging = false;
if (DetectConsoleAvailable)
{
string reason;
_pauseLogging = !ConsoleTargetHelper.IsConsoleAvailable(out reason);
if (_pauseLogging)
{
InternalLogger.Info("Console has been detected as turned off. Disable DetectConsoleAvailable to skip detection. Reason: {0}", reason);
}
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
if (_encoding != null && !_pauseLogging)
Console.OutputEncoding = _encoding;
#endif
base.InitializeTarget();
if (Header != null)
{
WriteToOutput(RenderLogEvent(Header, LogEventInfo.CreateNullEvent()));
}
}
/// <summary>
/// Closes the target and releases any unmanaged resources.
/// </summary>
protected override void CloseTarget()
{
if (Footer != null)
{
WriteToOutput(RenderLogEvent(Footer, LogEventInfo.CreateNullEvent()));
}
base.CloseTarget();
}
/// <summary>
/// Writes the specified logging event to the Console.Out or
/// Console.Error depending on the value of the Error flag.
/// </summary>
/// <param name="logEvent">The logging event.</param>
/// <remarks>
/// Note that the Error option is not supported on .NET Compact Framework.
/// </remarks>
protected override void Write(LogEventInfo logEvent)
{
if (_pauseLogging)
{
//check early for performance
return;
}
WriteToOutput(RenderLogEvent(Layout, logEvent));
}
/// <summary>
/// Write to output
/// </summary>
/// <param name="textLine">text to be written.</param>
private void WriteToOutput(string textLine)
{
if (_pauseLogging)
{
return;
}
var output = GetOutput();
try
{
output.WriteLine(textLine);
}
catch (IndexOutOfRangeException ex)
{
//this is a bug and therefor stopping logging. For docs, see PauseLogging property
_pauseLogging = true;
InternalLogger.Warn(ex, "An IndexOutOfRangeException has been thrown and this is probably due to a race condition." +
"Logging to the console will be paused. Enable by reloading the config or re-initialize the targets");
}
catch (ArgumentOutOfRangeException ex)
{
//this is a bug and therefor stopping logging. For docs, see PauseLogging property
_pauseLogging = true;
InternalLogger.Warn(ex, "An ArgumentOutOfRangeException has been thrown and this is probably due to a race condition." +
"Logging to the console will be paused. Enable by reloading the config or re-initialize the targets");
}
}
private TextWriter GetOutput()
{
return Error ? Console.Error : Console.Out;
}
}
}
#endif
| |
// ****************************************************************
// 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/?p=license&r=2.4
// ****************************************************************
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using NUnit.Util;
using NUnit.Core;
using CP.Windows.Forms;
namespace NUnit.UiKit
{
/// <summary>
/// Summary description for ErrorDisplay.
/// </summary>
public class ErrorDisplay : System.Windows.Forms.UserControl, TestObserver
{
private ISettings settings = null;
int hoverIndex = -1;
private System.Windows.Forms.Timer hoverTimer;
TipWindow tipWindow;
private bool wordWrap = false;
private System.Windows.Forms.ListBox detailList;
public CP.Windows.Forms.ExpandingTextBox stackTrace;
public System.Windows.Forms.Splitter tabSplitter;
private System.Windows.Forms.ContextMenu detailListContextMenu;
private System.Windows.Forms.MenuItem copyDetailMenuItem;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public ErrorDisplay()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Properties
private bool WordWrap
{
get { return wordWrap; }
set
{
if ( value != this.wordWrap )
{
this.wordWrap = value;
this.stackTrace.WordWrap = value;
RefillDetailList();
}
}
}
#endregion
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.detailList = new System.Windows.Forms.ListBox();
this.tabSplitter = new System.Windows.Forms.Splitter();
this.stackTrace = new CP.Windows.Forms.ExpandingTextBox();
this.detailListContextMenu = new System.Windows.Forms.ContextMenu();
this.copyDetailMenuItem = new System.Windows.Forms.MenuItem();
this.SuspendLayout();
//
// detailList
//
this.detailList.Dock = System.Windows.Forms.DockStyle.Top;
this.detailList.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.detailList.Font = new System.Drawing.Font("Courier New", 8.25F);
this.detailList.HorizontalExtent = 2000;
this.detailList.HorizontalScrollbar = true;
this.detailList.ItemHeight = 16;
this.detailList.Location = new System.Drawing.Point(0, 0);
this.detailList.Name = "detailList";
this.detailList.ScrollAlwaysVisible = true;
this.detailList.Size = new System.Drawing.Size(496, 128);
this.detailList.TabIndex = 1;
this.detailList.Resize += new System.EventHandler(this.detailList_Resize);
this.detailList.MouseHover += new System.EventHandler(this.OnMouseHover);
this.detailList.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.detailList_MeasureItem);
this.detailList.MouseMove += new System.Windows.Forms.MouseEventHandler(this.detailList_MouseMove);
this.detailList.MouseLeave += new System.EventHandler(this.detailList_MouseLeave);
this.detailList.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.detailList_DrawItem);
this.detailList.SelectedIndexChanged += new System.EventHandler(this.detailList_SelectedIndexChanged);
//
// tabSplitter
//
this.tabSplitter.Dock = System.Windows.Forms.DockStyle.Top;
this.tabSplitter.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.tabSplitter.Location = new System.Drawing.Point(0, 128);
this.tabSplitter.MinSize = 100;
this.tabSplitter.Name = "tabSplitter";
this.tabSplitter.Size = new System.Drawing.Size(496, 9);
this.tabSplitter.TabIndex = 3;
this.tabSplitter.TabStop = false;
this.tabSplitter.SplitterMoved += new System.Windows.Forms.SplitterEventHandler(this.tabSplitter_SplitterMoved);
//
// stackTrace
//
this.stackTrace.Dock = System.Windows.Forms.DockStyle.Fill;
this.stackTrace.Font = new System.Drawing.Font("Courier New", 9.75F);
this.stackTrace.Location = new System.Drawing.Point(0, 137);
this.stackTrace.Multiline = true;
this.stackTrace.Name = "stackTrace";
this.stackTrace.ReadOnly = true;
this.stackTrace.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.stackTrace.Size = new System.Drawing.Size(496, 151);
this.stackTrace.TabIndex = 2;
this.stackTrace.Text = "";
this.stackTrace.WordWrap = false;
this.stackTrace.KeyUp += new System.Windows.Forms.KeyEventHandler(this.stackTrace_KeyUp);
//
// detailListContextMenu
//
this.detailListContextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.copyDetailMenuItem});
//
// copyDetailMenuItem
//
this.copyDetailMenuItem.Index = 0;
this.copyDetailMenuItem.Text = "Copy";
this.copyDetailMenuItem.Click += new System.EventHandler(this.copyDetailMenuItem_Click);
//
// ErrorDisplay
//
this.Controls.Add(this.stackTrace);
this.Controls.Add(this.tabSplitter);
this.Controls.Add(this.detailList);
this.Name = "ErrorDisplay";
this.Size = new System.Drawing.Size(496, 288);
this.ResumeLayout(false);
}
#endregion
#region Form Level Events
protected override void OnLoad(EventArgs e)
{
// NOTE: DesignMode is not true when display is nested in another
// user control and the containing form is displayed in the designer.
// This is a problem with VS.Net.
//
// Consequently, we rely on the fact that Services.UserSettings
// returns a dummy Service, if the ServiceManager has not been
// initialized.
if ( !this.DesignMode )
{
this.settings = Services.UserSettings;
settings.Changed += new SettingsEventHandler(UserSettings_Changed);
int splitPosition = settings.GetSetting( "Gui.ResultTabs.ErrorsTabSplitterPosition", tabSplitter.SplitPosition );
if ( splitPosition >= tabSplitter.MinSize && splitPosition < this.ClientSize.Height )
this.tabSplitter.SplitPosition = splitPosition;
stackTrace.AutoExpand = settings.GetSetting( "Gui.ResultTabs.ErrorsTab.ToolTipsEnabled", true );
this.WordWrap = settings.GetSetting( "Gui.ResultTabs.ErrorsTab.WordWrapEnabled", true );
}
base.OnLoad (e);
}
#endregion
#region Public Methods
public void Clear()
{
detailList.Items.Clear();
detailList.ContextMenu = null;
stackTrace.Text = "";
}
#endregion
#region UserSettings Events
private void UserSettings_Changed( object sender, SettingsEventArgs args )
{
this.stackTrace.AutoExpand = settings.GetSetting( "Gui.ResultTabs.ErrorsTab.ToolTipsEnabled ", false );
this.WordWrap = settings.GetSetting( "Gui.ResultTabs.ErrorsTab.WordWrapEnabled", true );
}
#endregion
#region DetailList Events
/// <summary>
/// When one of the detail failure items is selected, display
/// the stack trace and set up the tool tip for that item.
/// </summary>
private void detailList_SelectedIndexChanged(object sender, System.EventArgs e)
{
TestResultItem resultItem = (TestResultItem)detailList.SelectedItem;
//string stackTrace = resultItem.StackTrace;
stackTrace.Text = resultItem.StackTrace;
// toolTip.SetToolTip(detailList,resultItem.GetToolTipMessage());
detailList.ContextMenu = detailListContextMenu;
}
private void detailList_MeasureItem(object sender, System.Windows.Forms.MeasureItemEventArgs e)
{
TestResultItem item = (TestResultItem) detailList.Items[e.Index];
//string s = item.ToString();
SizeF size = this.WordWrap
? e.Graphics.MeasureString(item.ToString(), detailList.Font, detailList.ClientSize.Width )
: e.Graphics.MeasureString(item.ToString(), detailList.Font );
e.ItemHeight = (int)size.Height;
e.ItemWidth = (int)size.Width;
}
private void detailList_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
if (e.Index >= 0)
{
e.DrawBackground();
TestResultItem item = (TestResultItem) detailList.Items[e.Index];
bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected) ? true : false;
Brush brush = selected ? SystemBrushes.HighlightText : SystemBrushes.WindowText;
RectangleF layoutRect = e.Bounds;
if ( this.WordWrap && layoutRect.Width > detailList.ClientSize.Width )
layoutRect.Width = detailList.ClientSize.Width;
e.Graphics.DrawString(item.ToString(),detailList.Font, brush, layoutRect);
}
}
private void detailList_Resize(object sender, System.EventArgs e)
{
if ( this.WordWrap ) RefillDetailList();
}
private void RefillDetailList()
{
if ( this.detailList.Items.Count > 0 )
{
this.detailList.BeginUpdate();
ArrayList copiedItems = new ArrayList( detailList.Items );
this.detailList.Items.Clear();
foreach( object item in copiedItems )
this.detailList.Items.Add( item );
this.detailList.EndUpdate();
}
}
private void copyDetailMenuItem_Click(object sender, System.EventArgs e)
{
if ( detailList.SelectedItem != null )
Clipboard.SetDataObject( detailList.SelectedItem.ToString() );
}
private void OnMouseHover(object sender, System.EventArgs e)
{
if ( tipWindow != null ) tipWindow.Close();
if ( settings.GetSetting( "Gui.ResultTabs.ErrorsTab.ToolTipsEnabled", false ) && hoverIndex >= 0 && hoverIndex < detailList.Items.Count )
{
Graphics g = Graphics.FromHwnd( detailList.Handle );
Rectangle itemRect = detailList.GetItemRectangle( hoverIndex );
string text = detailList.Items[hoverIndex].ToString();
SizeF sizeNeeded = g.MeasureString( text, detailList.Font );
bool expansionNeeded =
itemRect.Width < (int)sizeNeeded.Width ||
itemRect.Height < (int)sizeNeeded.Height;
if ( expansionNeeded )
{
tipWindow = new TipWindow( detailList, hoverIndex );
tipWindow.ItemBounds = itemRect;
tipWindow.TipText = text;
tipWindow.Expansion = TipWindow.ExpansionStyle.Both;
tipWindow.Overlay = true;
tipWindow.WantClicks = true;
tipWindow.Closed += new EventHandler( tipWindow_Closed );
tipWindow.Show();
}
}
}
private void tipWindow_Closed( object sender, System.EventArgs e )
{
tipWindow = null;
hoverIndex = -1;
ClearTimer();
}
private void detailList_MouseLeave(object sender, System.EventArgs e)
{
hoverIndex = -1;
ClearTimer();
}
private void detailList_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
ClearTimer();
hoverIndex = detailList.IndexFromPoint( e.X, e.Y );
if ( hoverIndex >= 0 && hoverIndex < detailList.Items.Count )
{
// Workaround problem of IndexFromPoint returning an
// index when mouse is over bottom part of list.
Rectangle r = detailList.GetItemRectangle( hoverIndex );
if ( e.Y > r.Bottom )
hoverIndex = -1;
else
{
hoverTimer = new System.Windows.Forms.Timer();
hoverTimer.Interval = 800;
hoverTimer.Tick += new EventHandler( OnMouseHover );
hoverTimer.Start();
}
}
}
private void ClearTimer()
{
if ( hoverTimer != null )
{
hoverTimer.Stop();
hoverTimer.Dispose();
}
}
private void stackTrace_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
if ( e.KeyCode == Keys.A && e.Modifiers == Keys.Control )
{
stackTrace.SelectAll();
}
}
private void tabSplitter_SplitterMoved( object sender, SplitterEventArgs e )
{
settings.SaveSetting( "Gui.ResultTabs.ErrorsTabSplitterPosition", tabSplitter.SplitPosition );
}
#endregion
#region TestObserver Interface
public void Subscribe(ITestEvents events)
{
events.TestFinished += new TestEventHandler(OnTestFinished);
events.SuiteFinished += new TestEventHandler(OnSuiteFinished);
events.TestException += new TestEventHandler(OnTestException);
}
#endregion
#region Test Event Handlers
private void OnTestFinished(object sender, TestEventArgs args)
{
TestResult result = args.Result;
if( result.Executed && result.IsFailure && result.FailureSite != FailureSite.Parent )
InsertTestResultItem( result );
}
private void OnSuiteFinished(object sender, TestEventArgs args)
{
TestResult result = args.Result;
if( result.Executed && result.IsFailure &&
result.FailureSite != FailureSite.Child )
InsertTestResultItem( result );
}
private void OnTestException(object sender, TestEventArgs args)
{
string msg = string.Format( "An unhandled {0} was thrown while executing this test : {1}",
args.Exception.GetType().FullName, args.Exception.Message );
TestResultItem item = new TestResultItem( args.Name, msg, args.Exception.StackTrace );
InsertTestResultItem( item );
}
private void InsertTestResultItem( TestResult result )
{
TestResultItem item = new TestResultItem(result);
InsertTestResultItem( item );
}
private void InsertTestResultItem( TestResultItem item )
{
detailList.BeginUpdate();
detailList.Items.Insert(detailList.Items.Count, item);
detailList.EndUpdate();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using hw.DebugFormatter;
using hw.Helper;
using hw.Scanner;
using Reni.Basics;
using Reni.Code;
using Reni.Context;
using Reni.SyntaxTree;
using Reni.TokenClasses;
using Reni.Type;
using Reni.Validation;
namespace Reni.Feature
{
static class Extension
{
static readonly
FunctionCache<Func<Category, ResultCache, ContextBase, ValueSyntax, Result>, MetaFunction>
MetaFunctionCache = new(function => new(function));
static readonly FunctionCache<Func<Category, Result>, FunctionCache<TypeBase, Value>> ValueCache
= new(
function =>
new(type => new(function, type)));
static readonly FunctionCache<Func<Category, Result>, FunctionCache<TypeBase, Conversion>> ConversionCache
= new(
function =>
new(type => new(function, type)));
internal static Value Value(Func<Category, Result> function, TypeBase target = null)
=> ValueCache[function][(target ?? function.Target as TypeBase).AssertNotNull()];
internal static Conversion Conversion
(Func<Category, Result> function, TypeBase target = null)
=> ConversionCache[function][(target ?? function.Target as TypeBase).AssertNotNull()];
internal static ObjectFunction FunctionFeature
(
Func<Category, IContextReference, TypeBase, Result> function,
IContextReferenceProvider target = null
)
{
var context = (target ?? function.Target as IContextReferenceProvider).AssertNotNull();
return new(function, context);
}
internal static Function FunctionFeature(Func<Category, TypeBase, Result> function) => new(function);
internal static IImplementation FunctionFeature<T>
(Func<Category, TypeBase, T, Result> function, T arg)
=> new ExtendedFunction<T>(function, arg);
internal static IValue ExtendedValue(this IImplementation feature)
{
var function = ((IEvalImplementation)feature).Function;
if(function != null && function.IsImplicit)
return null;
return feature.Value;
}
internal static MetaFunction MetaFeature
(Func<Category, ResultCache, ContextBase, ValueSyntax, Result> function)
=> MetaFunctionCache[function];
internal static TypeBase ResultType(this IConversion conversion)
=> conversion.Result(Category.Type).Type;
internal static Result Result(this IConversion conversion, Category category)
{
var result = conversion.Execute(category);
(result != null).Assert();
if(!result.HasIssue && category.HasCode && result.Code.ArgType != null)
(result.Code.ArgType == conversion.Source).Assert
(() => result.DebuggerDump());
return result;
}
public static IEnumerable<IGenericProviderForType> GenericListFromType<T>
(this T target, IEnumerable<IGenericProviderForType> baseList = null)
where T : TypeBase
=> CreateList(baseList, () => new GenericProviderForType<T>(target));
public static IEnumerable<IDeclarationProvider> GenericListFromDefinable<T>
(this T target, IEnumerable<IDeclarationProvider> baseList = null)
where T : Definable
=> CreateList(baseList, () => new GenericProviderForDefinable<T>(target));
static IEnumerable<TGeneric> CreateList<TGeneric>
(IEnumerable<TGeneric> baseList, Func<TGeneric> creator)
{
yield return creator();
if(baseList == null)
yield break;
foreach(var item in baseList)
yield return item;
}
internal static Result Result
(
this IEvalImplementation feature,
Category category,
SourcePart currentTarget,
ContextBase context,
ValueSyntax right
)
{
(feature.Function == null || !feature.Function.IsImplicit || feature.Value == null).Assert
();
var valueCategory = category;
if(right != null)
valueCategory = category.WithType;
var valueResult = feature.ValueResult(context, right, valueCategory);
if(right == null)
{
if(valueResult != null)
return valueResult;
return IssueId
.MissingRightExpression
.IssueResult(category, currentTarget);
}
if(valueResult == null)
{
if(feature.Function == null)
Dumpable.NotImplementedFunction(feature, category, currentTarget, context, right);
(feature.Function != null).Assert();
var argsResult = context.ResultAsReferenceCache(right);
var argsType = argsResult.Type;
if(argsType == null)
return argsResult.GetCategories(category);
var result = feature.Function.Result(category, argsType);
return result.ReplaceArg(argsResult);
}
return valueResult
.Type
.Execute(category, valueResult, currentTarget, null, context, right);
}
static Result ValueResult
(
this IEvalImplementation feature,
ContextBase context,
ValueSyntax right,
Category valueCategory
)
{
if(feature.Function != null && feature.Function.IsImplicit)
{
var result = feature
.Function
.Result(valueCategory, context.RootContext.VoidType);
return result
.ReplaceArg(context.RootContext.VoidType.Result(Category.All));
}
if(right != null && feature.Function != null)
return null;
return feature.Value?.Execute(valueCategory);
}
internal static Result Result
(
this IImplementation feature,
Category category,
ResultCache left,
SourcePart token,
ContextBase context,
ValueSyntax right
)
{
var metaFeature = ((IMetaImplementation)feature).Function;
if(metaFeature != null)
return metaFeature.Result(category, left, context, right);
return feature
.Result(category, token, context, right)
.ReplaceArg(left);
}
internal static T DistinctNotNull<T>(this IEnumerable<T> enumerable)
where T : class
=> enumerable
.Where(x => x != null)
.Distinct()
.SingleOrDefault();
internal static Result Result(this Issue[] issues, Category category) => new(category, issues);
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using BTDB.Buffer;
using BTDB.Collections;
using BTDB.Encrypted;
using BTDB.EventStoreLayer;
using BTDB.FieldHandler;
using BTDB.IL;
using BTDB.KVDBLayer;
using BTDB.ODBLayer;
using BTDB.StreamLayer;
namespace BTDB.EventStore2Layer
{
public class EventDeserializer : IEventDeserializer, ITypeDescriptorCallbacks, ITypeBinaryDeserializerContext
{
public const int ReservedBuildinTypes = 50;
readonly Dictionary<object, DeserializerTypeInfo> _typeOrDescriptor2Info =
new Dictionary<object, DeserializerTypeInfo>(ReferenceEqualityComparer<object>.Instance);
StructList<DeserializerTypeInfo?> _id2Info;
StructList<DeserializerTypeInfo?> _id2InfoNew;
readonly Dictionary<ITypeDescriptor, ITypeDescriptor> _remapToOld =
new Dictionary<ITypeDescriptor, ITypeDescriptor>(ReferenceEqualityComparer<ITypeDescriptor>.Instance);
StructList<object> _visited;
readonly object _lock = new object();
readonly ISymmetricCipher _symmetricCipher;
public EventDeserializer(ITypeNameMapper? typeNameMapper = null,
ITypeConvertorGenerator? typeConvertorGenerator = null, ISymmetricCipher? symmetricCipher = null)
{
TypeNameMapper = typeNameMapper ?? new FullNameTypeMapper();
ConvertorGenerator = typeConvertorGenerator ?? DefaultTypeConvertorGenerator.Instance;
_symmetricCipher = symmetricCipher ?? new InvalidSymmetricCipher();
_id2Info.Reserve(ReservedBuildinTypes + 10);
_id2Info.Add(null); // 0 = null
_id2Info.Add(null); // 1 = back reference
foreach (var predefinedType in BasicSerializersFactory.TypeDescriptors)
{
var infoForType = new DeserializerTypeInfo
{
Id = (int)_id2Info.Count,
Descriptor = predefinedType
};
_typeOrDescriptor2Info[predefinedType] = infoForType;
_id2Info.Add(infoForType);
_typeOrDescriptor2Info.TryAdd(predefinedType.GetPreferredType(), infoForType);
var descriptorMultipleNativeTypes = predefinedType as ITypeDescriptorMultipleNativeTypes;
if (descriptorMultipleNativeTypes == null) continue;
foreach (var type in descriptorMultipleNativeTypes.GetNativeTypes())
{
_typeOrDescriptor2Info[type] = infoForType;
}
}
while (_id2Info.Count < ReservedBuildinTypes) _id2Info.Add(null);
}
public ITypeDescriptor? DescriptorOf(object obj)
{
if (obj == null) return null;
var knowDescriptor = obj as IKnowDescriptor;
if (knowDescriptor != null) return knowDescriptor.GetDescriptor();
if (!_typeOrDescriptor2Info.TryGetValue(obj.GetType(), out var info))
return null;
return info.Descriptor;
}
public ITypeDescriptor? DescriptorOf(Type type)
{
return !_typeOrDescriptor2Info.TryGetValue(type, out var info) ? null : info.Descriptor;
}
public bool IsSafeToLoad(Type type)
{
if (!type.IsGenericType) return true;
if (type.GetGenericTypeDefinition() == typeof(IIndirect<>)) return false;
if (type.GetGenericArguments().Any(t => !IsSafeToLoad(t))) return false;
return true;
}
public ITypeConvertorGenerator ConvertorGenerator { get; }
public ITypeNameMapper TypeNameMapper { get; }
public Type LoadAsType(ITypeDescriptor descriptor)
{
return descriptor.GetPreferredType() ?? TypeNameMapper.ToType(descriptor.Name!) ?? typeof(object);
}
public Type LoadAsType(ITypeDescriptor descriptor, Type targetType)
{
return descriptor.GetPreferredType(targetType) ?? TypeNameMapper.ToType(descriptor.Name) ?? typeof(object);
}
ITypeDescriptor NestedDescriptorReader(ref SpanReader reader)
{
var typeId = reader.ReadVInt32();
if (typeId < 0 && -typeId - 1 < _id2InfoNew.Count)
{
var infoForType = _id2InfoNew[-typeId - 1];
if (infoForType != null)
return infoForType.Descriptor!;
}
else if (typeId > 0)
{
if (typeId >= _id2Info.Count)
throw new BTDBException("Metadata corrupted");
var infoForType = _id2Info[typeId];
if (infoForType == null)
throw new BTDBException("Metadata corrupted");
return infoForType.Descriptor!;
}
return new PlaceHolderDescriptor(typeId);
}
public void ProcessMetadataLog(ByteBuffer buffer)
{
lock (_lock)
{
var reader = new SpanReader(buffer);
var typeId = reader.ReadVInt32();
while (typeId != 0)
{
var typeCategory = (TypeCategory)reader.ReadUInt8();
ITypeDescriptor descriptor;
switch (typeCategory)
{
case TypeCategory.BuildIn:
throw new ArgumentOutOfRangeException();
case TypeCategory.Class:
descriptor = new ObjectTypeDescriptor(this, ref reader, NestedDescriptorReader);
break;
case TypeCategory.List:
descriptor = new ListTypeDescriptor(this, ref reader, NestedDescriptorReader);
break;
case TypeCategory.Dictionary:
descriptor = new DictionaryTypeDescriptor(this, ref reader, NestedDescriptorReader);
break;
case TypeCategory.Enum:
descriptor = new EnumTypeDescriptor(this, ref reader);
break;
case TypeCategory.Nullable:
descriptor = new NullableTypeDescriptor(this, ref reader, NestedDescriptorReader);
break;
case TypeCategory.Tuple:
descriptor = new TupleTypeDescriptor(this, ref reader, NestedDescriptorReader);
break;
default:
throw new ArgumentOutOfRangeException();
}
while (-typeId - 1 >= _id2InfoNew.Count)
_id2InfoNew.Add(null);
_id2InfoNew[-typeId - 1] ??= new DeserializerTypeInfo { Id = typeId, Descriptor = descriptor };
typeId = reader.ReadVInt32();
}
for (var i = 0; i < _id2InfoNew.Count; i++)
{
_id2InfoNew[i]!.Descriptor!.MapNestedTypes(d =>
d is PlaceHolderDescriptor placeHolderDescriptor
? _id2InfoNew[-placeHolderDescriptor.TypeId - 1]!.Descriptor
: d);
}
// This additional cycle is needed to fill names of recursive structures
for (var i = 0; i < _id2InfoNew.Count; i++)
{
_id2InfoNew[i]!.Descriptor!.MapNestedTypes(d => d);
}
for (var i = 0; i < _id2InfoNew.Count; i++)
{
var infoForType = _id2InfoNew[i];
for (var j = ReservedBuildinTypes; j < _id2Info.Count; j++)
{
if (infoForType!.Descriptor.Equals(_id2Info[j]!.Descriptor))
{
_remapToOld[infoForType.Descriptor] = _id2Info[j]!.Descriptor;
_id2InfoNew[i] = _id2Info[j];
infoForType = _id2InfoNew[i];
break;
}
}
if (infoForType!.Id < 0)
{
infoForType.Id = (int)_id2Info.Count;
_id2Info.Add(infoForType);
_typeOrDescriptor2Info[infoForType.Descriptor!] = infoForType;
}
}
for (var i = 0; i < _id2InfoNew.Count; i++)
{
_id2InfoNew[i]!.Descriptor!.MapNestedTypes(d => _remapToOld.TryGetValue(d, out var res) ? res : d);
}
_id2InfoNew.Clear();
_remapToOld.Clear();
}
}
Layer2Loader LoaderFactory(ITypeDescriptor descriptor)
{
var loadAsType = LoadAsType(descriptor);
var methodBuilder = ILBuilder.Instance.NewMethod<Layer2Loader>("DeserializerFor" + descriptor.Name);
var il = methodBuilder.Generator;
try
{
descriptor.GenerateLoad(il, ilGen => ilGen.Ldarg(0), ilGen => ilGen.Ldarg(1), ilGen => ilGen.Ldarg(2),
loadAsType);
}
catch (BTDBException ex)
{
throw new BTDBException("Deserialization of type " + loadAsType.FullName, ex);
}
if (loadAsType.IsValueType)
{
il.Box(loadAsType);
}
else if (loadAsType != typeof(object))
{
il.Castclass(typeof(object));
}
il.Ret();
return methodBuilder.Create();
}
public bool Deserialize(out object? @object, ByteBuffer buffer)
{
lock (_lock)
{
var reader = new SpanReader(buffer);
@object = null;
try
{
@object = LoadObject(ref reader);
}
catch (BtdbMissingMetadataException)
{
return false;
}
finally
{
_visited.Clear();
}
return true;
}
}
class BtdbMissingMetadataException : Exception
{
}
public object? LoadObject(ref SpanReader reader)
{
var typeId = reader.ReadVUInt32();
if (typeId == 0)
{
return null;
}
if (typeId == 1)
{
var backRefId = reader.ReadVUInt32();
return _visited[(int)backRefId];
}
if (typeId >= _id2Info.Count)
throw new BtdbMissingMetadataException();
var infoForType = _id2Info[(int)typeId];
if (infoForType!.Loader == null)
{
infoForType.Loader = LoaderFactory(infoForType.Descriptor!);
}
return infoForType.Loader(ref reader, this, infoForType.Descriptor!);
}
public void AddBackRef(object obj)
{
_visited.Add(obj);
}
public void SkipObject(ref SpanReader reader)
{
var typeId = reader.ReadVUInt32();
if (typeId == 0)
{
return;
}
if (typeId == 1)
{
var backRefId = reader.ReadVUInt32();
if (backRefId > _visited.Count) throw new InvalidDataException();
return;
}
if (typeId >= _id2Info.Count)
throw new BtdbMissingMetadataException();
var infoForType = _id2Info[(int)typeId];
if (infoForType!.Loader == null)
{
infoForType.Loader = LoaderFactory(infoForType.Descriptor!);
}
infoForType.Loader(ref reader, this, infoForType.Descriptor!);
}
public EncryptedString LoadEncryptedString(ref SpanReader reader)
{
var enc = reader.ReadByteArray();
var size = _symmetricCipher.CalcPlainSizeFor(enc);
var dec = new byte[size];
if (!_symmetricCipher.Decrypt(enc, dec))
{
throw new CryptographicException();
}
var r = new SpanReader(dec);
return r.ReadString();
}
public void SkipEncryptedString(ref SpanReader reader)
{
reader.SkipByteArray();
}
}
}
| |
// 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.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class UnionTests
{
private const int DuplicateFactor = 8;
// Get two ranges, with the right starting where the left ends
public static IEnumerable<object[]> UnionUnorderedCountData(int[] counts)
{
foreach (int left in counts)
{
foreach (int right in counts)
{
yield return new object[] { left, right };
}
}
}
public static IEnumerable<object[]> UnionUnorderedData(int[] counts)
{
foreach (object[] parms in UnorderedSources.BinaryRanges(counts, (l, r) => l, counts))
{
yield return parms.Take(4).ToArray();
}
}
// Union returns only the ordered portion ordered.
// Get two ranges, both ordered.
public static IEnumerable<object[]> UnionData(int[] counts)
{
foreach (object[] parms in UnionUnorderedData(counts))
{
yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] };
}
}
// Get two ranges, with only the left being ordered.
public static IEnumerable<object[]> UnionFirstOrderedData(int[] counts)
{
foreach (object[] parms in UnionUnorderedData(counts))
{
yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], parms[2], parms[3] };
}
}
// Get two ranges, with only the right being ordered.
public static IEnumerable<object[]> UnionSecondOrderedData(int[] counts)
{
foreach (object[] parms in UnionUnorderedData(counts))
{
yield return new object[] { parms[0], parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] };
}
}
// Get two ranges, both sourced from arrays, with duplicate items in each array.
// Used in distinctness tests, in contrast to relying on a Select predicate to generate duplicate items.
public static IEnumerable<object[]> UnionSourceMultipleData(int[] counts)
{
foreach (int leftCount in counts)
{
ParallelQuery<int> left = Enumerable.Range(0, leftCount * DuplicateFactor).Select(x => x % leftCount).ToArray().AsParallel();
foreach (int rightCount in new[] { 0, 1, Math.Max(DuplicateFactor, leftCount / 2), Math.Max(DuplicateFactor, leftCount) }.Distinct())
{
int rightStart = leftCount - Math.Min(leftCount, rightCount) / 2;
ParallelQuery<int> right = Enumerable.Range(0, rightCount * DuplicateFactor).Select(x => x % rightCount + rightStart).ToArray().AsParallel();
yield return new object[] { left, leftCount, right, rightCount, Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2 };
}
}
}
//
// Union
//
[Theory]
[MemberData(nameof(UnionUnorderedCountData), new[] { 0, 1, 2, 16 })]
public static void Union_Unordered(int leftCount, int rightCount)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(leftCount, rightCount);
IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount);
foreach (int i in leftQuery.Union(rightQuery))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void Union_Unordered_Longrunning()
{
Union_Unordered(Sources.OuterLoopCount, Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(UnionData), new[] { 0, 1, 2, 16 })]
public static void Union(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
foreach (int i in leftQuery.Union(rightQuery))
{
Assert.Equal(seen++, i);
}
Assert.Equal(leftCount + rightCount, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionData), new[] { 512, 1024 * 8 })]
public static void Union_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnionFirstOrderedData), new[] { 0, 1, 2, 16 })]
public static void Union_FirstOrdered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, rightCount);
int seen = 0;
foreach (int i in leftQuery.Union(rightQuery))
{
if (i < leftCount)
{
Assert.Equal(seen++, i);
}
else
{
seenUnordered.Add(i);
}
}
Assert.Equal(leftCount, seen);
seenUnordered.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionFirstOrderedData), new[] { 512, 1024 * 8 })]
public static void Union_FirstOrdered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_FirstOrdered(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnionSecondOrderedData), new[] { 0, 1, 2, 16 })]
public static void Union_SecondOrdered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount);
int seen = leftCount;
foreach (int i in leftQuery.Union(rightQuery))
{
if (i >= leftCount)
{
Assert.Equal(seen++, i);
}
else
{
seenUnordered.Add(i);
}
}
Assert.Equal(leftCount + rightCount, seen);
seenUnordered.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionSecondOrderedData), new[] { 512, 1024 * 8 })]
public static void Union_SecondOrdered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_SecondOrdered(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnionUnorderedCountData), new[] { 0, 1, 2, 16 })]
public static void Union_Unordered_NotPipelined(int leftCount, int rightCount)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(leftCount, rightCount);
IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount);
Assert.All(leftQuery.Union(rightQuery).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void Union_Unordered_NotPipelined_Longrunning()
{
Union_Unordered_NotPipelined(Sources.OuterLoopCount, Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(UnionData), new[] { 0, 1, 2, 16 })]
public static void Union_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
Assert.All(leftQuery.Union(rightQuery).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(leftCount + rightCount, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionData), new[] { 512, 1024 * 8 })]
public static void Union_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnionFirstOrderedData), new[] { 0, 1, 2, 16 })]
public static void Union_FirstOrdered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, rightCount);
int seen = 0;
Assert.All(leftQuery.Union(rightQuery).ToList(), x =>
{
if (x < leftCount) Assert.Equal(seen++, x);
else seenUnordered.Add(x);
});
Assert.Equal(leftCount, seen);
seenUnordered.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionFirstOrderedData), new[] { 512, 1024 * 8 })]
public static void Union_FirstOrdered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_FirstOrdered_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnionSecondOrderedData), new[] { 0, 1, 2, 16 })]
public static void Union_SecondOrdered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount);
int seen = leftCount;
Assert.All(leftQuery.Union(rightQuery).ToList(), x =>
{
if (x >= leftCount) Assert.Equal(seen++, x);
else seenUnordered.Add(x);
});
Assert.Equal(leftCount + rightCount, seen);
seenUnordered.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionSecondOrderedData), new[] { 512, 1024 * 8 })]
public static void Union_SecondOrdered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_SecondOrdered_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnionUnorderedCountData), new[] { 0, 1, 2, 16 })]
public static void Union_Unordered_Distinct(int leftCount, int rightCount)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(leftCount, rightCount);
leftCount = Math.Min(DuplicateFactor, leftCount);
rightCount = Math.Min(DuplicateFactor, rightCount);
int offset = leftCount - Math.Min(leftCount, rightCount) / 2;
int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2;
IntegerRangeSet seen = new IntegerRangeSet(0, expectedCount);
foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2)))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void Union_Unordered_Distinct_Longrunning()
{
Union_Unordered_Distinct(Sources.OuterLoopCount, Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(UnionData), new[] { 0, 1, 2, 16 })]
public static void Union_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
leftCount = Math.Min(DuplicateFactor, leftCount);
rightCount = Math.Min(DuplicateFactor, rightCount);
int offset = leftCount - Math.Min(leftCount, rightCount) / 2;
int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2;
int seen = 0;
foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2)))
{
Assert.Equal(seen++, i);
}
Assert.Equal(expectedCount, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionData), new[] { 512, 1024 * 8 })]
public static void Union_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_Distinct(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnionUnorderedCountData), new[] { 0, 1, 2, 16 })]
public static void Union_Unordered_Distinct_NotPipelined(int leftCount, int rightCount)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(leftCount, rightCount);
leftCount = Math.Min(DuplicateFactor, leftCount);
rightCount = Math.Min(DuplicateFactor, rightCount);
int offset = leftCount - Math.Min(leftCount, rightCount) / 2;
int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2;
IntegerRangeSet seen = new IntegerRangeSet(0, expectedCount);
Assert.All(leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2)).ToList(),
x => seen.Add(x));
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void Union_Unordered_Distinct_NotPipelined_Longrunning()
{
Union_Unordered_Distinct_NotPipelined(Sources.OuterLoopCount, Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(UnionData), new[] { 0, 1, 2, DuplicateFactor * 2 })]
public static void Union_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
leftCount = Math.Min(DuplicateFactor, leftCount);
rightCount = Math.Min(DuplicateFactor, rightCount);
int offset = leftCount - Math.Min(leftCount, rightCount) / 2;
int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2;
int seen = 0;
Assert.All(leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2)).ToList(),
x => Assert.Equal(seen++, x));
Assert.Equal(expectedCount, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionData), new[] { 512, 1024 * 8 })]
public static void Union_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_Distinct_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnionSourceMultipleData), new[] { 0, 1, 2, DuplicateFactor * 2 })]
public static void Union_Unordered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
// The difference between this test and the previous, is that it's not possible to
// get non-unique results from ParallelEnumerable.Range()...
// Those tests either need modification of source (via .Select(x => x / DuplicateFactor) or similar,
// or via a comparator that considers some elements equal.
_ = leftCount;
_ = rightCount;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(leftQuery.Union(rightQuery), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionSourceMultipleData), new[] { 512, 1024 * 8 })]
public static void Union_Unordered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Union_Unordered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count);
}
[Theory]
[MemberData(nameof(UnionSourceMultipleData), new[] { 0, 1, 2, DuplicateFactor * 2 })]
public static void Union_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
_ = leftCount;
_ = rightCount;
int seen = 0;
Assert.All(leftQuery.AsOrdered().Union(rightQuery.AsOrdered()), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionSourceMultipleData), new[] { 512, 1024 * 8 })]
public static void Union_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Union_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count);
}
[Fact]
public static void Union_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Union(Enumerable.Range(0, 1)));
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Union(Enumerable.Range(0, 1), null));
#pragma warning restore 618
}
[Fact]
// Should not get the same setting from both operands.
public static void Union_NoDuplicateSettings()
{
CancellationToken t = new CancellationTokenSource().Token;
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Union(ParallelEnumerable.Range(0, 1).WithCancellation(t)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Union(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Union(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Union(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default)));
}
[Fact]
public static void Union_ArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).Union(ParallelEnumerable.Range(0, 1)));
AssertExtensions.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Union(null));
AssertExtensions.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).Union(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default));
AssertExtensions.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Union(null, EqualityComparer<int>.Default));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.DigitalTwins.Core.Serialization;
namespace Azure.DigitalTwins.Core
{
internal partial class DigitalTwinModelsRestClient
{
// The modelUpdates parameter needs to be changed from IEnumerable<object> to IEnumerable<string>
// and not parsed like a json object.
public async Task<Response<IReadOnlyList<ModelData>>> AddAsync(IEnumerable<string> models = null, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope("DigitalTwinModelsClient.Add");
scope.Start();
try
{
using HttpMessage message = CreateAddRequest(models);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 201:
{
IReadOnlyList<ModelData> value = default;
using JsonDocument document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
List<ModelData> array = new List<ModelData>(document.RootElement.GetArrayLength());
foreach (JsonElement item in document.RootElement.EnumerateArray())
{
array.Add(ModelData.DeserializeModelData(item));
}
value = array;
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
// The modelUpdates parameter needs to be changed from IEnumerable<object> to IEnumerable<string>
// and not parsed like a json object.
internal Response<IReadOnlyList<ModelData>> Add(IEnumerable<string> models = null, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope("DigitalTwinModelsClient.Add");
scope.Start();
try
{
using HttpMessage message = CreateAddRequest(models);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 201:
{
IReadOnlyList<ModelData> value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
List<ModelData> array = new List<ModelData>(document.RootElement.GetArrayLength());
foreach (JsonElement item in document.RootElement.EnumerateArray())
{
array.Add(ModelData.DeserializeModelData(item));
}
value = array;
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
// The modelUpdates parameter needs to be changed from IEnumerable<object> to IEnumerable<string>
// and not parsed like a json object.
internal async Task<Response> UpdateAsync(string id, IEnumerable<string> modelUpdates, CancellationToken cancellationToken = default)
{
if (id == null)
{
throw new ArgumentNullException(nameof(id));
}
if (modelUpdates == null)
{
throw new ArgumentNullException(nameof(modelUpdates));
}
using DiagnosticScope scope = _clientDiagnostics.CreateScope("DigitalTwinModelsClient.Update");
scope.Start();
try
{
using HttpMessage message = CreateUpdateRequest(id, modelUpdates);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
return message.Response.Status switch
{
204 => message.Response,
_ => throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false),
};
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
// The modelUpdates parameter needs to be changed from IEnumerable<object> to IEnumerable<string>
// and not parsed like a json object.
internal Response Update(string id, IEnumerable<string> modelUpdates, CancellationToken cancellationToken = default)
{
if (id == null)
{
throw new ArgumentNullException(nameof(id));
}
if (modelUpdates == null)
{
throw new ArgumentNullException(nameof(modelUpdates));
}
using DiagnosticScope scope = _clientDiagnostics.CreateScope("DigitalTwinModelsClient.Update");
scope.Start();
try
{
using HttpMessage message = CreateUpdateRequest(id, modelUpdates);
_pipeline.Send(message, cancellationToken);
return message.Response.Status switch
{
204 => message.Response,
_ => throw _clientDiagnostics.CreateRequestFailedException(message.Response),
};
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
// The strings are already json, so we do not want them to be serialized.
// Instead, the payloads need to be concatenated into a json array.
private HttpMessage CreateAddRequest(IEnumerable<string> models)
{
HttpMessage message = _pipeline.CreateMessage();
Request request = message.Request;
request.Method = RequestMethod.Post;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/models", false);
uri.AppendQuery("api-version", apiVersion, true);
request.Uri = uri;
request.Headers.Add("Content-Type", "application/json; charset=utf-8");
if (models != null)
{
string modelsJsonArray = PayloadHelper.BuildArrayPayload(models);
request.Content = new StringRequestContent(modelsJsonArray);
}
return message;
}
// The strings are already json, so we do not want them to be serialized.
// Instead, the payloads need to be concatenated into a json array.
internal HttpMessage CreateUpdateRequest(string id, IEnumerable<string> modelUpdates)
{
HttpMessage message = _pipeline.CreateMessage();
Request request = message.Request;
request.Method = RequestMethod.Patch;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/models/", false);
uri.AppendPath(id, true);
uri.AppendQuery("api-version", apiVersion, true);
request.Uri = uri;
request.Headers.Add("Content-Type", "application/json; charset=utf-8");
if (modelUpdates != null)
{
string modelUpdatesArray = PayloadHelper.BuildArrayPayload(modelUpdates);
request.Content = new StringRequestContent(modelUpdatesArray);
}
return message;
}
#region null overrides
// The following methods are only declared so that autorest does not create these functions in the generated code.
// For methods that we need to override, when the parameter list is the same, autorest knows not to generate them again.
// When the parameter list changes, autorest generates the methods again.
// As such, these methods are declared here and made private, while the public method is declared above, too.
// These methods should never be called.
#pragma warning disable CA1801, IDE0051, IDE0060 // Remove unused parameter
// Original return type is Task<Response<IReadOnlyList<ModelData>>>. Changing to object to allow returning null.
private object AddAsync(IEnumerable<object> models = null, CancellationToken cancellationToken = default) => null;
private Response<IReadOnlyList<ModelData>> Add(IEnumerable<object> models = null, CancellationToken cancellationToken = default) => null;
// Original return type is ValueTask<Response>. Changing to object to allow returing null.
private object UpdateAsync(string id, IEnumerable<object> updateModel, CancellationToken cancellationToken = default) => null;
private Response Update(string id, IEnumerable<object> updateModel, CancellationToken cancellationToken = default) => null;
private HttpMessage CreateAddRequest(IEnumerable<object> models) => null;
#pragma warning restore CA1801, IDE0051, IDE0060 // Remove unused parameter
#endregion null overrides
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using Crownwood.DotNetMagic.Controls;
namespace HWD.DetailsControls
{
public enum OSLanguague
{
Arabic = 0x0001,
Chinese = 0x0004,
English = 0x0009,
Arabic_SaudiArabia = 0x0401,
Bulgarian = 0x0402,
Catalan = 0x0403,
Chinese_Taiwan = 0x0404,
Czech = 0x0405,
Danish = 0x0406,
German_Germany = 0x0407,
Greek = 0x0408,
English_UnitedStates = 0x0409,
Spanish_TraditionalSort = 0x040A,
Finnish = 0x040B,
French_France = 0x040C,
Hebrew = 0x040D,
Hungarian = 0x040E,
Icelandic = 0x040F,
Italian_Italy = 0x0410,
Japanese = 0x0411,
Korean = 0x0412,
Dutch_Netherlands = 0x0413,
Norwegian_Bokmal = 0x0414,
Polish = 0x0415,
Portuguese_Brazil = 0x0416,
RhaetoRomanic = 0x0417,
Romanian = 0x0418,
Russian = 0x0419,
Croatian = 0x041A,
Slovak = 0x041B,
Albanian = 0x041C,
Swedish = 0x041D,
Thai = 0x041E,
Turkish = 0x041F,
Urdu = 0x0420,
Indonesian = 0x0421,
Ukrainian = 0x0422,
Belarusian = 0x0423,
Slovenian = 0x0424,
Estonian = 0x0425,
Latvian = 0x0426,
Lithuanian = 0x0427,
Farsi = 0x0429,
Vietnamese = 0x042A,
Basque = 0x042D,
Serbian = 0x042E,
Macedonian_FYROM = 0x042F,
Sutu = 0x0430,
Tsonga = 0x0431,
Tswana = 0x0432,
Xhosa = 0x0434,
Zulu = 0x0435,
Afrikaans = 0x0436,
Faeroese = 0x0438,
Hindi = 0x0439,
Maltese = 0x043A,
Gaelic = 0x043C,
Yiddish = 0x043D,
Malay_Malaysia = 0x043E,
Arabic_Iraq = 0x0801,
Chinese_PRC = 0x0804,
German_Switzerland = 0x0807,
English_UnitedKingdom = 0x0809,
Spanish_Mexico = 0x080A,
French_Belgium = 0x080C,
Italian_Switzerland = 0x0810,
Dutch_Belgium = 0x0813,
Norwegian_Nynorsk = 0x0814,
Portuguese_Portugal = 0x0816,
Romanian_Moldova = 0x0818,
Russian_Moldova = 0x0819,
Serbian_Latin = 0x081A,
Swedish_Finland = 0x081D,
Arabic_Egypt = 0x0C01,
Chinese_HongKongSAR = 0x0C04,
German_Austria = 0x0C07,
English_Australia = 0x0C09,
Spanish_InternationalSort = 0x0C0A,
French_Canada = 0x0C0C,
Serbian_Cyrillic = 0x0C1A,
Arabic_Libya = 0x1001,
Chinese_Singapore = 0x1004,
German_Luxembourg = 0x1007,
English_Canada = 0x1009,
Spanish_Guatemala = 0x100A,
French_Switzerland = 0x100C,
Arabic_Algeria = 0x1401,
German_Liechtenstein = 0x1407,
English_NewZealand = 0x1409,
Spanish_CostaRica = 0x140A,
French_Luxembourg = 0x140C,
Arabic_Morocco = 0x1801,
English_Ireland = 0x1809,
Spanish_Panama = 0x180A,
Arabic_Tunisia = 0x1C01,
English_SouthAfrica = 0x1C09,
Spanish_DominicanRepublic = 0x1C0A,
Arabic_Oman = 0x2001,
English_Jamaica = 0x2009,
Spanish_Venezuela = 0x200A,
Arabic_Yemen = 0x2401,
Spanish_Colombia = 0x240A,
Arabic_Syria = 0x2801,
English_Belize = 0x2809,
Spanish_Peru = 0x280A,
Arabic_Jordan = 0x2C01,
English_Trinidad = 0x2C09,
Spanish_Argentina = 0x2C0A,
Arabic_Lebanon = 0x3001,
Spanish_Ecuador = 0x300A,
Arabic_Kuwait = 0x3401,
Spanish_Chile = 0x340A,
Arabic_UAE = 0x3801,
Spanish_Uruguay = 0x380A,
Arabic_Bahrain = 0x3C01,
Spanish_Paraguay = 0x3C0A,
Arabic_Qatar = 0x4001,
Spanish_Bolivia = 0x400A,
Spanish_ElSalvador = 0x440A,
Spanish_Honduras = 0x480A,
Spanish_Nicaragua = 0x4C0A,
Spanish_PuertoRico = 0x500A
}
public class Software : System.Windows.Forms.UserControl
{
private Crownwood.DotNetMagic.Controls.TreeControl treeControl2;
private Crownwood.DotNetMagic.Controls.Node node8;
private Crownwood.DotNetMagic.Controls.Node node9;
private Crownwood.DotNetMagic.Controls.ButtonWithStyle button2;
private Crownwood.DotNetMagic.Controls.ButtonWithStyle button5;
private ReportPrinting.ReportDocument reportDocument1;
private System.ComponentModel.Container components = null;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.RadioButton radioButton1;
private System.Windows.Forms.RadioButton radioButton2;
public delegate void Status(string e);
public event Status ChangeStatus;
private System.Resources.ResourceManager m_ResourceManager;
public System.Resources.ResourceManager rsxmgr
{
set
{
this.m_ResourceManager = value;
}
}
public Software()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Software));
this.treeControl2 = new Crownwood.DotNetMagic.Controls.TreeControl();
this.node8 = new Crownwood.DotNetMagic.Controls.Node();
this.node9 = new Crownwood.DotNetMagic.Controls.Node();
this.button2 = new Crownwood.DotNetMagic.Controls.ButtonWithStyle();
this.button5 = new Crownwood.DotNetMagic.Controls.ButtonWithStyle();
this.reportDocument1 = new ReportPrinting.ReportDocument();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.radioButton1 = new System.Windows.Forms.RadioButton();
this.radioButton2 = new System.Windows.Forms.RadioButton();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// treeControl2
//
this.treeControl2.Dock = System.Windows.Forms.DockStyle.Right;
this.treeControl2.GroupFont = new System.Drawing.Font("Tahoma", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
this.treeControl2.HotBackColor = System.Drawing.Color.Empty;
this.treeControl2.HotForeColor = System.Drawing.Color.Empty;
this.treeControl2.Location = new System.Drawing.Point(126, 0);
this.treeControl2.MinimumNodeHeight = 11;
this.treeControl2.Name = "treeControl2";
this.treeControl2.Nodes.AddRange(new Crownwood.DotNetMagic.Controls.Node[] {
this.node8,
this.node9});
this.treeControl2.SelectedNode = null;
this.treeControl2.SelectedNoFocusBackColor = System.Drawing.SystemColors.Control;
this.treeControl2.Size = new System.Drawing.Size(488, 289);
this.treeControl2.TabIndex = 30;
this.treeControl2.Text = "treeControl2";
this.treeControl2.ViewControllers = Crownwood.DotNetMagic.Controls.ViewControllers.Group;
//
// node8
//
this.node8.BackColor = System.Drawing.SystemColors.Window;
this.node8.Checked = true;
this.node8.CheckState = Crownwood.DotNetMagic.Controls.CheckState.Checked;
this.node8.ForeColor = System.Drawing.SystemColors.ControlText;
this.node8.Image = ((System.Drawing.Image)(resources.GetObject("node8.Image")));
this.node8.NodeFont = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
this.node8.Text = "OS";
//
// node9
//
this.node9.BackColor = System.Drawing.SystemColors.Window;
this.node9.Checked = true;
this.node9.CheckState = Crownwood.DotNetMagic.Controls.CheckState.Checked;
this.node9.ForeColor = System.Drawing.SystemColors.ControlText;
this.node9.Image = ((System.Drawing.Image)(resources.GetObject("node9.Image")));
this.node9.NodeFont = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
this.node9.Text = "Most Popular";
//
// button2
//
this.button2.Location = new System.Drawing.Point(8, 48);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(96, 32);
this.button2.TabIndex = 29;
this.button2.Text = "Scan Software";
this.button2.Click += new System.EventHandler(this.buttonWithStyle1_Click);
//
// button5
//
this.button5.Enabled = false;
this.button5.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
this.button5.Location = new System.Drawing.Point(8, 8);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(96, 32);
this.button5.TabIndex = 28;
this.button5.Text = "Report";
this.button5.Click += new System.EventHandler(this.button5_Click);
//
// reportDocument1
//
this.reportDocument1.Body = null;
this.reportDocument1.DocumentUnit = System.Drawing.GraphicsUnit.Inch;
this.reportDocument1.PageFooter = null;
this.reportDocument1.PageFooterMaxHeight = 1F;
this.reportDocument1.PageHeader = null;
this.reportDocument1.PageHeaderMaxHeight = 1F;
this.reportDocument1.ReportMaker = null;
this.reportDocument1.ResetAfterPrint = true;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.radioButton2);
this.groupBox1.Controls.Add(this.radioButton1);
this.groupBox1.Location = new System.Drawing.Point(8, 88);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(112, 64);
this.groupBox1.TabIndex = 31;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Software to scan";
//
// radioButton1
//
this.radioButton1.Checked = true;
this.radioButton1.Location = new System.Drawing.Point(8, 16);
this.radioButton1.Name = "radioButton1";
this.radioButton1.Size = new System.Drawing.Size(96, 16);
this.radioButton1.TabIndex = 0;
this.radioButton1.TabStop = true;
this.radioButton1.Text = "Most Popular";
this.radioButton1.CheckedChanged += new System.EventHandler(this.radioButton1_CheckedChanged);
//
// radioButton2
//
this.radioButton2.Location = new System.Drawing.Point(8, 40);
this.radioButton2.Name = "radioButton2";
this.radioButton2.Size = new System.Drawing.Size(88, 16);
this.radioButton2.TabIndex = 1;
this.radioButton2.Text = "All";
this.radioButton2.CheckedChanged += new System.EventHandler(this.radioButton2_CheckedChanged);
//
// Software
//
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.button5);
this.Controls.Add(this.treeControl2);
this.Controls.Add(this.button2);
this.Name = "Software";
this.Size = new System.Drawing.Size(614, 289);
this.Load += new System.EventHandler(this.Software_Load);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void changeStatus(string stringStatus)
{
if (ChangeStatus != null)
ChangeStatus(stringStatus);
}
private void button5_Click(object sender, System.EventArgs e)
{
/*this.Cursor = Cursors.WaitCursor;
try
{
ReportSWD tmpRep = new ReportSWD();
//tmpRep.dataview = this.dviSoftware;
preview pre = new preview();
pre.irp = tmpRep;
pre.ShowDialog();
}
catch
{
MessageBox.Show(this, "Unable Report.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
this.Cursor = Cursors.Default;*/
MessageBox.Show(this, "Software Report is disabled.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void buttonWithStyle1_Click(object sender, System.EventArgs e)
{
this.radioButton1.Enabled = false;
this.radioButton2.Enabled = false;
this.Update();
this.Cursor = Cursors.WaitCursor;
try
{
foreach(System.Management.ManagementObject mo in HWD.Details.Consulta("SELECT * FROM Win32_OperatingSystem"))
{
HWD.DetailsControls.OSLanguague oscode = (HWD.DetailsControls.OSLanguague) Convert.ToInt32(mo["OSLanguage"].ToString());
Node tmpnd = new Node("Name: " + mo["Caption"]);
this.node8.Nodes.Add(tmpnd);
tmpnd = new Node("Version: " + mo["Version"]);
this.node8.Nodes.Add(tmpnd);
tmpnd = new Node("Build Type: " + mo["BuildType"]);
this.node8.Nodes.Add(tmpnd);
tmpnd = new Node("Language: " + oscode.ToString());
this.node8.Nodes.Add(tmpnd);
tmpnd = new Node("Serial Number: " + mo["SerialNumber"]);
this.node8.Nodes.Add(tmpnd);
tmpnd = new Node("System Directory: " + mo["SystemDirectory"]);
this.node8.Nodes.Add(tmpnd);
tmpnd = new Node("Windows Directory: " + mo["WindowsDirectory"]);
this.node8.Nodes.Add(tmpnd);
}
}
catch
{
}
string tuser = string.Empty;
foreach (System.Management.ManagementObject mo in HWD.Details.Consulta("SELECT * FROM Win32_ComputerSystem"))
{
try
{
tuser = mo["UserName"].ToString();
}
catch
{
MessageBox.Show(this, "In order to perform a software scan, an user must be logged into the system." , "Scan Error" ,MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Cursor = Cursors.Default;
return;
}
}
if (tuser != string.Empty)
{
if (this.node9.Text == "Most Popular")
{
this.addSoftwareNode("Microsoft");
this.addSoftwareNode("Adobe");
this.addSoftwareNode("Macromedia");
this.addSoftwareNode("Corel");
this.addSoftwareNode("Borland");
}
else
{
try
{
foreach(System.Management.ManagementObject mo in HWD.Details.Consulta("SELECT * FROM Win32_Product"))
{
Node tmpnd = new Node(mo["Name"].ToString()+" version "+mo["version"].ToString());
this.node9.Nodes.Add(tmpnd);
}
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
}
}
this.Cursor = Cursors.Default;
}
private void addSoftwareNode(string Company)
{
try
{
Node tmpmas = new Node(Company + " Software");
foreach(System.Management.ManagementObject mo in HWD.Details.Consulta("SELECT * FROM Win32_Product WHERE Vendor like '%" + Company + "%'"))
{
Node tmpnd = new Node(mo["Name"].ToString()+" version "+mo["version"].ToString());
tmpmas.Nodes.Add(tmpnd);
}
if (tmpmas.Nodes.Count > 0)
{
this.node9.Nodes.Add(tmpmas);
}
}
catch
{
}
this.Update();
}
private void Software_Load(object sender, System.EventArgs e)
{
//this.button2.Text = m_ResourceManager.GetString("dbutton2");
//this.button5.Text = m_ResourceManager.GetString("dbtnReport");
}
private void radioButton2_CheckedChanged(object sender, System.EventArgs e)
{
this.node9.Text = "All";
}
private void radioButton1_CheckedChanged(object sender, System.EventArgs e)
{
this.node9.Text = "Most Popular";
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Threading;
using System.Windows.Forms;
using OpenLiveWriter.HtmlEditor;
namespace OpenLiveWriter.PostEditor.PostHtmlEditing.Behaviors
{
/// <summary>
/// Summary description for BehaviorControl.
/// </summary>
public class BehaviorControl : IBehaviorControlContainerControl, IDisposable
{
/// <summary>
/// The behavior control container for this behavior control. This will be either
/// another behavior control or a heavyweight control that is designed to contain
/// behavior controls through an implementation of the IBehaviorControlContainerControl
/// interface.
/// </summary>
private IBehaviorControlContainerControl containerControl;
/// <summary>
/// The the virtual location of the lightweight control relative to the upper-left corner
/// of its lightweight control container.
/// </summary>
private Point virtualLocation;
/// <summary>
/// The virtual size of the lightweight control.
/// </summary>
private Size virtualSize = new Size(0, 0);
/// <summary>
/// The collection of lightweight controls contained within the lightweight control.
/// </summary>
private BehaviorControlCollection controls;
/// <summary>
/// A value indicating whether the control is displayed.
/// </summary>
private bool visible = true;
/// <summary>
/// The suspend layout state of the lightweight control.
/// </summary>
private int suspendLayoutCount = 0;
public bool AllowDrop = false;
public bool AllowMouseWheel = false;
public BehaviorControl()
{
// Instantiate the lightweight control collection.
controls = new BehaviorControlCollection(this);
}
public IBehaviorControlContainerControl ContainerControl
{
get
{
return containerControl;
}
set
{
containerControl = value;
}
}
public BehaviorControlCollection Controls
{
get
{
return controls;
}
}
public ElementControlBehavior Parent
{
get
{
if (ContainerControl != null)
return ContainerControl.Parent;
return null;
}
}
public bool Visible
{
get
{
return visible;
}
set
{
if (visible != value)
{
visible = value;
Invalidate();
OnVisibleChanged(EventArgs.Empty);
}
}
}
/// <summary>
/// Gets or sets the virtual location of the lightweight control relative to the upper-left
/// corner of its lightweight control container.
/// </summary>
public Point VirtualLocation
{
get
{
return virtualLocation;
}
set
{
if (virtualLocation != value)
{
// Set the virtual location.
virtualLocation = value;
// If we have a lightweight control container, have it perform a layout.
if (containerControl != null)
containerControl.PerformLayout();
// Finally, raise the VirtualLocationChanged event.
OnVirtualLocationChanged(EventArgs.Empty);
}
}
}
/// <summary>
/// Gets or sets the virtual size of the lightweight control.
/// </summary>
public Size VirtualSize
{
get
{
return virtualSize;
}
set
{
Debug.Assert(value.Width >= 0 && value.Height >= 0, "virtual size must be a positive value");
// If the virtual size has changed, change it.
if (virtualSize != value)
{
// Set the virtual size.
virtualSize = value;
// Layout the control.
PerformLayout();
// If we have a lightweight control container, have it perform a layout.
if (containerControl != null)
containerControl.PerformLayout();
// Finally, raise the VirtualSizeChanged event.
OnVirtualSizeChanged(EventArgs.Empty);
}
}
}
/// <summary>
/// Gets the default virtual size of the lightweight control.
/// </summary>
public virtual Size DefaultVirtualSize
{
get
{
return new Size(0, 0);
}
}
/// <summary>
/// Gets the minimum virtual size of the lightweight control.
/// </summary>
public virtual Size MinimumVirtualSize
{
get
{
return new Size(0, 0);
}
}
/// <summary>
/// Gets or sets the virtual width of the lightweight control.
/// </summary>
public int VirtualWidth
{
get
{
return virtualSize.Width;
}
set
{
if (virtualSize.Width != value)
VirtualSize = new Size(value, VirtualHeight);
}
}
/// <summary>
/// Gets or sets the virtual height of the lightweight control.
/// </summary>
public int VirtualHeight
{
get
{
return virtualSize.Height;
}
set
{
if (virtualSize.Height != value)
VirtualSize = new Size(VirtualWidth, value);
}
}
/// <summary>
/// Gets or sets the virtual bounds, or size and location of the lightweight control.
/// </summary>
public Rectangle VirtualBounds
{
get
{
return new Rectangle(VirtualLocation, VirtualSize);
}
set
{
if (VirtualBounds != value)
{
SuspendLayout();
VirtualLocation = value.Location;
VirtualSize = value.Size;
ResumeLayout();
PerformLayout();
}
}
}
/// <summary>
/// Gets the rectangle that represents the client area of the lightweight control.
/// </summary>
public Rectangle VirtualClientRectangle
{
get
{
return new Rectangle(0, 0, VirtualSize.Width, VirtualSize.Height);
}
}
/// <summary>
/// Used by MSHTML to determine if the specified point should be considered as part of the element this BehaviorControl is attached to.
/// </summary>
/// <returns>true if the point is located in an area that should be considered part of the element this BehaviorControl is attached to, false otherwise</returns>
public virtual bool HitTestPoint(Point testPoint)
{
bool hit = false;
foreach (BehaviorControl lightweightControl in controls)
{
Point virtualTestPoint = lightweightControl.PointToVirtualClient(testPoint);
hit |= lightweightControl.HitTestPoint(virtualTestPoint);
}
return hit;
}
public void SuspendLayout()
{
Interlocked.Increment(ref suspendLayoutCount);
}
public void ResumeLayout()
{
Interlocked.Decrement(ref suspendLayoutCount);
}
protected bool IsLayoutSuspended
{
get
{
return Interlocked.CompareExchange(ref suspendLayoutCount, 0, 0) != 0;
}
}
/// <summary>
/// Invalidates the lightweight control.
/// </summary>
public void Invalidate()
{
if (Parent != null)
Parent.Invalidate(VirtualClientRectangleToParent());
}
public void PerformLayout()
{
// If layout is not suspended, invoke the OnLayout method.
if (!IsLayoutSuspended)
{
// During layout we suspend layout so that the control can change it's size as
// needed. This is the key to the lightweight control architecture working
// properly. As each lightweight control processes its layout event, it makes
// whatever changes are necessary to its size and layout at the same time.
SuspendLayout();
OnLayout(EventArgs.Empty);
ResumeLayout();
}
}
/// <interface>ILightweightControlContainer</interface>
/// <summary>
/// Translates the virtual client rectangle to a parent rectangle.
/// </summary>
/// <returns>Translated VirtualClientRectangle rectangle.</returns>
public Rectangle VirtualClientRectangleToParent()
{
return VirtualClientRectangleToParent(VirtualClientRectangle);
}
/// <interface>ILightweightControlContainer</interface>
/// <summary>
/// Translates a virtual client rectangle to a parent rectangle.
/// </summary>
/// <param name="rectangle">The rectangle to translate.</param>
/// <returns>Translated rectangle.</returns>
public Rectangle VirtualClientRectangleToParent(Rectangle rectangle)
{
// Translate the rectangle to be relative to the virtual location of this lightweight
// control.
rectangle.Offset(virtualLocation);
// Continue up the chain of lightweight control containers.
if (containerControl == null)
return rectangle;
else
return containerControl.VirtualClientRectangleToParent(rectangle);
}
/// <interface>ILightweightControlContainer</interface>
/// <summary>
/// Translates a point to be relative to the the virtual client rectangle.
/// </summary>
/// <param name="point">The point to translate.</param>
/// <returns>Translated point.</returns>
public Point PointToVirtualClient(Point point)
{
// Translate the point to be relative to the virtual location of this lightweight
// control.
point.Offset(VirtualLocation.X * -1, VirtualLocation.Y * -1);
// Continue up the chain of lightweight control container controls.
if (containerControl == null)
return point;
else
return containerControl.PointToVirtualClient(point);
}
/// <interface>ILightweightControlContainer</interface>
/// <summary>
/// Translates a virtual client point to be relative to a parent point.
/// </summary>
/// <param name="point">The point to translate.</param>
/// <returns>Translated point.</returns>
public Point VirtualClientPointToParent(Point point)
{
// Translate the point to be relative to the virtual location of this lightweight
// control.
point.Offset(VirtualLocation.X, VirtualLocation.Y);
// Continue up the chain of lightweight control container controls.
if (containerControl == null)
return point;
else
return containerControl.VirtualClientPointToParent(point);
}
#region Events
/// <summary>
/// Raises the VirtualSizeChanged event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnVirtualSizeChanged(EventArgs e)
{
if (VirtualSizeChanged != null)
VirtualSizeChanged(this, e);
}
public event EventHandler VirtualSizeChanged;
/// <summary>
/// Raises the VirtualLocationChanged event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnVirtualLocationChanged(EventArgs e)
{
if (VirtualLocationChanged != null)
VirtualLocationChanged(this, e);
}
public event EventHandler VirtualLocationChanged;
/// <summary>
/// Raises the Layout event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnLayout(EventArgs e)
{
if (Layout != null)
Layout(this, e);
}
public event EventHandler Layout;
/// <summary>
/// Raises the VisibleChanged event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnVisibleChanged(EventArgs e)
{
if (VisibleChanged != null)
VisibleChanged(this, e);
}
public event EventHandler VisibleChanged;
/// <summary>
/// Raises the MouseDown event.
/// </summary>
/// <param name="e">A MouseEventArgs that contains the event data.</param>
internal void RaiseMouseDown(MouseEventArgs e)
{
OnMouseDown(e);
}
/// <summary>
/// Raises the MouseEnter event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
internal void RaiseMouseEnter(EventArgs e)
{
OnMouseEnter(e);
}
/// <summary>
/// Raises the MouseHover event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
internal void RaiseMouseHover(EventArgs e)
{
OnMouseHover(e);
}
/// <summary>
/// Raises the MouseLeave event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
internal void RaiseMouseLeave(EventArgs e)
{
OnMouseLeave(e);
}
/// <summary>
/// Raises the MouseMove event.
/// </summary>
/// <param name="e">A MouseEventArgs that contains the event data.</param>
internal void RaiseMouseMove(MouseEventArgs e)
{
OnMouseMove(e);
}
/// <summary>
/// Raises the MouseUp event.
/// </summary>
/// <param name="e">A MouseEventArgs that contains the event data.</param>
internal void RaiseMouseUp(MouseEventArgs e)
{
OnMouseUp(e);
}
/// <summary>
/// Raises the MouseWheel event.
/// </summary>
/// <param name="e">A MouseEventArgs that contains the event data.</param>
internal void RaiseMouseWheel(MouseEventArgs e)
{
OnMouseWheel(e);
}
/// <summary>
/// Raises the Click event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
internal void RaiseClick(EventArgs e)
{
OnClick(e);
}
/// <summary>
/// Raises the MouseDown event.
/// </summary>
/// <param name="e">A MouseEventArgs that contains the event data.</param>
protected virtual void OnMouseDown(MouseEventArgs e)
{
if (MouseDown != null)
MouseDown(this, e);
}
public event MouseEventHandler MouseDown;
/// <summary>
/// Raises the MouseEnter event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnMouseEnter(EventArgs e)
{
if (MouseEnter != null)
MouseEnter(this, e);
}
public event EventHandler MouseEnter;
/// <summary>
/// Raises the MouseHover event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnMouseHover(EventArgs e)
{
if (MouseHover != null)
MouseHover(this, e);
}
public event EventHandler MouseHover;
/// <summary>
/// Raises the MouseLeave event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnMouseLeave(EventArgs e)
{
if (MouseLeave != null)
MouseLeave(this, e);
}
public event EventHandler MouseLeave;
/// <summary>
/// Raises the MouseMove event.
/// </summary>
/// <param name="e">A MouseEventArgs that contains the event data.</param>
protected virtual void OnMouseMove(MouseEventArgs e)
{
if (MouseMove != null)
MouseMove(this, e);
}
public event MouseEventHandler MouseMove;
/// <summary>
/// Raises the MouseUp event.
/// </summary>
/// <param name="e">A MouseEventArgs that contains the event data.</param>
protected virtual void OnMouseUp(MouseEventArgs e)
{
if (MouseUp != null)
MouseUp(this, e);
}
public event MouseEventHandler MouseUp;
/// <summary>
/// Raises the MouseWheel event.
/// </summary>
/// <param name="e">A MouseEventArgs that contains the event data.</param>
protected virtual void OnMouseWheel(MouseEventArgs e)
{
if (MouseWheel != null)
MouseWheel(this, e);
}
public event MouseEventHandler MouseWheel;
protected virtual void OnClick(EventArgs e)
{
if (Click != null)
Click(this, e);
}
public event EventHandler Click;
#endregion
/// <summary>
/// Raises the Paint event.
/// </summary>
/// <param name="e">A PaintEventArgs that contains the event data.</param>
internal void RaisePaint(PaintEventArgs e)
{
OnPaint(e);
}
/// <summary>
/// Raises the Paint event.
/// </summary>
/// <param name="e">A PaintEventArgs that contains the event data.</param>
protected virtual void OnPaint(PaintEventArgs e)
{
// Raise the paint event to get this lightweight control painted first.
//RaiseEvent(PaintEventKey, e);
// Enumerate the child lightweight controls and paint controls that need painting.
// This enumeration occurs in reverse Z order. Child controls lower in the Z order
// are painted before child controls higher in the Z order.
foreach (BehaviorControl lightweightControl in controls)
{
// If the control is visible and inside the clip rectangle, paint it.
if (lightweightControl.Visible &&
lightweightControl.VirtualWidth != 0 &&
lightweightControl.VirtualHeight != 0 &&
lightweightControl.VirtualBounds.IntersectsWith(e.ClipRectangle))
{
// Obtain the lightweight control virtual client rectangle.
Rectangle lightweightControlVirtualClientRectangle = lightweightControl.VirtualClientRectangle;
// Create the graphics container for the lightweight control paint event that
// causes anything applied to the lightweight control's virtual client
// rectangle to be mapped to the lightweight control's on-screen bounds.
GraphicsContainer graphicsContainer = e.Graphics.BeginContainer(lightweightControl.VirtualBounds,
lightweightControlVirtualClientRectangle,
GraphicsUnit.Pixel);
// Clip the graphics context to prevent the lightweight control from drawing
// outside its client rectangle.
e.Graphics.SetClip(lightweightControlVirtualClientRectangle);
// Set a new default compositing mode and quality.
e.Graphics.CompositingMode = CompositingMode.SourceOver;
e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
// Raise the Paint event for the lightweight control.
lightweightControl.OnPaint(new PaintEventArgs(e.Graphics, lightweightControlVirtualClientRectangle));
// End the graphics container for the lightweight control.
e.Graphics.EndContainer(graphicsContainer);
}
}
}
/// <summary>
/// Gets the Behavior control that is located at the specified point.
/// </summary>
/// <param name="point">A Point that contains the coordinates where you want to look for a control.
/// Coordinates are expressed relative to the upper-left corner of the control's client area.</param>
/// <returns>Behavior control at the specified point.</returns>
internal BehaviorControl GetBehaviorControlAtPoint(Point point)
{
// Enumerate the Behavior controls, in Z order, to locate one at the virtual point.
for (int index = Controls.Count - 1; index >= 0; index--)
{
// Access the Behavior control.
BehaviorControl BehaviorControl = Controls[index];
// If the Behavior control is visible, and the point is within its virtual
// bounds, then recursively search for the right control.
if (BehaviorControl.Visible && BehaviorControl.VirtualBounds.Contains(point))
{
// Translate the point to be relative to the location of the Behavior control.
point.Offset(BehaviorControl.VirtualLocation.X * -1, BehaviorControl.VirtualLocation.Y * -1);
// Recursively search for the right Behavior control.
return BehaviorControl.GetBehaviorControlAtPoint(point);
}
}
// The point is not inside a child Behavior control of this Behavior control,
// so it's inside this Behavior control.
return this;
}
/// <summary>
/// Gets the Behavior control that is located at the specified point and allows drag and drop events.
/// </summary>
/// <param name="point">A Point that contains the coordinates where you want to look for a control.
/// Coordinates are expressed relative to the upper-left corner of the control's client area.</param>
/// <returns>Behavior control at the specified point.</returns>
internal BehaviorControl GetDragDropBehaviorControlAtPoint(Point point)
{
// Enumerate the Behavior controls, in Z order, to locate one at the virtual point.
for (int index = Controls.Count - 1; index >= 0; index--)
{
// Access the Behavior control.
BehaviorControl BehaviorControl = Controls[index];
// If the Behavior control is visible, and the point is within its virtual
// bounds, then recursively call it sit is under the point.
if (BehaviorControl.Visible && BehaviorControl.VirtualBounds.Contains(point))
{
// Translate the point to be relative to the location of the Behavior control.
point.Offset(BehaviorControl.VirtualLocation.X * -1, BehaviorControl.VirtualLocation.Y * -1);
// Recursively search for the right drag and drop Behavior control.
return BehaviorControl.GetDragDropBehaviorControlAtPoint(point);
}
}
// The point is not inside a child Behavior control of this Behavior control
// that allows mouse wheel events. So it's inside this Behavior control. If this
// Behavior control allows mouse wheel events, return it. Otherwise, return null.
return AllowDrop ? this : null;
}
/// <summary>
/// Gets the Behavior control that is located at the specified point and allows mouse wheel events.
/// </summary>
/// <param name="point">A Point that contains the coordinates where you want to look for a control.
/// Coordinates are expressed relative to the upper-left corner of the control's client area.</param>
/// <returns>Behavior control at the specified point.</returns>
internal BehaviorControl GetMouseWheelBehaviorControlAtPoint(Point point)
{
// Enumerate the Behavior controls, in Z order, to locate one at the virtual point.
for (int index = Controls.Count - 1; index >= 0; index--)
{
// Access the Behavior control.
BehaviorControl BehaviorControl = Controls[index];
// If the Behavior control is visible, and the point is within its virtual
// bounds, then recursively call it sit is under the point.
if (BehaviorControl.Visible && BehaviorControl.VirtualBounds.Contains(point))
{
// Translate the point to be relative to the location of the Behavior control.
point.Offset(BehaviorControl.VirtualLocation.X * -1, BehaviorControl.VirtualLocation.Y * -1);
// Recursively search for the right mouse wheel Behavior control.
BehaviorControl childMouseWheelBehaviorControl = BehaviorControl.GetMouseWheelBehaviorControlAtPoint(point);
if (childMouseWheelBehaviorControl != null)
return childMouseWheelBehaviorControl;
}
}
// The point is not inside a child Behavior control of this Behavior control
// that allows mouse wheel events. So it's inside this Behavior control. If this
// Behavior control allows mouse wheel events, return it. Otherwise, return null.
return AllowMouseWheel ? this : null;
}
#region IDisposable Members
public virtual void Dispose()
{
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: Exposes routines for enumerating through a
** directory.
**
** April 11,2000
**
===========================================================*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using System.Security.Permissions;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Text;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Threading;
#if FEATURE_MACL
using System.Security.AccessControl;
#endif
namespace System.IO {
[ComVisible(true)]
public static class Directory {
public static DirectoryInfo GetParent(String path)
{
if (path==null)
throw new ArgumentNullException("path");
if (path.Length==0)
throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"), "path");
Contract.EndContractBlock();
String fullPath = Path.GetFullPathInternal(path);
String s = Path.GetDirectoryName(fullPath);
if (s==null)
return null;
return new DirectoryInfo(s);
}
[System.Security.SecuritySafeCritical]
public static DirectoryInfo CreateDirectory(String path) {
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
Contract.EndContractBlock();
#if FEATURE_LEGACYNETCF
if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
System.Reflection.Assembly callingAssembly = System.Reflection.Assembly.GetCallingAssembly();
if(callingAssembly != null && !callingAssembly.IsProfileAssembly) {
string caller = new System.Diagnostics.StackFrame(1).GetMethod().FullName;
string callee = System.Reflection.MethodBase.GetCurrentMethod().FullName;
throw new MethodAccessException(String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("Arg_MethodAccessException_WithCaller"),
caller,
callee));
}
}
#endif // FEATURE_LEGACYNETCF
return InternalCreateDirectoryHelper(path, true);
}
[System.Security.SecurityCritical]
internal static DirectoryInfo UnsafeCreateDirectory(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
Contract.EndContractBlock();
return InternalCreateDirectoryHelper(path, false);
}
[System.Security.SecurityCritical]
internal static DirectoryInfo InternalCreateDirectoryHelper(String path, bool checkHost)
{
Contract.Requires(path != null);
Contract.Requires(path.Length != 0);
String fullPath = Path.GetFullPathInternal(path);
// You need read access to the directory to be returned back and write access to all the directories
// that you need to create. If we fail any security checks we will not create any directories at all.
// We attempt to create directories only after all the security checks have passed. This is avoid doing
// a demand at every level.
String demandDir = GetDemandDir(fullPath, true);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, demandDir);
state.EnsureState(); // do the check on the AppDomainManager to make sure this is allowed
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandDir, false, false);
#endif
InternalCreateDirectory(fullPath, path, null, checkHost);
return new DirectoryInfo(fullPath, false);
}
#if FEATURE_MACL
[System.Security.SecuritySafeCritical] // auto-generated
public static DirectoryInfo CreateDirectory(String path, DirectorySecurity directorySecurity) {
if (path==null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
Contract.EndContractBlock();
String fullPath = Path.GetFullPathInternal(path);
// You need read access to the directory to be returned back and write access to all the directories
// that you need to create. If we fail any security checks we will not create any directories at all.
// We attempt to create directories only after all the security checks have passed. This is avoid doing
// a demand at every level.
String demandDir = GetDemandDir(fullPath, true);
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandDir, false, false );
InternalCreateDirectory(fullPath, path, directorySecurity);
return new DirectoryInfo(fullPath, false);
}
#endif // FEATURE_MACL
// Input to this method should already be fullpath. This method will ensure that we append
// the trailing slash only when appropriate and when thisDirOnly is specified append a "."
// at the end of the path to indicate that the demand is only for the fullpath and not
// everything underneath it.
internal static String GetDemandDir(string fullPath, bool thisDirOnly)
{
String demandPath;
if (thisDirOnly) {
if (fullPath.EndsWith( Path.DirectorySeparatorChar )
|| fullPath.EndsWith( Path.AltDirectorySeparatorChar ) )
demandPath = fullPath + ".";
else
demandPath = fullPath + Path.DirectorySeparatorCharAsString + ".";
}
else {
if (!(fullPath.EndsWith( Path.DirectorySeparatorChar )
|| fullPath.EndsWith( Path.AltDirectorySeparatorChar )) )
demandPath = fullPath + Path.DirectorySeparatorCharAsString;
else
demandPath = fullPath;
}
return demandPath;
}
internal static void InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj)
{
InternalCreateDirectory(fullPath, path, dirSecurityObj, false);
}
[System.Security.SecuritySafeCritical]
internal unsafe static void InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, bool checkHost)
{
#if FEATURE_MACL
DirectorySecurity dirSecurity = (DirectorySecurity)dirSecurityObj;
#endif // FEATURE_MACL
int length = fullPath.Length;
// We need to trim the trailing slash or the code will try to create 2 directories of the same name.
if (length >= 2 && Path.IsDirectorySeparator(fullPath[length - 1]))
length--;
int lengthRoot = Path.GetRootLength(fullPath);
// For UNC paths that are only // or ///
if (length == 2 && Path.IsDirectorySeparator(fullPath[1]))
throw new IOException(Environment.GetResourceString("IO.IO_CannotCreateDirectory", path));
// We can save a bunch of work if the directory we want to create already exists. This also
// saves us in the case where sub paths are inaccessible (due to ERROR_ACCESS_DENIED) but the
// final path is accessable and the directory already exists. For example, consider trying
// to create c:\Foo\Bar\Baz, where everything already exists but ACLS prevent access to c:\Foo
// and c:\Foo\Bar. In that case, this code will think it needs to create c:\Foo, and c:\Foo\Bar
// and fail to due so, causing an exception to be thrown. This is not what we want.
if (InternalExists(fullPath)) {
return;
}
List<string> stackDir = new List<string>();
// Attempt to figure out which directories don't exist, and only
// create the ones we need. Note that InternalExists may fail due
// to Win32 ACL's preventing us from seeing a directory, and this
// isn't threadsafe.
bool somepathexists = false;
if (length > lengthRoot) { // Special case root (fullpath = X:\\)
int i = length-1;
while (i >= lengthRoot && !somepathexists) {
String dir = fullPath.Substring(0, i+1);
if (!InternalExists(dir)) // Create only the ones missing
stackDir.Add(dir);
else
somepathexists = true;
while (i > lengthRoot && fullPath[i] != Path.DirectorySeparatorChar && fullPath[i] != Path.AltDirectorySeparatorChar) i--;
i--;
}
}
int count = stackDir.Count;
if (stackDir.Count != 0)
{
String [] securityList = new String[stackDir.Count];
stackDir.CopyTo(securityList, 0);
for (int j = 0 ; j < securityList.Length; j++)
securityList[j] += "\\."; // leaf will never have a slash at the end
// Security check for all directories not present only.
#if FEATURE_MACL
AccessControlActions control = (dirSecurity == null) ? AccessControlActions.None : AccessControlActions.Change;
new FileIOPermission(FileIOPermissionAccess.Write, control, securityList, false, false ).Demand();
#else
#if FEATURE_CORECLR
if (checkHost)
{
foreach (String demandPath in securityList)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, String.Empty, demandPath);
state.EnsureState();
}
}
#else
new FileIOPermission(FileIOPermissionAccess.Write, securityList, false, false ).Demand();
#endif
#endif //FEATURE_MACL
}
// If we were passed a DirectorySecurity, convert it to a security
// descriptor and set it in he call to CreateDirectory.
Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
#if FEATURE_MACL
if (dirSecurity != null) {
secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);
// For ACL's, get the security descriptor from the FileSecurity.
byte[] sd = dirSecurity.GetSecurityDescriptorBinaryForm();
byte * bytesOnStack = stackalloc byte[sd.Length];
Buffer.Memcpy(bytesOnStack, 0, sd, 0, sd.Length);
secAttrs.pSecurityDescriptor = bytesOnStack;
}
#endif
bool r = true;
int firstError = 0;
String errorString = path;
// If all the security checks succeeded create all the directories
while (stackDir.Count > 0) {
String name = stackDir[stackDir.Count - 1];
stackDir.RemoveAt(stackDir.Count - 1);
if (name.Length >= Path.MAX_DIRECTORY_PATH)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
r = Win32Native.CreateDirectory(name, secAttrs);
if (!r && (firstError == 0)) {
int currentError = Marshal.GetLastWin32Error();
// While we tried to avoid creating directories that don't
// exist above, there are at least two cases that will
// cause us to see ERROR_ALREADY_EXISTS here. InternalExists
// can fail because we didn't have permission to the
// directory. Secondly, another thread or process could
// create the directory between the time we check and the
// time we try using the directory. Thirdly, it could
// fail because the target does exist, but is a file.
if (currentError != Win32Native.ERROR_ALREADY_EXISTS)
firstError = currentError;
else {
// If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
if (File.InternalExists(name) || (!InternalExists(name, out currentError) && currentError == Win32Native.ERROR_ACCESS_DENIED)) {
firstError = currentError;
// Give the user a nice error message, but don't leak path information.
try {
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, GetDemandDir(name, true));
state.EnsureState();
}
#else
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, GetDemandDir(name, true)).Demand();
#endif // FEATURE_CORECLR
errorString = name;
}
catch(SecurityException) {}
}
}
}
}
// We need this check to mask OS differences
// Handle CreateDirectory("X:\\foo") when X: doesn't exist. Similarly for n/w paths.
if ((count == 0) && !somepathexists) {
String root = InternalGetDirectoryRoot(fullPath);
if (!InternalExists(root)) {
// Extract the root from the passed in path again for security.
__Error.WinIOError(Win32Native.ERROR_PATH_NOT_FOUND, InternalGetDirectoryRoot(path));
}
return;
}
// Only throw an exception if creating the exact directory we
// wanted failed to work correctly.
if (!r && (firstError != 0)) {
__Error.WinIOError(firstError, errorString);
}
}
// Tests if the given path refers to an existing DirectoryInfo on disk.
//
// Your application must have Read permission to the directory's
// contents.
//
[System.Security.SecuritySafeCritical] // auto-generated
public static bool Exists(String path)
{
return InternalExistsHelper(path, true);
}
[System.Security.SecurityCritical]
internal static bool UnsafeExists(String path)
{
return InternalExistsHelper(path, false);
}
[System.Security.SecurityCritical]
internal static bool InternalExistsHelper(String path, bool checkHost) {
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
// Get fully qualified file name ending in \* for security check
String fullPath = Path.GetFullPathInternal(path);
String demandPath = GetDemandDir(fullPath, true);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, demandPath);
state.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandPath, false, false);
#endif
return InternalExists(fullPath);
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
catch (SecurityException) { }
catch (IOException) { }
catch (UnauthorizedAccessException)
{
Contract.Assert(false, "Ignore this assert and send a repro to Microsoft. This assert was tracking purposes only.");
}
return false;
}
// Determine whether path describes an existing directory
// on disk, avoiding security checks.
[System.Security.SecurityCritical] // auto-generated
internal static bool InternalExists(String path) {
int lastError = Win32Native.ERROR_SUCCESS;
return InternalExists(path, out lastError);
}
// Determine whether path describes an existing directory
// on disk, avoiding security checks.
[System.Security.SecurityCritical] // auto-generated
internal static bool InternalExists(String path, out int lastError) {
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
lastError = File.FillAttributeInfo(path, ref data, false, true);
return (lastError == 0) && (data.fileAttributes != -1)
&& ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0);
}
public static void SetCreationTime(String path,DateTime creationTime)
{
SetCreationTimeUtc(path, creationTime.ToUniversalTime());
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static void SetCreationTimeUtc(String path,DateTime creationTimeUtc)
{
using (SafeFileHandle handle = Directory.OpenHandle(path)) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(creationTimeUtc.ToFileTimeUtc());
bool r = Win32Native.SetFileTime(handle, &fileTime, null, null);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
__Error.WinIOError(errorCode, path);
}
}
}
public static DateTime GetCreationTime(String path)
{
return File.GetCreationTime(path);
}
public static DateTime GetCreationTimeUtc(String path)
{
return File.GetCreationTimeUtc(path);
}
public static void SetLastWriteTime(String path,DateTime lastWriteTime)
{
SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime());
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static void SetLastWriteTimeUtc(String path,DateTime lastWriteTimeUtc)
{
using (SafeFileHandle handle = Directory.OpenHandle(path)) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastWriteTimeUtc.ToFileTimeUtc());
bool r = Win32Native.SetFileTime(handle, null, null, &fileTime);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
__Error.WinIOError(errorCode, path);
}
}
}
public static DateTime GetLastWriteTime(String path)
{
return File.GetLastWriteTime(path);
}
public static DateTime GetLastWriteTimeUtc(String path)
{
return File.GetLastWriteTimeUtc(path);
}
public static void SetLastAccessTime(String path,DateTime lastAccessTime)
{
SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime());
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static void SetLastAccessTimeUtc(String path,DateTime lastAccessTimeUtc)
{
using (SafeFileHandle handle = Directory.OpenHandle(path)) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastAccessTimeUtc.ToFileTimeUtc());
bool r = Win32Native.SetFileTime(handle, null, &fileTime, null);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
__Error.WinIOError(errorCode, path);
}
}
}
public static DateTime GetLastAccessTime(String path)
{
return File.GetLastAccessTime(path);
}
public static DateTime GetLastAccessTimeUtc(String path)
{
return File.GetLastAccessTimeUtc(path);
}
#if FEATURE_MACL
public static DirectorySecurity GetAccessControl(String path)
{
return new DirectorySecurity(path, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
}
public static DirectorySecurity GetAccessControl(String path, AccessControlSections includeSections)
{
return new DirectorySecurity(path, includeSections);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void SetAccessControl(String path, DirectorySecurity directorySecurity)
{
if (directorySecurity == null)
throw new ArgumentNullException("directorySecurity");
Contract.EndContractBlock();
String fullPath = Path.GetFullPathInternal(path);
directorySecurity.Persist(fullPath);
}
#endif
// Returns an array of filenames in the DirectoryInfo specified by path
public static String[] GetFiles(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt").
public static String[] GetFiles(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt") and search option
public static String[] GetFiles(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, searchPattern, searchOption);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt") and search option
private static String[] InternalGetFiles(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return InternalGetFileDirectoryNames(path, path, searchPattern, true, false, searchOption, true);
}
[System.Security.SecurityCritical]
internal static String[] UnsafeGetFiles(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return InternalGetFileDirectoryNames(path, path, searchPattern, true, false, searchOption, false);
}
// Returns an array of Directories in the current directory.
public static String[] GetDirectories(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
public static String[] GetDirectories(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
public static String[] GetDirectories(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, searchPattern, searchOption);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
private static String[] InternalGetDirectories(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<String[]>() != null);
return InternalGetFileDirectoryNames(path, path, searchPattern, false, true, searchOption, true);
}
[System.Security.SecurityCritical]
internal static String[] UnsafeGetDirectories(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<String[]>() != null);
return InternalGetFileDirectoryNames(path, path, searchPattern, false, true, searchOption, false);
}
// Returns an array of strongly typed FileSystemInfo entries in the path
public static String[] GetFileSystemEntries(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria
public static String[] GetFileSystemEntries(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria
public static String[] GetFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, searchPattern, searchOption);
}
private static String[] InternalGetFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return InternalGetFileDirectoryNames(path, path, searchPattern, true, true, searchOption, true);
}
// Private class that holds search data that is passed around
// in the heap based stack recursion
internal sealed class SearchData
{
public SearchData(String fullPath, String userPath, SearchOption searchOption)
{
Contract.Requires(fullPath != null && fullPath.Length > 0);
Contract.Requires(userPath != null && userPath.Length > 0);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
this.fullPath = fullPath;
this.userPath = userPath;
this.searchOption = searchOption;
}
public readonly string fullPath; // Fully qualified search path excluding the search criteria in the end (ex, c:\temp\bar\foo)
public readonly string userPath; // User specified path (ex, bar\foo)
public readonly SearchOption searchOption;
}
// Returns fully qualified user path of dirs/files that matches the search parameters.
// For recursive search this method will search through all the sub dirs and execute
// the given search criteria against every dir.
// For all the dirs/files returned, it will then demand path discovery permission for
// their parent folders (it will avoid duplicate permission checks)
internal static String[] InternalGetFileDirectoryNames(String path, String userPathOriginal, String searchPattern, bool includeFiles, bool includeDirs, SearchOption searchOption, bool checkHost)
{
Contract.Requires(path != null);
Contract.Requires(userPathOriginal != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<String> enble = FileSystemEnumerableFactory.CreateFileNameIterator(
path, userPathOriginal, searchPattern,
includeFiles, includeDirs, searchOption, checkHost);
List<String> fileList = new List<String>(enble);
return fileList.ToArray();
}
public static IEnumerable<String> EnumerateDirectories(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, searchPattern, SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, searchPattern, searchOption);
}
private static IEnumerable<String> InternalEnumerateDirectories(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return EnumerateFileSystemNames(path, searchPattern, searchOption, false, true);
}
public static IEnumerable<String> EnumerateFiles(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, "*", SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFiles(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFiles(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, searchPattern, searchOption);
}
private static IEnumerable<String> InternalEnumerateFiles(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return EnumerateFileSystemNames(path, searchPattern, searchOption, true, false);
}
public static IEnumerable<String> EnumerateFileSystemEntries(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, searchPattern, searchOption);
}
private static IEnumerable<String> InternalEnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return EnumerateFileSystemNames(path, searchPattern, searchOption, true, true);
}
private static IEnumerable<String> EnumerateFileSystemNames(String path, String searchPattern, SearchOption searchOption,
bool includeFiles, bool includeDirs)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return FileSystemEnumerableFactory.CreateFileNameIterator(path, path, searchPattern,
includeFiles, includeDirs, searchOption, true);
}
// Retrieves the names of the logical drives on this machine in the
// form "C:\".
//
// Your application must have System Info permission.
//
[System.Security.SecuritySafeCritical] // auto-generated
public static String[] GetLogicalDrives()
{
Contract.Ensures(Contract.Result<String[]>() != null);
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#pragma warning restore 618
int drives = Win32Native.GetLogicalDrives();
if (drives==0)
__Error.WinIOError();
uint d = (uint)drives;
int count = 0;
while (d != 0) {
if (((int)d & 1) != 0) count++;
d >>= 1;
}
String[] result = new String[count];
char[] root = new char[] {'A', ':', '\\'};
d = (uint)drives;
count = 0;
while (d != 0) {
if (((int)d & 1) != 0) {
result[count++] = new String(root);
}
d >>= 1;
root[0]++;
}
return result;
}
[System.Security.SecuritySafeCritical]
public static String GetDirectoryRoot(String path) {
if (path==null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
String fullPath = Path.GetFullPathInternal(path);
String root = fullPath.Substring(0, Path.GetRootLength(fullPath));
String demandPath = GetDemandDir(root, true);
#if FEATURE_CORECLR
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, path, demandPath);
state.EnsureState();
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, demandPath, false, false);
#endif
return root;
}
internal static String InternalGetDirectoryRoot(String path) {
if (path == null) return null;
return path.Substring(0, Path.GetRootLength(path));
}
/*===============================CurrentDirectory===============================
**Action: Provides a getter and setter for the current directory. The original
** current DirectoryInfo is the one from which the process was started.
**Returns: The current DirectoryInfo (from the getter). Void from the setter.
**Arguments: The current DirectoryInfo to which to switch to the setter.
**Exceptions:
==============================================================================*/
[System.Security.SecuritySafeCritical]
public static String GetCurrentDirectory()
{
return InternalGetCurrentDirectory(true);
}
[System.Security.SecurityCritical]
internal static String UnsafeGetCurrentDirectory()
{
return InternalGetCurrentDirectory(false);
}
[System.Security.SecurityCritical]
private static String InternalGetCurrentDirectory(bool checkHost)
{
StringBuilder sb = StringBuilderCache.Acquire(Path.MaxPath + 1);
if (Win32Native.GetCurrentDirectory(sb.Capacity, sb) == 0)
__Error.WinIOError();
String currentDirectory = sb.ToString();
// Note that if we have somehow put our command prompt into short
// file name mode (ie, by running edlin or a DOS grep, etc), then
// this will return a short file name.
if (currentDirectory.IndexOf('~') >= 0) {
int r = Win32Native.GetLongPathName(currentDirectory, sb, sb.Capacity);
if (r == 0 || r >= Path.MaxPath) {
int errorCode = Marshal.GetLastWin32Error();
if (r >= Path.MaxPath)
errorCode = Win32Native.ERROR_FILENAME_EXCED_RANGE;
if (errorCode != Win32Native.ERROR_FILE_NOT_FOUND &&
errorCode != Win32Native.ERROR_PATH_NOT_FOUND &&
errorCode != Win32Native.ERROR_INVALID_FUNCTION && // by design - enough said.
errorCode != Win32Native.ERROR_ACCESS_DENIED)
__Error.WinIOError(errorCode, String.Empty);
}
currentDirectory = sb.ToString();
}
StringBuilderCache.Release(sb);
String demandPath = GetDemandDir(currentDirectory, true);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPath);
state.EnsureState();
}
#else
new FileIOPermission( FileIOPermissionAccess.PathDiscovery, new String[] { demandPath }, false, false ).Demand();
#endif
return currentDirectory;
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
public static void SetCurrentDirectory(String path)
{
if (path==null)
throw new ArgumentNullException("value");
if (path.Length==0)
throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
Contract.EndContractBlock();
if (path.Length >= Path.MaxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
// This will have some large effects on the rest of the runtime
// and other appdomains in this process. Demand unmanaged code.
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#pragma warning restore 618
String fulldestDirName = Path.GetFullPathInternal(path);
if (!Win32Native.SetCurrentDirectory(fulldestDirName)) {
// If path doesn't exist, this sets last error to 2 (File
// not Found). LEGACY: This may potentially have worked correctly
// on Win9x, maybe.
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Win32Native.ERROR_FILE_NOT_FOUND)
errorCode = Win32Native.ERROR_PATH_NOT_FOUND;
__Error.WinIOError(errorCode, fulldestDirName);
}
}
[System.Security.SecuritySafeCritical]
public static void Move(String sourceDirName,String destDirName) {
InternalMove(sourceDirName, destDirName, true);
}
[System.Security.SecurityCritical]
internal static void UnsafeMove(String sourceDirName,String destDirName) {
InternalMove(sourceDirName, destDirName, false);
}
[System.Security.SecurityCritical]
private static void InternalMove(String sourceDirName,String destDirName,bool checkHost) {
if (sourceDirName==null)
throw new ArgumentNullException("sourceDirName");
if (sourceDirName.Length==0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceDirName");
if (destDirName==null)
throw new ArgumentNullException("destDirName");
if (destDirName.Length==0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destDirName");
Contract.EndContractBlock();
String fullsourceDirName = Path.GetFullPathInternal(sourceDirName);
String sourcePath = GetDemandDir(fullsourceDirName, false);
if (sourcePath.Length >= Path.MAX_DIRECTORY_PATH)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
String fulldestDirName = Path.GetFullPathInternal(destDirName);
String destPath = GetDemandDir(fulldestDirName, false);
if (destPath.Length >= Path.MAX_DIRECTORY_PATH)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
#if FEATURE_CORECLR
if (checkHost) {
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, sourceDirName, sourcePath);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destDirName, destPath);
sourceState.EnsureState();
destState.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, sourcePath, false, false);
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, destPath, false, false);
#endif
if (String.Compare(sourcePath, destPath, StringComparison.OrdinalIgnoreCase) == 0)
throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent"));
String sourceRoot = Path.GetPathRoot(sourcePath);
String destinationRoot = Path.GetPathRoot(destPath);
if (String.Compare(sourceRoot, destinationRoot, StringComparison.OrdinalIgnoreCase) != 0)
throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustHaveSameRoot"));
if (!Win32Native.MoveFile(sourceDirName, destDirName))
{
int hr = Marshal.GetLastWin32Error();
if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // Source dir not found
{
hr = Win32Native.ERROR_PATH_NOT_FOUND;
__Error.WinIOError(hr, fullsourceDirName);
}
// This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons.
if (hr == Win32Native.ERROR_ACCESS_DENIED) // WinNT throws IOException. This check is for Win9x. We can't change it for backcomp.
throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", sourceDirName), Win32Native.MakeHRFromErrorCode(hr));
__Error.WinIOError(hr, String.Empty);
}
}
[System.Security.SecuritySafeCritical]
public static void Delete(String path)
{
String fullPath = Path.GetFullPathInternal(path);
Delete(fullPath, path, false, true);
}
[System.Security.SecuritySafeCritical]
public static void Delete(String path, bool recursive)
{
String fullPath = Path.GetFullPathInternal(path);
Delete(fullPath, path, recursive, true);
}
[System.Security.SecurityCritical]
internal static void UnsafeDelete(String path, bool recursive)
{
String fullPath = Path.GetFullPathInternal(path);
Delete(fullPath, path, recursive, false);
}
// Called from DirectoryInfo as well. FullPath is fully qualified,
// while the user path is used for feedback in exceptions.
[System.Security.SecurityCritical] // auto-generated
internal static void Delete(String fullPath, String userPath, bool recursive, bool checkHost)
{
String demandPath;
// If not recursive, do permission check only on this directory
// else check for the whole directory structure rooted below
demandPath = GetDemandDir(fullPath, !recursive);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, userPath, demandPath);
state.EnsureState();
}
#else
// Make sure we have write permission to this directory
new FileIOPermission(FileIOPermissionAccess.Write, new String[] { demandPath }, false, false ).Demand();
#endif
// Do not recursively delete through reparse points. Perhaps in a
// future version we will add a new flag to control this behavior,
// but for now we're much safer if we err on the conservative side.
// This applies to symbolic links and mount points.
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = File.FillAttributeInfo(fullPath, ref data, false, true);
if (dataInitialised != 0) {
// Ensure we throw a DirectoryNotFoundException.
if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND)
dataInitialised = Win32Native.ERROR_PATH_NOT_FOUND;
__Error.WinIOError(dataInitialised, fullPath);
}
if (((FileAttributes)data.fileAttributes & FileAttributes.ReparsePoint) != 0)
recursive = false;
DeleteHelper(fullPath, userPath, recursive, true);
}
// Note that fullPath is fully qualified, while userPath may be
// relative. Use userPath for all exception messages to avoid leaking
// fully qualified path information.
[System.Security.SecurityCritical] // auto-generated
private static void DeleteHelper(String fullPath, String userPath, bool recursive, bool throwOnTopLevelDirectoryNotFound)
{
bool r;
int hr;
Exception ex = null;
// Do not recursively delete through reparse points. Perhaps in a
// future version we will add a new flag to control this behavior,
// but for now we're much safer if we err on the conservative side.
// This applies to symbolic links and mount points.
// Note the logic to check whether fullPath is a reparse point is
// in Delete(String, String, bool), and will set "recursive" to false.
// Note that Win32's DeleteFile and RemoveDirectory will just delete
// the reparse point itself.
if (recursive) {
Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA();
// Open a Find handle
using (SafeFindHandle hnd = Win32Native.FindFirstFile(fullPath+Path.DirectorySeparatorCharAsString+"*", data)) {
if (hnd.IsInvalid) {
hr = Marshal.GetLastWin32Error();
__Error.WinIOError(hr, fullPath);
}
do {
bool isDir = (0!=(data.dwFileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY));
if (isDir) {
// Skip ".", "..".
if (data.cFileName.Equals(".") || data.cFileName.Equals(".."))
continue;
// Recurse for all directories, unless they are
// reparse points. Do not follow mount points nor
// symbolic links, but do delete the reparse point
// itself.
bool shouldRecurse = (0 == (data.dwFileAttributes & (int) FileAttributes.ReparsePoint));
if (shouldRecurse) {
String newFullPath = Path.InternalCombine(fullPath, data.cFileName);
String newUserPath = Path.InternalCombine(userPath, data.cFileName);
try {
DeleteHelper(newFullPath, newUserPath, recursive, false);
}
catch(Exception e) {
if (ex == null) {
ex = e;
}
}
}
else {
// Check to see if this is a mount point, and
// unmount it.
if (data.dwReserved0 == Win32Native.IO_REPARSE_TAG_MOUNT_POINT) {
// Use full path plus a trailing '\'
String mountPoint = Path.InternalCombine(fullPath, data.cFileName + Path.DirectorySeparatorChar);
r = Win32Native.DeleteVolumeMountPoint(mountPoint);
if (!r) {
hr = Marshal.GetLastWin32Error();
if (hr != Win32Native.ERROR_PATH_NOT_FOUND) {
try {
__Error.WinIOError(hr, data.cFileName);
}
catch(Exception e) {
if (ex == null) {
ex = e;
}
}
}
}
}
// RemoveDirectory on a symbolic link will
// remove the link itself.
String reparsePoint = Path.InternalCombine(fullPath, data.cFileName);
r = Win32Native.RemoveDirectory(reparsePoint);
if (!r) {
hr = Marshal.GetLastWin32Error();
if (hr != Win32Native.ERROR_PATH_NOT_FOUND) {
try {
__Error.WinIOError(hr, data.cFileName);
}
catch(Exception e) {
if (ex == null) {
ex = e;
}
}
}
}
}
}
else {
String fileName = Path.InternalCombine(fullPath, data.cFileName);
r = Win32Native.DeleteFile(fileName);
if (!r) {
hr = Marshal.GetLastWin32Error();
if (hr != Win32Native.ERROR_FILE_NOT_FOUND) {
try {
__Error.WinIOError(hr, data.cFileName);
}
catch (Exception e) {
if (ex == null) {
ex = e;
}
}
}
}
}
} while (Win32Native.FindNextFile(hnd, data));
// Make sure we quit with a sensible error.
hr = Marshal.GetLastWin32Error();
}
if (ex != null)
throw ex;
if (hr!=0 && hr!=Win32Native.ERROR_NO_MORE_FILES)
__Error.WinIOError(hr, userPath);
}
r = Win32Native.RemoveDirectory(fullPath);
if (!r) {
hr = Marshal.GetLastWin32Error();
if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // A dubious error code.
hr = Win32Native.ERROR_PATH_NOT_FOUND;
// This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons.
if (hr == Win32Native.ERROR_ACCESS_DENIED)
throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", userPath));
// don't throw the DirectoryNotFoundException since this is a subdir and there could be a race condition
// between two Directory.Delete callers
if (hr == Win32Native.ERROR_PATH_NOT_FOUND && !throwOnTopLevelDirectoryNotFound)
return;
__Error.WinIOError(hr, fullPath);
}
}
// WinNT only. Win9x this code will not work.
[System.Security.SecurityCritical] // auto-generated
private static SafeFileHandle OpenHandle(String path)
{
String fullPath = Path.GetFullPathInternal(path);
String root = Path.GetPathRoot(fullPath);
if (root == fullPath && root[1] == Path.VolumeSeparatorChar)
throw new ArgumentException(Environment.GetResourceString("Arg_PathIsVolume"));
#if !FEATURE_CORECLR
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, GetDemandDir(fullPath, true), false, false);
#endif
SafeFileHandle handle = Win32Native.SafeCreateFile (
fullPath,
GENERIC_WRITE,
(FileShare) (FILE_SHARE_WRITE|FILE_SHARE_DELETE),
null,
FileMode.Open,
FILE_FLAG_BACKUP_SEMANTICS,
IntPtr.Zero
);
if (handle.IsInvalid) {
int hr = Marshal.GetLastWin32Error();
__Error.WinIOError(hr, fullPath);
}
return handle;
}
private const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
private const int GENERIC_WRITE = unchecked((int)0x40000000);
private const int FILE_SHARE_WRITE = 0x00000002;
private const int FILE_SHARE_DELETE = 0x00000004;
private const int OPEN_EXISTING = 0x00000003;
private const int FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
}
}
| |
using UnityEngine;
using System.Collections.Generic;
#if UNITY_EDITOR || !UNITY_FLASH
namespace tk2dRuntime.TileMap
{
public static class BuilderUtil
{
/// Syncs layer data and makes sure data is valid
public static bool InitDataStore(tk2dTileMap tileMap)
{
bool dataChanged = false;
int numLayers = tileMap.data.NumLayers;
if (tileMap.Layers == null)
{
tileMap.Layers = new Layer[numLayers];
for (int i = 0; i < numLayers; ++i)
tileMap.Layers[i] = new Layer(tileMap.data.Layers[i].hash, tileMap.width, tileMap.height, tileMap.partitionSizeX, tileMap.partitionSizeY);
dataChanged = true;
}
else
{
// link up layer hashes
Layer[] newLayers = new Layer[numLayers];
for (int i = 0; i < numLayers; ++i)
{
var layerInfo = tileMap.data.Layers[i];
bool found = false;
// Find an existing layer with this hash
for (int j = 0; j < tileMap.Layers.Length; ++j)
{
if (tileMap.Layers[j].hash == layerInfo.hash)
{
newLayers[i] = tileMap.Layers[j];
found = true;
break;
}
}
if (!found)
newLayers[i] = new Layer(layerInfo.hash, tileMap.width, tileMap.height, tileMap.partitionSizeX, tileMap.partitionSizeY);
}
// Identify if it has changed
int numActiveLayers = 0;
foreach (var layer in newLayers)
if (!layer.IsEmpty)
numActiveLayers++;
int numPreviousActiveLayers = 0;
foreach (var layer in tileMap.Layers)
{
if (!layer.IsEmpty)
numPreviousActiveLayers++;
}
if (numActiveLayers != numPreviousActiveLayers)
dataChanged = true;
tileMap.Layers = newLayers;
}
if (tileMap.ColorChannel == null)
{
tileMap.ColorChannel = new ColorChannel(tileMap.width, tileMap.height, tileMap.partitionSizeX, tileMap.partitionSizeY);
}
return dataChanged;
}
/// Deletes all generated instances
public static void CleanRenderData(tk2dTileMap tileMap)
{
if (tileMap.renderData == null)
return;
// Build a list of all children
// All children will appear after the parent
int currentProcessedChild = 0;
List<Transform> children = new List<Transform>();
children.Add(tileMap.renderData.transform);
while (currentProcessedChild < children.Count)
{
var thisChild = children[currentProcessedChild++];
int childCount = thisChild.GetChildCount();
for (int i = 0; i < childCount; ++i)
children.Add(thisChild.GetChild(i));
}
currentProcessedChild = children.Count - 1;
while (currentProcessedChild > 0) // skip very first as it is the root object
{
var go = children[currentProcessedChild--].gameObject;
MeshFilter mf = go.GetComponent<MeshFilter>();
if (mf != null)
{
Mesh mesh = mf.sharedMesh;
mf.sharedMesh = null;
tileMap.DestroyMesh(mesh);
}
MeshCollider meshCollider = go.GetComponent<MeshCollider>();
if (meshCollider)
{
Mesh mesh = meshCollider.sharedMesh;
meshCollider.sharedMesh = null;
tileMap.DestroyMesh(mesh);
}
GameObject.DestroyImmediate(go);
}
tileMap.buildKey++; // force a rebuild
}
/// Spawns all prefabs for a given chunk
/// Expects the chunk to have a valid GameObject
public static void SpawnPrefabsForChunk(tk2dTileMap tileMap, SpriteChunk chunk, int baseX, int baseY)
{
var chunkData = chunk.spriteIds;
var tilePrefabs = tileMap.data.tilePrefabs;
Vector3 tileSize = tileMap.data.tileSize;
int[] prefabCounts = new int[tilePrefabs.Length];
var parent = chunk.gameObject.transform;
float xOffsetMult = 0.0f, yOffsetMult = 0.0f;
tileMap.data.GetTileOffset(out xOffsetMult, out yOffsetMult);
for (int y = 0; y < tileMap.partitionSizeY; ++y)
{
float xOffset = ((baseY + y) & 1) * xOffsetMult;
for (int x = 0; x < tileMap.partitionSizeX; ++x)
{
int tile = chunkData[y * tileMap.partitionSizeX + x];
if (tile < 0 || tile >= tilePrefabs.Length)
continue;
Vector3 currentPos = new Vector3(tileSize.x * (x + xOffset), tileSize.y * y, 0);
Object prefab = tilePrefabs[tile];
if (prefab != null)
{
prefabCounts[tile]++;
#if UNITY_EDITOR && !(UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4)
GameObject go = UnityEditor.PrefabUtility.InstantiatePrefab(prefab) as GameObject;
#else
GameObject go = GameObject.Instantiate(prefab, Vector3.zero, Quaternion.identity) as GameObject;
#endif
if (go)
{
go.name = prefab.name + " " + prefabCounts[tile].ToString();
// Position after transforming, as it is in local space
go.transform.parent = parent;
go.transform.localPosition = currentPos;
go.transform.localRotation = Quaternion.identity;
go.transform.localScale = Vector3.one;
}
}
}
}
}
/// Spawns all prefabs for a given tilemap
/// Expects populated chunks to have valid GameObjects
public static void SpawnPrefabs(tk2dTileMap tileMap)
{
int numLayers = tileMap.Layers.Length;
for (int layerId = 0; layerId < numLayers; ++layerId)
{
var layer = tileMap.Layers[layerId];
if (layer.IsEmpty || tileMap.data.Layers[layerId].skipMeshGeneration)
continue;
for (int cellY = 0; cellY < layer.numRows; ++cellY)
{
int baseY = cellY * layer.divY;
for (int cellX = 0; cellX < layer.numColumns; ++cellX)
{
int baseX = cellX * layer.divX;
var chunk = layer.GetChunk(cellX, cellY);
if (chunk.IsEmpty)
continue;
SpawnPrefabsForChunk(tileMap, chunk, baseX, baseY);
}
}
}
}
static Vector3 GetTilePosition(tk2dTileMap tileMap, int x, int y)
{
return new Vector3(tileMap.data.tileSize.x * x, tileMap.data.tileSize.y * y, 0.0f);
}
/// Creates render data for given tilemap
public static void CreateRenderData(tk2dTileMap tileMap, bool editMode)
{
// Create render data
if (tileMap.renderData == null)
tileMap.renderData = new GameObject(tileMap.name + " Render Data");
tileMap.renderData.transform.position = tileMap.transform.position;
float accumulatedLayerZ = 0.0f;
// Create all objects
int layerId = 0;
foreach (var layer in tileMap.Layers)
{
// We skip offsetting the first one
if (layerId != 0)
accumulatedLayerZ -= tileMap.data.Layers[layerId].z;
if (layer.IsEmpty && layer.gameObject != null)
{
GameObject.DestroyImmediate(layer.gameObject);
layer.gameObject = null;
}
else if (!layer.IsEmpty && layer.gameObject == null)
{
var go = layer.gameObject = new GameObject("");
go.transform.parent = tileMap.renderData.transform;
}
int unityLayer = tileMap.data.Layers[layerId].unityLayer;
if (layer.gameObject != null)
{
#if UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_3_6 || UNITY_3_7 || UNITY_3_8 || UNITY_3_9
if (!editMode && layer.gameObject.active == false)
layer.gameObject.SetActiveRecursively(true);
#else
if (!editMode && layer.gameObject.activeSelf == false)
layer.gameObject.SetActive(true);
#endif
layer.gameObject.name = tileMap.data.Layers[layerId].name;
layer.gameObject.transform.localPosition = new Vector3(0, 0, accumulatedLayerZ);
layer.gameObject.transform.localRotation = Quaternion.identity;
layer.gameObject.transform.localScale = Vector3.one;
layer.gameObject.layer = unityLayer;
}
int x0, x1, dx;
int y0, y1, dy;
BuilderUtil.GetLoopOrder(tileMap.data.sortMethod,
layer.numColumns, layer.numRows,
out x0, out x1, out dx,
out y0, out y1, out dy);
float z = 0.0f;
for (int y = y0; y != y1; y += dy)
{
for (int x = x0; x != x1; x += dx)
{
var chunk = layer.GetChunk(x, y);
bool isEmpty = layer.IsEmpty || chunk.IsEmpty;
if (isEmpty && chunk.HasGameData)
{
chunk.DestroyGameData(tileMap);
}
else if (!isEmpty && chunk.gameObject == null)
{
string chunkName = "Chunk " + y.ToString() + " " + x.ToString();
var go = chunk.gameObject = new GameObject(chunkName);
go.transform.parent = layer.gameObject.transform;
// render mesh
MeshFilter meshFilter = go.AddComponent<MeshFilter>();
go.AddComponent<MeshRenderer>();
chunk.mesh = tileMap.GetOrCreateMesh();
meshFilter.mesh = chunk.mesh;
// collider mesh
chunk.meshCollider = go.AddComponent<MeshCollider>();
chunk.meshCollider.sharedMesh = null;
chunk.colliderMesh = null;
}
if (chunk.gameObject != null)
{
Vector3 tilePosition = GetTilePosition(tileMap, x * tileMap.partitionSizeX, y * tileMap.partitionSizeY);
tilePosition.z += z;
chunk.gameObject.transform.localPosition = tilePosition;
chunk.gameObject.transform.localRotation = Quaternion.identity;
chunk.gameObject.transform.localScale = Vector3.one;
chunk.gameObject.layer = unityLayer;
// We won't be generating collider data in edit mode, so clear everything
if (editMode)
{
if (chunk.colliderMesh)
chunk.DestroyColliderData(tileMap);
}
}
z -= 0.000001f;
}
}
++layerId;
}
}
public static void GetLoopOrder(tk2dTileMapData.SortMethod sortMethod, int w, int h, out int x0, out int x1, out int dx, out int y0, out int y1, out int dy)
{
switch (sortMethod)
{
case tk2dTileMapData.SortMethod.BottomLeft:
x0 = 0; x1 = w; dx = 1;
y0 = 0; y1 = h; dy = 1;
break;
case tk2dTileMapData.SortMethod.BottomRight:
x0 = w - 1; x1 = -1; dx = -1;
y0 = 0; y1 = h; dy = 1;
break;
case tk2dTileMapData.SortMethod.TopLeft:
x0 = 0; x1 = w; dx = 1;
y0 = h - 1; y1 = -1; dy = -1;
break;
case tk2dTileMapData.SortMethod.TopRight:
x0 = w - 1; x1 = -1; dx = -1;
y0 = h - 1; y1 = -1; dy = -1;
break;
default:
Debug.LogError("Unhandled sort method");
goto case tk2dTileMapData.SortMethod.BottomLeft;
}
}
}
}
#endif
| |
//
// 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.Net.Http;
using Microsoft.Azure.Subscriptions;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
namespace Microsoft.Azure.Subscriptions
{
public partial class SubscriptionClient : ServiceClient<SubscriptionClient>, ISubscriptionClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private CloudCredentials _credentials;
/// <summary>
/// Credentials used to authenticate requests.
/// </summary>
public CloudCredentials Credentials
{
get { return this._credentials; }
set { this._credentials = value; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private ISubscriptionOperations _subscriptions;
/// <summary>
/// Operations for managing subscriptions.
/// </summary>
public virtual ISubscriptionOperations Subscriptions
{
get { return this._subscriptions; }
}
private ITenantOperations _tenants;
/// <summary>
/// Operations for managing tenants.
/// </summary>
public virtual ITenantOperations Tenants
{
get { return this._tenants; }
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
private SubscriptionClient()
: base()
{
this._subscriptions = new SubscriptionOperations(this);
this._tenants = new TenantOperations(this);
this._apiVersion = "2014-04-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials used to authenticate requests.
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public SubscriptionClient(CloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials used to authenticate requests.
/// </param>
public SubscriptionClient(CloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
private SubscriptionClient(HttpClient httpClient)
: base(httpClient)
{
this._subscriptions = new SubscriptionOperations(this);
this._tenants = new TenantOperations(this);
this._apiVersion = "2014-04-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials used to authenticate requests.
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SubscriptionClient(CloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials used to authenticate requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SubscriptionClient(CloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// SubscriptionClient instance
/// </summary>
/// <param name='client'>
/// Instance of SubscriptionClient to clone to
/// </param>
protected override void Clone(ServiceClient<SubscriptionClient> client)
{
base.Clone(client);
if (client is SubscriptionClient)
{
SubscriptionClient clonedClient = ((SubscriptionClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
// Copyright (c) .NET Foundation. 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.Buffers;
using System.Diagnostics;
using System.IO;
using System.IO.Pipelines;
using System.Threading;
using System.Threading.Tasks;
using HtcSharp.HttpModule.Connections.Abstractions.Exceptions;
using HtcSharp.HttpModule.Core.Internal.Http;
using HtcSharp.HttpModule.Core.Internal.Http2.FlowControl;
using HtcSharp.HttpModule.Core.Internal.Infrastructure;
using HtcSharp.HttpModule.Http;
using HtcSharp.HttpModule.Shared.ServerInfrastructure;
using Microsoft.Extensions.Primitives;
using HeaderNames = HtcSharp.HttpModule.Http.Headers.HeaderNames;
namespace HtcSharp.HttpModule.Core.Internal.Http2 {
// SourceTools-Start
// Remote-File C:\ASP\src\Servers\Kestrel\Core\src\Internal\Http2\Http2Stream.cs
// Start-At-Remote-Line 19
// SourceTools-End
internal abstract partial class Http2Stream : HttpProtocol, IThreadPoolWorkItem {
private readonly Http2StreamContext _context;
private readonly Http2OutputProducer _http2Output;
private readonly StreamInputFlowControl _inputFlowControl;
private readonly StreamOutputFlowControl _outputFlowControl;
private bool _decrementCalled;
public Pipe RequestBodyPipe { get; }
internal long DrainExpirationTicks { get; set; }
private StreamCompletionFlags _completionState;
private readonly object _completionLock = new object();
public Http2Stream(Http2StreamContext context)
: base(context) {
_context = context;
_inputFlowControl = new StreamInputFlowControl(
context.StreamId,
context.FrameWriter,
context.ConnectionInputFlowControl,
context.ServerPeerSettings.InitialWindowSize,
context.ServerPeerSettings.InitialWindowSize / 2);
_outputFlowControl = new StreamOutputFlowControl(
context.ConnectionOutputFlowControl,
context.ClientPeerSettings.InitialWindowSize);
_http2Output = new Http2OutputProducer(
context.StreamId,
context.FrameWriter,
_outputFlowControl,
context.MemoryPool,
this,
context.ServiceContext.Log);
RequestBodyPipe = CreateRequestBodyPipe(context.ServerPeerSettings.InitialWindowSize);
Output = _http2Output;
}
public int StreamId => _context.StreamId;
public long? InputRemaining { get; internal set; }
public bool RequestBodyStarted { get; private set; }
public bool EndStreamReceived => (_completionState & StreamCompletionFlags.EndStreamReceived) == StreamCompletionFlags.EndStreamReceived;
private bool IsAborted => (_completionState & StreamCompletionFlags.Aborted) == StreamCompletionFlags.Aborted;
internal bool RstStreamReceived => (_completionState & StreamCompletionFlags.RstStreamReceived) == StreamCompletionFlags.RstStreamReceived;
public bool ReceivedEmptyRequestBody {
get {
lock (_completionLock) {
return EndStreamReceived && !RequestBodyStarted;
}
}
}
protected override void OnReset() {
ResetHttp2Features();
}
protected override void OnRequestProcessingEnded() {
try {
// https://tools.ietf.org/html/rfc7540#section-8.1
// If the app finished without reading the request body tell the client not to finish sending it.
if (!EndStreamReceived && !RstStreamReceived) {
Log.RequestBodyNotEntirelyRead(ConnectionIdFeature, TraceIdentifier);
var (oldState, newState) = ApplyCompletionFlag(StreamCompletionFlags.Aborted);
if (oldState != newState) {
Debug.Assert(_decrementCalled);
// Don't block on IO. This never faults.
_ = _http2Output.WriteRstStreamAsync(Http2ErrorCode.NO_ERROR);
RequestBodyPipe.Writer.Complete();
}
}
_http2Output.Dispose();
RequestBodyPipe.Reader.Complete();
// The app can no longer read any more of the request body, so return any bytes that weren't read to the
// connection's flow-control window.
_inputFlowControl.Abort();
Reset();
} finally {
_context.StreamLifetimeHandler.OnStreamCompleted(this);
}
}
protected override string CreateRequestId()
=> StringUtilities.ConcatAsHexSuffix(ConnectionId, ':', (uint)StreamId);
protected override MessageBody CreateMessageBody()
=> Http2MessageBody.For(this);
// Compare to Http1Connection.OnStartLine
protected override bool TryParseRequest(ReadResult result, out bool endConnection) {
// We don't need any of the parameters because we don't implement BeginRead to actually
// do the reading from a pipeline, nor do we use endConnection to report connection-level errors.
endConnection = !TryValidatePseudoHeaders();
return true;
}
private bool TryValidatePseudoHeaders() {
// The initial pseudo header validation takes place in Http2Connection.ValidateHeader and StartStream
// They make sure the right fields are at least present (except for Connect requests) exactly once.
_httpVersion = Http.HttpVersion.Http2;
if (!TryValidateMethod()) {
return false;
}
if (!TryValidateAuthorityAndHost(out var hostText)) {
return false;
}
// CONNECT - :scheme and :path must be excluded
if (Method == HttpMethod.Connect) {
if (!String.IsNullOrEmpty(RequestHeaders[HeaderNames.Scheme]) || !String.IsNullOrEmpty(RequestHeaders[HeaderNames.Path])) {
ResetAndAbort(new ConnectionAbortedException(CoreStrings.Http2ErrorConnectMustNotSendSchemeOrPath), Http2ErrorCode.PROTOCOL_ERROR);
return false;
}
RawTarget = hostText;
return true;
}
// :scheme https://tools.ietf.org/html/rfc7540#section-8.1.2.3
// ":scheme" is not restricted to "http" and "https" schemed URIs. A
// proxy or gateway can translate requests for non - HTTP schemes,
// enabling the use of HTTP to interact with non - HTTP services.
// - That said, we shouldn't allow arbitrary values or use them to populate Request.Scheme, right?
// - For now we'll restrict it to http/s and require it match the transport.
// - We'll need to find some concrete scenarios to warrant unblocking this.
if (!string.Equals(RequestHeaders[HeaderNames.Scheme], Scheme, StringComparison.OrdinalIgnoreCase)) {
ResetAndAbort(new ConnectionAbortedException(
CoreStrings.FormatHttp2StreamErrorSchemeMismatch(RequestHeaders[HeaderNames.Scheme], Scheme)), Http2ErrorCode.PROTOCOL_ERROR);
return false;
}
// :path (and query) - Required
// Must start with / except may be * for OPTIONS
var path = RequestHeaders[HeaderNames.Path].ToString();
RawTarget = path;
// OPTIONS - https://tools.ietf.org/html/rfc7540#section-8.1.2.3
// This pseudo-header field MUST NOT be empty for "http" or "https"
// URIs; "http" or "https" URIs that do not contain a path component
// MUST include a value of '/'. The exception to this rule is an
// OPTIONS request for an "http" or "https" URI that does not include
// a path component; these MUST include a ":path" pseudo-header field
// with a value of '*'.
if (Method == HttpMethod.Options && path.Length == 1 && path[0] == '*') {
// * is stored in RawTarget only since HttpRequest expects Path to be empty or start with a /.
Path = string.Empty;
QueryString = string.Empty;
return true;
}
// Approximate MaxRequestLineSize by totaling the required pseudo header field lengths.
var requestLineLength = _methodText.Length + Scheme.Length + hostText.Length + path.Length;
if (requestLineLength > ServerOptions.Limits.MaxRequestLineSize) {
ResetAndAbort(new ConnectionAbortedException(CoreStrings.BadRequest_RequestLineTooLong), Http2ErrorCode.PROTOCOL_ERROR);
return false;
}
var queryIndex = path.IndexOf('?');
QueryString = queryIndex == -1 ? string.Empty : path.Substring(queryIndex);
var pathSegment = queryIndex == -1 ? path.AsSpan() : path.AsSpan(0, queryIndex);
return TryValidatePath(pathSegment);
}
private bool TryValidateMethod() {
// :method
_methodText = RequestHeaders[HeaderNames.Method].ToString();
Method = HttpUtilities.GetKnownMethod(_methodText);
if (Method == HttpMethod.None) {
ResetAndAbort(new ConnectionAbortedException(CoreStrings.FormatHttp2ErrorMethodInvalid(_methodText)), Http2ErrorCode.PROTOCOL_ERROR);
return false;
}
if (Method == HttpMethod.Custom) {
if (HttpCharacters.IndexOfInvalidTokenChar(_methodText) >= 0) {
ResetAndAbort(new ConnectionAbortedException(CoreStrings.FormatHttp2ErrorMethodInvalid(_methodText)), Http2ErrorCode.PROTOCOL_ERROR);
return false;
}
}
return true;
}
private bool TryValidateAuthorityAndHost(out string hostText) {
// :authority (optional)
// Prefer this over Host
var authority = RequestHeaders[HeaderNames.Authority];
var host = HttpRequestHeaders.HeaderHost;
if (!StringValues.IsNullOrEmpty(authority)) {
// https://tools.ietf.org/html/rfc7540#section-8.1.2.3
// Clients that generate HTTP/2 requests directly SHOULD use the ":authority"
// pseudo - header field instead of the Host header field.
// An intermediary that converts an HTTP/2 request to HTTP/1.1 MUST
// create a Host header field if one is not present in a request by
// copying the value of the ":authority" pseudo - header field.
// We take this one step further, we don't want mismatched :authority
// and Host headers, replace Host if :authority is defined. The application
// will operate on the Host header.
HttpRequestHeaders.HeaderHost = authority;
host = authority;
}
// https://tools.ietf.org/html/rfc7230#section-5.4
// A server MUST respond with a 400 (Bad Request) status code to any
// HTTP/1.1 request message that lacks a Host header field and to any
// request message that contains more than one Host header field or a
// Host header field with an invalid field-value.
hostText = host.ToString();
if (host.Count > 1 || !HttpUtilities.IsHostHeaderValid(hostText)) {
// RST replaces 400
ResetAndAbort(new ConnectionAbortedException(CoreStrings.FormatBadRequest_InvalidHostHeader_Detail(hostText)), Http2ErrorCode.PROTOCOL_ERROR);
return false;
}
return true;
}
private bool TryValidatePath(ReadOnlySpan<char> pathSegment) {
// Must start with a leading slash
if (pathSegment.Length == 0 || pathSegment[0] != '/') {
ResetAndAbort(new ConnectionAbortedException(CoreStrings.FormatHttp2StreamErrorPathInvalid(RawTarget)), Http2ErrorCode.PROTOCOL_ERROR);
return false;
}
var pathEncoded = pathSegment.Contains('%');
// Compare with Http1Connection.OnOriginFormTarget
// URIs are always encoded/escaped to ASCII https://tools.ietf.org/html/rfc3986#page-11
// Multibyte Internationalized Resource Identifiers (IRIs) are first converted to utf8;
// then encoded/escaped to ASCII https://www.ietf.org/rfc/rfc3987.txt "Mapping of IRIs to URIs"
try {
// The decoder operates only on raw bytes
var pathBuffer = new byte[pathSegment.Length].AsSpan();
for (int i = 0; i < pathSegment.Length; i++) {
var ch = pathSegment[i];
// The header parser should already be checking this
Debug.Assert(32 < ch && ch < 127);
pathBuffer[i] = (byte)ch;
}
Path = PathNormalizer.DecodePath(pathBuffer, pathEncoded, RawTarget, QueryString.Length);
return true;
} catch (InvalidOperationException) {
ResetAndAbort(new ConnectionAbortedException(CoreStrings.FormatHttp2StreamErrorPathInvalid(RawTarget)), Http2ErrorCode.PROTOCOL_ERROR);
return false;
}
}
public Task OnDataAsync(Http2Frame dataFrame, in ReadOnlySequence<byte> payload) {
// Since padding isn't buffered, immediately count padding bytes as read for flow control purposes.
if (dataFrame.DataHasPadding) {
// Add 1 byte for the padding length prefix.
OnDataRead(dataFrame.DataPadLength + 1);
}
var dataPayload = payload.Slice(0, dataFrame.DataPayloadLength); // minus padding
var endStream = dataFrame.DataEndStream;
if (dataPayload.Length > 0) {
lock (_completionLock) {
RequestBodyStarted = true;
if (endStream) {
// No need to send any more window updates for this stream now that we've received all the data.
// Call before flushing the request body pipe, because that might induce a window update.
_inputFlowControl.StopWindowUpdates();
}
_inputFlowControl.Advance((int)dataPayload.Length);
// This check happens after flow control so that when we throw and abort, the byte count is returned to the connection
// level accounting.
if (InputRemaining.HasValue) {
// https://tools.ietf.org/html/rfc7540#section-8.1.2.6
if (dataPayload.Length > InputRemaining.Value) {
throw new Http2StreamErrorException(StreamId, CoreStrings.Http2StreamErrorMoreDataThanLength, Http2ErrorCode.PROTOCOL_ERROR);
}
InputRemaining -= dataPayload.Length;
}
// Ignore data frames for aborted streams, but only after counting them for purposes of connection level flow control.
if (!IsAborted) {
foreach (var segment in dataPayload) {
RequestBodyPipe.Writer.Write(segment.Span);
}
// If the stream is completed go ahead and call RequestBodyPipe.Writer.Complete().
// Data will still be available to the reader.
if (!endStream) {
var flushTask = RequestBodyPipe.Writer.FlushAsync();
// It shouldn't be possible for the RequestBodyPipe to fill up an return an incomplete task if
// _inputFlowControl.Advance() didn't throw.
Debug.Assert(flushTask.IsCompleted);
}
}
}
}
if (endStream) {
OnEndStreamReceived();
}
return Task.CompletedTask;
}
public void OnEndStreamReceived() {
ApplyCompletionFlag(StreamCompletionFlags.EndStreamReceived);
if (InputRemaining.HasValue) {
// https://tools.ietf.org/html/rfc7540#section-8.1.2.6
if (InputRemaining.Value != 0) {
throw new Http2StreamErrorException(StreamId, CoreStrings.Http2StreamErrorLessDataThanLength, Http2ErrorCode.PROTOCOL_ERROR);
}
}
OnTrailersComplete();
RequestBodyPipe.Writer.Complete();
_inputFlowControl.StopWindowUpdates();
}
public void OnDataRead(int bytesRead) {
_inputFlowControl.UpdateWindows(bytesRead);
}
public bool TryUpdateOutputWindow(int bytes) {
return _context.FrameWriter.TryUpdateStreamWindow(_outputFlowControl, bytes);
}
public void AbortRstStreamReceived() {
// Client sent a reset stream frame, decrement total count.
DecrementActiveClientStreamCount();
ApplyCompletionFlag(StreamCompletionFlags.RstStreamReceived);
Abort(new IOException(CoreStrings.Http2StreamResetByClient));
}
public void Abort(IOException abortReason) {
var (oldState, newState) = ApplyCompletionFlag(StreamCompletionFlags.Aborted);
if (oldState == newState) {
return;
}
AbortCore(abortReason);
}
protected override void OnErrorAfterResponseStarted() {
// We can no longer change the response, send a Reset instead.
var abortReason = new ConnectionAbortedException(CoreStrings.Http2StreamErrorAfterHeaders);
ResetAndAbort(abortReason, Http2ErrorCode.INTERNAL_ERROR);
}
protected override void ApplicationAbort() {
var abortReason = new ConnectionAbortedException(CoreStrings.ConnectionAbortedByApplication);
ResetAndAbort(abortReason, Http2ErrorCode.INTERNAL_ERROR);
}
internal void ResetAndAbort(ConnectionAbortedException abortReason, Http2ErrorCode error) {
// Future incoming frames will drain for a default grace period to avoid destabilizing the connection.
var (oldState, newState) = ApplyCompletionFlag(StreamCompletionFlags.Aborted);
if (oldState == newState) {
return;
}
Log.Http2StreamResetAbort(TraceIdentifier, error, abortReason);
DecrementActiveClientStreamCount();
// Don't block on IO. This never faults.
_ = _http2Output.WriteRstStreamAsync(error);
AbortCore(abortReason);
}
private void AbortCore(Exception abortReason) {
// Call _http2Output.Stop() prior to poisoning the request body stream or pipe to
// ensure that an app that completes early due to the abort doesn't result in header frames being sent.
_http2Output.Stop();
AbortRequest();
// Unblock the request body.
PoisonRequestBodyStream(abortReason);
RequestBodyPipe.Writer.Complete(abortReason);
_inputFlowControl.Abort();
}
public void DecrementActiveClientStreamCount() {
// Decrement can be called twice, via calling CompleteAsync and then Abort on the HttpContext.
// Only decrement once total.
lock (_completionLock) {
if (_decrementCalled) {
return;
}
_decrementCalled = true;
}
_context.StreamLifetimeHandler.DecrementActiveClientStreamCount();
}
private Pipe CreateRequestBodyPipe(uint windowSize)
=> new Pipe(new PipeOptions
(
pool: _context.MemoryPool,
readerScheduler: ServiceContext.Scheduler,
writerScheduler: PipeScheduler.Inline,
// Never pause within the window range. Flow control will prevent more data from being added.
// See the assert in OnDataAsync.
pauseWriterThreshold: windowSize + 1,
resumeWriterThreshold: windowSize + 1,
useSynchronizationContext: false,
minimumSegmentSize: _context.MemoryPool.GetMinimumSegmentSize()
));
private (StreamCompletionFlags OldState, StreamCompletionFlags NewState) ApplyCompletionFlag(StreamCompletionFlags completionState) {
lock (_completionLock) {
var oldCompletionState = _completionState;
_completionState |= completionState;
return (oldCompletionState, _completionState);
}
}
/// <summary>
/// Used to kick off the request processing loop by derived classes.
/// </summary>
public abstract void Execute();
[Flags]
private enum StreamCompletionFlags {
None = 0,
RstStreamReceived = 1,
EndStreamReceived = 2,
Aborted = 4,
}
}
}
| |
using System;
using System.Net;
using System.Web;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Timers;
using Galilei.Core;
namespace Galilei
{
public class Galilei
{
private Server srv;
private HttpListener listener;
private Thread workFlow;
private Configurator config;
private TreeBuilder builder;
private Queue<Node> queueToSave;
private System.Timers.Timer saveTimer;
public Galilei(string configPath)
{
srv = new Server();
config = new Configurator(configPath, srv);
builder = new TreeBuilder(srv);
builder.ConfigChange += new TreeBuilder.ConfigChangeHandler(OnConfig);
queueToSave = new Queue<Node>();
listener = new HttpListener();
workFlow = new Thread(new ThreadStart(WorkFlow));
}
public void Start()
{
Console.Write("Load config....");
config.Load();
Console.WriteLine(" Ok");
string prefix = String.Format("http://{0}:{1}/", srv.Host, srv.Port);
listener.Prefixes.Clear();
listener.Prefixes.Add(prefix);
saveTimer = new System.Timers.Timer(1000);
saveTimer.Elapsed += new System.Timers.ElapsedEventHandler(SaveConfig);
listener.Start();
Console.WriteLine("Start listener on " + prefix);
workFlow.Start();
Console.WriteLine("Start Galilei");
}
public void Stop()
{
Console.WriteLine("Stop Galilei");
listener.Close();
workFlow.Abort();
workFlow.Join();
}
private void WorkFlow()
{
IAsyncResult result = null;
try {
while(true){
HttpListenerContext context = listener.GetContext();
DateTime t = DateTime.Now;
Console.WriteLine("Request: {0} : {1}",
context.Request.HttpMethod,
context.Request.RawUrl);
Process(context);
Console.WriteLine("Response: {0} : {1} [{2} ms]",
context.Response.StatusCode,
context.Response.StatusDescription,
(DateTime.Now - t).Milliseconds
);
}
}
catch(ThreadAbortException)
{
Thread.ResetAbort();
}
}
private void SaveConfig(object sender, System.Timers.ElapsedEventArgs e)
{
if (queueToSave.Count > 0) {
while(queueToSave.Count > 0) {
Console.WriteLine("Config changes in node:{0}",
queueToSave.Dequeue().FullName
);
}
config.Save();
Console.WriteLine("Save config");
}
}
private void Process(HttpListenerContext context)
{
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
try {
switch (request.HttpMethod) {
case "GET":
GetRespond (request, response);
break;
case "POST":
PostRespond (request, response);
break;
case "PUT":
PutRespond (request, response);
break;
case "DELETE":
DeleteRespond (request, response);
break;
default:
break;
}
}
catch(XpcaTypeError ex) {
response.StatusCode = 500;
response.StatusDescription = ex.Message;
}
catch(XpcaPathError ex) {
response.StatusCode = 400;
response.StatusDescription = ex.Message;
}
catch {
response.StatusCode = 500;
}
finally {
response.Close();
}
}
void GetRespond (HttpListenerRequest request, HttpListenerResponse response)
{
string[] rawUrl = request.RawUrl.Split('.');
string url = rawUrl[0];
string format = "json";
if (rawUrl.Length == 2) {
format = rawUrl[1];
}
Node node = srv[url];
Serializer serializer = null;
switch (format) {
case "json":
serializer = new JsonSerializer(node.GetType());
response.ContentType = "application/json";
break;
case "xml":
serializer = new XmlSerializer(node.GetType());
response.ContentType = "application/xml";
break;
default:
response.StatusCode = 400;
break;
}
if (response.StatusCode == 200) {
string data = serializer.Serialize(node);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(data);
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.OutputStream.Flush();
response.OutputStream.Close();
}
}
void PostRespond (HttpListenerRequest request, HttpListenerResponse response)
{
NameValueCollection parms = GetParams(request);
try {
builder.Update(request.RawUrl, parms);
response.StatusCode = 200;
}
catch (XpcaPathError) {
builder.Build(request.RawUrl, parms);
response.StatusCode = 201;
}
}
void PutRespond (HttpListenerRequest request, HttpListenerResponse response)
{
builder.Update(request.RawUrl, GetParams(request));
response.StatusCode = 200;
}
void DeleteRespond (HttpListenerRequest request, HttpListenerResponse response)
{
builder.Delete(request.RawUrl);
response.StatusCode = 200;
}
private NameValueCollection GetParams(HttpListenerRequest request)
{
byte[] buffer = new byte[request.ContentLength64];
request.InputStream.Read(buffer,0,(int)request.ContentLength64);
string data = HttpUtility.UrlDecode(System.Text.Encoding.UTF8.GetString(buffer));
return HttpUtility.ParseQueryString(data);
}
private void OnConfig(Node node)
{
queueToSave.Enqueue(node);
saveTimer.Stop();
saveTimer.Start();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.Rule
{
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using ODataValidator.Rule.Helper;
using ODataValidator.RuleEngine;
using ODataValidator.RuleEngine.Common;
/// <summary>
/// Class of extension rule
/// </summary>
//[Export(typeof(ExtensionRule))] // Section 15 rules have not been supported by services now.
public class MetadataCore4506 : ExtensionRule
{
/// <summary>
/// Gets Category property
/// </summary>
public override string Category
{
get
{
return "core";
}
}
/// <summary>
/// Gets rule name
/// </summary>
public override string Name
{
get
{
return "Metadata.Core.4506";
}
}
/// <summary>
/// Gets rule description
/// </summary>
public override string Description
{
get
{
return "A reference is identified by its Uri property, which is the absolute value of the Uri attribute after resolving a relative value against the xml:base attribute.";
}
}
/// <summary>
/// Gets rule specification in OData document
/// </summary>
public override string SpecificationSection
{
get
{
return "15.1";
}
}
/// <summary>
/// Gets location of help information of the rule
/// </summary>
public override string HelpLink
{
get
{
return null;
}
}
/// <summary>
/// Gets the error message for validation failure
/// </summary>
public override string ErrorMessage
{
get
{
return this.Description;
}
}
/// <summary>
/// Gets the requirement level.
/// </summary>
public override RequirementLevel RequirementLevel
{
get
{
return RequirementLevel.Must;
}
}
/// <summary>
/// Gets the version.
/// </summary>
public override ODataVersion? Version
{
get
{
return ODataVersion.V4;
}
}
/// <summary>
/// Gets the payload type to which the rule applies.
/// </summary>
public override PayloadType? PayloadType
{
get
{
return RuleEngine.PayloadType.Metadata;
}
}
/// <summary>
/// Gets the flag whether the rule requires metadata document
/// </summary>
public override bool? RequireMetadata
{
get
{
return true;
}
}
/// <summary>
/// Gets the offline context to which the rule applies
/// </summary>
public override bool? IsOfflineContext
{
get
{
return false;
}
}
/// <summary>
/// Gets the payload format to which the rule applies.
/// </summary>
public override PayloadFormat? PayloadFormat
{
get
{
return RuleEngine.PayloadFormat.Xml;
}
}
/// <summary>
/// Verify Metadata.Core.4506
/// </summary>
/// <param name="context">Service context</param>
/// <param name="info">out parameter to return violation information when rule fail</param>
/// <returns>true if rule passes; false otherwise</returns>
public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
bool? passed = null;
info = null;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(context.MetadataDocument);
XmlNodeList references = xmlDoc.SelectNodes("//*[local-name()='Reference']");
HashSet<string> referenceUris = new HashSet<string>();
foreach(XmlNode reference in references)
{
Uri referenceUri = new Uri(reference.Attributes["Uri"].Value, UriKind.RelativeOrAbsolute);
var payload = XElement.Parse(context.MetadataDocument);
string baseUriString = payload.GetAttributeValue("xml:base", ODataNamespaceManager.Instance);
if (!string.IsNullOrEmpty(baseUriString) && Uri.IsWellFormedUriString(reference.Attributes["Uri"].Value, UriKind.Relative))
{
Uri referenceUriRelative = new Uri(reference.Attributes["Uri"].Value, UriKind.Relative);
Uri baseUri = new Uri(baseUriString, UriKind.Absolute);
referenceUri = new Uri(baseUri, referenceUriRelative);
}
if(referenceUris.Add(referenceUri.ToString()))
{
passed = true;
}
else
{
passed = false;
info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
}
}
return passed;
}
}
}
| |
using Discord.Rest;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Model = Discord.API.Message;
namespace Discord.WebSocket
{
/// <summary>
/// Represents a WebSocket-based message sent by a user.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class SocketUserMessage : SocketMessage, IUserMessage
{
private bool _isMentioningEveryone, _isTTS, _isPinned;
private long? _editedTimestampTicks;
private IUserMessage _referencedMessage;
private ImmutableArray<Attachment> _attachments = ImmutableArray.Create<Attachment>();
private ImmutableArray<Embed> _embeds = ImmutableArray.Create<Embed>();
private ImmutableArray<ITag> _tags = ImmutableArray.Create<ITag>();
private ImmutableArray<SocketRole> _roleMentions = ImmutableArray.Create<SocketRole>();
private ImmutableArray<SocketUser> _userMentions = ImmutableArray.Create<SocketUser>();
/// <inheritdoc />
public override bool IsTTS => _isTTS;
/// <inheritdoc />
public override bool IsPinned => _isPinned;
/// <inheritdoc />
public override bool IsSuppressed => Flags.HasValue && Flags.Value.HasFlag(MessageFlags.SuppressEmbeds);
/// <inheritdoc />
public override DateTimeOffset? EditedTimestamp => DateTimeUtils.FromTicks(_editedTimestampTicks);
/// <inheritdoc />
public override bool MentionedEveryone => _isMentioningEveryone;
/// <inheritdoc />
public override IReadOnlyCollection<Attachment> Attachments => _attachments;
/// <inheritdoc />
public override IReadOnlyCollection<Embed> Embeds => _embeds;
/// <inheritdoc />
public override IReadOnlyCollection<ITag> Tags => _tags;
/// <inheritdoc />
public override IReadOnlyCollection<SocketGuildChannel> MentionedChannels => MessageHelper.FilterTagsByValue<SocketGuildChannel>(TagType.ChannelMention, _tags);
/// <inheritdoc />
public override IReadOnlyCollection<SocketRole> MentionedRoles => _roleMentions;
/// <inheritdoc />
public override IReadOnlyCollection<SocketUser> MentionedUsers => _userMentions;
/// <inheritdoc />
public IUserMessage ReferencedMessage => _referencedMessage;
internal SocketUserMessage(DiscordSocketClient discord, ulong id, ISocketMessageChannel channel, SocketUser author, MessageSource source)
: base(discord, id, channel, author, source)
{
}
internal new static SocketUserMessage Create(DiscordSocketClient discord, ClientState state, SocketUser author, ISocketMessageChannel channel, Model model)
{
var entity = new SocketUserMessage(discord, model.Id, channel, author, MessageHelper.GetSource(model));
entity.Update(state, model);
return entity;
}
internal override void Update(ClientState state, Model model)
{
base.Update(state, model);
SocketGuild guild = (Channel as SocketGuildChannel)?.Guild;
if (model.IsTextToSpeech.IsSpecified)
_isTTS = model.IsTextToSpeech.Value;
if (model.Pinned.IsSpecified)
_isPinned = model.Pinned.Value;
if (model.EditedTimestamp.IsSpecified)
_editedTimestampTicks = model.EditedTimestamp.Value?.UtcTicks;
if (model.MentionEveryone.IsSpecified)
_isMentioningEveryone = model.MentionEveryone.Value;
if (model.RoleMentions.IsSpecified)
_roleMentions = model.RoleMentions.Value.Select(x => guild.GetRole(x)).ToImmutableArray();
if (model.Attachments.IsSpecified)
{
var value = model.Attachments.Value;
if (value.Length > 0)
{
var attachments = ImmutableArray.CreateBuilder<Attachment>(value.Length);
for (int i = 0; i < value.Length; i++)
attachments.Add(Attachment.Create(value[i]));
_attachments = attachments.ToImmutable();
}
else
_attachments = ImmutableArray.Create<Attachment>();
}
if (model.Embeds.IsSpecified)
{
var value = model.Embeds.Value;
if (value.Length > 0)
{
var embeds = ImmutableArray.CreateBuilder<Embed>(value.Length);
for (int i = 0; i < value.Length; i++)
embeds.Add(value[i].ToEntity());
_embeds = embeds.ToImmutable();
}
else
_embeds = ImmutableArray.Create<Embed>();
}
if (model.UserMentions.IsSpecified)
{
var value = model.UserMentions.Value;
if (value.Length > 0)
{
var newMentions = ImmutableArray.CreateBuilder<SocketUser>(value.Length);
for (int i = 0; i < value.Length; i++)
{
var val = value[i];
if (val.Object != null)
{
var user = Channel.GetUserAsync(val.Object.Id, CacheMode.CacheOnly).GetAwaiter().GetResult() as SocketUser;
if (user != null)
newMentions.Add(user);
else
newMentions.Add(SocketUnknownUser.Create(Discord, state, val.Object));
}
}
_userMentions = newMentions.ToImmutable();
}
}
if (model.Content.IsSpecified)
{
var text = model.Content.Value;
_tags = MessageHelper.ParseTags(text, Channel, guild, _userMentions);
model.Content = text;
}
if (model.ReferencedMessage.IsSpecified && model.ReferencedMessage.Value != null)
{
var refMsg = model.ReferencedMessage.Value;
ulong? webhookId = refMsg.WebhookId.ToNullable();
SocketUser refMsgAuthor = null;
if (refMsg.Author.IsSpecified)
{
if (guild != null)
{
if (webhookId != null)
refMsgAuthor = SocketWebhookUser.Create(guild, state, refMsg.Author.Value, webhookId.Value);
else
refMsgAuthor = guild.GetUser(refMsg.Author.Value.Id);
}
else
refMsgAuthor = (Channel as SocketChannel).GetUser(refMsg.Author.Value.Id);
if (refMsgAuthor == null)
refMsgAuthor = SocketUnknownUser.Create(Discord, state, refMsg.Author.Value);
}
else
// Message author wasn't specified in the payload, so create a completely anonymous unknown user
refMsgAuthor = new SocketUnknownUser(Discord, id: 0);
_referencedMessage = SocketUserMessage.Create(Discord, state, refMsgAuthor, Channel, refMsg);
}
}
/// <inheritdoc />
/// <exception cref="InvalidOperationException">Only the author of a message may modify the message.</exception>
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task ModifyAsync(Action<MessageProperties> func, RequestOptions options = null)
=> MessageHelper.ModifyAsync(this, Discord, func, options);
/// <inheritdoc />
public Task PinAsync(RequestOptions options = null)
=> MessageHelper.PinAsync(this, Discord, options);
/// <inheritdoc />
public Task UnpinAsync(RequestOptions options = null)
=> MessageHelper.UnpinAsync(this, Discord, options);
/// <inheritdoc />
public Task ModifySuppressionAsync(bool suppressEmbeds, RequestOptions options = null)
=> MessageHelper.SuppressEmbedsAsync(this, Discord, suppressEmbeds, options);
public string Resolve(int startIndex, TagHandling userHandling = TagHandling.Name, TagHandling channelHandling = TagHandling.Name,
TagHandling roleHandling = TagHandling.Name, TagHandling everyoneHandling = TagHandling.Ignore, TagHandling emojiHandling = TagHandling.Name)
=> MentionUtils.Resolve(this, startIndex, userHandling, channelHandling, roleHandling, everyoneHandling, emojiHandling);
/// <inheritdoc />
public string Resolve(TagHandling userHandling = TagHandling.Name, TagHandling channelHandling = TagHandling.Name,
TagHandling roleHandling = TagHandling.Name, TagHandling everyoneHandling = TagHandling.Ignore, TagHandling emojiHandling = TagHandling.Name)
=> MentionUtils.Resolve(this, 0, userHandling, channelHandling, roleHandling, everyoneHandling, emojiHandling);
/// <inheritdoc />
/// <exception cref="InvalidOperationException">This operation may only be called on a <see cref="INewsChannel"/> channel.</exception>
public async Task CrosspostAsync(RequestOptions options = null)
{
if (!(Channel is INewsChannel))
{
throw new InvalidOperationException("Publishing (crossposting) is only valid in news channels.");
}
await MessageHelper.CrosspostAsync(this, Discord, options);
}
private string DebuggerDisplay => $"{Author}: {Content} ({Id}{(Attachments.Count > 0 ? $", {Attachments.Count} Attachments" : "")})";
internal new SocketUserMessage Clone() => MemberwiseClone() as SocketUserMessage;
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Tests.Common.Builders.Extensions;
using Umbraco.Cms.Tests.Common.Builders.Interfaces;
using Constants = Umbraco.Cms.Core.Constants;
namespace Umbraco.Cms.Tests.Common.Builders
{
public class PropertyTypeBuilder : PropertyTypeBuilder<NullPropertyTypeBuilderParent>
{
public PropertyTypeBuilder()
: base(null)
{
}
}
public class NullPropertyTypeBuilderParent : IBuildPropertyTypes
{
}
public class PropertyTypeBuilder<TParent>
: ChildBuilderBase<TParent, PropertyType>,
IWithIdBuilder,
IWithKeyBuilder,
IWithAliasBuilder,
IWithNameBuilder,
IWithCreateDateBuilder,
IWithUpdateDateBuilder,
IWithSortOrderBuilder,
IWithDescriptionBuilder,
IWithSupportsPublishing
where TParent : IBuildPropertyTypes
{
private int? _id;
private Guid? _key;
private string _propertyEditorAlias;
private ValueStorageType? _valueStorageType;
private string _alias;
private string _name;
private DateTime? _createDate;
private DateTime? _updateDate;
private int? _sortOrder;
private string _description;
private int? _dataTypeId;
private Lazy<int> _propertyGroupId;
private bool? _mandatory;
private bool? _labelOnTop;
private string _mandatoryMessage;
private string _validationRegExp;
private string _validationRegExpMessage;
private bool? _supportsPublishing;
private ContentVariation? _variations;
public PropertyTypeBuilder(TParent parentBuilder)
: base(parentBuilder)
{
}
public PropertyTypeBuilder<TParent> WithPropertyEditorAlias(string propertyEditorAlias)
{
_propertyEditorAlias = propertyEditorAlias;
return this;
}
public PropertyTypeBuilder<TParent> WithValueStorageType(ValueStorageType valueStorageType)
{
_valueStorageType = valueStorageType;
return this;
}
public PropertyTypeBuilder<TParent> WithDataTypeId(int dataTypeId)
{
_dataTypeId = dataTypeId;
return this;
}
public PropertyTypeBuilder<TParent> WithPropertyGroupId(int propertyGroupId)
{
_propertyGroupId = new Lazy<int>(() => propertyGroupId);
return this;
}
public PropertyTypeBuilder<TParent> WithMandatory(bool mandatory, string mandatoryMessage = "")
{
_mandatory = mandatory;
_mandatoryMessage = mandatoryMessage;
return this;
}
public PropertyTypeBuilder<TParent> WithLabelOnTop(bool labelOnTop)
{
_labelOnTop = labelOnTop;
return this;
}
public PropertyTypeBuilder<TParent> WithValidationRegExp(string validationRegExp, string validationRegExpMessage = "")
{
_validationRegExp = validationRegExp;
_validationRegExpMessage = validationRegExpMessage;
return this;
}
public PropertyTypeBuilder<TParent> WithVariations(ContentVariation variation)
{
_variations = variation;
return this;
}
public override PropertyType Build()
{
var id = _id ?? 0;
Guid key = _key ?? Guid.NewGuid();
var propertyEditorAlias = _propertyEditorAlias ?? Constants.PropertyEditors.Aliases.TextBox;
ValueStorageType valueStorageType = _valueStorageType ?? ValueStorageType.Nvarchar;
var name = _name ?? Guid.NewGuid().ToString();
var alias = _alias ?? name.ToCamelCase();
DateTime createDate = _createDate ?? DateTime.Now;
DateTime updateDate = _updateDate ?? DateTime.Now;
var sortOrder = _sortOrder ?? 0;
var dataTypeId = _dataTypeId ?? -88;
var description = _description ?? string.Empty;
Lazy<int> propertyGroupId = _propertyGroupId ?? null;
var mandatory = _mandatory ?? false;
var mandatoryMessage = _mandatoryMessage ?? string.Empty;
var validationRegExp = _validationRegExp ?? string.Empty;
var validationRegExpMessage = _validationRegExpMessage ?? string.Empty;
var supportsPublishing = _supportsPublishing ?? false;
var labelOnTop = _labelOnTop ?? false;
ContentVariation variations = _variations ?? ContentVariation.Nothing;
var shortStringHelper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig());
var propertyType = new PropertyType(shortStringHelper, propertyEditorAlias, valueStorageType)
{
Id = id,
Key = key,
Alias = alias,
Name = name,
SortOrder = sortOrder,
DataTypeId = dataTypeId,
Description = description,
CreateDate = createDate,
UpdateDate = updateDate,
PropertyGroupId = propertyGroupId,
Mandatory = mandatory,
MandatoryMessage = mandatoryMessage,
ValidationRegExp = validationRegExp,
ValidationRegExpMessage = validationRegExpMessage,
SupportsPublishing = supportsPublishing,
Variations = variations,
LabelOnTop = labelOnTop,
};
return propertyType;
}
int? IWithIdBuilder.Id
{
get => _id;
set => _id = value;
}
Guid? IWithKeyBuilder.Key
{
get => _key;
set => _key = value;
}
string IWithAliasBuilder.Alias
{
get => _alias;
set => _alias = value;
}
string IWithNameBuilder.Name
{
get => _name;
set => _name = value;
}
DateTime? IWithCreateDateBuilder.CreateDate
{
get => _createDate;
set => _createDate = value;
}
DateTime? IWithUpdateDateBuilder.UpdateDate
{
get => _updateDate;
set => _updateDate = value;
}
int? IWithSortOrderBuilder.SortOrder
{
get => _sortOrder;
set => _sortOrder = value;
}
string IWithDescriptionBuilder.Description
{
get => _description;
set => _description = value;
}
bool? IWithSupportsPublishing.SupportsPublishing
{
get => _supportsPublishing;
set => _supportsPublishing = value;
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using NLog.Config;
namespace NLog.UnitTests.LayoutRenderers
{
using System;
using System.Globalization;
using Xunit;
public class MessageTests : NLogTestBase
{
[Fact]
public void MessageWithoutPaddingTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "a");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", "a1");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01/01/2005 00:00:00");
}
[Fact]
public void MessageRightPaddingTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=3}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", " a");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", " a1");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01/01/2005 00:00:00");
}
[Fact]
public void MessageFixedLengthRightPaddingLeftAlignmentTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=3:fixedlength=true}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", " a");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", " a1");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01");
}
[Fact]
public void MessageFixedLengthRightPaddingRightAlignmentTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=3:fixedlength=true:alignmentOnTruncation=right}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", " a");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", " a1");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", ":00");
}
[Fact]
public void MessageLeftPaddingTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=-3:padcharacter=x}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "axx");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", "a1x");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01/01/2005 00:00:00");
}
[Fact]
public void MessageFixedLengthLeftPaddingLeftAlignmentTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=-3:padcharacter=x:fixedlength=true}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "axx");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", "a1x");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", "a01");
}
[Fact]
public void MessageFixedLengthLeftPaddingRightAlignmentTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:padding=-3:padcharacter=x:fixedlength=true:alignmentOnTruncation=right}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "axx");
logger.Debug("a{0}", 1);
AssertDebugLastMessage("debug", "a1x");
logger.Debug("a{0}{1}", 1, "2");
AssertDebugLastMessage("debug", "a12");
logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1));
AssertDebugLastMessage("debug", ":00");
}
[Fact]
public void MessageWithExceptionAndCustomSeparatorTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message:withException=true:exceptionSeparator=,}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "a");
var ex = new InvalidOperationException("Exception message.");
logger.Debug(ex, "Foo");
AssertDebugLastMessage("debug", "Foo," + ex.ToString());
logger.Debug(ex);
AssertDebugLastMessage("debug", ex.ToString());
}
[Fact]
public void SingleParameterException_OutputsSingleStackTrace()
{
// Arrange
var logFactory = new LogFactory();
var logConfig = new LoggingConfiguration(logFactory);
var logTarget = new NLog.Targets.DebugTarget("debug") { Layout = "${message}|${exception}" };
logConfig.AddRuleForAllLevels(logTarget);
logFactory.Configuration = logConfig;
var logger = logFactory.GetLogger("SingleParameterException");
// Act
try
{
logger.Info("Hello");
Exception argumentException = new ArgumentException("Holy Moly");
#if !NET35
argumentException = new AggregateException(argumentException);
#endif
throw argumentException;
}
catch (Exception ex)
{
logger.Fatal(ex);
}
// Assert
Assert.StartsWith("System.ArgumentException: Holy Moly|System.ArgumentException", logTarget.LastMessage);
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using EasyNetQ.Events;
using EasyNetQ.Internals;
using EasyNetQ.Producer;
using RabbitMQ.Client;
namespace EasyNetQ.Persistent;
using UnconfirmedRequests = ConcurrentDictionary<ulong, TaskCompletionSource<object>>;
/// <inheritdoc />
public class PublishConfirmationListener : IPublishConfirmationListener
{
private readonly IDisposable[] subscriptions;
private readonly ConcurrentDictionary<int, UnconfirmedRequests> unconfirmedChannelRequests;
/// <summary>
/// Creates publish confirmations listener
/// </summary>
/// <param name="eventBus">The event bus</param>
public PublishConfirmationListener(IEventBus eventBus)
{
unconfirmedChannelRequests = new ConcurrentDictionary<int, UnconfirmedRequests>();
subscriptions = new[]
{
eventBus.Subscribe<MessageConfirmationEvent>(OnMessageConfirmation),
eventBus.Subscribe<ChannelRecoveredEvent>(OnChannelRecovered),
eventBus.Subscribe<ChannelShutdownEvent>(OnChannelShutdown),
eventBus.Subscribe<ReturnedMessageEvent>(OnReturnedMessage)
};
}
/// <inheritdoc />
public IPublishPendingConfirmation CreatePendingConfirmation(IModel model)
{
var sequenceNumber = model.NextPublishSeqNo;
if (sequenceNumber == 0UL)
throw new InvalidOperationException("Confirms not selected");
var requests = unconfirmedChannelRequests.GetOrAdd(model.ChannelNumber, _ => new UnconfirmedRequests());
var confirmationTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
if (!requests.TryAdd(sequenceNumber, confirmationTcs))
throw new InvalidOperationException($"Confirmation {sequenceNumber} already exists");
return new PublishPendingConfirmation(
sequenceNumber, confirmationTcs, () => requests.Remove(sequenceNumber)
);
}
/// <inheritdoc />
public void Dispose()
{
foreach (var subscription in subscriptions)
subscription.Dispose();
InterruptAllUnconfirmedRequests(true);
}
private void OnMessageConfirmation(in MessageConfirmationEvent @event)
{
if (!unconfirmedChannelRequests.TryGetValue(@event.Channel.ChannelNumber, out var requests))
return;
var deliveryTag = @event.DeliveryTag;
var multiple = @event.Multiple;
var type = @event.IsNack ? ConfirmationType.Nack : ConfirmationType.Ack;
if (multiple)
{
foreach (var sequenceNumber in requests.Select(x => x.Key))
if (sequenceNumber <= deliveryTag && requests.TryRemove(sequenceNumber, out var confirmationTcs))
Confirm(confirmationTcs, sequenceNumber, type);
}
else if (requests.TryRemove(deliveryTag, out var confirmation))
Confirm(confirmation, deliveryTag, type);
}
private void OnChannelRecovered(in ChannelRecoveredEvent @event)
{
if (@event.Channel.NextPublishSeqNo == 0)
return;
InterruptUnconfirmedRequests(@event.Channel.ChannelNumber);
}
private void OnChannelShutdown(in ChannelShutdownEvent @event)
{
if (@event.Channel.NextPublishSeqNo == 0)
return;
InterruptUnconfirmedRequests(@event.Channel.ChannelNumber);
}
private void OnReturnedMessage(in ReturnedMessageEvent @event)
{
if (@event.Channel.NextPublishSeqNo == 0)
return;
if (!@event.Properties.TryGetConfirmationId(out var confirmationId))
return;
if (!unconfirmedChannelRequests.TryGetValue(@event.Channel.ChannelNumber, out var requests))
return;
if (!requests.TryRemove(confirmationId, out var confirmationTcs))
return;
Confirm(confirmationTcs, confirmationId, ConfirmationType.Return);
}
private void InterruptUnconfirmedRequests(int channelNumber, bool cancellationInsteadOfInterruption = false)
{
if (!unconfirmedChannelRequests.TryRemove(channelNumber, out var requests))
return;
do
{
foreach (var sequenceNumber in requests.Select(x => x.Key))
{
if (!requests.TryRemove(sequenceNumber, out var confirmationTcs))
continue;
if (cancellationInsteadOfInterruption)
confirmationTcs.TrySetCanceled();
else
confirmationTcs.TrySetException(new PublishInterruptedException());
}
} while (!requests.IsEmpty);
}
private void InterruptAllUnconfirmedRequests(bool cancellationInsteadOfInterruption = false)
{
do
{
foreach (var channelNumber in unconfirmedChannelRequests.Select(x => x.Key))
InterruptUnconfirmedRequests(channelNumber, cancellationInsteadOfInterruption);
} while (!unconfirmedChannelRequests.IsEmpty);
}
private static void Confirm(
TaskCompletionSource<object> confirmationTcs, ulong sequenceNumber, ConfirmationType type
)
{
switch (type)
{
case ConfirmationType.Return:
confirmationTcs.TrySetException(
new PublishReturnedException("Broker has signalled that message is returned")
);
break;
case ConfirmationType.Nack:
confirmationTcs.TrySetException(
new PublishNackedException($"Broker has signalled that publish {sequenceNumber} is nacked")
);
break;
case ConfirmationType.Ack:
confirmationTcs.TrySetResult(null);
break;
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
}
private enum ConfirmationType
{
Ack,
Nack,
Return
}
private sealed class PublishPendingConfirmation : IPublishPendingConfirmation
{
private readonly ulong id;
private readonly TaskCompletionSource<object> confirmationTcs;
private readonly Action cleanup;
public PublishPendingConfirmation(ulong id, TaskCompletionSource<object> confirmationTcs, Action cleanup)
{
this.id = id;
this.confirmationTcs = confirmationTcs;
this.cleanup = cleanup;
}
public ulong Id => id;
public async Task WaitAsync(CancellationToken cancellationToken)
{
try
{
confirmationTcs.AttachCancellation(cancellationToken);
await confirmationTcs.Task.ConfigureAwait(false);
}
finally
{
cleanup();
}
}
public void Cancel()
{
try
{
confirmationTcs.TrySetCanceled();
}
finally
{
cleanup();
}
}
}
}
| |
using System;
using System.IO;
using FF9;
using Memoria;
using Memoria.Assets;
using Memoria.Data;
using UnityEngine;
public class btl2d
{
static btl2d()
{
// Note: this type is marked as 'beforefieldinit'.
SByte[][] array = new SByte[19][];
array[0] = new SByte[]
{
-1,
-2,
-9,
-10,
-6,
0
};
array[1] = new SByte[]
{
-1,
-2,
-9,
-10,
-6,
0
};
array[2] = new SByte[]
{
0,
-1,
-7,
-8,
-3,
0
};
array[3] = new SByte[]
{
-1,
-2,
-9,
-8,
-5,
0
};
array[4] = new SByte[]
{
-1,
-2,
-9,
-8,
-5,
0
};
array[5] = new SByte[]
{
-1,
-2,
-9,
-8,
-5,
0
};
array[6] = new SByte[]
{
-1,
-2,
-9,
-8,
-5,
0
};
array[7] = new SByte[]
{
0,
-3,
-8,
-9,
-5,
0
};
array[8] = new SByte[]
{
0,
-3,
-8,
-9,
-5,
0
};
array[9] = new SByte[]
{
0,
-1,
-10,
-9,
-5,
0
};
array[10] = new SByte[]
{
-1,
0,
-7,
-7,
-5,
0
};
array[11] = new SByte[]
{
-1,
0,
-7,
-7,
-5,
0
};
array[12] = new SByte[]
{
0,
-2,
-8,
-8,
-4,
0
};
Int32 num = 13;
SByte[] array2 = new SByte[6];
array2[2] = -8;
array2[3] = -11;
array2[4] = -6;
array[num] = array2;
array[14] = new SByte[]
{
-2,
-2,
-9,
-9,
-6,
0
};
array[15] = new SByte[]
{
-1,
-1,
-9,
-9,
-5,
0
};
array[16] = new SByte[]
{
-1,
-1,
-8,
-8,
-5,
0
};
array[17] = new SByte[]
{
-1,
-1,
-8,
-8,
-5,
0
};
array[18] = new SByte[]
{
-1,
-2,
-7,
-8,
-5,
0
};
btl2d.wZofsPC = array;
}
public static void Btl2dInit()
{
FF9StateBattleSystem ff9Battle = FF9StateSystem.Battle.FF9Battle;
ff9Battle.btl2d_work_set.NewID = 0;
ff9Battle.btl2d_work_set.Timer = 0;
ff9Battle.btl2d_work_set.OldDisappear = Byte.MaxValue;
BTL2D_ENT[] entry = ff9Battle.btl2d_work_set.Entry;
for (Int16 num = 0; num < 16; num++)
entry[num].BtlPtr = null;
}
public static void InitBattleSPSBin()
{
String[] arg = new String[]
{
"st_doku.dat",
"st_mdoku.dat",
"st_moku.dat",
"st_moum.dat",
"st_nemu.dat",
"st_heat.dat",
"st_friz.dat",
"st_basak.dat",
"st_meiwa.dat",
"st_slow.dat",
"st_heis.dat",
"st_rif.dat"
};
for (Int32 i = 0; i < btl2d.wStatIconTbl.Length; i++)
{
Byte[] bytes = AssetManager.LoadBytes("BattleMap/BattleSPS/" + arg + ".sps", out _);
if (bytes == null)
return;
}
}
public static void Btl2dReq(BTL_DATA pBtl)
{
Btl2dReq(pBtl, ref pBtl.fig_info, ref pBtl.fig, ref pBtl.m_fig);
}
public static void Btl2dReq(BTL_DATA pBtl, ref UInt16 fig_info, ref Int32 fig, ref Int32 m_fig)
{
Byte delay = 0;
if (pBtl.bi.disappear == 0)
{
if ((fig_info & Param.FIG_INFO_TROUBLE) != 0)
btl_para.SetTroubleDamage(new BattleUnit(pBtl), fig >> 1);
if ((fig_info & Param.FIG_INFO_GUARD) != 0)
{
btl2d.Btl2dReqSymbol(pBtl, 2, 0, 0);
}
else if ((fig_info & (Param.FIG_INFO_MISS | Param.FIG_INFO_DEATH)) != 0)
{
if ((fig_info & Param.FIG_INFO_MISS) != 0)
{
btl2d.Btl2dReqSymbol(pBtl, 0, 0, 0);
delay = 2;
}
if ((fig_info & Param.FIG_INFO_DEATH) != 0)
btl2d.Btl2dReqSymbol(pBtl, 1, 0, delay);
}
else
{
if ((fig_info & Param.FIG_INFO_DISP_HP) != 0)
{
if ((fig_info & Param.FIG_INFO_HP_CRITICAL) != 0)
{
btl2d.Btl2dReqSymbol(pBtl, 3, 128, 0);
delay = 2;
}
if ((fig_info & Param.FIG_INFO_HP_RECOVER) != 0)
btl2d.Btl2dReqHP(pBtl, fig, 192, delay);
else
btl2d.Btl2dReqHP(pBtl, fig, 0, delay);
delay += 4;
}
if ((fig_info & Param.FIG_INFO_DISP_MP) != 0)
{
if ((fig_info & Param.FIG_INFO_MP_RECOVER) != 0)
btl2d.Btl2dReqMP(pBtl, m_fig, 192, delay);
else
btl2d.Btl2dReqMP(pBtl, m_fig, 0, delay);
}
}
}
fig_info = 0;
fig = 0;
m_fig = 0;
}
public static void Btl2dStatReq(BTL_DATA pBtl)
{
Byte b = 0;
UInt16 fig_stat_info = pBtl.fig_stat_info;
if (pBtl.bi.disappear == 0)
{
if ((fig_stat_info & Param.FIG_STAT_INFO_REGENE_HP) != 0)
{
BTL2D_ENT btl2D_ENT = btl2d.Btl2dReqHP(pBtl, pBtl.fig_regene_hp, (UInt16)(((fig_stat_info & Param.FIG_STAT_INFO_REGENE_DMG) == 0) ? 192 : 0), 0);
btl2D_ENT.NoClip = 1;
btl2D_ENT.Yofs = -12;
b = 4;
}
if ((fig_stat_info & Param.FIG_STAT_INFO_POISON_HP) != 0)
{
BTL2D_ENT btl2D_ENT = btl2d.Btl2dReqHP(pBtl, pBtl.fig_poison_hp, 0, b);
btl2D_ENT.NoClip = 1;
btl2D_ENT.Yofs = -12;
b += 4;
}
if ((fig_stat_info & Param.FIG_STAT_INFO_POISON_MP) != 0)
{
BTL2D_ENT btl2D_ENT = btl2d.Btl2dReqMP(pBtl, pBtl.fig_poison_mp, 0, b);
btl2D_ENT.NoClip = 1;
btl2D_ENT.Yofs = -12;
}
}
pBtl.fig_stat_info = 0;
pBtl.fig_regene_hp = 0;
pBtl.fig_poison_hp = 0;
pBtl.fig_poison_mp = 0;
}
public static BTL2D_ENT GetFreeEntry(BTL_DATA pBtl)
{
FF9StateBattleSystem ff9Battle = FF9StateSystem.Battle.FF9Battle;
BTL2D_WORK btl2d_work_set = ff9Battle.btl2d_work_set;
Int16 num = (Int16)(btl2d_work_set.NewID - 1);
if (num < 0)
num = 15;
btl2d_work_set.NewID = num;
BTL2D_ENT btl2D_ENT = btl2d_work_set.Entry[num];
btl2D_ENT.BtlPtr = pBtl;
btl2D_ENT.Cnt = 0;
btl2D_ENT.Delay = 0;
btl2D_ENT.trans = pBtl.gameObject.transform.GetChildByName("bone" + pBtl.tar_bone.ToString("D3"));
Vector3 position = btl2D_ENT.trans.position;
btl2D_ENT.Yofs += 4;
btl2D_ENT.trans.position = position;
return btl2D_ENT;
}
public static BTL2D_ENT Btl2dReqHP(BTL_DATA pBtl, Int32 pNum, UInt16 pCol, Byte pDelay)
{
BTL2D_ENT freeEntry = btl2d.GetFreeEntry(pBtl);
freeEntry.Type = 0;
freeEntry.Delay = pDelay;
freeEntry.Work.Num.Color = pCol;
freeEntry.Work.Num.Value = (UInt32)pNum;
return freeEntry;
}
public static BTL2D_ENT Btl2dReqMP(BTL_DATA pBtl, Int32 pNum, UInt16 pCol, Byte pDelay)
{
BTL2D_ENT freeEntry = btl2d.GetFreeEntry(pBtl);
freeEntry.Type = 1;
freeEntry.Delay = pDelay;
freeEntry.Work.Num.Color = pCol;
freeEntry.Work.Num.Value = (UInt32)pNum;
return freeEntry;
}
public static BTL2D_ENT Btl2dReqSymbol(BTL_DATA pBtl, Byte pNum, UInt16 pCol, Byte pDelay)
{
BTL2D_ENT freeEntry = btl2d.GetFreeEntry(pBtl);
freeEntry.Type = 2;
freeEntry.Delay = pDelay;
freeEntry.Work.Num.Color = pCol;
freeEntry.Work.Num.Value = pNum;
return freeEntry;
}
public static void Btl2dMain()
{
FF9StateBattleSystem ff9Battle = FF9StateSystem.Battle.FF9Battle;
BTL2D_WORK btl2d_work_set = ff9Battle.btl2d_work_set;
Int16 num = btl2d_work_set.NewID;
for (Int16 num2 = 0; num2 < 16; num2++)
{
BTL2D_ENT btl2D_ENT = btl2d_work_set.Entry[num];
if (btl2D_ENT.BtlPtr != null)
{
if (btl2D_ENT.Type > 2)
{
btl2D_ENT.BtlPtr = null;
}
else if (btl2D_ENT.Delay != 0)
{
btl2D_ENT.Delay--;
}
else
{
String text = String.Empty;
HUDMessage.MessageStyle style = HUDMessage.MessageStyle.DAMAGE;
if (btl2D_ENT.Type == 0)
{
if (btl2D_ENT.Work.Num.Color == 0)
style = HUDMessage.MessageStyle.DAMAGE;
else
style = HUDMessage.MessageStyle.RESTORE_HP;
text = btl2D_ENT.Work.Num.Value.ToString();
}
else if (btl2D_ENT.Type == 1)
{
if (btl2D_ENT.Work.Num.Color == 0)
style = HUDMessage.MessageStyle.DAMAGE;
else
style = HUDMessage.MessageStyle.RESTORE_MP;
text = btl2D_ENT.Work.Num.Value.ToString() + " " + Localization.Get("MPCaption");
}
else if (btl2D_ENT.Type == 2)
{
if (btl2D_ENT.Work.Num.Value == 0u)
{
text = Localization.Get("Miss");
style = HUDMessage.MessageStyle.MISS;
}
else if (btl2D_ENT.Work.Num.Value == 1u)
{
text = Localization.Get("Death");
style = HUDMessage.MessageStyle.DEATH;
}
else if (btl2D_ENT.Work.Num.Value == 2u)
{
text = Localization.Get("Guard");
style = HUDMessage.MessageStyle.GUARD;
}
else if (btl2D_ENT.Work.Num.Value == 3u)
{
text = NGUIText.FF9YellowColor + Localization.Get("Critical") + "[-] \n " + text;
style = HUDMessage.MessageStyle.CRITICAL;
}
}
Singleton<HUDMessage>.Instance.Show(btl2D_ENT.trans, text, style, new Vector3(0f, btl2D_ENT.Yofs, 0f), 0);
UIManager.Battle.DisplayParty();
btl2D_ENT.BtlPtr = null;
}
}
num++;
if (num >= 16)
num = 0;
}
btl2d.Btl2dStatCount();
if (SFX.GetEffectJTexUsed() == 0)
btl2d.Btl2dStatIcon();
btl2d_work_set.Timer++;
Byte b = Byte.MaxValue;
for (BTL_DATA next = ff9Battle.btl_list.next; next != null; next = next.next)
if (next.bi.disappear == 0)
b &= (Byte)(~(Byte)next.btl_id);
btl2d_work_set.OldDisappear = b;
}
private static void Btl2dStatIcon()
{
FF9StateBattleSystem ff9Battle = FF9StateSystem.Battle.FF9Battle;
BTL2D_WORK btl2d_work_set = ff9Battle.btl2d_work_set;
Vector3 rot;
rot.x = 0f;
rot.z = 0f;
for (BTL_DATA next = ff9Battle.btl_list.next; next != null; next = next.next)
{
if (next.bi.disappear == 0)
{
if ((next.flags & geo.GEO_FLAGS_CLIP) == 0)
{
if ((btl2d_work_set.OldDisappear & next.btl_id) == 0)
{
BattleStatus num = next.stat.cur | next.stat.permanent;
if ((num & BattleStatus.Death) == 0u)
{
if ((num & STATUS_2D_ICON) != 0u)
{
if (next.bi.player == 0 || !btl_mot.checkMotion(next, BattlePlayerCharacter.PlayerMotionIndex.MP_ESCAPE))
{
Int32 num2 = ff9.rsin(fixedPointAngle: (Int32)(next.rot.eulerAngles.y / 360f * 4096f));
Int32 num3 = ff9.rcos(fixedPointAngle: (Int32)(next.rot.eulerAngles.y / 360f * 4096f));
Int16 num4;
Byte[] array;
SByte[] array2;
SByte[] array3;
if (next.bi.player != 0)
{
if (next.is_monster_transform)
{
array = next.monster_transform.icon_bone;
array2 = next.monster_transform.icon_y;
array3 = next.monster_transform.icon_z;
}
else
{
num4 = FF9StateSystem.Common.FF9.player[next.bi.slot_no].info.serial_no;
array = btl2d.wBonePC[num4];
array2 = btl2d.wYofsPC[num4];
array3 = btl2d.wZofsPC[num4];
}
}
else
{
ENEMY_TYPE et = ff9Battle.enemy[next.bi.slot_no].et;
array = et.icon_bone;
array2 = et.icon_y;
array3 = et.icon_z;
}
Int32 num5 = 0;
num4 = 12;
for (;;)
{
Int16 num6 = num4;
num4 = (Int16)(num6 - 1);
if (num6 == 0)
{
break;
}
btl2d.STAT_ICON_TBL stat_ICON_TBL = btl2d.wStatIconTbl[num5];
if ((num & stat_ICON_TBL.Mask) != 0u)
{
if ((num & stat_ICON_TBL.Mask2) == 0u)
{
Int16 num7 = (Int16)(array2[stat_ICON_TBL.Pos] << 4);
Int16 num8 = (Int16)(array3[stat_ICON_TBL.Pos] << 4);
if ((next.flags & geo.GEO_FLAGS_SCALE) != 0)
{
num7 = (Int16)((Int32)(num7 * next.gameObject.transform.localScale.y));
num8 = (Int16)((Int32)(num8 * next.gameObject.transform.localScale.z));
}
Vector3 position = next.gameObject.transform.GetChildByName("bone" + array[stat_ICON_TBL.Pos].ToString("D3")).position;
Vector3 pos;
pos.x = position.x + (num8 * num2 >> 12);
pos.y = position.y - num7;
pos.z = position.z + (num8 * num3 >> 12);
if (stat_ICON_TBL.Type != 0)
{
rot.y = 0f;
HonoluluBattleMain.battleSPS.UpdateBtlStatus(next, stat_ICON_TBL.Mask, pos, rot, btl2d_work_set.Timer);
}
else
{
Int32 ang = stat_ICON_TBL.Ang;
if (ang != 0)
{
Int32 num9 = (Int32)(next.rot.eulerAngles.y / 360f * 4095f);
num9 = (num9 + 3072 & 4095);
rot.y = num9 / 4095f * 360f;
}
else
{
rot.y = 0f;
}
HonoluluBattleMain.battleSPS.UpdateBtlStatus(next, stat_ICON_TBL.Mask, pos, rot, btl2d_work_set.Timer);
}
}
}
num5++;
}
}
}
}
}
}
}
}
}
public static Int16 S_GetShpFrame(BinaryReader shp)
{
shp.BaseStream.Seek(0L, SeekOrigin.Begin);
return (Int16)(shp.ReadInt16() & Int16.MaxValue);
}
public static UInt16 acUShort(BinaryReader p, Int32 index = 0)
{
p.BaseStream.Seek(index, SeekOrigin.Begin);
return p.ReadUInt16();
}
public static Byte acChar(BinaryReader p, Int32 index = 0)
{
p.BaseStream.Seek(index, SeekOrigin.Begin);
return p.ReadByte();
}
public static UInt64 acULong(BinaryReader p, Int32 index = 0)
{
p.BaseStream.Seek(index, SeekOrigin.Begin);
return p.ReadUInt64();
}
public static Int32 SAbrID(Int32 abr)
{
return (abr & 3) << 5;
}
public static Int32 getSprtcode(Int32 abr)
{
return 100 | ((abr != 255) ? 2 : 0);
}
public static void S_ShpNScPut(BinaryReader shp, Vector3 pos, Int32 frame, Int32 abr, Int32 fade)
{
}
public static void S_SpsNScPut(BinaryReader sps, Vector3 pos, Vector3 ang, Int32 sc, Int32 frame, Int32 abr, Int32 fade, Int32 pad)
{
}
private static void Btl2dStatCount()
{
btl2d.STAT_CNT_TBL[] array = new btl2d.STAT_CNT_TBL[]
{
new btl2d.STAT_CNT_TBL(BattleStatus.Doom, 11, 0),
new btl2d.STAT_CNT_TBL(BattleStatus.GradualPetrify, 15, 1)
};
FF9StateBattleSystem ff9Battle = FF9StateSystem.Battle.FF9Battle;
BattleStatus status = BattleStatus.Doom | BattleStatus.GradualPetrify;
Int16 num2 = 2;
for (BTL_DATA next = ff9Battle.btl_list.next; next != null; next = next.next)
{
if (next.bi.disappear == 0)
{
if ((next.flags & geo.GEO_FLAGS_CLIP) == 0)
{
if ((ff9Battle.btl2d_work_set.OldDisappear & next.btl_id) == 0)
{
BattleStatus cur = next.stat.cur;
if ((cur & BattleStatus.Death) == 0u)
{
if ((cur & status) != 0u)
{
Int16 num3;
Int16 num4;
Int16 num5;
if (next.bi.player != 0)
{
num3 = FF9StateSystem.Common.FF9.player[next.bi.slot_no].info.serial_no;
num4 = btl2d.wBonePC[num3][5];
num5 = btl2d.wYofsPC[num3][5];
}
else
{
ENEMY_TYPE et = ff9Battle.enemy[next.bi.slot_no].et;
num4 = et.icon_bone[5];
num5 = et.icon_y[5];
}
if ((next.flags & geo.GEO_FLAGS_SCALE) != 0)
{
num5 = (Int16)((Int32)(num5 * next.gameObject.transform.localScale.y));
}
Transform childByName = next.gameObject.transform.GetChildByName("bone" + num4.ToString("D3"));
Int32 num6 = -(num5 << 4);
Int32 num7 = 0;
num3 = num2;
for (;;)
{
Int16 num8 = num3;
num3 = (Int16)(num8 - 1);
if (num8 == 0)
{
break;
}
btl2d.STAT_CNT_TBL stat_CNT_TBL = array[num7];
if ((cur & stat_CNT_TBL.Mask) != 0u)
{
Int16 cdown_max;
if ((cdown_max = next.stat.cnt.cdown_max) < 1)
{
break;
}
Int16 num9;
if ((num9 = next.stat.cnt.conti[stat_CNT_TBL.Idx]) < 0)
{
break;
}
Int16 num10 = next.cur.at_coef;
num4 = (Int16)(num9 * 10 / cdown_max);
UInt16 num11;
if (num9 <= 0)
{
num11 = 2;
}
else
{
num5 = (Int16)((num9 - num10) * 10 / cdown_max);
num11 = (UInt16)((num4 == num5) ? 0 : 2);
}
Int32 num12;
if (stat_CNT_TBL.Col != 0)
{
Byte b = (Byte)((num4 << 4) + 32);
num12 = (b << 16 | b << 8 | b);
}
else
{
num12 = 16777216;
}
num12 |= num11 << 24;
num4 = (Int16)(num4 + 1);
if (num4 > 10)
{
num4 = 10;
}
if (num7 == 0)
{
if (next.deathMessage == null)
{
next.deathMessage = Singleton<HUDMessage>.Instance.Show(childByName, "10", HUDMessage.MessageStyle.DEATH_SENTENCE, new Vector3(0f, num6), 0);
UIManager.Battle.DisplayParty();
}
else
{
next.deathMessage.Label = num4.ToString();
}
}
else if (num7 == 1)
{
if (next.petrifyMessage == null)
{
next.petrifyMessage = Singleton<HUDMessage>.Instance.Show(childByName, "10", HUDMessage.MessageStyle.PETRIFY, new Vector3(0f, num6), 0);
UIManager.Battle.DisplayParty();
}
else
{
String str = "[" + (num12 & 16777215).ToString("X6") + "]";
next.petrifyMessage.Label = str + num4.ToString();
}
}
}
num7++;
}
}
}
}
}
}
}
}
public const Byte BTL2D_NUM = 16;
public const Byte BTL2D_TYPE_HP = 0;
public const Byte BTL2D_TYPE_MP = 1;
public const Byte BTL2D_TYPE_SYM = 2;
public const Byte BTL2D_TYPE_MAX = 2;
public const Byte DMG_COL_WHITE = 0;
public const Byte DMG_COL_RED = 64;
public const Byte DMG_COL_YELLOW = 128;
public const Byte DMG_COL_GREEN = 192;
public const BattleStatus STATUS_2D_ICON = BattleStatus.Venom | BattleStatus.Silence | BattleStatus.Blind | BattleStatus.Trouble | BattleStatus.Berserk | BattleStatus.Poison | BattleStatus.Sleep | BattleStatus.Haste | BattleStatus.Slow | BattleStatus.Heat | BattleStatus.Freeze | BattleStatus.Reflect;
public const UInt32 STATUS_2D_ICON_MASK = 588974138u;
public const Byte ABR_OFF = 255;
public const Byte ABR_50ADD = 0;
public const Byte ABR_ADD = 1;
public const Byte ABR_SUB = 2;
public const Byte ABR_25ADD = 3;
public const Int16 STAT_ICON_NUM = 12;
public const Int32 SOTSIZE = 4096;
public const Byte Sprtcode = 100;
public static btl2d.STAT_ICON_TBL[] wStatIconTbl = new btl2d.STAT_ICON_TBL[]
{
new btl2d.STAT_ICON_TBL(BattleStatus.Poison, 0u, null, 0, 1, 0, 0),
new btl2d.STAT_ICON_TBL(BattleStatus.Venom, 0u, null, 0, 1, 0, 0),
new btl2d.STAT_ICON_TBL(BattleStatus.Slow, 0u, null, 0, Byte.MaxValue, 1, 0),
new btl2d.STAT_ICON_TBL(BattleStatus.Haste, 0u, null, 0, Byte.MaxValue, 1, 0),
new btl2d.STAT_ICON_TBL(BattleStatus.Sleep, 0u, null, 0, Byte.MaxValue, 0, 1),
new btl2d.STAT_ICON_TBL(BattleStatus.Heat, 0u, null, 1, 1, 0, 0),
new btl2d.STAT_ICON_TBL(BattleStatus.Freeze, 0u, null, 1, 1, 0, 0),
new btl2d.STAT_ICON_TBL(BattleStatus.Reflect, BattleStatus.Petrify, null, 1, 1, 0, 0),
new btl2d.STAT_ICON_TBL(BattleStatus.Silence, 0u, null, 2, Byte.MaxValue, 1, 1),
new btl2d.STAT_ICON_TBL(BattleStatus.Blind, 0u, null, 3, 2, 0, 0),
new btl2d.STAT_ICON_TBL(BattleStatus.Trouble, 0u, null, 4, Byte.MaxValue, 1, 0),
new btl2d.STAT_ICON_TBL(BattleStatus.Berserk, 0u, null, 4, 1, 0, 0)
};
public static Byte[][] wBonePC = new Byte[][]
{
new Byte[]
{
8,
8,
8,
8,
8,
1
},
new Byte[]
{
8,
8,
8,
8,
8,
1
},
new Byte[]
{
7,
7,
7,
7,
7,
1
},
new Byte[]
{
19,
19,
19,
19,
19,
1
},
new Byte[]
{
19,
19,
19,
19,
19,
1
},
new Byte[]
{
19,
19,
19,
19,
19,
1
},
new Byte[]
{
19,
19,
19,
19,
19,
1
},
new Byte[]
{
20,
20,
20,
20,
20,
1
},
new Byte[]
{
20,
20,
20,
20,
20,
1
},
new Byte[]
{
6,
6,
6,
6,
6,
1
},
new Byte[]
{
19,
19,
19,
19,
19,
1
},
new Byte[]
{
19,
19,
19,
19,
19,
1
},
new Byte[]
{
8,
8,
8,
8,
8,
1
},
new Byte[]
{
18,
18,
18,
18,
18,
1
},
new Byte[]
{
12,
12,
12,
12,
12,
1
},
new Byte[]
{
8,
8,
8,
8,
8,
1
},
new Byte[]
{
3,
3,
3,
3,
3,
1
},
new Byte[]
{
3,
3,
3,
3,
3,
1
},
new Byte[]
{
18,
18,
18,
18,
18,
1
}
};
private static SByte[][] wYofsPC = new SByte[][]
{
new SByte[]
{
-10,
0,
-7,
-1,
-7,
-18
},
new SByte[]
{
-10,
0,
-7,
-1,
-7,
-18
},
new SByte[]
{
-11,
0,
-8,
-3,
-8,
-18
},
new SByte[]
{
-10,
0,
-7,
-1,
-7,
-18
},
new SByte[]
{
-10,
0,
-7,
-1,
-7,
-18
},
new SByte[]
{
-10,
0,
-7,
-1,
-7,
-18
},
new SByte[]
{
-10,
0,
-7,
-1,
-7,
-18
},
new SByte[]
{
-11,
0,
-6,
-1,
-6,
-22
},
new SByte[]
{
-11,
0,
-6,
-1,
-6,
-22
},
new SByte[]
{
-12,
-2,
-9,
-1,
-9,
-23
},
new SByte[]
{
-10,
0,
-7,
-1,
-7,
-17
},
new SByte[]
{
-10,
0,
-7,
-1,
-7,
-17
},
new SByte[]
{
-13,
0,
-7,
-2,
-7,
-23
},
new SByte[]
{
-13,
-2,
-7,
1,
-7,
-21
},
new SByte[]
{
-11,
0,
-8,
-2,
-8,
-19
},
new SByte[]
{
-9,
0,
-6,
-1,
-6,
-21
},
new SByte[]
{
-12,
0,
-8,
-2,
-8,
-19
},
new SByte[]
{
-10,
0,
-8,
-2,
-8,
-18
},
new SByte[]
{
-10,
0,
-6,
-1,
-6,
-18
}
};
public static SByte[][] wZofsPC;
public class STAT_CNT_TBL
{
public STAT_CNT_TBL(BattleStatus mask, Int16 idx, UInt16 col)
{
this.Mask = mask;
this.Idx = idx;
this.Col = col;
}
public BattleStatus Mask;
public Int16 Idx;
public UInt16 Col;
}
public class STAT_ICON_TBL
{
public STAT_ICON_TBL(BattleStatus mask, BattleStatus mask2, BinaryReader spr, Byte pos, Byte abr, Byte type, Byte ang)
{
this.Mask = mask;
this.Mask2 = mask2;
this.Spr = spr;
this.Pos = pos;
this.Abr = abr;
this.Type = type;
this.Ang = ang;
this.texture = null;
}
public BattleStatus Mask;
public BattleStatus Mask2;
public BinaryReader Spr;
public Byte Pos;
public Byte Abr;
public Byte Type;
public Byte Ang;
public Texture2D texture;
}
public class S_InShpWork
{
public UInt32 rgbcode;
public Int32 sx;
public Int32 sy;
public Int32 abr;
public Int32 clut;
public Int32 prim;
public Int32 otadd;
}
public class S_InSpsWork
{
public BinaryReader pt;
public BinaryReader rgb;
public Int32 w;
public Int32 h;
public Int32 tpage;
public Int32 clut;
public Int32 fade;
public Int32 prim;
public Int32 otadd;
public Int32 code;
}
}
| |
#region License
//
// Copyright (c) 2018, Fluent Migrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System.Data;
using FluentMigrator.Runner.Generators.Oracle;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Generators.Oracle
{
[TestFixture]
public class OracleConstraintsTests : BaseConstraintsTests
{
protected OracleGenerator Generator;
[SetUp]
public void Setup()
{
Generator = new OracleGenerator();
}
[Test]
public override void CanCreateForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT FK_TestTable1_TestColumn1_TestTable2_TestColumn2 FOREIGN KEY (TestColumn1) REFERENCES TestSchema.TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT FK_TestTable1_TestColumn1_TestTable2_TestColumn2 FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT FK_TestTable1_TestColumn1_TestTable2_TestColumn2 FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateMultiColumnForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4 FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestSchema.TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateMultiColumnForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4 FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateMultiColumnForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4 FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateMultiColumnPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnPrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT PK_TestTable1_TestColumn1_TestColumn2 PRIMARY KEY (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateMultiColumnPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT PK_TestTable1_TestColumn1_TestColumn2 PRIMARY KEY (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateMultiColumnUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT UC_TestTable1_TestColumn1_TestColumn2 UNIQUE (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateMultiColumnUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT UC_TestTable1_TestColumn1_TestColumn2 UNIQUE (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateNamedForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestSchema.TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateNamedForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateNamedForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2)");
}
[Test]
public override void CanCreateNamedForeignKeyWithOnDeleteAndOnUpdateOptions()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.OnDelete = Rule.Cascade;
expression.ForeignKey.OnUpdate = Rule.SetDefault;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2) ON DELETE CASCADE ON UPDATE SET DEFAULT");
}
[TestCase(Rule.SetDefault, "SET DEFAULT"), TestCase(Rule.SetNull, "SET NULL"), TestCase(Rule.Cascade, "CASCADE")]
public override void CanCreateNamedForeignKeyWithOnDeleteOptions(Rule rule, string output)
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.OnDelete = rule;
var result = Generator.Generate(expression);
result.ShouldBe(string.Format("ALTER TABLE TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2) ON DELETE {0}", output));
}
[TestCase(Rule.SetDefault, "SET DEFAULT"), TestCase(Rule.SetNull, "SET NULL"), TestCase(Rule.Cascade, "CASCADE")]
public override void CanCreateNamedForeignKeyWithOnUpdateOptions(Rule rule, string output)
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.OnUpdate = rule;
var result = Generator.Generate(expression);
result.ShouldBe(string.Format("ALTER TABLE TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1) REFERENCES TestTable2 (TestColumn2) ON UPDATE {0}", output));
}
[Test]
public override void CanCreateNamedMultiColumnForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestSchema.TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateNamedMultiColumnForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateNamedMultiColumnForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT FK_Test FOREIGN KEY (TestColumn1, TestColumn3) REFERENCES TestTable2 (TestColumn2, TestColumn4)");
}
[Test]
public override void CanCreateNamedMultiColumnPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnPrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TESTPRIMARYKEY PRIMARY KEY (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateNamedMultiColumnPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT TESTPRIMARYKEY PRIMARY KEY (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateNamedMultiColumnUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TESTUNIQUECONSTRAINT UNIQUE (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateNamedMultiColumnUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT TESTUNIQUECONSTRAINT UNIQUE (TestColumn1, TestColumn2)");
}
[Test]
public override void CanCreateNamedPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedPrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TESTPRIMARYKEY PRIMARY KEY (TestColumn1)");
}
[Test]
public override void CanCreateNamedPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT TESTPRIMARYKEY PRIMARY KEY (TestColumn1)");
}
[Test]
public override void CanCreateNamedUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT TESTUNIQUECONSTRAINT UNIQUE (TestColumn1)");
}
[Test]
public override void CanCreateNamedUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT TESTUNIQUECONSTRAINT UNIQUE (TestColumn1)");
}
[Test]
public override void CanCreatePrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreatePrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT PK_TestTable1_TestColumn1 PRIMARY KEY (TestColumn1)");
}
[Test]
public override void CanCreatePrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreatePrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT PK_TestTable1_TestColumn1 PRIMARY KEY (TestColumn1)");
}
[Test]
public override void CanCreateUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 ADD CONSTRAINT UC_TestTable1_TestColumn1 UNIQUE (TestColumn1)");
}
[Test]
public override void CanCreateUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 ADD CONSTRAINT UC_TestTable1_TestColumn1 UNIQUE (TestColumn1)");
}
[Test]
public override void CanDropForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 DROP CONSTRAINT FK_Test");
}
[Test]
public override void CanDropForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 DROP CONSTRAINT FK_Test");
}
[Test]
public override void CanDropPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeletePrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 DROP CONSTRAINT TESTPRIMARYKEY");
}
[Test]
public override void CanDropPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeletePrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 DROP CONSTRAINT TESTPRIMARYKEY");
}
[Test]
public override void CanDropUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestSchema.TestTable1 DROP CONSTRAINT TESTUNIQUECONSTRAINT");
}
[Test]
public override void CanDropUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 DROP CONSTRAINT TESTUNIQUECONSTRAINT");
}
[Test]
public void CanAlterDefaultConstraintWithValueAsDefault()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 MODIFY TestColumn1 DEFAULT 1");
}
[Test]
public void CanAlterDefaultConstraintWithStringValueAsDefault()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.DefaultValue = "1";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 MODIFY TestColumn1 DEFAULT '1'");
}
[Test]
public void CanAlterDefaultConstraintWithDefaultSystemMethodNewGuid()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.DefaultValue = SystemMethods.NewGuid;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 MODIFY TestColumn1 DEFAULT sys_guid()");
}
[Test]
public void CanAlterDefaultConstraintWithDefaultSystemMethodCurrentDateTime()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.DefaultValue = SystemMethods.CurrentDateTime;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 MODIFY TestColumn1 DEFAULT LOCALTIMESTAMP");
}
[Test]
public void CanAlterDefaultConstraintWithDefaultSystemMethodCurrentUser()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.DefaultValue = SystemMethods.CurrentUser;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 MODIFY TestColumn1 DEFAULT USER");
}
[Test]
public void CanAlterDefaultConstraintForCustomSchemaWithValueAsDefault()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.SchemaName = "USER";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE USER.TestTable1 MODIFY TestColumn1 DEFAULT 1");
}
[Test]
public void CanAlterDefaultConstraintForCustomSchemaWithStringValueAsDefault()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.SchemaName = "USER";
expression.DefaultValue = "1";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE USER.TestTable1 MODIFY TestColumn1 DEFAULT '1'");
}
[Test]
public void CanAlterDefaultConstraintForCustomSchemaWithDefaultSystemMethodNewGuid()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.SchemaName = "USER";
expression.DefaultValue = SystemMethods.NewGuid;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE USER.TestTable1 MODIFY TestColumn1 DEFAULT sys_guid()");
}
[Test]
public void CanAlterDefaultConstraintForCustomSchemaWithDefaultSystemMethodCurrentDateTime()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.SchemaName = "USER";
expression.DefaultValue = SystemMethods.CurrentDateTime;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE USER.TestTable1 MODIFY TestColumn1 DEFAULT LOCALTIMESTAMP");
}
[Test]
public void CanAlterDefaultConstraintForCustomSchemaWithDefaultSystemMethodCurrentUser()
{
var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
expression.SchemaName = "USER";
expression.DefaultValue = SystemMethods.CurrentUser;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE USER.TestTable1 MODIFY TestColumn1 DEFAULT USER");
}
[Test]
public void CanRemoveDefaultConstraint()
{
var expression = GeneratorTestHelper.GetDeleteDefaultConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE TestTable1 MODIFY TestColumn1 DEFAULT NULL");
}
[Test]
public void CanRemoveDefaultConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteDefaultConstraintExpression();
expression.SchemaName = "USER";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE USER.TestTable1 MODIFY TestColumn1 DEFAULT NULL");
}
}
}
| |
// 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.IO;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Infrastructure.Common;
using Xunit;
public static partial class ServiceContractTests
{
// End operation includes keyword "out" on an Int as an arg.
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_AsyncEndOperation_IntOutArg()
{
string message = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IServiceContractIntOutService> factory = null;
IServiceContractIntOutService serviceProxy = null;
int number = 0;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
factory = new ChannelFactory<IServiceContractIntOutService>(binding, new EndpointAddress(Endpoints.ServiceContractAsyncIntOut_Address));
serviceProxy = factory.CreateChannel();
ManualResetEvent waitEvent = new ManualResetEvent(false);
// *** EXECUTE *** \\
// This delegate will execute when the call has completed, which is how we get the result of the call.
AsyncCallback callback = (iar) =>
{
serviceProxy.EndRequest(out number, iar);
waitEvent.Set();
};
IAsyncResult ar = serviceProxy.BeginRequest(message, callback, null);
// *** VALIDATE *** \\
Assert.True(waitEvent.WaitOne(ScenarioTestHelpers.TestTimeout), "AsyncCallback was not called.");
Assert.True((number == message.Count<char>()), String.Format("The local int variable was not correctly set, expected {0} but got {1}", message.Count<char>(), number));
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
// End operation includes keyword "out" on a unique type as an arg.
// The unique type used must not appear anywhere else in any contracts in order
// test the static analysis logic of the Net Native toolchain.
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_AsyncEndOperation_UniqueTypeOutArg()
{
string message = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IServiceContractUniqueTypeOutService> factory = null;
IServiceContractUniqueTypeOutService serviceProxy = null;
UniqueType uniqueType = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
factory = new ChannelFactory<IServiceContractUniqueTypeOutService>(binding, new EndpointAddress(Endpoints.ServiceContractAsyncUniqueTypeOut_Address));
serviceProxy = factory.CreateChannel();
ManualResetEvent waitEvent = new ManualResetEvent(false);
// *** EXECUTE *** \\
// This delegate will execute when the call has completed, which is how we get the result of the call.
AsyncCallback callback = (iar) =>
{
serviceProxy.EndRequest(out uniqueType, iar);
waitEvent.Set();
};
IAsyncResult ar = serviceProxy.BeginRequest(message, callback, null);
// *** VALIDATE *** \\
Assert.True(waitEvent.WaitOne(ScenarioTestHelpers.TestTimeout), "AsyncCallback was not called.");
Assert.True((uniqueType.stringValue == message),
String.Format("The 'stringValue' field in the instance of 'UniqueType' was not as expected. expected {0} but got {1}", message, uniqueType.stringValue));
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
// End & Begin operations include keyword "ref" on an Int as an arg.
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_AsyncEndOperation_IntRefArg()
{
string message = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IServiceContractIntRefService> factory = null;
IServiceContractIntRefService serviceProxy = null;
int number = 0;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
factory = new ChannelFactory<IServiceContractIntRefService>(binding, new EndpointAddress(Endpoints.ServiceContractAsyncIntRef_Address));
serviceProxy = factory.CreateChannel();
ManualResetEvent waitEvent = new ManualResetEvent(false);
// *** EXECUTE *** \\
// This delegate will execute when the call has completed, which is how we get the result of the call.
AsyncCallback callback = (iar) =>
{
serviceProxy.EndRequest(ref number, iar);
waitEvent.Set();
};
IAsyncResult ar = serviceProxy.BeginRequest(message, ref number, callback, null);
// *** VALIDATE *** \\
Assert.True(waitEvent.WaitOne(ScenarioTestHelpers.TestTimeout), "AsyncCallback was not called.");
Assert.True((number == message.Count<char>()),
String.Format("The value of the integer sent by reference was not the expected value. expected {0} but got {1}", message.Count<char>(), number));
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
// End & Begin operations include keyword "ref" on a unique type as an arg.
// The unique type used must not appear anywhere else in any contracts in order
// test the static analysis logic of the Net Native toolchain.
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_AsyncEndOperation_UniqueTypeRefArg()
{
string message = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IServiceContractUniqueTypeRefService> factory = null;
IServiceContractUniqueTypeRefService serviceProxy = null;
UniqueType uniqueType = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
factory = new ChannelFactory<IServiceContractUniqueTypeRefService>(binding, new EndpointAddress(Endpoints.ServiceContractAsyncUniqueTypeRef_Address));
serviceProxy = factory.CreateChannel();
ManualResetEvent waitEvent = new ManualResetEvent(false);
// *** EXECUTE *** \\
// This delegate will execute when the call has completed, which is how we get the result of the call.
AsyncCallback callback = (iar) =>
{
serviceProxy.EndRequest(ref uniqueType, iar);
waitEvent.Set();
};
IAsyncResult ar = serviceProxy.BeginRequest(message, ref uniqueType, callback, null);
// *** VALIDATE *** \\
Assert.True(waitEvent.WaitOne(ScenarioTestHelpers.TestTimeout), "AsyncCallback was not called.");
Assert.True((uniqueType.stringValue == message),
String.Format("The 'stringValue' field in the instance of 'UniqueType' was not as expected. expected {0} but got {1}", message, uniqueType.stringValue));
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
// Synchronous operation using the keyword "out" on a unique type as an arg.
// The unique type used must not appear anywhere else in any contracts in order
// test the static analysis logic of the Net Native toolchain.
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_SyncOperation_UniqueTypeOutArg()
{
string message = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IServiceContractUniqueTypeOutSyncService> factory = null;
IServiceContractUniqueTypeOutSyncService serviceProxy = null;
UniqueType uniqueType = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
factory = new ChannelFactory<IServiceContractUniqueTypeOutSyncService>(binding, new EndpointAddress(Endpoints.ServiceContractSyncUniqueTypeOut_Address));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
serviceProxy.Request(message, out uniqueType);
// *** VALIDATE *** \\
Assert.True((uniqueType.stringValue == message),
String.Format("The value of the 'stringValue' field in the UniqueType instance was not as expected. expected {0} but got {1}", message, uniqueType.stringValue));
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
// Synchronous operation using the keyword "ref" on a unique type as an arg.
// The unique type used must not appear anywhere else in any contracts in order
// test the static analysis logic of the Net Native toolchain.
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_SyncOperation_UniqueTypeRefArg()
{
string message = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IServiceContractUniqueTypeRefSyncService> factory = null;
IServiceContractUniqueTypeRefSyncService serviceProxy = null;
UniqueType uniqueType = new UniqueType();
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding();
factory = new ChannelFactory<IServiceContractUniqueTypeRefSyncService>(binding, new EndpointAddress(Endpoints.ServiceContractSyncUniqueTypeRef_Address));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
serviceProxy.Request(message, ref uniqueType);
// *** VALIDATE *** \\
Assert.True((uniqueType.stringValue == message),
String.Format("The value of the 'stringValue' field in the UniqueType instance was not as expected. expected {0} but got {1}", message, uniqueType.stringValue));
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[OuterLoop]
public static void BasicHttp_Async_Open_ChannelFactory()
{
string testString = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
string result = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.OpenTimeout = ScenarioTestHelpers.TestTimeout;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
// *** EXECUTE *** \\
Task t = Task.Factory.FromAsync(factory.BeginOpen, factory.EndOpen, TaskCreationOptions.None);
// *** VALIDATE *** \\
t.GetAwaiter().GetResult();
Assert.True(factory.State == CommunicationState.Opened,
String.Format("Expected factory state 'Opened', actual was '{0}'", factory.State));
serviceProxy = factory.CreateChannel();
result = serviceProxy.Echo(testString); // verifies factory did open correctly
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[OuterLoop]
public static void BasicHttp_Async_Open_ChannelFactory_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
TestTypes.SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => ServiceContractTests.BasicHttp_Async_Open_ChannelFactory(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: BasicHttp_Async_Open_ChannelFactory_WithSingleThreadedSyncContext timed-out.");
}
[WcfFact]
[OuterLoop]
public static void BasicHttp_Async_Open_Proxy()
{
string testString = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
string result = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
ICommunicationObject proxyAsCommunicationObject = (ICommunicationObject)serviceProxy;
Task t = Task.Factory.FromAsync(proxyAsCommunicationObject.BeginOpen, proxyAsCommunicationObject.EndOpen, TaskCreationOptions.None);
// *** VALIDATE *** \\
t.GetAwaiter().GetResult();
Assert.True(proxyAsCommunicationObject.State == CommunicationState.Opened,
String.Format("Expected proxy state 'Opened', actual was '{0}'", proxyAsCommunicationObject.State));
result = serviceProxy.Echo(testString); // verifies proxy did open correctly
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[OuterLoop]
public static void BasicHttp_Async_Open_Proxy_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
TestTypes.SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => ServiceContractTests.BasicHttp_Async_Open_Proxy(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: BasicHttp_Async_Open_Proxy_WithSingleThreadedSyncContext timed-out.");
}
[WcfFact]
[OuterLoop]
public static void BasicHttp_Async_Close_ChannelFactory()
{
string testString = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
string result = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.CloseTimeout = ScenarioTestHelpers.TestTimeout;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
serviceProxy = factory.CreateChannel();
result = serviceProxy.Echo(testString); // force proxy and factory to open as part of setup
((ICommunicationObject)serviceProxy).Close(); // force proxy closed before close factory
// *** EXECUTE *** \\
Task t = Task.Factory.FromAsync(factory.BeginClose, factory.EndClose, TaskCreationOptions.None);
// *** VALIDATE *** \\
t.GetAwaiter().GetResult();
Assert.True(factory.State == CommunicationState.Closed,
String.Format("Expected factory state 'Closed', actual was '{0}'", factory.State));
// *** CLEANUP *** \\
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[OuterLoop]
public static void BasicHttp_Async_Close_ChannelFactory_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
TestTypes.SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => ServiceContractTests.BasicHttp_Async_Close_ChannelFactory(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: BasicHttp_Async_Close_ChannelFactory_WithSingleThreadedSyncContext timed-out.");
}
[WcfFact]
[OuterLoop]
public static void BasicHttp_Async_Close_Proxy()
{
string testString = "Hello";
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
serviceProxy = factory.CreateChannel();
serviceProxy.Echo(testString); // force sync open as part of setup
// *** EXECUTE *** \\
ICommunicationObject proxyAsCommunicationObject = (ICommunicationObject)serviceProxy;
Task t = Task.Factory.FromAsync(proxyAsCommunicationObject.BeginClose, proxyAsCommunicationObject.EndClose, TaskCreationOptions.None);
// *** VALIDATE *** \\
t.GetAwaiter().GetResult();
Assert.True(proxyAsCommunicationObject.State == CommunicationState.Closed,
String.Format("Expected proxy state 'Closed', actual was '{0}'", proxyAsCommunicationObject.State));
// *** CLEANUP *** \\
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[OuterLoop]
public static void BasicHttp_Async_Close_Proxy_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
TestTypes.SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => ServiceContractTests.BasicHttp_Async_Close_Proxy(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: BasicHttp_Async_Close_Proxy_WithSingleThreadedSyncContext timed-out.");
}
private static string StreamToString(Stream stream)
{
var reader = new StreamReader(stream, Encoding.UTF8);
return reader.ReadToEnd();
}
private static Stream StringToStream(string str)
{
var ms = new MemoryStream();
var sw = new StreamWriter(ms, Encoding.UTF8);
sw.Write(str);
sw.Flush();
ms.Position = 0;
return ms;
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using GData.Synchronizer.Tasks;
using Google.GData.Client;
using log4net;
namespace GData.Synchronizer
{
public abstract class GDataWatcher<TAtomEntry> : IDisposable
where TAtomEntry : AbstractEntry
{
private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool _disposed;
private string _id;
private readonly TaskFactory _watchTaskFactory = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.None);
private readonly List<Tuple<Task, CancellationTokenSource>> _watchTasks = new List<Tuple<Task, CancellationTokenSource>>();
private readonly TaskCollection<TAtomEntry> _tasks = new TaskCollection<TAtomEntry>();
protected GDataWatcher(string id)
{
Id = id;
WatchInterval = TimeSpan.FromMinutes(30);
}
public string Id
{
get { return _id; }
protected set
{
_id = value;
_tasks.UnicityToken = _id;
}
}
public ICollection<IGDataTask<TAtomEntry>> Tasks
{
get { return _tasks; }
}
public TimeSpan WatchInterval { get; set; }
private static IEnumerable<TAtomEntry> GetLatestEntries(IEnumerable<TAtomEntry> previousEntries,
IEnumerable<TAtomEntry> actualEntries)
{
if (Logger.IsInfoEnabled)
{
Logger.InfoFormat("Getting the latest entries of type: {0}.", actualEntries);
}
return from aEntry in actualEntries
let intersectionEntry = (from TAtomEntry pEntry in previousEntries
where aEntry.SelfUri.Content == pEntry.SelfUri.Content
select pEntry).FirstOrDefault() where intersectionEntry == null select aEntry;
}
private void Watch(Func<IEnumerable<TAtomEntry>> retriever, CancellationToken cancellationToken)
{
Stopwatch debugWatch = new Stopwatch();
Stopwatch watch = new Stopwatch ();
IEnumerable<TAtomEntry> previousEntries = new List<TAtomEntry>();
while (!cancellationToken.IsCancellationRequested)
{
if (watch.ElapsedMilliseconds == 0 || watch.Elapsed >= WatchInterval)
{
if (Logger.IsInfoEnabled)
{
Logger.InfoFormat("Retriever: {0} is checking for new data.", retriever);
}
if (Logger.IsDebugEnabled)
{
debugWatch.Start();
}
IEnumerable<TAtomEntry> entries = retriever();
foreach (TAtomEntry entry in GetLatestEntries(previousEntries, entries))
{
if (cancellationToken.IsCancellationRequested)
{
cancellationToken.ThrowIfCancellationRequested();
}
foreach (IGDataTask<TAtomEntry> task in Tasks)
{
// TODO: parallelize
if (task.Prerequisites == null || task.Prerequisites(entry))
{
task.Do(entry, cancellationToken);
}
if (cancellationToken.IsCancellationRequested)
{
cancellationToken.ThrowIfCancellationRequested();
}
}
}
if (Logger.IsDebugEnabled)
{
debugWatch.Stop();
Logger.DebugFormat("Tasks done in: {0}.", debugWatch.ElapsedMilliseconds);
}
previousEntries = entries;
watch.Restart();
if (Logger.IsInfoEnabled)
{
Logger.InfoFormat("Retriver: {0} is waiting for the next checking time.", retriever);
}
}
Thread.Sleep (1000);
}
}
/// <summary>
/// Start watching data returned by the given retriever.
/// </summary>
/// <param name="retriever">A source of data.</param>
/// <returns>A token that can be use to cancel the task.</returns>
public CancellationTokenSource StartWatch(Func<IEnumerable<TAtomEntry>> retriever)
{
if (Logger.IsInfoEnabled)
{
Logger.InfoFormat("Starting a watcher for: {0}.", retriever);
}
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
Task task = _watchTaskFactory.StartNew(() => Watch(retriever, cancellationTokenSource.Token), cancellationTokenSource.Token);
_watchTasks.Add(new Tuple<Task, CancellationTokenSource>(task, cancellationTokenSource));
return cancellationTokenSource;
}
#region IDisposable implementation
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize(this);
}
protected void Dispose (bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
if (Logger.IsDebugEnabled)
{
Logger.DebugFormat("Disposing watcher: {0}.", this);
}
foreach (Tuple<Task, CancellationTokenSource> watchTask in _watchTasks)
{
if (Logger.IsInfoEnabled)
{
Logger.InfoFormat("Stopping task: {0}.", watchTask.Item1.Id);
}
watchTask.Item2.Cancel();
try
{
watchTask.Item1.Wait();
}
catch (AggregateException ae)
{
// TODO: Handle exception correctly.
if (ae.InnerException is TaskCanceledException)
{
Logger.InfoFormat("Task: {0} has stopped.", watchTask.Item1.Id);
}
else
{
throw;
}
}
watchTask.Item1.Dispose();
watchTask.Item2.Dispose();
}
_watchTasks.Clear();
}
_disposed = true;
}
#endregion
}
}
| |
#region license
// Copyright (c) 2004, 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
namespace BooCompiler.Tests
{
using System;
using NUnit.Framework;
[TestFixture]
public class CompilationTestFixture : AbstractCompilerTestCase
{
[Test]
public void TestHello()
{
Assert.AreEqual("Hello!\n", RunString("print('Hello!')"));
}
[Test]
public void TestHello2()
{
string stdin = "Test2\n";
string code = "name = prompt(''); print(\"Hello, ${name}!\")";
Assert.AreEqual("Hello, Test2!\n", RunString(code, stdin));
}
[Test]
public void TypeReferenceRepresentsType()
{
RunCompilerTestCase("typereference0.boo");
}
[Test]
public void TestIfModifier0()
{
RunCompilerTestCase("if0.boo");
}
[Test]
public void TimeSpanLiteral()
{
RunCompilerTestCase("timespan0.boo");
}
[Test]
public void TestMatch0()
{
RunCompilerTestCase("match0.boo");
}
[Test]
public void TestMatch1()
{
RunCompilerTestCase("match1.boo");
}
[Test]
public void TestNot0()
{
RunCompilerTestCase("not0.boo");
}
[Test]
public void ArrayMember()
{
RunCompilerTestCase("in0.boo");
}
[Test]
public void ArrayNotMember()
{
RunCompilerTestCase("in1.boo");
}
[Test]
public void IsNotIs()
{
RunCompilerTestCase("is0.boo");
}
[Test]
public void RealType()
{
RunCompilerTestCase("double0.boo");
}
[Test]
public void PreIncrement()
{
RunCompilerTestCase("preincrement0.boo");
}
[Test]
public void PreDecrement()
{
RunCompilerTestCase("predecrement0.boo");
}
[Test]
public void SumLocals()
{
RunCompilerTestCase("sum0.boo");
}
[Test]
public void MultLocals()
{
RunCompilerTestCase("mult0.boo");
}
[Test]
public void InPlaceAddLocals()
{
RunCompilerTestCase("inplaceadd0.boo");
}
[Test]
public void InPlaceField()
{
RunCompilerTestCase("inplace1.boo");
}
[Test]
public void LongLiterals()
{
RunCompilerTestCase("long0.boo");
}
[Test]
public void BooleanFromBoxedValueTypes()
{
RunCompilerTestCase("bool0.boo");
}
[Test]
public void GreaterThanEqualForInts()
{
RunCompilerTestCase("gte_int.boo");
}
[Test]
public void LessThanEqualForInts()
{
RunCompilerTestCase("lte_int.boo");
}
[Test]
public void IndexedProperty()
{
RunCompilerTestCase("indexed.boo");
}
[Test]
public void IndexPropertyWithSyntacticAttribute()
{
RunCompilerTestCase("indexed2.boo");
}
[Test]
public void ImportInternalNamespace()
{
RunMultiFileTestCase("multifile0.boo", "Character.boo");
}
[Test]
public void ImportAutomaticallyFromModulesInTheSameNamespace()
{
RunMultiFileTestCase("multifile1.boo", "Character.boo");
}
[Test]
public void ImportFunctionsFromModulesInTheGlobalNamespace()
{
RunMultiFileTestCase("multifile2.boo", "math.boo");
}
[Test]
public void ImportFunctionsFromModulesInTheSameNamespace()
{
RunMultiFileTestCase("multifile3.boo", "mathwithns.boo");
}
[Test]
public void ClassesCanUseModuleMethods()
{
RunCompilerTestCase("module_methods0.boo");
}
[Test]
public void RangeBuiltin()
{
RunCompilerTestCase("range.boo");
}
[Test]
public void StringAddition()
{
RunCompilerTestCase("stringadd0.boo");
}
[Test]
public void StringMultiplyByInt()
{
RunCompilerTestCase("stringmultiply0.boo");
}
[Test]
public void ListRichOperators()
{
RunCompilerTestCase("listoperators.boo");
}
[Test]
public void CustomerAddresses()
{
RunCompilerTestCase("customer_addresses.boo");
}
[Test]
public void NumberExponentiation()
{
RunCompilerTestCase("pow0.boo");
}
[Test]
public void UnlessModifier()
{
RunCompilerTestCase("unless.boo");
}
[Test]
public void StringFormattingWithTripleQuotedString()
{
RunCompilerTestCase("formatting0.boo");
}
[Test]
public void UnpackLocals()
{
RunCompilerTestCase("unpack_locals.boo");
}
[Test]
public void StatementModifierOnUnpack()
{
RunCompilerTestCase("modifiers0.boo");
}
[Test]
public void StaticFieldSimple()
{
RunCompilerTestCase("static_field0.boo");
}
[Test]
public void StaticLiteralField()
{
RunCompilerTestCase("static_literalfield0.boo");
}
[Test]
public void StaticConstructorIsCalledBeforeFirstStaticFieldAccess()
{
RunCompilerTestCase("static_constructor0.boo");
}
[Test]
public void IncrementProperty()
{
RunCompilerTestCase("increment_property0.boo");
}
[Test]
public void IncrementPropertyAndUseValue()
{
RunCompilerTestCase("increment_property1.boo");
}
[Test]
public void EnumComparisons()
{
RunCompilerTestCase("enum_comparisons.boo");
}
[Test]
public void TypeIsCallable()
{
RunCompilerTestCase("typeiscallable.boo");
}
[Test]
public void TypeAsICallable()
{
RunCompilerTestCase("typeiscallable1.boo");
}
[Test]
public void OverloadedMethodsCanBeDeclaredInAnyOrder()
{
RunCompilerTestCase("logservice.boo");
}
[Test]
public void ParameterAsLValue()
{
RunCompilerTestCase("parameter_as_lvalue.boo");
}
[Test]
public void NullIsCompatibleWithInternalClasses()
{
RunCompilerTestCase("null0.boo");
}
[Test]
public void TextReaderIsEnumerable()
{
RunCompilerTestCase("textreaderisenumerable.boo");
}
[Test]
public void RegularExpressionLiteralIsRegex()
{
RunCompilerTestCase("re0.boo");
}
[Test]
public void RegularExpressionMatch()
{
RunCompilerTestCase("re1.boo");
}
[Test]
public void CaseInsensitiveHash()
{
RunCompilerTestCase("caseinsensitivehash.boo");
}
[Test]
public void EnumeratorItemTypeForClasses()
{
RunCompilerTestCase("enumeratoritemtype0.boo");
}
[Test]
public void EnumeratorItemTypeForInternalClasses()
{
RunCompilerTestCase("enumeratoritemtype1.boo");
}
[Test]
public void EnumeratorItemTypeForMethods()
{
RunCompilerTestCase("enumeratoritemtype2.boo");
}
[Test]
public void UnaryMinusWithLocal()
{
RunCompilerTestCase("unary0.boo");
}
[Test]
public void RedefineBuiltin()
{
RunCompilerTestCase("redefine_builtin.boo");
}
[Test]
public void ExternalConstants()
{
RunCompilerTestCase("const0.boo");
}
[Test]
public void ListSort()
{
RunCompilerTestCase("sort.boo");
}
[Test]
public void CustomCollection()
{
RunCompilerTestCase("CustomCollection.boo");
}
[Test]
public void UsingNestedType()
{
RunCompilerTestCase("UsingNestedType.boo");
}
}
}
| |
using System;
using Csla;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// ProductSupplierItem (editable child object).<br/>
/// This is a generated base class of <see cref="ProductSupplierItem"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="ProductSupplierColl"/> collection.
/// </remarks>
[Serializable]
public partial class ProductSupplierItem : BusinessBase<ProductSupplierItem>
{
#region Static Fields
private static int _lastId;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="ProductSupplierId"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> ProductSupplierIdProperty = RegisterProperty<int>(p => p.ProductSupplierId, "Product Supplier Id");
/// <summary>
/// Gets the Product Supplier Id.
/// </summary>
/// <value>The Product Supplier Id.</value>
public int ProductSupplierId
{
get { return GetProperty(ProductSupplierIdProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="SupplierId"/> property.
/// </summary>
public static readonly PropertyInfo<int> SupplierIdProperty = RegisterProperty<int>(p => p.SupplierId, "Supplier Id");
/// <summary>
/// Gets or sets the Supplier Id.
/// </summary>
/// <value>The Supplier Id.</value>
public int SupplierId
{
get { return GetProperty(SupplierIdProperty); }
set { SetProperty(SupplierIdProperty, value); }
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ProductSupplierItem"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ProductSupplierItem()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="ProductSupplierItem"/> object properties.
/// </summary>
[RunLocal]
protected override void Child_Create()
{
LoadProperty(ProductSupplierIdProperty, System.Threading.Interlocked.Decrement(ref _lastId));
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="ProductSupplierItem"/> object from the given <see cref="ProductSupplierItemDto"/>.
/// </summary>
/// <param name="data">The ProductSupplierItemDto to use.</param>
private void Child_Fetch(ProductSupplierItemDto data)
{
// Value properties
LoadProperty(ProductSupplierIdProperty, data.ProductSupplierId);
LoadProperty(SupplierIdProperty, data.SupplierId);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Inserts a new <see cref="ProductSupplierItem"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(ProductEdit parent)
{
var dto = new ProductSupplierItemDto();
dto.Parent_ProductId = parent.ProductId;
dto.SupplierId = SupplierId;
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IProductSupplierItemDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
LoadProperty(ProductSupplierIdProperty, resultDto.ProductSupplierId);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="ProductSupplierItem"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
var dto = new ProductSupplierItemDto();
dto.ProductSupplierId = ProductSupplierId;
dto.SupplierId = SupplierId;
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IProductSupplierItemDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="ProductSupplierItem"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IProductSupplierItemDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(ProductSupplierIdProperty));
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Securities.Option;
namespace QuantConnect.Data.UniverseSelection
{
/// <summary>
/// Defines a universe for a single option chain
/// </summary>
public class OptionChainUniverse : Universe
{
private readonly OptionFilterUniverse _optionFilterUniverse;
private readonly UniverseSettings _universeSettings;
private readonly bool _liveMode;
// as an array to make it easy to prepend to selected symbols
private readonly Symbol[] _underlyingSymbol;
private DateTime _cacheDate;
private DateTime _lastExchangeDate;
// used for time-based removals in live mode
private readonly TimeSpan _minimumTimeInUniverse = TimeSpan.FromMinutes(15);
private readonly Dictionary<Symbol, DateTime> _addTimesBySymbol = new Dictionary<Symbol, DateTime>();
/// <summary>
/// Initializes a new instance of the <see cref="OptionChainUniverse"/> class
/// </summary>
/// <param name="option">The canonical option chain security</param>
/// <param name="universeSettings">The universe settings to be used for new subscriptions</param>
/// <param name="liveMode">True if we're running in live mode, false for backtest mode</param>
public OptionChainUniverse(Option option,
UniverseSettings universeSettings,
bool liveMode)
: base(option.SubscriptionDataConfig)
{
Option = option;
_underlyingSymbol = new[] { Option.Symbol.Underlying };
_universeSettings = new UniverseSettings(universeSettings) { DataNormalizationMode = DataNormalizationMode.Raw };
_liveMode = liveMode;
_optionFilterUniverse = new OptionFilterUniverse();
}
/// <summary>
/// The canonical option chain security
/// </summary>
public Option Option { get; }
/// <summary>
/// Gets the settings used for subscriptons added for this universe
/// </summary>
public override UniverseSettings UniverseSettings
{
get { return _universeSettings; }
}
/// <summary>
/// Performs universe selection using the data specified
/// </summary>
/// <param name="utcTime">The current utc time</param>
/// <param name="data">The symbols to remain in the universe</param>
/// <returns>The data that passes the filter</returns>
public override IEnumerable<Symbol> SelectSymbols(DateTime utcTime, BaseDataCollection data)
{
var optionsUniverseDataCollection = data as OptionChainUniverseDataCollection;
if (optionsUniverseDataCollection == null)
{
throw new ArgumentException($"Expected data of type '{typeof(OptionChainUniverseDataCollection).Name}'");
}
// date change detection needs to be done in exchange time zone
var exchangeDate = data.Time.ConvertFromUtc(Option.Exchange.TimeZone).Date;
if (_cacheDate == exchangeDate)
{
return Unchanged;
}
var availableContracts = optionsUniverseDataCollection.Data.Select(x => x.Symbol);
// we will only update unique strikes when there is an exchange date change
_optionFilterUniverse.Refresh(availableContracts, optionsUniverseDataCollection.Underlying, _lastExchangeDate != exchangeDate);
_lastExchangeDate = exchangeDate;
var results = Option.ContractFilter.Filter(_optionFilterUniverse);
// if results are not dynamic, we cache them and won't call filtering till the end of the day
if (!results.IsDynamic)
{
_cacheDate = data.Time.ConvertFromUtc(Option.Exchange.TimeZone).Date;
}
// always prepend the underlying symbol
var resultingSymbols = _underlyingSymbol.Concat(results).ToHashSet();
// we save off the filtered results to the universe data collection for later
// population into the OptionChain. This is non-ideal and could be remedied by
// the universe subscription emitting a special type after selection that could
// be checked for in TimeSlice.Create, but for now this will do
optionsUniverseDataCollection.FilteredContracts = resultingSymbols;
return resultingSymbols;
}
/// <summary>
/// Adds the specified security to this universe
/// </summary>
/// <param name="utcTime">The current utc date time</param>
/// <param name="security">The security to be added</param>
/// <param name="isInternal">True if internal member</param>
/// <returns>True if the security was successfully added,
/// false if the security was already in the universe</returns>
internal override bool AddMember(DateTime utcTime, Security security, bool isInternal)
{
// never add members to disposed universes
if (DisposeRequested)
{
return false;
}
if (Securities.ContainsKey(security.Symbol))
{
return false;
}
// method take into account the case, when the option has experienced an adjustment
// we update member reference in this case
if (Securities.Any(x => x.Value.Security == security))
{
Member member;
Securities.TryRemove(security.Symbol, out member);
}
var added = Securities.TryAdd(security.Symbol, new Member(utcTime, security, isInternal));
if (added && _liveMode)
{
_addTimesBySymbol[security.Symbol] = utcTime;
}
return added;
}
/// <summary>
/// Determines whether or not the specified security can be removed from
/// this universe. This is useful to prevent securities from being taken
/// out of a universe before the algorithm has had enough time to make
/// decisions on the security
/// </summary>
/// <param name="utcTime">The current utc time</param>
/// <param name="security">The security to check if its ok to remove</param>
/// <returns>True if we can remove the security, false otherwise</returns>
public override bool CanRemoveMember(DateTime utcTime, Security security)
{
// can always remove securities after dispose requested
if (DisposeRequested)
{
return true;
}
// if we haven't begun receiving data for this security then it's safe to remove
var lastData = security.Cache.GetData();
if (lastData == null)
{
return true;
}
if (_liveMode)
{
// Only remove members when they have been in the universe for a minimum period of time.
// This prevents us from needing to move contracts in and out too fast,
// as price moves and filtered contracts change throughout the day.
DateTime timeAdded;
// get the date/time this symbol was added to the universe
if (!_addTimesBySymbol.TryGetValue(security.Symbol, out timeAdded))
{
return true;
}
if (timeAdded.Add(_minimumTimeInUniverse) > utcTime)
{
// minimum time span not yet elapsed, do not remove
return false;
}
// ok to remove
_addTimesBySymbol.Remove(security.Symbol);
return true;
}
// only remove members on day changes, this prevents us from needing to
// fast forward contracts continuously as price moves and out filtered
// contracts change throughout the day
var localTime = utcTime.ConvertFromUtc(security.Exchange.TimeZone);
return localTime.Date != lastData.Time.Date;
}
/// <summary>
/// Gets the subscription requests to be added for the specified security
/// </summary>
/// <param name="security">The security to get subscriptions for</param>
/// <param name="currentTimeUtc">The current time in utc. This is the frontier time of the algorithm</param>
/// <param name="maximumEndTimeUtc">The max end time</param>
/// <param name="subscriptionService">Instance which implements <see cref="ISubscriptionDataConfigService"/> interface</param>
/// <returns>All subscriptions required by this security</returns>
public override IEnumerable<SubscriptionRequest> GetSubscriptionRequests(Security security, DateTime currentTimeUtc, DateTime maximumEndTimeUtc,
ISubscriptionDataConfigService subscriptionService)
{
if (Option.Symbol.Underlying == security.Symbol)
{
Option.Underlying = security;
security.SetDataNormalizationMode(DataNormalizationMode.Raw);
}
else
{
// set the underlying security and pricing model from the canonical security
var option = (Option)security;
option.PriceModel = Option.PriceModel;
}
return base.GetSubscriptionRequests(security, currentTimeUtc, maximumEndTimeUtc, subscriptionService);
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel.Channels;
using System.Web;
using System.Xml;
using ServiceStack.Common.Web;
using ServiceStack.ServiceClient.Web;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceModel.Serialization;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints.Extensions;
using ServiceStack.WebHost.EndPoints.Utils;
namespace ServiceStack.WebHost.Endpoints.Support
{
public class SoapHandler : EndpointHandlerBase, IOneWay, ISyncReply
{
public SoapHandler(EndpointAttributes soapType)
{
this.HandlerAttributes = soapType;
}
public void SendOneWay(Message requestMsg)
{
var endpointAttributes = EndpointAttributes.AsyncOneWay | this.HandlerAttributes;
ExecuteMessage(requestMsg, endpointAttributes);
}
public Message Send(Message requestMsg)
{
var endpointAttributes = EndpointAttributes.SyncReply | this.HandlerAttributes;
return ExecuteMessage(requestMsg, endpointAttributes);
}
public Message EmptyResponse(Message requestMsg, Type requestType)
{
var responseType = AssemblyUtils.FindType(requestType.FullName + "Response");
var response = ReflectionExtensions.CreateInstance(responseType ?? typeof(object));
return requestMsg.Headers.Action == null
? Message.CreateMessage(requestMsg.Version, null, response)
: Message.CreateMessage(requestMsg.Version, requestType.Name + "Response", response);
}
protected Message ExecuteMessage(Message requestMsg, EndpointAttributes endpointAttributes)
{
if ((EndpointAttributes.Soap11 & this.HandlerAttributes) == EndpointAttributes.Soap11)
EndpointHost.Config.AssertFeatures(Feature.Soap11);
else if ((EndpointAttributes.Soap12 & this.HandlerAttributes) == EndpointAttributes.Soap12)
EndpointHost.Config.AssertFeatures(Feature.Soap12);
string requestXml;
using (var reader = requestMsg.GetReaderAtBodyContents())
{
requestXml = reader.ReadOuterXml();
}
var requestType = GetRequestType(requestMsg, requestXml);
try
{
var request = DataContractDeserializer.Instance.Parse(requestXml, requestType);
IHttpRequest httpReq = null;
IHttpResponse httpRes = null;
var hasRequestFilters = EndpointHost.RequestFilters.Count > 0
|| FilterAttributeCache.GetRequestFilterAttributes(request.GetType()).Any();
if (hasRequestFilters)
{
httpReq = HttpContext.Current != null
? new HttpRequestWrapper(requestType.Name, HttpContext.Current.Request)
: null;
httpRes = HttpContext.Current != null
? new HttpResponseWrapper(HttpContext.Current.Response)
: null;
}
if (hasRequestFilters && EndpointHost.ApplyRequestFilters(httpReq, httpRes, request))
return EmptyResponse(requestMsg, requestType);
var response = ExecuteService(request, endpointAttributes, httpReq, httpRes);
var hasResponseFilters = EndpointHost.ResponseFilters.Count > 0
|| FilterAttributeCache.GetResponseFilterAttributes(response.GetType()).Any();
if (hasResponseFilters && httpRes == null)
{
httpRes = HttpContext.Current != null
? new HttpResponseWrapper(HttpContext.Current.Response)
: null;
}
if (hasResponseFilters && EndpointHost.ApplyResponseFilters(httpReq, httpRes, response))
return EmptyResponse(requestMsg, requestType);
return requestMsg.Headers.Action == null
? Message.CreateMessage(requestMsg.Version, null, response)
: Message.CreateMessage(requestMsg.Version, requestType.Name + "Response", response);
}
catch (Exception ex)
{
throw new SerializationException("3) Error trying to deserialize requestType: "
+ requestType
+ ", xml body: " + requestXml, ex);
}
}
protected static Message GetSoap12RequestMessage(HttpContext context)
{
return GetRequestMessage(context, MessageVersion.Soap12WSAddressingAugust2004);
}
protected static Message GetSoap11RequestMessage(HttpContext context)
{
return GetRequestMessage(context, MessageVersion.Soap11WSAddressingAugust2004);
}
protected static Message GetRequestMessage(HttpContext context, MessageVersion msgVersion)
{
using (var sr = new StreamReader(context.Request.InputStream))
{
var requestXml = sr.ReadToEnd();
var doc = new XmlDocument();
doc.LoadXml(requestXml);
var msg = Message.CreateMessage(new XmlNodeReader(doc), int.MaxValue,
msgVersion);
return msg;
}
}
protected Type GetRequestType(Message requestMsg, string xml)
{
var action = GetAction(requestMsg, xml);
var operationType = EndpointHost.ServiceOperations.GetOperationType(action);
AssertOperationExists(action, operationType);
return operationType;
}
protected string GetAction(Message requestMsg, string xml)
{
var action = GetActionFromHttpContext();
if (action != null) return action;
if (requestMsg.Headers.Action != null)
{
return requestMsg.Headers.Action;
}
if (xml.StartsWith("<"))
{
return xml.Substring(1, xml.IndexOf(" ") - 1);
}
return null;
}
protected static string GetActionFromHttpContext()
{
var context = HttpContext.Current;
return GetAction(context);
}
private static string GetAction(HttpContext context)
{
if (context != null)
{
var contentType = context.Request.ContentType;
return GetOperationName(contentType);
}
return null;
}
private static string GetOperationName(string contentType)
{
var urlActionPos = contentType.IndexOf("action=\"");
if (urlActionPos != -1)
{
var startIndex = urlActionPos + "action=\"".Length;
var urlAction = contentType.Substring(
startIndex,
contentType.IndexOf('"', startIndex) - startIndex);
var parts = urlAction.Split('/');
var operationName = parts.Last();
return operationName;
}
return null;
}
public string GetSoapContentType(HttpContext context)
{
var requestOperationName = GetAction(context);
return requestOperationName != null
? context.Request.ContentType.Replace(requestOperationName, requestOperationName + "Response")
: (this.HandlerAttributes == EndpointAttributes.Soap11 ? ContentType.Soap11 : ContentType.Soap12);
}
public override object CreateRequest(IHttpRequest request, string operationName)
{
throw new NotImplementedException();
}
public override object GetResponse(IHttpRequest httpReq, IHttpResponse httpRes, object request)
{
throw new NotImplementedException();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
public partial class FileStream : Stream
{
// This is an internal object extending TaskCompletionSource with fields
// for all of the relevant data necessary to complete the IO operation.
// This is used by IOCallback and all of the async methods.
private unsafe class FileStreamCompletionSource : TaskCompletionSource<int>
{
private const long NoResult = 0;
private const long ResultSuccess = (long)1 << 32;
private const long ResultError = (long)2 << 32;
private const long RegisteringCancellation = (long)4 << 32;
private const long CompletedCallback = (long)8 << 32;
private const ulong ResultMask = ((ulong)uint.MaxValue) << 32;
private static Action<object> s_cancelCallback;
private readonly FileStream _stream;
private readonly int _numBufferedBytes;
private CancellationTokenRegistration _cancellationRegistration;
#if DEBUG
private bool _cancellationHasBeenRegistered;
#endif
private NativeOverlapped* _overlapped; // Overlapped class responsible for operations in progress when an appdomain unload occurs
private long _result; // Using long since this needs to be used in Interlocked APIs
// Using RunContinuationsAsynchronously for compat reasons (old API used Task.Factory.StartNew for continuations)
protected FileStreamCompletionSource(FileStream stream, int numBufferedBytes, byte[] bytes)
: base(TaskCreationOptions.RunContinuationsAsynchronously)
{
_numBufferedBytes = numBufferedBytes;
_stream = stream;
_result = NoResult;
// Create the native overlapped. We try to use the preallocated overlapped if possible: it's possible if the byte
// buffer is null (there's nothing to pin) or the same one that's associated with the preallocated overlapped (and
// thus is already pinned) and if no one else is currently using the preallocated overlapped. This is the fast-path
// for cases where the user-provided buffer is smaller than the FileStream's buffer (such that the FileStream's
// buffer is used) and where operations on the FileStream are not being performed concurrently.
Debug.Assert((bytes == null || ReferenceEquals(bytes, _stream._buffer)));
// The _preallocatedOverlapped is null if the internal buffer was never created, so we check for
// a non-null bytes before using the stream's _preallocatedOverlapped
_overlapped = bytes != null && _stream.CompareExchangeCurrentOverlappedOwner(this, null) == null ?
_stream._fileHandle.ThreadPoolBinding.AllocateNativeOverlapped(_stream._preallocatedOverlapped) :
_stream._fileHandle.ThreadPoolBinding.AllocateNativeOverlapped(s_ioCallback, this, bytes);
Debug.Assert(_overlapped != null, "AllocateNativeOverlapped returned null");
}
internal NativeOverlapped* Overlapped
{
get { return _overlapped; }
}
public void SetCompletedSynchronously(int numBytes)
{
ReleaseNativeResource();
TrySetResult(numBytes + _numBufferedBytes);
}
public void RegisterForCancellation(CancellationToken cancellationToken)
{
#if DEBUG
Debug.Assert(cancellationToken.CanBeCanceled);
Debug.Assert(!_cancellationHasBeenRegistered, "Cannot register for cancellation twice");
_cancellationHasBeenRegistered = true;
#endif
// Quick check to make sure the IO hasn't completed
if (_overlapped != null)
{
var cancelCallback = s_cancelCallback;
if (cancelCallback == null) s_cancelCallback = cancelCallback = Cancel;
// Register the cancellation only if the IO hasn't completed
long packedResult = Interlocked.CompareExchange(ref _result, RegisteringCancellation, NoResult);
if (packedResult == NoResult)
{
_cancellationRegistration = cancellationToken.Register(cancelCallback, this);
// Switch the result, just in case IO completed while we were setting the registration
packedResult = Interlocked.Exchange(ref _result, NoResult);
}
else if (packedResult != CompletedCallback)
{
// Failed to set the result, IO is in the process of completing
// Attempt to take the packed result
packedResult = Interlocked.Exchange(ref _result, NoResult);
}
// If we have a callback that needs to be completed
if ((packedResult != NoResult) && (packedResult != CompletedCallback) && (packedResult != RegisteringCancellation))
{
CompleteCallback((ulong)packedResult);
}
}
}
internal virtual void ReleaseNativeResource()
{
// Ensure that cancellation has been completed and cleaned up.
_cancellationRegistration.Dispose();
// Free the overlapped.
// NOTE: The cancellation must *NOT* be running at this point, or it may observe freed memory
// (this is why we disposed the registration above).
if (_overlapped != null)
{
_stream._fileHandle.ThreadPoolBinding.FreeNativeOverlapped(_overlapped);
_overlapped = null;
}
// Ensure we're no longer set as the current completion source (we may not have been to begin with).
// Only one operation at a time is eligible to use the preallocated overlapped,
_stream.CompareExchangeCurrentOverlappedOwner(null, this);
}
// When doing IO asynchronously (i.e. _isAsync==true), this callback is
// called by a free thread in the threadpool when the IO operation
// completes.
internal static unsafe void IOCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped)
{
// Extract the completion source from the overlapped. The state in the overlapped
// will either be a Win32FileStream (in the case where the preallocated overlapped was used),
// in which case the operation being completed is its _currentOverlappedOwner, or it'll
// be directly the FileStreamCompletion that's completing (in the case where the preallocated
// overlapped was already in use by another operation).
object state = ThreadPoolBoundHandle.GetNativeOverlappedState(pOverlapped);
FileStream fs = state as FileStream;
FileStreamCompletionSource completionSource = fs != null ?
fs._currentOverlappedOwner :
(FileStreamCompletionSource)state;
Debug.Assert(completionSource._overlapped == pOverlapped, "Overlaps don't match");
// Handle reading from & writing to closed pipes. While I'm not sure
// this is entirely necessary anymore, maybe it's possible for
// an async read on a pipe to be issued and then the pipe is closed,
// returning this error. This may very well be necessary.
ulong packedResult;
if (errorCode != 0 && errorCode != ERROR_BROKEN_PIPE && errorCode != ERROR_NO_DATA)
{
packedResult = ((ulong)ResultError | errorCode);
}
else
{
packedResult = ((ulong)ResultSuccess | numBytes);
}
// Stow the result so that other threads can observe it
// And, if no other thread is registering cancellation, continue
if (NoResult == Interlocked.Exchange(ref completionSource._result, (long)packedResult))
{
// Successfully set the state, attempt to take back the callback
if (Interlocked.Exchange(ref completionSource._result, CompletedCallback) != NoResult)
{
// Successfully got the callback, finish the callback
completionSource.CompleteCallback(packedResult);
}
// else: Some other thread stole the result, so now it is responsible to finish the callback
}
// else: Some other thread is registering a cancellation, so it *must* finish the callback
}
private void CompleteCallback(ulong packedResult)
{
// Free up the native resource and cancellation registration
CancellationToken cancellationToken = _cancellationRegistration.Token; // access before disposing registration
ReleaseNativeResource();
// Unpack the result and send it to the user
long result = (long)(packedResult & ResultMask);
if (result == ResultError)
{
int errorCode = unchecked((int)(packedResult & uint.MaxValue));
if (errorCode == Interop.Errors.ERROR_OPERATION_ABORTED)
{
TrySetCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true));
}
else
{
TrySetException(Win32Marshal.GetExceptionForWin32Error(errorCode));
}
}
else
{
Debug.Assert(result == ResultSuccess, "Unknown result");
TrySetResult((int)(packedResult & uint.MaxValue) + _numBufferedBytes);
}
}
private static void Cancel(object state)
{
// WARNING: This may potentially be called under a lock (during cancellation registration)
FileStreamCompletionSource completionSource = state as FileStreamCompletionSource;
Debug.Assert(completionSource != null, "Unknown state passed to cancellation");
Debug.Assert(completionSource._overlapped != null && !completionSource.Task.IsCompleted, "IO should not have completed yet");
// If the handle is still valid, attempt to cancel the IO
if (!completionSource._stream._fileHandle.IsInvalid &&
!Interop.Kernel32.CancelIoEx(completionSource._stream._fileHandle, completionSource._overlapped))
{
int errorCode = Marshal.GetLastWin32Error();
// ERROR_NOT_FOUND is returned if CancelIoEx cannot find the request to cancel.
// This probably means that the IO operation has completed.
if (errorCode != Interop.Errors.ERROR_NOT_FOUND)
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
}
public static FileStreamCompletionSource Create(FileStream stream, int numBufferedBytesRead, ReadOnlyMemory<byte> memory)
{
// If the memory passed in is the stream's internal buffer, we can use the base FileStreamCompletionSource,
// which has a PreAllocatedOverlapped with the memory already pinned. Otherwise, we use the derived
// MemoryFileStreamCompletionSource, which Retains the memory, which will result in less pinning in the case
// where the underlying memory is backed by pre-pinned buffers.
return MemoryMarshal.TryGetArray(memory, out ArraySegment<byte> buffer) && ReferenceEquals(buffer.Array, stream._buffer) ?
new FileStreamCompletionSource(stream, numBufferedBytesRead, buffer.Array) :
new MemoryFileStreamCompletionSource(stream, numBufferedBytesRead, memory);
}
}
/// <summary>
/// Extends <see cref="FileStreamCompletionSource"/> with to support disposing of a
/// <see cref="MemoryHandle"/> when the operation has completed. This should only be used
/// when memory doesn't wrap a byte[].
/// </summary>
private sealed class MemoryFileStreamCompletionSource : FileStreamCompletionSource
{
private MemoryHandle _handle; // mutable struct; do not make this readonly
internal MemoryFileStreamCompletionSource(FileStream stream, int numBufferedBytes, ReadOnlyMemory<byte> memory) :
base(stream, numBufferedBytes, bytes: null) // this type handles the pinning, so null is passed for bytes
{
_handle = memory.Pin();
}
internal override void ReleaseNativeResource()
{
_handle.Dispose();
base.ReleaseNativeResource();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ----------------------------------------------------------------------------------
// Interop library code
//
// Marshalling helpers used by MCG
//
// NOTE:
// These source code are being published to InternalAPIs and consumed by RH builds
// Use PublishInteropAPI.bat to keep the InternalAPI copies in sync
// ----------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Threading;
using System.Text;
using System.Runtime;
using System.Runtime.CompilerServices;
using Internal.NativeFormat;
#if !CORECLR
using Internal.Runtime.Augments;
#endif
#if RHTESTCL
using OutputClass = System.Console;
#else
using OutputClass = System.Diagnostics.Debug;
#endif
namespace System.Runtime.InteropServices
{
/// <summary>
/// Expose functionality from System.Private.CoreLib and forwards calls to InteropExtensions in System.Private.CoreLib
/// </summary>
[CLSCompliant(false)]
public static partial class McgMarshal
{
public static void SaveLastWin32Error()
{
PInvokeMarshal.SaveLastWin32Error();
}
public static void ClearLastWin32Error()
{
PInvokeMarshal.ClearLastWin32Error();
}
public static bool GuidEquals(ref Guid left, ref Guid right)
{
return InteropExtensions.GuidEquals(ref left, ref right);
}
public static bool ComparerEquals<T>(T left, T right)
{
return InteropExtensions.ComparerEquals<T>(left, right);
}
public static T CreateClass<T>() where T : class
{
return InteropExtensions.UncheckedCast<T>(InteropExtensions.RuntimeNewObject(typeof(T).TypeHandle));
}
public static bool IsEnum(object obj)
{
#if RHTESTCL
return false;
#else
return InteropExtensions.IsEnum(obj.GetTypeHandle());
#endif
}
/// <summary>
/// Return true if the type is __COM or derived from __COM. False otherwise
/// </summary>
public static bool IsComObject(Type type)
{
#if RHTESTCL
return false;
#else
return type == typeof(__ComObject) || type.GetTypeInfo().IsSubclassOf(typeof(__ComObject));
#endif
}
/// <summary>
/// Return true if the object is a RCW. False otherwise
/// </summary>
internal static bool IsComObject(object obj)
{
return (obj is __ComObject);
}
public static T FastCast<T>(object value) where T : class
{
// We have an assert here, to verify that a "real" cast would have succeeded.
// However, casting on weakly-typed RCWs modifies their state, by doing a QI and caching
// the result. This often makes things work which otherwise wouldn't work (especially variance).
Debug.Assert(value == null || value is T);
return InteropExtensions.UncheckedCast<T>(value);
}
/// <summary>
/// Converts a managed DateTime to native OLE datetime
/// Used by MCG marshalling code
/// </summary>
public static double ToNativeOleDate(DateTime dateTime)
{
return InteropExtensions.ToNativeOleDate(dateTime);
}
/// <summary>
/// Converts native OLE datetime to managed DateTime
/// Used by MCG marshalling code
/// </summary>
public static DateTime FromNativeOleDate(double nativeOleDate)
{
return InteropExtensions.FromNativeOleDate(nativeOleDate);
}
/// <summary>
/// Used in Marshalling code
/// Call safeHandle.InitializeHandle to set the internal _handle field
/// </summary>
public static void InitializeHandle(SafeHandle safeHandle, IntPtr win32Handle)
{
InteropExtensions.InitializeHandle(safeHandle, win32Handle);
}
/// <summary>
/// Check if obj's type is the same as represented by normalized handle
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool IsOfType(object obj, RuntimeTypeHandle handle)
{
return obj.IsOfType(handle);
}
#if ENABLE_MIN_WINRT
public static unsafe void SetExceptionErrorCode(Exception exception, int errorCode)
{
InteropExtensions.SetExceptionErrorCode(exception, errorCode);
}
/// <summary>
/// Used in Marshalling code
/// Gets the handle of the CriticalHandle
/// </summary>
public static IntPtr GetHandle(CriticalHandle criticalHandle)
{
return InteropExtensions.GetCriticalHandle(criticalHandle);
}
/// <summary>
/// Used in Marshalling code
/// Sets the handle of the CriticalHandle
/// </summary>
public static void SetHandle(CriticalHandle criticalHandle, IntPtr handle)
{
InteropExtensions.SetCriticalHandle(criticalHandle, handle);
}
#endif
}
/// <summary>
/// McgMarshal helpers exposed to be used by MCG
/// </summary>
public static partial class McgMarshal
{
#region Type marshalling
public static Type TypeNameToType(HSTRING nativeTypeName, int nativeTypeKind)
{
#if ENABLE_WINRT
return McgTypeHelpers.TypeNameToType(nativeTypeName, nativeTypeKind);
#else
throw new NotSupportedException("TypeNameToType");
#endif
}
internal static Type TypeNameToType(string nativeTypeName, int nativeTypeKind)
{
#if ENABLE_WINRT
return McgTypeHelpers.TypeNameToType(nativeTypeName, nativeTypeKind, checkTypeKind: false);
#else
throw new NotSupportedException("TypeNameToType");
#endif
}
public static unsafe void TypeToTypeName(
Type type,
out HSTRING nativeTypeName,
out int nativeTypeKind)
{
#if ENABLE_WINRT
McgTypeHelpers.TypeToTypeName(type, out nativeTypeName, out nativeTypeKind);
#else
throw new NotSupportedException("TypeToTypeName");
#endif
}
/// <summary>
/// Fetch type name
/// </summary>
/// <param name="typeHandle">type</param>
/// <returns>type name</returns>
internal static string TypeToTypeName(RuntimeTypeHandle typeHandle, out int nativeTypeKind)
{
#if ENABLE_WINRT
TypeKind typekind;
string typeName;
McgTypeHelpers.TypeToTypeName(typeHandle, out typeName, out typekind);
nativeTypeKind = (int)typekind;
return typeName;
#else
throw new NotSupportedException("TypeToTypeName");
#endif
}
#endregion
#region String marshalling
[CLSCompliant(false)]
public static unsafe void StringBuilderToUnicodeString(System.Text.StringBuilder stringBuilder, ushort* destination)
{
PInvokeMarshal.StringBuilderToUnicodeString(stringBuilder, destination);
}
[CLSCompliant(false)]
public static unsafe void UnicodeStringToStringBuilder(ushort* newBuffer, System.Text.StringBuilder stringBuilder)
{
PInvokeMarshal.UnicodeStringToStringBuilder(newBuffer, stringBuilder);
}
#if !RHTESTCL
[CLSCompliant(false)]
public static unsafe void StringBuilderToAnsiString(System.Text.StringBuilder stringBuilder, byte* pNative,
bool bestFit, bool throwOnUnmappableChar)
{
PInvokeMarshal.StringBuilderToAnsiString(stringBuilder, pNative, bestFit, throwOnUnmappableChar);
}
[CLSCompliant(false)]
public static unsafe void AnsiStringToStringBuilder(byte* newBuffer, System.Text.StringBuilder stringBuilder)
{
PInvokeMarshal.AnsiStringToStringBuilder(newBuffer, stringBuilder);
}
/// <summary>
/// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG
/// </summary>
/// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string.
/// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling
/// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks>
[CLSCompliant(false)]
public static unsafe string AnsiStringToString(byte* pchBuffer)
{
return PInvokeMarshal.AnsiStringToString(pchBuffer);
}
/// <summary>
/// Convert UNICODE string to ANSI string.
/// </summary>
/// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that
/// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks>
[CLSCompliant(false)]
public static unsafe byte* StringToAnsiString(string str, bool bestFit, bool throwOnUnmappableChar)
{
return PInvokeMarshal.StringToAnsiString(str, bestFit, throwOnUnmappableChar);
}
/// <summary>
/// Convert UNICODE wide char array to ANSI ByVal byte array.
/// </summary>
/// <remarks>
/// * This version works with array instead string, it means that there will be NO NULL to terminate the array.
/// * The buffer to store the byte array must be allocated by the caller and must fit managedArray.Length.
/// </remarks>
/// <param name="managedArray">UNICODE wide char array</param>
/// <param name="pNative">Allocated buffer where the ansi characters must be placed. Could NOT be null. Buffer size must fit char[].Length.</param>
[CLSCompliant(false)]
public static unsafe void ByValWideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, int expectedCharCount,
bool bestFit, bool throwOnUnmappableChar)
{
PInvokeMarshal.ByValWideCharArrayToAnsiCharArray(managedArray, pNative, expectedCharCount, bestFit, throwOnUnmappableChar);
}
[CLSCompliant(false)]
public static unsafe void ByValAnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray)
{
PInvokeMarshal.ByValAnsiCharArrayToWideCharArray(pNative, managedArray);
}
[CLSCompliant(false)]
public static unsafe void WideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, bool bestFit, bool throwOnUnmappableChar)
{
PInvokeMarshal.WideCharArrayToAnsiCharArray(managedArray, pNative, bestFit, throwOnUnmappableChar);
}
/// <summary>
/// Convert ANSI ByVal byte array to UNICODE wide char array, best fit
/// </summary>
/// <remarks>
/// * This version works with array instead to string, it means that the len must be provided and there will be NO NULL to
/// terminate the array.
/// * The buffer to the UNICODE wide char array must be allocated by the caller.
/// </remarks>
/// <param name="pNative">Pointer to the ANSI byte array. Could NOT be null.</param>
/// <param name="lenInBytes">Maximum buffer size.</param>
/// <param name="managedArray">Wide char array that has already been allocated.</param>
[CLSCompliant(false)]
public static unsafe void AnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray)
{
PInvokeMarshal.AnsiCharArrayToWideCharArray(pNative, managedArray);
}
/// <summary>
/// Convert a single UNICODE wide char to a single ANSI byte.
/// </summary>
/// <param name="managedArray">single UNICODE wide char value</param>
public static unsafe byte WideCharToAnsiChar(char managedValue, bool bestFit, bool throwOnUnmappableChar)
{
return PInvokeMarshal.WideCharToAnsiChar(managedValue, bestFit, throwOnUnmappableChar);
}
/// <summary>
/// Convert a single ANSI byte value to a single UNICODE wide char value, best fit.
/// </summary>
/// <param name="nativeValue">Single ANSI byte value.</param>
public static unsafe char AnsiCharToWideChar(byte nativeValue)
{
return PInvokeMarshal.AnsiCharToWideChar(nativeValue);
}
/// <summary>
/// Convert UNICODE string to ANSI ByVal string.
/// </summary>
/// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that
/// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks>
/// <param name="str">Unicode string.</param>
/// <param name="pNative"> Allocated buffer where the ansi string must be placed. Could NOT be null. Buffer size must fit str.Length.</param>
[CLSCompliant(false)]
public static unsafe void StringToByValAnsiString(string str, byte* pNative, int charCount, bool bestFit, bool throwOnUnmappableChar)
{
PInvokeMarshal.StringToByValAnsiString(str, pNative, charCount, bestFit, throwOnUnmappableChar);
}
/// <summary>
/// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG
/// </summary>
/// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string.
/// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling
/// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks>
[CLSCompliant(false)]
public static unsafe string ByValAnsiStringToString(byte* pchBuffer, int charCount)
{
return PInvokeMarshal.ByValAnsiStringToString(pchBuffer, charCount);
}
#endif
#if ENABLE_MIN_WINRT
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static unsafe HSTRING StringToHString(string sourceString)
{
if (sourceString == null)
throw new ArgumentNullException(nameof(sourceString), SR.Null_HString);
return StringToHStringInternal(sourceString);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static unsafe HSTRING StringToHStringForField(string sourceString)
{
#if !RHTESTCL
if (sourceString == null)
throw new MarshalDirectiveException(SR.BadMarshalField_Null_HString);
#endif
return StringToHStringInternal(sourceString);
}
private static unsafe HSTRING StringToHStringInternal(string sourceString)
{
HSTRING ret;
int hr = StringToHStringNoNullCheck(sourceString, &ret);
if (hr < 0)
throw Marshal.GetExceptionForHR(hr);
return ret;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
internal static unsafe int StringToHStringNoNullCheck(string sourceString, HSTRING* hstring)
{
fixed (char* pChars = sourceString)
{
int hr = ExternalInterop.WindowsCreateString(pChars, (uint)sourceString.Length, (void*)hstring);
return hr;
}
}
#endif //ENABLE_MIN_WINRT
#endregion
#region COM marshalling
/// <summary>
/// Explicit AddRef for RCWs
/// You can't call IFoo.AddRef anymore as IFoo no longer derive from IUnknown
/// You need to call McgMarshal.AddRef();
/// </summary>
/// <remarks>
/// Used by prefast MCG plugin (mcgimportpft) only
/// </remarks>
[CLSCompliant(false)]
public static int AddRef(__ComObject obj)
{
return obj.AddRef();
}
/// <summary>
/// Explicit Release for RCWs
/// You can't call IFoo.Release anymore as IFoo no longer derive from IUnknown
/// You need to call McgMarshal.Release();
/// </summary>
/// <remarks>
/// Used by prefast MCG plugin (mcgimportpft) only
/// </remarks>
[CLSCompliant(false)]
public static int Release(__ComObject obj)
{
return obj.Release();
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static unsafe int ComAddRef(IntPtr pComItf)
{
return CalliIntrinsics.StdCall__AddRef(((__com_IUnknown*)(void*)pComItf)->pVtable->
pfnAddRef, pComItf);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static unsafe int ComRelease_StdCall(IntPtr pComItf)
{
return CalliIntrinsics.StdCall__Release(((__com_IUnknown*)(void*)pComItf)->pVtable->
pfnRelease, pComItf);
}
/// <summary>
/// Inline version of ComRelease
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)] //reduces MCG-generated code size
public static unsafe int ComRelease(IntPtr pComItf)
{
IntPtr pRelease = ((__com_IUnknown*)(void*)pComItf)->pVtable->pfnRelease;
// Check if the COM object is implemented by PN Interop code, for which we can call directly
if (pRelease == AddrOfIntrinsics.AddrOf<AddrOfRelease>(__vtable_IUnknown.Release))
{
return __interface_ccw.DirectRelease(pComItf);
}
// Normal slow path, do not inline
return ComRelease_StdCall(pComItf);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static unsafe int ComSafeRelease(IntPtr pComItf)
{
if (pComItf != default(IntPtr))
{
return ComRelease(pComItf);
}
return 0;
}
public static int FinalReleaseComObject(object o)
{
if (o == null)
throw new ArgumentNullException(nameof(o));
__ComObject co = null;
// Make sure the obj is an __ComObject.
try
{
co = (__ComObject)o;
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
}
co.FinalReleaseSelf();
return 0;
}
/// <summary>
/// Returns the cached WinRT factory RCW under the current context
/// </summary>
[CLSCompliant(false)]
public static unsafe __ComObject GetActivationFactory(string className, RuntimeTypeHandle factoryIntf)
{
#if ENABLE_MIN_WINRT
return FactoryCache.Get().GetActivationFactory(className, factoryIntf);
#else
throw new PlatformNotSupportedException("GetActivationFactory");
#endif
}
/// <summary>
/// Used by CCW infrastructure code to return the target object from this pointer
/// </summary>
/// <returns>The target object pointed by this pointer</returns>
public static object ThisPointerToTargetObject(IntPtr pUnk)
{
return ComCallableObject.GetTarget(pUnk);
}
[CLSCompliant(false)]
public static object ComInterfaceToObject_NoUnboxing(
IntPtr pComItf,
RuntimeTypeHandle interfaceType)
{
return McgComHelpers.ComInterfaceToObjectInternal(
pComItf,
interfaceType,
default(RuntimeTypeHandle),
McgComHelpers.CreateComObjectFlags.SkipTypeResolutionAndUnboxing
);
}
/// <summary>
/// Shared CCW Interface To Object
/// </summary>
/// <param name="pComItf"></param>
/// <param name="interfaceType"></param>
/// <param name="classTypeInSignature"></param>
/// <returns></returns>
[CLSCompliant(false)]
public static object ComInterfaceToObject(
System.IntPtr pComItf,
RuntimeTypeHandle interfaceType,
RuntimeTypeHandle classTypeInSignature)
{
#if ENABLE_MIN_WINRT
if (interfaceType.Equals(typeof(object).TypeHandle))
{
return McgMarshal.IInspectableToObject(pComItf);
}
if (interfaceType.Equals(typeof(System.String).TypeHandle))
{
return McgMarshal.HStringToString(pComItf);
}
if (interfaceType.IsComClass())
{
RuntimeTypeHandle defaultInterface = interfaceType.GetDefaultInterface();
Debug.Assert(!defaultInterface.IsNull());
return ComInterfaceToObjectInternal(pComItf, defaultInterface, interfaceType);
}
#endif
return ComInterfaceToObjectInternal(
pComItf,
interfaceType,
classTypeInSignature
);
}
[CLSCompliant(false)]
public static object ComInterfaceToObject(
IntPtr pComItf,
RuntimeTypeHandle interfaceType)
{
return ComInterfaceToObject(pComItf, interfaceType, default(RuntimeTypeHandle));
}
private static object ComInterfaceToObjectInternal(
IntPtr pComItf,
RuntimeTypeHandle interfaceType,
RuntimeTypeHandle classTypeInSignature)
{
object result = McgComHelpers.ComInterfaceToObjectInternal(pComItf, interfaceType, classTypeInSignature, McgComHelpers.CreateComObjectFlags.None);
//
// Make sure the type we returned is actually of the right type
// NOTE: Don't pass null to IsInstanceOfClass as it'll return false
//
if (!classTypeInSignature.IsNull() && result != null)
{
if (!InteropExtensions.IsInstanceOfClass(result, classTypeInSignature))
throw new InvalidCastException();
}
return result;
}
public static unsafe IntPtr ComQueryInterfaceNoThrow(IntPtr pComItf, ref Guid iid)
{
int hr = 0;
return ComQueryInterfaceNoThrow(pComItf, ref iid, out hr);
}
public static unsafe IntPtr ComQueryInterfaceNoThrow(IntPtr pComItf, ref Guid iid, out int hr)
{
IntPtr pComIUnk;
hr = ComQueryInterfaceWithHR(pComItf, ref iid, out pComIUnk);
return pComIUnk;
}
internal static unsafe int ComQueryInterfaceWithHR(IntPtr pComItf, ref Guid iid, out IntPtr ppv)
{
IntPtr pComIUnk;
int hr;
fixed (Guid* unsafe_iid = &iid)
{
hr = CalliIntrinsics.StdCall__QueryInterface(((__com_IUnknown*)(void*)pComItf)->pVtable->
pfnQueryInterface,
pComItf,
new IntPtr(unsafe_iid),
new IntPtr(&pComIUnk));
}
if (hr != 0)
{
ppv = default(IntPtr);
}
else
{
ppv = pComIUnk;
}
return hr;
}
/// <summary>
/// Helper function to copy vTable to native heap on CoreCLR.
/// </summary>
/// <typeparam name="T">Vtbl type</typeparam>
/// <param name="pVtbl">static v-table field , always a valid pointer</param>
/// <param name="pNativeVtbl">Pointer to Vtable on native heap on CoreCLR , on N it's an alias for pVtbl</param>
public static unsafe IntPtr GetCCWVTableCopy(void* pVtbl, ref IntPtr pNativeVtbl, int size)
{
if (pNativeVtbl == default(IntPtr))
{
#if CORECLR
// On CoreCLR copy vTable to native heap , on N VTable is frozen.
IntPtr pv = Marshal.AllocHGlobal(size);
int* pSrc = (int*)pVtbl;
int* pDest = (int*)pv.ToPointer();
int pSize = sizeof(int);
// this should never happen , if a CCW is discarded we never get here.
Debug.Assert(size >= pSize);
for (int i = 0; i < size; i += pSize)
{
*pDest++ = *pSrc++;
}
if (Interlocked.CompareExchange(ref pNativeVtbl, pv, default(IntPtr)) != default(IntPtr))
{
// Another thread sneaked-in and updated pNativeVtbl , just use the update from other thread
Marshal.FreeHGlobal(pv);
}
#else // .NET NATIVE
// Wrap it in an IntPtr
pNativeVtbl = (IntPtr)pVtbl;
#endif // CORECLR
}
return pNativeVtbl;
}
[CLSCompliant(false)]
public static IntPtr ObjectToComInterface(
object obj,
RuntimeTypeHandle typeHnd)
{
#if ENABLE_MIN_WINRT
if (typeHnd.Equals(typeof(object).TypeHandle))
{
return McgMarshal.ObjectToIInspectable(obj);
}
if (typeHnd.Equals(typeof(System.String).TypeHandle))
{
return McgMarshal.StringToHString((string)obj).handle;
}
if (typeHnd.IsComClass())
{
// This code path should be executed only for WinRT classes
typeHnd = typeHnd.GetDefaultInterface();
Debug.Assert(!typeHnd.IsNull());
}
#endif
return McgComHelpers.ObjectToComInterfaceInternal(
obj,
typeHnd
);
}
public static IntPtr ObjectToIInspectable(Object obj)
{
#if ENABLE_MIN_WINRT
return ObjectToComInterface(obj, InternalTypes.IInspectable);
#else
throw new PlatformNotSupportedException("ObjectToIInspectable");
#endif
}
// This is not a safe function to use for any funtion pointers that do not point
// at a static function. This is due to the behavior of shared generics,
// where instance function entry points may share the exact same address
// but static functions are always represented in delegates with customized
// stubs.
private static bool DelegateTargetMethodEquals(Delegate del, IntPtr pfn)
{
RuntimeTypeHandle thDummy;
return del.GetFunctionPointer(out thDummy) == pfn;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static IntPtr DelegateToComInterface(Delegate del, RuntimeTypeHandle typeHnd)
{
if (del == null)
return default(IntPtr);
IntPtr stubFunctionAddr = typeHnd.GetDelegateInvokeStub();
object targetObj;
//
// If the delegate points to the forward stub for the native delegate,
// then we want the RCW associated with the native interface. Otherwise,
// this is a managed delegate, and we want the CCW associated with it.
//
if (DelegateTargetMethodEquals(del, stubFunctionAddr))
targetObj = del.Target;
else
targetObj = del;
return McgMarshal.ObjectToComInterface(targetObj, typeHnd);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Delegate ComInterfaceToDelegate(IntPtr pComItf, RuntimeTypeHandle typeHnd)
{
if (pComItf == default(IntPtr))
return null;
object obj = ComInterfaceToObject(pComItf, typeHnd, /* classIndexInSignature */ default(RuntimeTypeHandle));
//
// If the object we got back was a managed delegate, then we're good. Otherwise,
// the object is an RCW for a native delegate, so we need to wrap it with a managed
// delegate that invokes the correct stub.
//
Delegate del = obj as Delegate;
if (del == null)
{
Debug.Assert(obj is __ComObject);
IntPtr stubFunctionAddr = typeHnd.GetDelegateInvokeStub();
del = InteropExtensions.CreateDelegate(
typeHnd,
stubFunctionAddr,
obj,
/*isStatic:*/ true,
/*isVirtual:*/ false,
/*isOpen:*/ false);
}
return del;
}
/// <summary>
/// Marshal array of objects
/// </summary>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
unsafe public static void ObjectArrayToComInterfaceArray(uint len, System.IntPtr* dst, object[] src, RuntimeTypeHandle typeHnd)
{
for (uint i = 0; i < len; i++)
{
dst[i] = McgMarshal.ObjectToComInterface(src[i], typeHnd);
}
}
/// <summary>
/// Allocate native memory, and then marshal array of objects
/// </summary>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
unsafe public static System.IntPtr* ObjectArrayToComInterfaceArrayAlloc(object[] src, RuntimeTypeHandle typeHnd, out uint len)
{
System.IntPtr* dst = null;
len = 0;
if (src != null)
{
len = (uint)src.Length;
dst = (System.IntPtr*)PInvokeMarshal.CoTaskMemAlloc((System.UIntPtr)(len * (sizeof(System.IntPtr))));
for (uint i = 0; i < len; i++)
{
dst[i] = McgMarshal.ObjectToComInterface(src[i], typeHnd);
}
}
return dst;
}
/// <summary>
/// Get outer IInspectable for managed object deriving from native scenario
/// At this point the inner is not created yet - you need the outer first and pass it to the factory
/// to create the inner
/// </summary>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
[CLSCompliant(false)]
public static IntPtr GetOuterIInspectableForManagedObject(__ComObject managedObject)
{
ComCallableObject ccw = null;
try
{
//
// Create the CCW over the RCW
// Note that they are actually both the same object
// Base class = inner
// Derived class = outer
//
ccw = new ComCallableObject(
managedObject, // The target object = managedObject
managedObject // The inner RCW (as __ComObject) = managedObject
);
//
// Retrieve the outer IInspectable
// Pass skipInterfaceCheck = true to avoid redundant checks
//
return ccw.GetComInterfaceForType_NoCheck(InternalTypes.IInspectable, ref Interop.COM.IID_IInspectable);
}
finally
{
//
// Free the extra ref count initialized by __native_ccw.Init (to protect the CCW from being collected)
//
if (ccw != null)
ccw.Release();
}
}
[CLSCompliant(false)]
public static unsafe IntPtr ManagedObjectToComInterface(Object obj, RuntimeTypeHandle interfaceType)
{
return McgComHelpers.ManagedObjectToComInterface(obj, interfaceType);
}
public static unsafe object IInspectableToObject(IntPtr pComItf)
{
#if ENABLE_WINRT
return ComInterfaceToObject(pComItf, InternalTypes.IInspectable);
#else
throw new PlatformNotSupportedException("IInspectableToObject");
#endif
}
public static unsafe IntPtr CoCreateInstanceEx(Guid clsid, string server)
{
#if ENABLE_WINRT
Interop.COM.MULTI_QI results;
IntPtr pResults = new IntPtr(&results);
fixed (Guid* pIID = &Interop.COM.IID_IUnknown)
{
Guid* pClsid = &clsid;
results.pIID = new IntPtr(pIID);
results.pItf = IntPtr.Zero;
results.hr = 0;
int hr;
// if server name is specified, do remote server activation
if (!String.IsNullOrEmpty(server))
{
Interop.COM.COSERVERINFO serverInfo;
fixed (char* pName = server)
{
serverInfo.Name = new IntPtr(pName);
IntPtr pServerInfo = new IntPtr(&serverInfo);
hr = ExternalInterop.CoCreateInstanceFromApp(pClsid, IntPtr.Zero, (int)Interop.COM.CLSCTX.CLSCTX_REMOTE_SERVER, pServerInfo, 1, pResults);
}
}
else
{
hr = ExternalInterop.CoCreateInstanceFromApp(pClsid, IntPtr.Zero, (int)Interop.COM.CLSCTX.CLSCTX_SERVER, IntPtr.Zero, 1, pResults);
}
if (hr < 0)
{
throw McgMarshal.GetExceptionForHR(hr, /*isWinRTScenario = */ false);
}
if (results.hr < 0)
{
throw McgMarshal.GetExceptionForHR(results.hr, /* isWinRTScenario = */ false);
}
return results.pItf;
}
#else
throw new PlatformNotSupportedException("CoCreateInstanceEx");
#endif
}
public static unsafe IntPtr CoCreateInstanceEx(Guid clsid)
{
return CoCreateInstanceEx(clsid, string.Empty);
}
#endregion
#region Testing
/// <summary>
/// Internal-only method to allow testing of apartment teardown code
/// </summary>
public static void ReleaseRCWsInCurrentApartment()
{
ContextEntry.RemoveCurrentContext();
}
/// <summary>
/// Used by detecting leaks
/// Used in prefast MCG only
/// </summary>
public static int GetTotalComObjectCount()
{
return ComObjectCache.s_comObjectMap.Count;
}
/// <summary>
/// Used by detecting and dumping leaks
/// Used in prefast MCG only
/// </summary>
public static IEnumerable<__ComObject> GetAllComObjects()
{
List<__ComObject> list = new List<__ComObject>();
for (int i = 0; i < ComObjectCache.s_comObjectMap.GetMaxCount(); ++i)
{
IntPtr pHandle = default(IntPtr);
if (ComObjectCache.s_comObjectMap.GetValue(i, ref pHandle) && (pHandle != default(IntPtr)))
{
GCHandle handle = GCHandle.FromIntPtr(pHandle);
list.Add(InteropExtensions.UncheckedCast<__ComObject>(handle.Target));
}
}
return list;
}
#endregion
/// <summary>
/// This method returns HR for the exception being thrown.
/// 1. On Windows8+, WinRT scenarios we do the following.
/// a. Check whether the exception has any IRestrictedErrorInfo associated with it.
/// If so, it means that this exception was actually caused by a native exception in which case we do simply use the same
/// message and stacktrace.
/// b. If not, this is actually a managed exception and in this case we RoOriginateLanguageException with the msg, hresult and the IErrorInfo
/// associated with the managed exception. This helps us to retrieve the same exception in case it comes back to native.
/// 2. On win8 and for classic COM scenarios.
/// a. We create IErrorInfo for the given Exception object and SetErrorInfo with the given IErrorInfo.
/// </summary>
/// <param name="ex"></param>
[MethodImpl(MethodImplOptions.NoInlining)]
public static int GetHRForExceptionWinRT(Exception ex)
{
#if ENABLE_WINRT
return ExceptionHelpers.GetHRForExceptionWithErrorPropagationNoThrow(ex, true);
#else
// TODO : ExceptionHelpers should be platform specific , move it to
// seperate source files
return 0;
//return Marshal.GetHRForException(ex);
#endif
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static int GetHRForException(Exception ex)
{
#if ENABLE_WINRT
return ExceptionHelpers.GetHRForExceptionWithErrorPropagationNoThrow(ex, false);
#else
return ex.HResult;
#endif
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void ThrowOnExternalCallFailed(int hr, System.RuntimeTypeHandle typeHnd)
{
bool isWinRTScenario
#if ENABLE_WINRT
= typeHnd.IsSupportIInspectable();
#else
= false;
#endif
throw McgMarshal.GetExceptionForHR(hr, isWinRTScenario);
}
/// <summary>
/// This method returns a new Exception object given the HR value.
/// </summary>
/// <param name="hr"></param>
/// <param name="isWinRTScenario"></param>
public static Exception GetExceptionForHR(int hr, bool isWinRTScenario)
{
#if ENABLE_WINRT
return ExceptionHelpers.GetExceptionForHRInternalNoThrow(hr, isWinRTScenario, !isWinRTScenario);
#elif CORECLR
return Marshal.GetExceptionForHR(hr);
#else
// TODO: Map HR to exeption even without COM interop support?
return new COMException(hr);
#endif
}
#region Shared templates
#if ENABLE_MIN_WINRT
public static void CleanupNative<T>(IntPtr pObject)
{
if (typeof(T) == typeof(string))
{
global::System.Runtime.InteropServices.McgMarshal.FreeHString(pObject);
}
else
{
global::System.Runtime.InteropServices.McgMarshal.ComSafeRelease(pObject);
}
}
#endif
#endregion
#if ENABLE_MIN_WINRT
[MethodImpl(MethodImplOptions.NoInlining)]
public static unsafe IntPtr ActivateInstance(string typeName)
{
__ComObject target = McgMarshal.GetActivationFactory(
typeName,
InternalTypes.IActivationFactoryInternal
);
IntPtr pIActivationFactoryInternalItf = target.QueryInterface_NoAddRef_Internal(
InternalTypes.IActivationFactoryInternal,
/* cacheOnly= */ false,
/* throwOnQueryInterfaceFailure= */ true
);
__com_IActivationFactoryInternal* pIActivationFactoryInternal = (__com_IActivationFactoryInternal*)pIActivationFactoryInternalItf;
IntPtr pResult = default(IntPtr);
int hr = CalliIntrinsics.StdCall__int(
pIActivationFactoryInternal->pVtable->pfnActivateInstance,
pIActivationFactoryInternal,
&pResult
);
GC.KeepAlive(target);
if (hr < 0)
{
throw McgMarshal.GetExceptionForHR(hr, /* isWinRTScenario = */ true);
}
return pResult;
}
#endif
[MethodImpl(MethodImplOptions.NoInlining)]
public static IntPtr GetInterface(
__ComObject obj,
RuntimeTypeHandle typeHnd)
{
return obj.QueryInterface_NoAddRef_Internal(
typeHnd);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static object GetDynamicAdapter(__ComObject obj, RuntimeTypeHandle requestedType, RuntimeTypeHandle existingType)
{
return obj.GetDynamicAdapter(requestedType, existingType);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static object GetDynamicAdapter(__ComObject obj, RuntimeTypeHandle requestedType)
{
return obj.GetDynamicAdapter(requestedType, default(RuntimeTypeHandle));
}
#region "PInvoke Delegate"
public static IntPtr GetStubForPInvokeDelegate(RuntimeTypeHandle delegateType, Delegate dele)
{
#if CORECLR
throw new NotSupportedException();
#else
return PInvokeMarshal.GetFunctionPointerForDelegate(dele);
#endif
}
/// <summary>
/// Retrieve the corresponding P/invoke instance from the stub
/// </summary>
public static Delegate GetPInvokeDelegateForStub(IntPtr pStub, RuntimeTypeHandle delegateType)
{
#if CORECLR
if (pStub == IntPtr.Zero)
return null;
McgPInvokeDelegateData pInvokeDelegateData;
if (!McgModuleManager.GetPInvokeDelegateData(delegateType, out pInvokeDelegateData))
{
return null;
}
return CalliIntrinsics.Call__Delegate(
pInvokeDelegateData.ForwardDelegateCreationStub,
pStub
);
#else
return PInvokeMarshal.GetDelegateForFunctionPointer(pStub, delegateType);
#endif
}
/// <summary>
/// Retrieves the function pointer for the current open static delegate that is being called
/// </summary>
public static IntPtr GetCurrentCalleeOpenStaticDelegateFunctionPointer()
{
#if !RHTESTCL && PROJECTN
return PInvokeMarshal.GetCurrentCalleeOpenStaticDelegateFunctionPointer();
#else
throw new NotSupportedException();
#endif
}
/// <summary>
/// Retrieves the current delegate that is being called
/// </summary>
public static T GetCurrentCalleeDelegate<T>() where T : class // constraint can't be System.Delegate
{
#if !RHTESTCL && PROJECTN
return PInvokeMarshal.GetCurrentCalleeDelegate<T>();
#else
throw new NotSupportedException();
#endif
}
#endregion
}
/// <summary>
/// McgMarshal helpers exposed to be used by MCG
/// </summary>
public static partial class McgMarshal
{
public static object UnboxIfBoxed(object target)
{
return UnboxIfBoxed(target, null);
}
public static object UnboxIfBoxed(object target, string className)
{
//
// If it is a managed wrapper, unbox it
//
object unboxedObj = McgComHelpers.UnboxManagedWrapperIfBoxed(target);
if (unboxedObj != target)
return unboxedObj;
if (className == null)
className = System.Runtime.InteropServices.McgComHelpers.GetRuntimeClassName(target);
if (!String.IsNullOrEmpty(className))
{
IntPtr unboxingStub;
if (McgModuleManager.TryGetUnboxingStub(className, out unboxingStub))
{
object ret = CalliIntrinsics.Call<object>(unboxingStub, target);
if (ret != null)
return ret;
}
#if ENABLE_WINRT
else if(McgModuleManager.UseDynamicInterop)
{
BoxingInterfaceKind boxingInterfaceKind;
RuntimeTypeHandle[] genericTypeArgument;
if (DynamicInteropBoxingHelpers.TryGetBoxingArgumentTypeHandleFromString(className, out boxingInterfaceKind, out genericTypeArgument))
{
Debug.Assert(target is __ComObject);
return DynamicInteropBoxingHelpers.Unboxing(boxingInterfaceKind, genericTypeArgument, target);
}
}
#endif
}
return null;
}
internal static object BoxIfBoxable(object target)
{
return BoxIfBoxable(target, default(RuntimeTypeHandle));
}
/// <summary>
/// Given a boxed value type, return a wrapper supports the IReference interface
/// </summary>
/// <param name="typeHandleOverride">
/// You might want to specify how to box this. For example, any object[] derived array could
/// potentially boxed as object[] if everything else fails
/// </param>
internal static object BoxIfBoxable(object target, RuntimeTypeHandle typeHandleOverride)
{
RuntimeTypeHandle expectedTypeHandle = typeHandleOverride;
if (expectedTypeHandle.Equals(default(RuntimeTypeHandle)))
expectedTypeHandle = target.GetTypeHandle();
RuntimeTypeHandle boxingWrapperType;
IntPtr boxingStub;
int boxingPropertyType;
if (McgModuleManager.TryGetBoxingWrapperType(expectedTypeHandle, target, out boxingWrapperType, out boxingPropertyType, out boxingStub))
{
if (!boxingWrapperType.IsInvalid())
{
//
// IReference<T> / IReferenceArray<T> / IKeyValuePair<K, V>
// All these scenarios require a managed wrapper
//
// Allocate the object
object refImplType = InteropExtensions.RuntimeNewObject(boxingWrapperType);
if (boxingPropertyType >= 0)
{
Debug.Assert(refImplType is BoxedValue);
BoxedValue boxed = InteropExtensions.UncheckedCast<BoxedValue>(refImplType);
// Call ReferenceImpl<T>.Initialize(obj, type);
boxed.Initialize(target, boxingPropertyType);
}
else
{
Debug.Assert(refImplType is BoxedKeyValuePair);
BoxedKeyValuePair boxed = InteropExtensions.UncheckedCast<BoxedKeyValuePair>(refImplType);
// IKeyValuePair<,>, call CLRIKeyValuePairImpl<K,V>.Initialize(object obj);
// IKeyValuePair<,>[], call CLRIKeyValuePairArrayImpl<K,V>.Initialize(object obj);
refImplType = boxed.Initialize(target);
}
return refImplType;
}
else
{
//
// General boxing for projected types, such as System.Uri
//
return CalliIntrinsics.Call<object>(boxingStub, target);
}
}
return null;
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Diagnostics;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Threading;
class UtilityExtension : IExtension<IPeerNeighbor>
{
uint linkUtility;
uint updateCount;
IOThreadTimer ackTimer;
const uint linkUtilityIncrement = 128;
const uint maxLinkUtility = 4096;
int outTotal;
uint inTotal;
uint inUseful;
IPeerNeighbor owner;
object thisLock = new object();
object throttleLock = new object();
public event EventHandler UtilityInfoReceived;
public event EventHandler UtilityInfoSent;
TypedMessageConverter messageConverter;
public const int AcceptableMissDistance = 2;
int pendingSends = 0;
int checkPointPendingSends = 0;
bool isMonitoring = false;
int expectedClearance;
IOThreadTimer pruneTimer;
const int PruneIntervalMilliseconds = 10000;
TimeSpan pruneInterval;
const int MinimumPendingMessages = 8;
public delegate void PruneNeighborCallback(IPeerNeighbor peer);
PruneNeighborCallback pruneNeighbor;
UtilityExtension()
{
ackTimer = new IOThreadTimer(new Action<object>(AcknowledgeLoop), null, false);
pendingSends = 0;
pruneTimer = new IOThreadTimer(new Action<object>(VerifyCheckPoint), null, false);
pruneInterval = TimeSpan.FromMilliseconds(PruneIntervalMilliseconds + new Random(Process.GetCurrentProcess().Id).Next(PruneIntervalMilliseconds));
}
public bool IsAccurate
{
get { return updateCount >= 32; }
}
public uint LinkUtility
{
get
{
return linkUtility;
}
}
internal TypedMessageConverter MessageConverter
{
get
{
if (messageConverter == null)
{
messageConverter = TypedMessageConverter.Create(typeof(UtilityInfo), PeerStrings.LinkUtilityAction);
}
return messageConverter;
}
}
public void Attach(IPeerNeighbor host)
{
this.owner = host;
ackTimer.Set(PeerTransportConstants.AckTimeout);
}
static public void OnNeighborConnected(IPeerNeighbor neighbor)
{
Fx.Assert(neighbor != null, "Neighbor must have a value");
neighbor.Extensions.Add(new UtilityExtension());
}
static public void OnNeighborClosed(IPeerNeighbor neighbor)
{
Fx.Assert(neighbor != null, "Neighbor must have a value");
UtilityExtension ext = neighbor.Extensions.Find<UtilityExtension>();
if (ext != null) neighbor.Extensions.Remove(ext);
}
public void Detach(IPeerNeighbor host)
{
ackTimer.Cancel();
owner = null;
lock (throttleLock)
{
pruneTimer.Cancel();
}
}
public object ThisLock
{
get
{
return thisLock;
}
}
public static void OnMessageSent(IPeerNeighbor neighbor)
{
UtilityExtension ext = neighbor.Extensions.Find<UtilityExtension>();
if (ext != null) ext.OnMessageSent();
}
void OnMessageSent()
{
lock (ThisLock)
{
outTotal++;
}
Interlocked.Increment(ref pendingSends);
}
public static void OnEndSend(IPeerNeighbor neighbor, FloodAsyncResult fresult)
{
if (neighbor.State >= PeerNeighborState.Disconnecting)
return;
UtilityExtension instance = neighbor.Utility;
if (instance == null)
return;
instance.OnEndSend(fresult);
}
public void OnEndSend(FloodAsyncResult fresult)
{
Interlocked.Decrement(ref pendingSends);
}
void AcknowledgeLoop(object state)
{
IPeerNeighbor peer = owner;
if (peer == null || !peer.IsConnected)
return;
FlushAcknowledge();
if (owner != null)
ackTimer.Set(PeerTransportConstants.AckTimeout);
}
static public void ProcessLinkUtility(IPeerNeighbor neighbor, UtilityInfo umessage)
{
Fx.Assert(neighbor != null, "Neighbor must have a value");
UtilityExtension ext = neighbor.Extensions.Find<UtilityExtension>();
if (ext != null)
{
ext.ProcessLinkUtility(umessage.Useful, umessage.Total);
}
}
// Update link utility for the neighbor. received from the neighbor
void ProcessLinkUtility(uint useful, uint total)
{
uint i = 0;
lock (ThisLock)
{
if (total > PeerTransportConstants.AckWindow
|| useful > total
|| (uint)outTotal < total
)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.PeerLinkUtilityInvalidValues, useful, total)));
}
//VERIFY with in this range, we are hoping that the order of useful/useless messages doesnt matter much.
for (i = 0; i < useful; i++)
{
this.linkUtility = Calculate(this.linkUtility, true);
}
for (; i < total; i++)
{
this.linkUtility = Calculate(this.linkUtility, false);
}
outTotal -= (int)total;
}
if (UtilityInfoReceived != null)
{
UtilityInfoReceived(this, EventArgs.Empty);
}
}
uint Calculate(uint current, bool increase)
{
uint utility = 0;
// Refer to graph maintenance white paper for explanation of the formula
// used to compute utility index.
utility = (uint)current * 31 / 32;
if (increase)
utility += linkUtilityIncrement;
if (!(utility <= maxLinkUtility))
{
throw Fx.AssertAndThrow("Link utility should not exceed " + maxLinkUtility);
}
if (!IsAccurate)
++updateCount;
return utility;
}
public static uint UpdateLinkUtility(IPeerNeighbor neighbor, bool useful)
{
Fx.Assert(neighbor != null, "Neighbor must have a value");
uint linkUtility = 0;
UtilityExtension ext = neighbor.Extensions.Find<UtilityExtension>();
if (ext != null)
{
// Can happen if the neighbor has been closed for instance
linkUtility = ext.UpdateLinkUtility(useful);
}
return linkUtility;
}
public uint UpdateLinkUtility(bool useful)
{
lock (ThisLock)
{
inTotal++;
if (useful)
inUseful++;
linkUtility = Calculate(linkUtility, useful);
if (inTotal == PeerTransportConstants.AckWindow)
{
FlushAcknowledge();
}
}
return linkUtility;
}
public void FlushAcknowledge()
{
if (inTotal == 0)
return;
uint tempUseful = 0, tempTotal = 0;
lock (ThisLock)
{
tempUseful = inUseful;
tempTotal = inTotal;
inUseful = 0;
inTotal = 0;
}
SendUtilityMessage(tempUseful, tempTotal);
}
class AsyncUtilityState
{
public Message message;
public UtilityInfo info;
public AsyncUtilityState(Message message, UtilityInfo info)
{
this.message = message;
this.info = info;
}
}
void SendUtilityMessage(uint useful, uint total)
{
IPeerNeighbor host = owner;
if (host == null || !PeerNeighborStateHelper.IsConnected(host.State) || total == 0)
return;
UtilityInfo umessage = new UtilityInfo(useful, total);
IAsyncResult result = null;
Message message = MessageConverter.ToMessage(umessage, MessageVersion.Soap12WSAddressing10);
bool fatal = false;
try
{
result = host.BeginSend(message, Fx.ThunkCallback(new AsyncCallback(UtilityMessageSent)), new AsyncUtilityState(message, umessage));
if (result.CompletedSynchronously)
{
host.EndSend(result);
EventHandler handler = UtilityInfoSent;
if (handler != null)
handler(this, EventArgs.Empty);
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
fatal = true;
throw;
}
if (null != HandleSendException(host, e, umessage))
throw;
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
}
finally
{
if (!fatal && (result == null || result.CompletedSynchronously))
message.Close();
}
}
void UtilityMessageSent(IAsyncResult result)
{
if (result == null || result.AsyncState == null)
return;
IPeerNeighbor host = this.owner;
if (host == null || !PeerNeighborStateHelper.IsConnected(host.State))
return;
if (result.CompletedSynchronously)
return;
AsyncUtilityState state = (AsyncUtilityState)result.AsyncState;
Fx.Assert(state != null, "IAsyncResult.AsyncState does not contain AsyncUtilityState");
Message message = state.message;
UtilityInfo umessage = state.info;
bool fatal = false;
if (!(umessage != null))
{
throw Fx.AssertAndThrow("expecting a UtilityInfo message in the AsyncState!");
}
try
{
host.EndSend(result);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
fatal = true;
throw;
}
if (null != HandleSendException(host, e, umessage))
throw;
DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
}
finally
{
if (!fatal)
{
Fx.Assert(!result.CompletedSynchronously, "result.CompletedSynchronously");
message.Close();
}
}
EventHandler handler = UtilityInfoSent;
if (handler != null)
handler(this, EventArgs.Empty);
}
Exception HandleSendException(IPeerNeighbor host, Exception e, UtilityInfo umessage)
{
if ((e is ObjectDisposedException) ||
(e is TimeoutException) ||
(e is CommunicationException))
{
if (!(!(e.InnerException is QuotaExceededException)))
{
throw Fx.AssertAndThrow("insufficient quota for sending messages!");
}
lock (ThisLock)
{
this.inTotal += umessage.Total;
this.inUseful += umessage.Useful;
}
return null;
}
else
{
return e;
}
}
static internal void ReportCacheMiss(IPeerNeighbor neighbor, int missedBy)
{
Fx.Assert(missedBy > AcceptableMissDistance, "Call this method for cache misses ONLY!");
Fx.Assert(neighbor != null, "Neighbor must have a value");
if (!neighbor.IsConnected)
return;
UtilityExtension ext = neighbor.Extensions.Find<UtilityExtension>();
if (ext != null)
{
ext.ReportCacheMiss(missedBy);
}
}
void ReportCacheMiss(int missedBy)
{
lock (ThisLock)
{
for (int i = 0; i < missedBy; i++)
{
this.linkUtility = Calculate(this.linkUtility, false);
}
}
}
public int PendingMessages
{
get
{
return this.pendingSends;
}
}
public void BeginCheckPoint(PruneNeighborCallback pruneCallback)
{
if (this.isMonitoring)
return;
lock (throttleLock)
{
if (this.isMonitoring)
return;
this.checkPointPendingSends = this.pendingSends;
this.pruneNeighbor = pruneCallback;
this.expectedClearance = this.pendingSends / 2;
this.isMonitoring = true;
if (owner == null)
return;
pruneTimer.Set(pruneInterval);
}
}
void VerifyCheckPoint(object state)
{
int lclPendingSends;
int lclCheckPointPendingSends;
IPeerNeighbor peer = (IPeerNeighbor)owner;
if (peer == null || !peer.IsConnected)
return;
lock (throttleLock)
{
lclPendingSends = this.pendingSends;
lclCheckPointPendingSends = this.checkPointPendingSends;
}
if (lclPendingSends <= MinimumPendingMessages)
{
lock (throttleLock)
{
isMonitoring = false;
}
}
else if (lclPendingSends + this.expectedClearance >= lclCheckPointPendingSends)
{
pruneNeighbor(peer);
}
else
{
lock (throttleLock)
{
if (owner == null)
return;
this.checkPointPendingSends = this.pendingSends;
this.expectedClearance = this.expectedClearance / 2;
pruneTimer.Set(pruneInterval);
}
}
}
}
}
| |
// Copyright 2018 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 Android.App;
using Android.OS;
using Android.Widget;
using Esri.ArcGISRuntime.ArcGISServices;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
namespace ArcGISRuntime.Samples.MapImageLayerTables
{
[Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Map image layer tables",
category: "Layers",
description: "Find features in a spatial table related to features in a non-spatial table.",
instructions: "Once the map image layer loads, a list view will be populated with comment data from non-spatial features. Tap on one of the comments to query related spatial features and display the first result on the map.",
tags: new[] { "features", "query", "related features", "search" })]
[ArcGISRuntime.Samples.Shared.Attributes.AndroidLayoutAttribute("MapImageLayerTables.axml")]
public class MapImageLayerTables : Activity
{
// Hold a reference to the map view.
private MapView _myMapView;
// A graphics overlay for showing selected features.
private GraphicsOverlay _selectedFeaturesOverlay;
// A list view to show all service request comments.
private ListView _commentsListBox;
// A list to hold service request comments.
private List<Feature> _commentFeatures = new List<Feature>();
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "Query map image layer tables";
// Create the UI.
CreateLayout();
// Initialize the map and show the list of comments.
Initialize();
}
private async void Initialize()
{
try
{
// Create a new Map with a streets basemap.
Map myMap = new Map(BasemapStyle.ArcGISStreets);
// Create the URI to the Service Requests map service.
Uri serviceRequestUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/ServiceRequest/MapServer");
// Create a new ArcGISMapImageLayer that uses the service URI.
ArcGISMapImageLayer serviceRequestsMapImageLayer = new ArcGISMapImageLayer(serviceRequestUri);
// Load all sublayers and tables contained by the map image layer.
await serviceRequestsMapImageLayer.LoadTablesAndLayersAsync();
// Set the initial map extent to the extent of all service request features.
Envelope requestsExtent = serviceRequestsMapImageLayer.FullExtent;
myMap.InitialViewpoint = new Viewpoint(requestsExtent);
// Add the layer to the map.
myMap.OperationalLayers.Add(serviceRequestsMapImageLayer);
// Get the service request comments table from the map image layer.
ServiceFeatureTable commentsTable = serviceRequestsMapImageLayer.Tables[0];
// Create query parameters to get all non-null service request comment records (features) from the table.
QueryParameters queryToGetNonNullComments = new QueryParameters
{
WhereClause = "requestid <> '' AND comments <> ''"
};
// Query the comments table to get the non-null records.
FeatureQueryResult commentQueryResult = await commentsTable.QueryFeaturesAsync(queryToGetNonNullComments, QueryFeatureFields.LoadAll);
// Store the comments in a list.
_commentFeatures = commentQueryResult.ToList();
// Show the comment text from the service request comments records in the list view control.
IEnumerable<object> comments = _commentFeatures.Select(c => c.Attributes["comments"]);
ArrayAdapter commentsAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, comments.ToArray());
_commentsListBox.Adapter = commentsAdapter;
// Create a graphics overlay to show selected features and add it to the map view.
_selectedFeaturesOverlay = new GraphicsOverlay();
_myMapView.GraphicsOverlays.Add(_selectedFeaturesOverlay);
// Assign the map to the MapView.
_myMapView.Map = myMap;
}
catch (Exception e)
{
new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show();
}
}
private void CreateLayout()
{
// Load the UI layout from an .axml file in the project resources.
SetContentView(Resource.Layout.MapImageLayerTables);
// Update control references to point to the controls defined in the layout.
_myMapView = FindViewById<MapView>(Resource.Id.mapImageLayerTables_MyMapView);
// List view for displaying rows from the comments table.
_commentsListBox = FindViewById<ListView>(Resource.Id.mapImageLayerTables_commentListView);
// Handle an item (comment) being clicked in the list.
_commentsListBox.ItemClick += CommentsListBox_ItemClick;
}
// When a comment is clicked, get the related feature (service request) and select it on the map.
private async void CommentsListBox_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
// Clear selected features from the graphics overlay.
_selectedFeaturesOverlay.Graphics.Clear();
// Get the clicked record (ArcGISFeature) using the list position. If one is not found, return.
ArcGISFeature selectedComment = _commentFeatures[e.Position] as ArcGISFeature;
if (selectedComment == null) { return; }
// Get the map image layer that contains the service request sublayer and the service request comments table.
ArcGISMapImageLayer serviceRequestsMapImageLayer = (ArcGISMapImageLayer)_myMapView.Map.OperationalLayers[0];
// Get the (non-spatial) table that contains the service request comments.
ServiceFeatureTable commentsTable = serviceRequestsMapImageLayer.Tables[0];
// Get the relationship that defines related service request features to features in the comments table (this is the first and only relationship).
RelationshipInfo commentsRelationshipInfo = commentsTable.LayerInfo.RelationshipInfos.FirstOrDefault();
// Create query parameters to get the related service request for features in the comments table.
RelatedQueryParameters relatedQueryParams = new RelatedQueryParameters(commentsRelationshipInfo)
{
ReturnGeometry = true
};
try
{
// Query the comments table to get the related service request feature for the selected comment.
IReadOnlyList<RelatedFeatureQueryResult> relatedRequestsResult = await commentsTable.QueryRelatedFeaturesAsync(selectedComment, relatedQueryParams);
// Get the first result.
RelatedFeatureQueryResult result = relatedRequestsResult.FirstOrDefault();
// Get the first feature from the result. If it's null, warn the user and return.
ArcGISFeature serviceRequestFeature = result.FirstOrDefault() as ArcGISFeature;
if (serviceRequestFeature == null)
{
// Report to the user that a related feature was not found, then return.
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
AlertDialog alert = alertBuilder.Create();
alert.SetMessage("Related feature not found.");
alert.Show();
return;
}
// Load the related service request feature (so its geometry is available).
await serviceRequestFeature.LoadAsync();
// Get the service request geometry (point).
MapPoint serviceRequestPoint = serviceRequestFeature.Geometry as MapPoint;
// Create a cyan marker symbol to display the related feature.
Symbol selectedRequestSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Cyan, 14);
// Create a graphic using the service request point and marker symbol.
Graphic requestGraphic = new Graphic(serviceRequestPoint, selectedRequestSymbol);
// Add the graphic to the graphics overlay and zoom the map view to its extent.
_selectedFeaturesOverlay.Graphics.Add(requestGraphic);
await _myMapView.SetViewpointCenterAsync(serviceRequestPoint, 150000);
}
catch (Exception ex)
{
new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class GroupJoinTests : EnumerableTests
{
public struct CustomerRec
{
public string name;
public int? custID;
}
public struct OrderRec
{
public int? orderID;
public int? custID;
public int? total;
}
public struct AnagramRec
{
public string name;
public int? orderID;
public int? total;
}
public struct JoinRec : IEquatable<JoinRec>
{
public string name;
public int?[] orderID;
public int?[] total;
public override int GetHashCode()
{
// Not great, but it'll serve.
return name.GetHashCode() ^ orderID.Length ^ (total.Length * 31);
}
public bool Equals(JoinRec other)
{
if (!string.Equals(name, other.name)) return false;
if (orderID == null)
{
if (other.orderID != null) return false;
}
else
{
if (other.orderID == null) return false;
if (orderID.Length != other.orderID.Length) return false;
for (int i = 0; i != other.orderID.Length; ++i)
if (orderID[i] != other.orderID[i]) return false;
}
if (total == null)
{
if (other.total != null) return false;
}
else
{
if (other.total == null) return false;
if (total.Length != other.total.Length) return false;
for (int i = 0; i != other.total.Length; ++i)
if (total[i] != other.total[i]) return false;
}
return true;
}
public override bool Equals(object obj)
{
return obj is JoinRec && Equals((JoinRec)obj);
}
}
public static JoinRec createJoinRec(CustomerRec cr, IEnumerable<OrderRec> orIE)
{
return new JoinRec
{
name = cr.name,
orderID = orIE.Select(o => o.orderID).ToArray(),
total = orIE.Select(o => o.total).ToArray(),
};
}
public static JoinRec createJoinRec(CustomerRec cr, IEnumerable<AnagramRec> arIE)
{
return new JoinRec
{
name = cr.name,
orderID = arIE.Select(o => o.orderID).ToArray(),
total = arIE.Select(o => o.total).ToArray(),
};
}
[Fact]
public void OuterEmptyInnerNonEmpty()
{
CustomerRec[] outer = { };
OrderRec[] inner = new []
{
new OrderRec{ orderID = 45321, custID = 98022, total = 50 },
new OrderRec{ orderID = 97865, custID = 32103, total = 25 }
};
Assert.Empty(outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec));
}
[Fact]
public void CustomComparer()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Tim", custID = 1234 },
new CustomerRec{ name = "Bob", custID = 9865 },
new CustomerRec{ name = "Robert", custID = 9895 }
};
AnagramRec[] inner = new []
{
new AnagramRec{ name = "Robert", orderID = 93483, total = 19 },
new AnagramRec{ name = "miT", orderID = 93489, total = 45 }
};
JoinRec[] expected = new []
{
new JoinRec{ name = "Tim", orderID = new int?[]{ 93489 }, total = new int?[]{ 45 } },
new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } },
new JoinRec{ name = "Robert", orderID = new int?[]{ 93483 }, total = new int?[]{ 19 } }
};
Assert.Equal(expected, outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec, new AnagramEqualityComparer()));
}
[Fact]
public void OuterNull()
{
CustomerRec[] outer = null;
AnagramRec[] inner = new AnagramRec[]
{
new AnagramRec{ name = "Robert", orderID = 93483, total = 19 },
new AnagramRec{ name = "miT", orderID = 93489, total = 45 }
};
Assert.Throws<ArgumentNullException>("outer", () => outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec, new AnagramEqualityComparer()));
}
[Fact]
public void InnerNull()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Tim", custID = 1234 },
new CustomerRec{ name = "Bob", custID = 9865 },
new CustomerRec{ name = "Robert", custID = 9895 }
};
AnagramRec[] inner = null;
Assert.Throws<ArgumentNullException>("inner", () => outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec, new AnagramEqualityComparer()));
}
[Fact]
public void OuterKeySelectorNull()
{
CustomerRec[] outer = new CustomerRec[]
{
new CustomerRec{ name = "Tim", custID = 1234 },
new CustomerRec{ name = "Bob", custID = 9865 },
new CustomerRec{ name = "Robert", custID = 9895 }
};
AnagramRec[] inner = new AnagramRec[]
{
new AnagramRec{ name = "Robert", orderID = 93483, total = 19 },
new AnagramRec{ name = "miT", orderID = 93489, total = 45 }
};
Assert.Throws<ArgumentNullException>("outerKeySelector", () => outer.GroupJoin(inner, null, e => e.name, createJoinRec, new AnagramEqualityComparer()));
}
[Fact]
public void InnerKeySelectorNull()
{
CustomerRec[] outer = new CustomerRec[]
{
new CustomerRec{ name = "Tim", custID = 1234 },
new CustomerRec{ name = "Bob", custID = 9865 },
new CustomerRec{ name = "Robert", custID = 9895 }
};
AnagramRec[] inner = new AnagramRec[]
{
new AnagramRec{ name = "Robert", orderID = 93483, total = 19 },
new AnagramRec{ name = "miT", orderID = 93489, total = 45 }
};
Assert.Throws<ArgumentNullException>("innerKeySelector", () => outer.GroupJoin(inner, e => e.name, null, createJoinRec, new AnagramEqualityComparer()));
}
[Fact]
public void ResultSelectorNull()
{
CustomerRec[] outer = new CustomerRec[]
{
new CustomerRec{ name = "Tim", custID = 1234 },
new CustomerRec{ name = "Bob", custID = 9865 },
new CustomerRec{ name = "Robert", custID = 9895 }
};
AnagramRec[] inner = new AnagramRec[]
{
new AnagramRec{ name = "Robert", orderID = 93483, total = 19 },
new AnagramRec{ name = "miT", orderID = 93489, total = 45 }
};
Assert.Throws<ArgumentNullException>("resultSelector", () => outer.GroupJoin(inner, e => e.name, e => e.name, (Func<CustomerRec, IEnumerable<AnagramRec>, JoinRec>)null, new AnagramEqualityComparer()));
}
[Fact]
public void OuterNullNoComparer()
{
CustomerRec[] outer = null;
AnagramRec[] inner = new AnagramRec[]
{
new AnagramRec{ name = "Robert", orderID = 93483, total = 19 },
new AnagramRec{ name = "miT", orderID = 93489, total = 45 }
};
Assert.Throws<ArgumentNullException>("outer", () => outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec));
}
[Fact]
public void InnerNullNoComparer()
{
CustomerRec[] outer = new[]
{
new CustomerRec{ name = "Tim", custID = 1234 },
new CustomerRec{ name = "Bob", custID = 9865 },
new CustomerRec{ name = "Robert", custID = 9895 }
};
AnagramRec[] inner = null;
Assert.Throws<ArgumentNullException>("inner", () => outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec));
}
[Fact]
public void OuterKeySelectorNullNoComparer()
{
CustomerRec[] outer = new CustomerRec[]
{
new CustomerRec{ name = "Tim", custID = 1234 },
new CustomerRec{ name = "Bob", custID = 9865 },
new CustomerRec{ name = "Robert", custID = 9895 }
};
AnagramRec[] inner = new AnagramRec[]
{
new AnagramRec{ name = "Robert", orderID = 93483, total = 19 },
new AnagramRec{ name = "miT", orderID = 93489, total = 45 }
};
Assert.Throws<ArgumentNullException>("outerKeySelector", () => outer.GroupJoin(inner, null, e => e.name, createJoinRec));
}
[Fact]
public void InnerKeySelectorNullNoComparer()
{
CustomerRec[] outer = new CustomerRec[]
{
new CustomerRec{ name = "Tim", custID = 1234 },
new CustomerRec{ name = "Bob", custID = 9865 },
new CustomerRec{ name = "Robert", custID = 9895 }
};
AnagramRec[] inner = new AnagramRec[]
{
new AnagramRec{ name = "Robert", orderID = 93483, total = 19 },
new AnagramRec{ name = "miT", orderID = 93489, total = 45 }
};
Assert.Throws<ArgumentNullException>("innerKeySelector", () => outer.GroupJoin(inner, e => e.name, null, createJoinRec));
}
[Fact]
public void ResultSelectorNullNoComparer()
{
CustomerRec[] outer = new CustomerRec[]
{
new CustomerRec{ name = "Tim", custID = 1234 },
new CustomerRec{ name = "Bob", custID = 9865 },
new CustomerRec{ name = "Robert", custID = 9895 }
};
AnagramRec[] inner = new AnagramRec[]
{
new AnagramRec{ name = "Robert", orderID = 93483, total = 19 },
new AnagramRec{ name = "miT", orderID = 93489, total = 45 }
};
Assert.Throws<ArgumentNullException>("resultSelector", () => outer.GroupJoin(inner, e => e.name, e => e.name, (Func<CustomerRec, IEnumerable<AnagramRec>, JoinRec>)null));
}
[Fact]
public void OuterInnerBothSingleNullElement()
{
string[] outer = new string[] { null };
string[] inner = new string[] { null };
string[] expected = new string[] { null };
Assert.Equal(expected, outer.GroupJoin(inner, e => e, e => e, (x, y) => x, EqualityComparer<string>.Default));
}
[Fact]
public void OuterNonEmptyInnerEmpty()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Tim", custID = 43434 },
new CustomerRec{ name = "Bob", custID = 34093 }
};
OrderRec[] inner = { };
JoinRec[] expected = new []
{
new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } },
new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } }
};
Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec));
}
[Fact]
public void SingleElementEachAndMatches()
{
CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 43434 } };
OrderRec[] inner = new [] { new OrderRec{ orderID = 97865, custID = 43434, total = 25 } };
JoinRec[] expected = new [] { new JoinRec{ name = "Tim", orderID = new int?[]{ 97865 }, total = new int?[]{ 25 } } };
Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec));
}
[Fact]
public void SingleElementEachAndDoesntMatch()
{
CustomerRec[] outer = new [] { new CustomerRec{ name = "Tim", custID = 43434 } };
OrderRec[] inner = new [] { new OrderRec{ orderID = 97865, custID = 49434, total = 25 } };
JoinRec[] expected = new JoinRec[] { new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } } };
Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec));
}
[Fact]
public void SelectorsReturnNull()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Tim", custID = null },
new CustomerRec{ name = "Bob", custID = null }
};
OrderRec[] inner = new []
{
new OrderRec{ orderID = 97865, custID = null, total = 25 },
new OrderRec{ orderID = 34390, custID = null, total = 19 }
};
JoinRec[] expected = new []
{
new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } },
new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } }
};
Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec));
}
[Fact]
public void InnerSameKeyMoreThanOneElementAndMatches()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Tim", custID = 1234 },
new CustomerRec{ name = "Bob", custID = 9865 }
};
OrderRec[] inner = new []
{
new OrderRec{ orderID = 97865, custID = 1234, total = 25 },
new OrderRec{ orderID = 34390, custID = 1234, total = 19 },
new OrderRec{ orderID = 34390, custID = 9865, total = 19 }
};
JoinRec[] expected = new []
{
new JoinRec { name = "Tim", orderID = new int?[]{ 97865, 34390 }, total = new int?[] { 25, 19 } },
new JoinRec { name = "Bob", orderID = new int?[]{ 34390 }, total = new int?[]{ 19 } }
};
Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec));
}
[Fact]
public void OuterSameKeyMoreThanOneElementAndMatches()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Tim", custID = 1234 },
new CustomerRec{ name = "Bob", custID = 9865 },
new CustomerRec{ name = "Robert", custID = 9865 }
};
OrderRec[] inner = new []
{
new OrderRec{ orderID = 97865, custID = 1234, total = 25 },
new OrderRec{ orderID = 34390, custID = 9865, total = 19 }
};
JoinRec[] expected = new []
{
new JoinRec { name = "Tim", orderID = new int?[]{ 97865 }, total = new int?[]{ 25 } },
new JoinRec { name = "Bob", orderID = new int?[]{ 34390 }, total = new int?[]{ 19 } },
new JoinRec { name = "Robert", orderID = new int?[]{ 34390 }, total = new int?[]{ 19 } }
};
Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec));
}
[Fact]
public void NoMatches()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Tim", custID = 1234 },
new CustomerRec{ name = "Bob", custID = 9865 },
new CustomerRec{ name = "Robert", custID = 9895 }
};
OrderRec[] inner = new []
{
new OrderRec{ orderID = 97865, custID = 2334, total = 25 },
new OrderRec{ orderID = 34390, custID = 9065, total = 19 }
};
JoinRec[] expected = new []
{
new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } },
new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } },
new JoinRec{ name = "Robert", orderID = new int?[]{ }, total = new int?[]{ } }
};
Assert.Equal(expected, outer.GroupJoin(inner, e => e.custID, e => e.custID, createJoinRec));
}
[Fact]
public void NullComparer()
{
CustomerRec[] outer = new []
{
new CustomerRec{ name = "Tim", custID = 1234 },
new CustomerRec{ name = "Bob", custID = 9865 },
new CustomerRec{ name = "Robert", custID = 9895 }
};
AnagramRec[] inner = new []
{
new AnagramRec{ name = "Robert", orderID = 93483, total = 19 },
new AnagramRec{ name = "miT", orderID = 93489, total = 45 }
};
JoinRec[] expected = new []
{
new JoinRec{ name = "Tim", orderID = new int?[]{ }, total = new int?[]{ } },
new JoinRec{ name = "Bob", orderID = new int?[]{ }, total = new int?[]{ } },
new JoinRec{ name = "Robert", orderID = new int?[]{ 93483 }, total = new int?[]{ 19 } }
};
Assert.Equal(expected, outer.GroupJoin(inner, e => e.name, e => e.name, createJoinRec, null));
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerate()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).GroupJoin(Enumerable.Empty<int>(), i => i, i => i, (o, i) => i);
// Don't insist on this behaviour, but check its correct if it happens
var en = iterator as IEnumerator<IEnumerable<int>>;
Assert.False(en != null && en.MoveNext());
}
}
}
| |
/*
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.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Runtime.Caching;
using Microsoft.Xrm.Client.Collections.Generic;
using Microsoft.Xrm.Client.Runtime;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Client.Threading;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
namespace Microsoft.Xrm.Client.Configuration
{
/// <summary>
/// Provides configuration settings based on the <see cref="ConfigurationManager"/>.
/// </summary>
public class CrmConfigurationProvider
{
private static CrmSection CreateConfiguration()
{
var configuration = ConfigurationManager.GetSection(CrmSection.SectionName) as CrmSection ?? new CrmSection();
var args = new CrmSectionCreatedEventArgs { Configuration = configuration };
var handler = ConfigurationCreated;
if (handler != null)
{
handler(null, args);
}
return args.Configuration;
}
/// <summary>
/// Occurs after the <see cref="CrmSection"/> configuration is created.
/// </summary>
public static event EventHandler<CrmSectionCreatedEventArgs> ConfigurationCreated;
private CrmSection _crmSection;
/// <summary>
/// Retrieves the configuration section.
/// </summary>
/// <returns></returns>
public virtual CrmSection GetCrmSection()
{
return _crmSection ?? (_crmSection = CreateConfiguration());
}
/// <summary>
/// Retrieves the configured connection string settings.
/// </summary>
/// <param name="connectionStringName"></param>
/// <returns></returns>
public virtual ConnectionStringSettings CreateConnectionStringSettings(string connectionStringName)
{
var section = GetCrmSection();
return section.ConnectionStrings[connectionStringName]
?? ConfigurationManager.ConnectionStrings[connectionStringName];
}
/// <summary>
/// Retrieves the connection string name from the context name.
/// </summary>
/// <param name="contextName"></param>
/// <param name="allowDefaultFallback"></param>
/// <returns></returns>
public virtual string GetConnectionStringNameFromContext(string contextName, bool allowDefaultFallback = false)
{
var section = GetCrmSection();
var contextElement = section.Contexts.GetElementOrDefault(contextName, allowDefaultFallback);
var connectionStringName = !string.IsNullOrWhiteSpace(contextElement.ConnectionStringName)
? contextElement.ConnectionStringName
: contextElement.Name;
return connectionStringName;
}
/// <summary>
/// Retrieves the configured <see cref="OrganizationServiceContext"/>.
/// </summary>
/// <param name="contextName"></param>
/// <param name="allowDefaultFallback"></param>
/// <returns></returns>
public virtual OrganizationServiceContext CreateContext(string contextName = null, bool allowDefaultFallback = false)
{
var section = GetCrmSection();
var contextElement = section.Contexts.GetElementOrDefault(contextName, allowDefaultFallback);
if (contextElement.Name == null)
{
throw new ConfigurationErrorsException("A custom context must be specified.");
}
var service = CreateService(contextName, true);
var context = contextElement.CreateOrganizationServiceContext(service);
return context;
}
/// <summary>
/// Retrieves the configured <see cref="IOrganizationService"/>.
/// </summary>
/// <param name="contextName"></param>
/// <param name="allowDefaultFallback"></param>
/// <returns></returns>
public virtual IOrganizationService CreateService(string contextName = null, bool allowDefaultFallback = false)
{
var section = GetCrmSection();
var contextElement = section.Contexts.GetElementOrDefault(contextName, allowDefaultFallback);
var serviceName = !string.IsNullOrWhiteSpace(contextElement.ServiceName)
? contextElement.ServiceName
: contextElement.Name;
var connectionStringName = !string.IsNullOrWhiteSpace(contextElement.ConnectionStringName)
? contextElement.ConnectionStringName
: contextElement.Name;
var service = CreateService(new CrmConnection(connectionStringName), serviceName, true);
return service;
}
private IOrganizationService _service;
private readonly ConcurrentDictionary<string, IOrganizationService> _serviceLookup = new ConcurrentDictionary<string, IOrganizationService>();
/// <summary>
/// Retrieves the configured <see cref="IOrganizationService"/>.
/// </summary>
/// <param name="connection"></param>
/// <param name="serviceName"></param>
/// <param name="allowDefaultFallback"></param>
/// <returns></returns>
public virtual IOrganizationService CreateService(CrmConnection connection, string serviceName = null, bool allowDefaultFallback = false)
{
var section = GetCrmSection();
var serviceElement = section.Services.GetElementOrDefault(serviceName, allowDefaultFallback);
var mode = serviceElement.InstanceMode;
var name = serviceElement.Name;
if (mode == OrganizationServiceInstanceMode.Static)
{
// return a single instance
return _service ?? (_service = CreateService(serviceElement, connection));
}
if (mode == OrganizationServiceInstanceMode.PerName)
{
var key = name ?? GetDefaultContextName();
if (!_serviceLookup.ContainsKey(key))
{
_serviceLookup[key] = CreateService(serviceElement, connection);
}
return _serviceLookup[key];
}
if (mode == OrganizationServiceInstanceMode.PerRequest && HttpSingleton<IOrganizationService>.Enabled)
{
var key = name ?? GetDefaultContextName();
return HttpSingleton<IOrganizationService>.GetInstance(key, () => CreateService(serviceElement, connection));
}
var service = CreateService(serviceElement, connection);
return service;
}
private IOrganizationService CreateService(OrganizationServiceElement serviceElement, CrmConnection connection)
{
var serviceCacheName = !string.IsNullOrWhiteSpace(serviceElement.ServiceCacheName)
? serviceElement.ServiceCacheName
: serviceElement.Name;
var serviceCache = CreateServiceCache(serviceCacheName, connection.GetConnectionId(), true);
var service = serviceElement.CreateOrganizationService(connection, serviceCache);
return service;
}
/// <summary>
/// Retrieves the configured <see cref="IOrganizationServiceCache"/>.
/// </summary>
/// <param name="serviceCacheName"></param>
/// <param name="connectionId"></param>
/// <param name="allowDefaultFallback"></param>
/// <returns></returns>
public virtual IOrganizationServiceCache CreateServiceCache(string serviceCacheName = null, string connectionId = null, bool allowDefaultFallback = false)
{
var section = GetCrmSection();
var serviceCacheElement = section.ServiceCache.GetElementOrDefault(serviceCacheName, allowDefaultFallback);
var objectCacheName = !string.IsNullOrWhiteSpace(serviceCacheElement.ObjectCacheName)
? serviceCacheElement.ObjectCacheName
: serviceCacheElement.Name;
var objectCacheElement = section.ObjectCache.GetElementOrDefault(objectCacheName, allowDefaultFallback);
var settings = new OrganizationServiceCacheSettings(connectionId)
{
ConnectionId = connectionId,
CacheRegionName = serviceCacheElement.CacheRegionName,
QueryHashingEnabled = serviceCacheElement.QueryHashingEnabled,
PolicyFactory = objectCacheElement,
};
var objectCache = CreateObjectCache(objectCacheName, true);
var serviceCache = serviceCacheElement.CreateOrganizationServiceCache(objectCache, settings);
return serviceCache;
}
/// <summary>
/// Retrieves the configured <see cref="IOrganizationServiceCache"/>.
/// </summary>
/// <param name="serviceCacheName"></param>
/// <param name="connection"></param>
/// <param name="allowDefaultFallback"></param>
/// <returns></returns>
public virtual IOrganizationServiceCache CreateServiceCache(string serviceCacheName, CrmConnection connection, bool allowDefaultFallback = false)
{
return CreateServiceCache(serviceCacheName, connection.GetConnectionId(), allowDefaultFallback);
}
private ObjectCache _objectCache;
private readonly ConcurrentDictionary<string, ObjectCache> _objectCacheLookup = new ConcurrentDictionary<string, ObjectCache>();
/// <summary>
/// Retrieves the configured <see cref="ObjectCache"/>.
/// </summary>
/// <param name="objectCacheName"></param>
/// <param name="allowDefaultFallback"></param>
/// <returns></returns>
public virtual ObjectCache CreateObjectCache(string objectCacheName = null, bool allowDefaultFallback = false)
{
var section = GetCrmSection();
var objectCacheElement = section.ObjectCache.GetElementOrDefault(objectCacheName, allowDefaultFallback);
var mode = objectCacheElement.InstanceMode;
var name = !string.IsNullOrWhiteSpace(objectCacheElement.Name) ? objectCacheElement.Name : GetDefaultContextName();
if (mode == ObjectCacheInstanceMode.Static)
{
// return a single instance
return _objectCache ?? (_objectCache = objectCacheElement.CreateObjectCache(name));
}
if (mode == ObjectCacheInstanceMode.PerName)
{
var key = name ?? GetDefaultContextName() ?? ObjectCacheElement.DefaultObjectCacheName;
if (!_objectCacheLookup.ContainsKey(key))
{
_objectCacheLookup[key] = objectCacheElement.CreateObjectCache(name);
}
return _objectCacheLookup[key];
}
// return a new instance for each call
var objectCache = objectCacheElement.CreateObjectCache(name);
return objectCache;
}
/// <summary>
/// Retrieves the configured <see cref="CacheItemPolicy"/>.
/// </summary>
/// <param name="objectCacheName"></param>
/// <param name="allowDefaultFallback"></param>
/// <returns></returns>
public virtual CacheItemPolicy CreateCacheItemPolicy(string objectCacheName = null, bool allowDefaultFallback = false)
{
var section = GetCrmSection();
var objectCacheElement = section.ObjectCache.GetElementOrDefault(objectCacheName, allowDefaultFallback);
var policy = objectCacheElement.CreateCacheItemPolicy();
return policy;
}
/// <summary>
/// Retrieves the cached <see cref="ObjectCache"/> objects.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public virtual IEnumerable<ObjectCache> GetObjectCaches(string name = null)
{
if (name != null)
{
ObjectCache cache;
if (_objectCacheLookup.TryGetValue(name, out cache))
{
yield return cache;
}
yield break;
}
if (_objectCache != null) yield return _objectCache;
foreach (var cache in _objectCacheLookup.Values) yield return cache;
}
private readonly ConcurrentDictionary<string, IDictionary<string, string>> _connectionLookup = new ConcurrentDictionary<string, IDictionary<string, string>>();
/// <summary>
/// Creates and caches connection strings by name.
/// </summary>
/// <param name="connectionString"></param>
/// <returns></returns>
public virtual IDictionary<string, string> CreateConnectionDictionary(ConnectionStringSettings connectionString)
{
connectionString.ThrowOnNull("connectionString");
var name = connectionString.Name;
if (!_connectionLookup.ContainsKey(name))
{
// cache ths mapping for performance
_connectionLookup[name] = connectionString.ConnectionString.ToDictionary();
}
return _connectionLookup[name];
}
private string GetDefaultContextName()
{
var section = GetCrmSection();
var element = section.Contexts.GetElementOrDefault(null);
return element.Name;
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace System.Net
{
using Runtime.CompilerServices;
/// <devdoc>
/// <para>Provides an internet protocol (IP) address.</para>
/// </devdoc>
[Serializable]
public class IPAddress
{
public static readonly IPAddress Any = new IPAddress(0x0000000000000000);
public static readonly IPAddress Loopback = new IPAddress(0x000000000100007F);
//--//
internal long m_Address;
public IPAddress(long newAddress)
{
if (newAddress < 0 || newAddress > 0x00000000FFFFFFFF)
{
// BUG: This always throws. Needs investigation
//throw new ArgumentOutOfRangeException();
}
m_Address = newAddress;
}
public IPAddress(byte[] newAddressBytes)
: this(((((newAddressBytes[3] << 0x18) | (newAddressBytes[2] << 0x10)) | (newAddressBytes[1] << 0x08)) | newAddressBytes[0]) & ((long)0xFFFFFFFF))
{
}
public override bool Equals(object obj)
{
IPAddress addr = obj as IPAddress;
if (obj == null)
return false;
return this.m_Address == addr.m_Address;
}
public override int GetHashCode()
{
return (int)this.m_Address;
}
public byte[] GetAddressBytes()
{
return new byte[]
{
(byte)(m_Address),
(byte)(m_Address >> 8),
(byte)(m_Address >> 16),
(byte)(m_Address >> 24)
};
}
public static IPAddress Parse(string ipString)
{
if (ipString == null)
throw new ArgumentNullException();
ulong ipAddress = 0L;
int lastIndex = 0;
int shiftIndex = 0;
ulong mask = 0x00000000000000FF;
ulong octet = 0L;
int length = ipString.Length;
for (int i = 0; i < length; ++i)
{
// Parse to '.' or end of IP address
if (ipString[i] == '.' || i == length - 1)
// If the IP starts with a '.'
// or a segment is longer than 3 characters or shiftIndex > last bit position throw.
if (i == 0 || i - lastIndex > 3 || shiftIndex > 24)
{
throw new ArgumentException();
}
else
{
i = i == length - 1 ? ++i : i;
octet = (ulong)(ConvertStringToInt32(ipString.Substring(lastIndex, i - lastIndex)) & 0x00000000000000FF);
ipAddress = ipAddress + (ulong)((octet << shiftIndex) & mask);
lastIndex = i + 1;
shiftIndex = shiftIndex + 8;
mask = (mask << 8);
}
}
return new IPAddress((long)ipAddress);
}
public override string ToString()
{
return ((byte)(m_Address)).ToString() +
"." +
((byte)(m_Address >> 8)).ToString() +
"." +
((byte)(m_Address >> 16)).ToString() +
"." +
((byte)(m_Address >> 24)).ToString();
}
//--//
////////////////////////////////////////////////////////////////////////////////////////
// this method ToInt32 is part of teh Convert class which we will bring over later
// at that time we will get rid of this code
//
/// <summary>
/// Converts the specified System.String representation of a number to an equivalent
/// 32-bit signed integer.
/// </summary>
/// <param name="value">A System.String containing a number to convert.</param>
/// <returns>
/// A 32-bit signed integer equivalent to the value of value.-or- Zero if value
/// is null.
/// </returns>
/// <exception cref="System.OverflowException">
/// Value represents a number less than System.Int32.MinValue or greater than
/// System.Int32.MaxValue.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// The value parameter is null.
/// </exception>
/// <exception cref="System.FormatException">
/// Value does not consist of an optional sign followed by a sequence of digits
/// (zero through nine).
/// </exception>
private static int ConvertStringToInt32(string value)
{
char[] num = value.ToCharArray();
int result = 0;
bool isNegative = false;
int signIndex = 0;
if (num[0] == '-')
{
isNegative = true;
signIndex = 1;
}
else if (num[0] == '+')
{
signIndex = 1;
}
int exp = 1;
for (int i = num.Length - 1; i >= signIndex; i--)
{
if (num[i] < '0' || num[i] > '9')
{
throw new ArgumentException();
}
result += ((num[i] - '0') * exp);
exp *= 10;
}
return (isNegative) ? (-1 * result) : result;
}
// this method ToInt32 is part of teh Convert class which we will bring over later
////////////////////////////////////////////////////////////////////////////////////////
public static IPAddress GetDefaultLocalAddress()
{
// Special conditions are implemented here because of a ptoblem with GetHostEntry
// on the digi device and NetworkInterface from the emulator.
// In the emulator we must use GetHostEntry.
// On the device and Windows NetworkInterface works and is preferred.
try
{
string localAddress = GetDefaultLocalAddressImpl();
if (string.IsNullOrEmpty(localAddress))
{
return IPAddress.Parse(localAddress);
}
}
catch
{
}
try
{
IPAddress localAddress = null;
IPHostEntry hostEntry = Dns.GetHostEntry("");
int cnt = hostEntry.AddressList.Length;
for (int i = 0; i < cnt; ++i)
{
if ((localAddress = hostEntry.AddressList[i]) != null)
{
if(localAddress.m_Address != 0)
{
return localAddress;
}
}
}
}
catch
{
}
return IPAddress.Any;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static string GetDefaultLocalAddressImpl();
} // class IPAddress
} // namespace System.Net
| |
// 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.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Runtime.CompilerServices;
// TODO when we upgrade to C# V6 you can remove this.
// warning CS0420: 'P.x': a reference to a volatile field will not be treated as volatile
// This happens when you pass a _subcribers (a volatile field) to interlocked operations (which are byref).
// This was fixed in C# V6.
#pragma warning disable 0420
namespace System.Diagnostics
{
/// <summary>
/// A DiagnosticListener is something that forwards on events written with DiagnosticSource.
/// It is an IObservable (has Subscribe method), and it also has a Subscribe overload that
/// lets you specify a 'IsEnabled' predicate that users of DiagnosticSource will use for
/// 'quick checks'.
///
/// The item in the stream is a KeyValuePair[string, object] where the string is the name
/// of the diagnostic item and the object is the payload (typically an anonymous type).
///
/// There may be many DiagnosticListeners in the system, but we encourage the use of
/// The DiagnosticSource.DefaultSource which goes to the DiagnosticListener.DefaultListener.
///
/// If you need to see 'everything' you can subscribe to the 'AllListeners' event that
/// will fire for every live DiagnosticListener in the appdomain (past or present).
/// </summary>
public class DiagnosticListener : DiagnosticSource, IObservable<KeyValuePair<string, object>>, IDisposable
{
/// <summary>
/// When you subscribe to this you get callbacks for all NotificationListeners in the appdomain
/// as well as those that occurred in the past, and all future Listeners created in the future.
/// </summary>
public static IObservable<DiagnosticListener> AllListeners
{
get
{
if (s_allListenerObservable == null)
{
s_allListenerObservable = new AllListenerObservable();
}
return s_allListenerObservable;
}
}
// Subscription implementation
/// <summary>
/// Add a subscriber (Observer). If 'IsEnabled' == null (or not present), then the Source's IsEnabled
/// will always return true.
/// </summary>
virtual public IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer, Predicate<string> isEnabled)
{
// If we have been disposed, we silently ignore any subscriptions.
if (_disposed)
{
return new DiagnosticSubscription() { Owner = this };
}
DiagnosticSubscription newSubscription = new DiagnosticSubscription() { Observer = observer, IsEnabled = isEnabled, Owner = this, Next = _subscriptions };
while (Interlocked.CompareExchange(ref _subscriptions, newSubscription, newSubscription.Next) != newSubscription.Next)
newSubscription.Next = _subscriptions;
return newSubscription;
}
/// <summary>
/// Same as other Subscribe overload where the predicate is assumed to always return true.
/// </summary>
public IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer)
{
return Subscribe(observer, null);
}
/// <summary>
/// Make a new DiagnosticListener, it is a NotificationSource, which means the returned result can be used to
/// log notifications, but it also has a Subscribe method so notifications can be forwarded
/// arbitrarily. Thus its job is to forward things from the producer to all the listeners
/// (multi-casting). Generally you should not be making your own DiagnosticListener but use the
/// DiagnosticListener.Default, so that notifications are as 'public' as possible.
/// </summary>
public DiagnosticListener(string name)
{
Name = name;
// Insert myself into the list of all Listeners.
lock (s_lock)
{
// Issue the callback for this new diagnostic listener.
var allListenerObservable = s_allListenerObservable;
if (allListenerObservable != null)
allListenerObservable.OnNewDiagnosticListener(this);
// And add it to the list of all past listeners.
_next = s_allListeners;
s_allListeners = this;
}
// Call IsEnabled just so we insure that the DiagnosticSourceEventSource has been
// constructed (and thus is responsive to ETW requests to be enabled).
DiagnosticSourceEventSource.Logger.IsEnabled();
}
/// <summary>
/// Clean up the NotificationListeners. Notification listeners do NOT DIE ON THEIR OWN
/// because they are in a global list (for discoverability). You must dispose them explicitly.
/// Note that we do not do the Dispose(bool) pattern because we frankly don't want to support
/// subclasses that have non-managed state.
/// </summary>
virtual public void Dispose()
{
// Remove myself from the list of all listeners.
lock (s_lock)
{
if (_disposed)
{
return;
}
_disposed = true;
if (s_allListeners == this)
s_allListeners = s_allListeners._next;
else
{
var cur = s_allListeners;
while (cur != null)
{
if (cur._next == this)
{
cur._next = _next;
break;
}
cur = cur._next;
}
}
_next = null;
}
// Indicate completion to all subscribers.
DiagnosticSubscription subscriber = null;
Interlocked.Exchange(ref subscriber, _subscriptions);
while (subscriber != null)
{
subscriber.Observer.OnCompleted();
subscriber = subscriber.Next;
}
// The code above also nulled out all subscriptions.
}
/// <summary>
/// When a DiagnosticListener is created it is given a name. Return this.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Return the name for the ToString() to aid in debugging.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Name;
}
#region private
// NotificationSource implementation
/// <summary>
/// Override abstract method
/// </summary>
public override bool IsEnabled(string name)
{
for (DiagnosticSubscription curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next)
{
if (curSubscription.IsEnabled == null || curSubscription.IsEnabled(name))
return true;
}
return false;
}
/// <summary>
/// Override abstract method
/// </summary>
public override void Write(string name, object value)
{
for (DiagnosticSubscription curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next)
curSubscription.Observer.OnNext(new KeyValuePair<string, object>(name, value));
}
// Note that Subscriptions are READ ONLY. This means you never update any fields (even on removal!)
private class DiagnosticSubscription : IDisposable
{
internal IObserver<KeyValuePair<string, object>> Observer;
internal Predicate<string> IsEnabled;
internal DiagnosticListener Owner; // The DiagnosticListener this is a subscription for.
internal DiagnosticSubscription Next; // Linked list of subscribers
public void Dispose()
{
// TO keep this lock free and easy to analyze, the linked list is READ ONLY. Thus we copy
for (;;)
{
DiagnosticSubscription subscriptions = Owner._subscriptions;
DiagnosticSubscription newSubscriptions = Remove(subscriptions, this); // Make a new list, with myself removed.
// try to update, but if someone beat us to it, then retry.
if (Interlocked.CompareExchange(ref Owner._subscriptions, newSubscriptions, subscriptions) == subscriptions)
{
#if DEBUG
var cur = newSubscriptions;
while (cur != null)
{
Debug.Assert(!(cur.Observer == Observer && cur.IsEnabled == IsEnabled), "Did not remove subscription!");
cur = cur.Next;
}
#endif
break;
}
}
}
// Create a new linked list where 'subscription has been removed from the linked list of 'subscriptions'.
private static DiagnosticSubscription Remove(DiagnosticSubscription subscriptions, DiagnosticSubscription subscription)
{
if (subscriptions == null)
{
// May happen if the IDisposable returned from Subscribe is Dispose'd again
return null;
}
if (subscriptions.Observer == subscription.Observer && subscriptions.IsEnabled == subscription.IsEnabled)
return subscriptions.Next;
#if DEBUG
// Delay a bit. This makes it more likely that races will happen.
for (int i = 0; i < 100; i++)
GC.KeepAlive("");
#endif
return new DiagnosticSubscription() { Observer = subscriptions.Observer, Owner = subscriptions.Owner, IsEnabled = subscriptions.IsEnabled, Next = Remove(subscriptions.Next, subscription) };
}
}
#region AllListenerObservable
/// <summary>
/// Logically AllListenerObservable has a very simple task. It has a linked list of subscribers that want
/// a callback when a new listener gets created. When a new DiagnosticListener gets created it should call
/// OnNewDiagnosticListener so that AllListenerObservable can forward it on to all the subscribers.
/// </summary>
private class AllListenerObservable : IObservable<DiagnosticListener>
{
public IDisposable Subscribe(IObserver<DiagnosticListener> observer)
{
lock (s_lock)
{
// Call back for each existing listener on the new callback (catch-up).
for (DiagnosticListener cur = s_allListeners; cur != null; cur = cur._next)
observer.OnNext(cur);
// Add the observer to the list of subscribers.
_subscriptions = new AllListenerSubscription(this, observer, _subscriptions);
return _subscriptions;
}
}
/// <summary>
/// Called when a new DiagnosticListener gets created to tell anyone who subscribed that this happened.
/// </summary>
/// <param name="diagnosticListener"></param>
internal void OnNewDiagnosticListener(DiagnosticListener diagnosticListener)
{
Debug.Assert(Monitor.IsEntered(s_lock)); // We should only be called when we hold this lock
// Simply send a callback to every subscriber that we have a new listener
for (var cur = _subscriptions; cur != null; cur = cur.Next)
cur.Subscriber.OnNext(diagnosticListener);
}
#region private
/// <summary>
/// Remove 'subscription from the list of subscriptions that the observable has. Called when
/// subscriptions are disposed. Returns true if the subscription was removed.
/// </summary>
private bool Remove(AllListenerSubscription subscription)
{
lock (s_lock)
{
if (_subscriptions == subscription)
{
_subscriptions = subscription.Next;
return true;
}
else if (_subscriptions != null)
{
for (var cur = _subscriptions; cur.Next != null; cur = cur.Next)
{
if (cur.Next == subscription)
{
cur.Next = cur.Next.Next;
return true;
}
}
}
// Subscriber likely disposed multiple times
return false;
}
}
/// <summary>
/// One node in the linked list of subscriptions that AllListenerObservable keeps. It is
/// IDisposable, and when that is called it removes itself from the list.
/// </summary>
internal class AllListenerSubscription : IDisposable
{
internal AllListenerSubscription(AllListenerObservable owner, IObserver<DiagnosticListener> subscriber, AllListenerSubscription next)
{
this._owner = owner;
this.Subscriber = subscriber;
this.Next = next;
}
public void Dispose()
{
if (_owner.Remove(this))
{
Subscriber.OnCompleted(); // Called outside of a lock
}
}
private readonly AllListenerObservable _owner; // the list this is a member of.
internal readonly IObserver<DiagnosticListener> Subscriber;
internal AllListenerSubscription Next;
}
private AllListenerSubscription _subscriptions;
#endregion
}
#endregion
private volatile DiagnosticSubscription _subscriptions;
private DiagnosticListener _next; // We keep a linked list of all NotificationListeners (s_allListeners)
private bool _disposed; // Has Dispose been called?
private static DiagnosticListener s_allListeners; // linked list of all instances of DiagnosticListeners.
private static AllListenerObservable s_allListenerObservable; // to make callbacks to this object when listeners come into existence.
private static object s_lock = new object(); // A lock for
#if false
private static readonly DiagnosticListener s_default = new DiagnosticListener("DiagnosticListener.DefaultListener");
#endif
#endregion
}
}
| |
using System;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Orleans.Runtime;
using System.Net;
namespace Orleans.Storage
{
/// <summary>
/// Interface to be implemented for a storage able to read and write Orleans grain state data.
/// </summary>
public interface IGrainStorage
{
/// <summary>Read data function for this storage instance.</summary>
/// <param name="grainType">Type of this grain [fully qualified class name]</param>
/// <param name="grainReference">Grain reference object for this grain.</param>
/// <param name="grainState">State data object to be populated for this grain.</param>
/// <typeparam name="T">The grain state type.</typeparam>
/// <returns>Completion promise for the Read operation on the specified grain.</returns>
Task ReadStateAsync<T>(string grainType, GrainReference grainReference, IGrainState<T> grainState);
/// <summary>Write data function for this storage instance.</summary>
/// <param name="grainType">Type of this grain [fully qualified class name]</param>
/// <param name="grainReference">Grain reference object for this grain.</param>
/// <param name="grainState">State data object to be written for this grain.</param>
/// <typeparam name="T">The grain state type.</typeparam>
/// <returns>Completion promise for the Write operation on the specified grain.</returns>
Task WriteStateAsync<T>(string grainType, GrainReference grainReference, IGrainState<T> grainState);
/// <summary>Delete / Clear data function for this storage instance.</summary>
/// <param name="grainType">Type of this grain [fully qualified class name]</param>
/// <param name="grainReference">Grain reference object for this grain.</param>
/// <param name="grainState">Copy of last-known state data object for this grain.</param>
/// <typeparam name="T">The grain state type.</typeparam>
/// <returns>Completion promise for the Delete operation on the specified grain.</returns>
Task ClearStateAsync<T>(string grainType, GrainReference grainReference, IGrainState<T> grainState);
}
/// <summary>
/// Interface to be optionally implemented by storage to return richer exception details.
/// TODO: Remove this interface. Move to decorator pattern for monitoring purposes. - jbragg
/// </summary>
public interface IRestExceptionDecoder
{
/// <summary>
/// Decode details of the exception.
/// </summary>
/// <param name="exception">Exception to decode.</param>
/// <param name="httpStatusCode">HTTP status code for the error.</param>
/// <param name="restStatus">REST status for the error.</param>
/// <param name="getExtendedErrors">Whether or not to extract REST error code.</param>
/// <returns>A value indicating whether the exception was decoded.</returns>
bool DecodeException(Exception exception, out HttpStatusCode httpStatusCode, out string restStatus, bool getExtendedErrors = false);
}
/// <summary>
/// Exception thrown whenever a grain call is attempted with a bad / missing storage configuration settings for that grain.
/// </summary>
[Serializable]
[GenerateSerializer]
public class BadGrainStorageConfigException : BadProviderConfigException
{
/// <summary>
/// Initializes a new instance of the <see cref="BadGrainStorageConfigException"/> class.
/// </summary>
public BadGrainStorageConfigException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BadGrainStorageConfigException"/> class.
/// </summary>
/// <param name="message">The message.</param>
public BadGrainStorageConfigException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BadGrainStorageConfigException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The inner exception.</param>
public BadGrainStorageConfigException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BadGrainStorageConfigException"/> class.
/// </summary>
/// <param name="info">The serialization info.</param>
/// <param name="context">The context.</param>
protected BadGrainStorageConfigException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
/// <summary>
/// Exception thrown when a storage detects an Etag inconsistency when attempting to perform a WriteStateAsync operation.
/// </summary>
[Serializable]
[GenerateSerializer]
public class InconsistentStateException : OrleansException
{
/// <summary>
/// Gets or sets a value indicating whether this exception occurred on the current activation.
/// </summary>
[Id(0)]
internal bool IsSourceActivation { get; set; } = true;
/// <summary>Gets the Etag value currently held in persistent storage.</summary>
[Id(1)]
public string StoredEtag { get; private set; }
/// <summary>Gets the Etag value currently help in memory, and attempting to be updated.</summary>
[Id(2)]
public string CurrentEtag { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="InconsistentStateException"/> class.
/// </summary>
public InconsistentStateException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InconsistentStateException"/> class.
/// </summary>
/// <param name="message">The message.</param>
public InconsistentStateException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InconsistentStateException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The inner exception.</param>
public InconsistentStateException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InconsistentStateException"/> class.
/// </summary>
/// <param name="info">The serialization info.</param>
/// <param name="context">The context.</param>
protected InconsistentStateException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.StoredEtag = info.GetString(nameof(StoredEtag));
this.CurrentEtag = info.GetString(nameof(CurrentEtag));
this.IsSourceActivation = info.GetBoolean(nameof(this.IsSourceActivation));
}
/// <summary>
/// Initializes a new instance of the <see cref="InconsistentStateException"/> class.
/// </summary>
/// <param name="errorMsg">The error message.</param>
/// <param name="storedEtag">The stored ETag.</param>
/// <param name="currentEtag">The current ETag.</param>
/// <param name="storageException">The inner exception.</param>
public InconsistentStateException(
string errorMsg,
string storedEtag,
string currentEtag,
Exception storageException) : base(errorMsg, storageException)
{
StoredEtag = storedEtag;
CurrentEtag = currentEtag;
}
/// <summary>
/// Initializes a new instance of the <see cref="InconsistentStateException"/> class.
/// </summary>
/// <param name="errorMsg">The error message.</param>
/// <param name="storedEtag">The stored ETag.</param>
/// <param name="currentEtag">The current ETag.</param>
public InconsistentStateException(
string errorMsg,
string storedEtag,
string currentEtag)
: this(errorMsg, storedEtag, currentEtag, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InconsistentStateException"/> class.
/// </summary>
/// <param name="storedEtag">The stored ETag.</param>
/// <param name="currentEtag">The current ETag.</param>
/// <param name="storageException">The storage exception.</param>
public InconsistentStateException(string storedEtag, string currentEtag, Exception storageException)
: this(storageException.Message, storedEtag, currentEtag, storageException)
{
}
/// <inheritdoc/>
public override string ToString()
{
return String.Format("InconsistentStateException: {0} Expected Etag={1} Received Etag={2} {3}",
Message, StoredEtag, CurrentEtag, InnerException);
}
/// <inheritdoc/>
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null) throw new ArgumentNullException(nameof(info));
info.AddValue(nameof(StoredEtag), this.StoredEtag);
info.AddValue(nameof(CurrentEtag), this.CurrentEtag);
info.AddValue(nameof(this.IsSourceActivation), this.IsSourceActivation);
base.GetObjectData(info, context);
}
}
}
| |
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Torque6.Engine.SimObjects;
using Torque6.Engine.SimObjects.Scene;
using Torque6.Engine.Namespaces;
using Torque6.Utility;
namespace Torque6.Engine.SimObjects
{
public unsafe class AssetBase : SimObject
{
public AssetBase()
{
ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.AssetBaseCreateInstance());
}
public AssetBase(uint pId) : base(pId)
{
}
public AssetBase(string pName) : base(pName)
{
}
public AssetBase(IntPtr pObjPtr) : base(pObjPtr)
{
}
public AssetBase(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr)
{
}
public AssetBase(SimObject pObj) : base(pObj)
{
}
#region UnsafeNativeMethods
new internal struct InternalUnsafeMethods
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _AssetBaseCreateInstance();
private static _AssetBaseCreateInstance _AssetBaseCreateInstanceFunc;
internal static IntPtr AssetBaseCreateInstance()
{
if (_AssetBaseCreateInstanceFunc == null)
{
_AssetBaseCreateInstanceFunc =
(_AssetBaseCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AssetBaseCreateInstance"), typeof(_AssetBaseCreateInstance));
}
return _AssetBaseCreateInstanceFunc();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _AssetBaseGetAssetName(IntPtr assetBase);
private static _AssetBaseGetAssetName _AssetBaseGetAssetNameFunc;
internal static IntPtr AssetBaseGetAssetName(IntPtr assetBase)
{
if (_AssetBaseGetAssetNameFunc == null)
{
_AssetBaseGetAssetNameFunc =
(_AssetBaseGetAssetName)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AssetBaseGetAssetName"), typeof(_AssetBaseGetAssetName));
}
return _AssetBaseGetAssetNameFunc(assetBase);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _AssetBaseSetAssetName(IntPtr assetBase, string name);
private static _AssetBaseSetAssetName _AssetBaseSetAssetNameFunc;
internal static void AssetBaseSetAssetName(IntPtr assetBase, string name)
{
if (_AssetBaseSetAssetNameFunc == null)
{
_AssetBaseSetAssetNameFunc =
(_AssetBaseSetAssetName)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AssetBaseSetAssetName"), typeof(_AssetBaseSetAssetName));
}
_AssetBaseSetAssetNameFunc(assetBase, name);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _AssetBaseGetAssetDescription(IntPtr assetBase);
private static _AssetBaseGetAssetDescription _AssetBaseGetAssetDescriptionFunc;
internal static IntPtr AssetBaseGetAssetDescription(IntPtr assetBase)
{
if (_AssetBaseGetAssetDescriptionFunc == null)
{
_AssetBaseGetAssetDescriptionFunc =
(_AssetBaseGetAssetDescription)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AssetBaseGetAssetDescription"), typeof(_AssetBaseGetAssetDescription));
}
return _AssetBaseGetAssetDescriptionFunc(assetBase);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _AssetBaseSetAssetDescription(IntPtr assetBase, string val);
private static _AssetBaseSetAssetDescription _AssetBaseSetAssetDescriptionFunc;
internal static void AssetBaseSetAssetDescription(IntPtr assetBase, string val)
{
if (_AssetBaseSetAssetDescriptionFunc == null)
{
_AssetBaseSetAssetDescriptionFunc =
(_AssetBaseSetAssetDescription)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AssetBaseSetAssetDescription"), typeof(_AssetBaseSetAssetDescription));
}
_AssetBaseSetAssetDescriptionFunc(assetBase, val);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _AssetBaseGetAssetCategory(IntPtr assetBase);
private static _AssetBaseGetAssetCategory _AssetBaseGetAssetCategoryFunc;
internal static IntPtr AssetBaseGetAssetCategory(IntPtr assetBase)
{
if (_AssetBaseGetAssetCategoryFunc == null)
{
_AssetBaseGetAssetCategoryFunc =
(_AssetBaseGetAssetCategory)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AssetBaseGetAssetCategory"), typeof(_AssetBaseGetAssetCategory));
}
return _AssetBaseGetAssetCategoryFunc(assetBase);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _AssetBaseSetAssetCategory(IntPtr assetBase, string val);
private static _AssetBaseSetAssetCategory _AssetBaseSetAssetCategoryFunc;
internal static void AssetBaseSetAssetCategory(IntPtr assetBase, string val)
{
if (_AssetBaseSetAssetCategoryFunc == null)
{
_AssetBaseSetAssetCategoryFunc =
(_AssetBaseSetAssetCategory)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AssetBaseSetAssetCategory"), typeof(_AssetBaseSetAssetCategory));
}
_AssetBaseSetAssetCategoryFunc(assetBase, val);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _AssetBaseGetAssetAutoUnload(IntPtr assetBase);
private static _AssetBaseGetAssetAutoUnload _AssetBaseGetAssetAutoUnloadFunc;
internal static bool AssetBaseGetAssetAutoUnload(IntPtr assetBase)
{
if (_AssetBaseGetAssetAutoUnloadFunc == null)
{
_AssetBaseGetAssetAutoUnloadFunc =
(_AssetBaseGetAssetAutoUnload)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AssetBaseGetAssetAutoUnload"), typeof(_AssetBaseGetAssetAutoUnload));
}
return _AssetBaseGetAssetAutoUnloadFunc(assetBase);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _AssetBaseSetAssetAutoUnload(IntPtr assetBase, bool val);
private static _AssetBaseSetAssetAutoUnload _AssetBaseSetAssetAutoUnloadFunc;
internal static void AssetBaseSetAssetAutoUnload(IntPtr assetBase, bool val)
{
if (_AssetBaseSetAssetAutoUnloadFunc == null)
{
_AssetBaseSetAssetAutoUnloadFunc =
(_AssetBaseSetAssetAutoUnload)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AssetBaseSetAssetAutoUnload"), typeof(_AssetBaseSetAssetAutoUnload));
}
_AssetBaseSetAssetAutoUnloadFunc(assetBase, val);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _AssetBaseGetAssetInternal(IntPtr assetBase);
private static _AssetBaseGetAssetInternal _AssetBaseGetAssetInternalFunc;
internal static bool AssetBaseGetAssetInternal(IntPtr assetBase)
{
if (_AssetBaseGetAssetInternalFunc == null)
{
_AssetBaseGetAssetInternalFunc =
(_AssetBaseGetAssetInternal)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AssetBaseGetAssetInternal"), typeof(_AssetBaseGetAssetInternal));
}
return _AssetBaseGetAssetInternalFunc(assetBase);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _AssetBaseSetAssetInternal(IntPtr assetBase, bool val);
private static _AssetBaseSetAssetInternal _AssetBaseSetAssetInternalFunc;
internal static void AssetBaseSetAssetInternal(IntPtr assetBase, bool val)
{
if (_AssetBaseSetAssetInternalFunc == null)
{
_AssetBaseSetAssetInternalFunc =
(_AssetBaseSetAssetInternal)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AssetBaseSetAssetInternal"), typeof(_AssetBaseSetAssetInternal));
}
_AssetBaseSetAssetInternalFunc(assetBase, val);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _AssetBaseGetAssetPrivate(IntPtr assetBase);
private static _AssetBaseGetAssetPrivate _AssetBaseGetAssetPrivateFunc;
internal static bool AssetBaseGetAssetPrivate(IntPtr assetBase)
{
if (_AssetBaseGetAssetPrivateFunc == null)
{
_AssetBaseGetAssetPrivateFunc =
(_AssetBaseGetAssetPrivate)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AssetBaseGetAssetPrivate"), typeof(_AssetBaseGetAssetPrivate));
}
return _AssetBaseGetAssetPrivateFunc(assetBase);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _AssetBaseRefreshAsset(IntPtr assetBase);
private static _AssetBaseRefreshAsset _AssetBaseRefreshAssetFunc;
internal static void AssetBaseRefreshAsset(IntPtr assetBase)
{
if (_AssetBaseRefreshAssetFunc == null)
{
_AssetBaseRefreshAssetFunc =
(_AssetBaseRefreshAsset)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AssetBaseRefreshAsset"), typeof(_AssetBaseRefreshAsset));
}
_AssetBaseRefreshAssetFunc(assetBase);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _AssetBaseGetAssetId(IntPtr assetBase);
private static _AssetBaseGetAssetId _AssetBaseGetAssetIdFunc;
internal static IntPtr AssetBaseGetAssetId(IntPtr assetBase)
{
if (_AssetBaseGetAssetIdFunc == null)
{
_AssetBaseGetAssetIdFunc =
(_AssetBaseGetAssetId)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"AssetBaseGetAssetId"), typeof(_AssetBaseGetAssetId));
}
return _AssetBaseGetAssetIdFunc(assetBase);
}
}
#endregion
#region Properties
#endregion
#region Methods
public string GetAssetName()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.AssetBaseGetAssetName(ObjectPtr->ObjPtr));
}
public void SetAssetName(string name)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.AssetBaseSetAssetName(ObjectPtr->ObjPtr, name);
}
public string GetAssetDescription()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.AssetBaseGetAssetDescription(ObjectPtr->ObjPtr));
}
public void SetAssetDescription(string val)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.AssetBaseSetAssetDescription(ObjectPtr->ObjPtr, val);
}
public string GetAssetCategory()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.AssetBaseGetAssetCategory(ObjectPtr->ObjPtr));
}
public void SetAssetCategory(string val)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.AssetBaseSetAssetCategory(ObjectPtr->ObjPtr, val);
}
public bool GetAssetAutoUnload()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.AssetBaseGetAssetAutoUnload(ObjectPtr->ObjPtr);
}
public void SetAssetAutoUnload(bool val)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.AssetBaseSetAssetAutoUnload(ObjectPtr->ObjPtr, val);
}
public bool GetAssetInternal()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.AssetBaseGetAssetInternal(ObjectPtr->ObjPtr);
}
public void SetAssetInternal(bool val)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.AssetBaseSetAssetInternal(ObjectPtr->ObjPtr, val);
}
public bool GetAssetPrivate()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.AssetBaseGetAssetPrivate(ObjectPtr->ObjPtr);
}
public void RefreshAsset()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.AssetBaseRefreshAsset(ObjectPtr->ObjPtr);
}
public string GetAssetId()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.AssetBaseGetAssetId(ObjectPtr->ObjPtr));
}
#endregion
}
}
| |
/************************************************************************
*
* The MIT License (MIT)
*
* Copyright (c) 2025 - Christian Falch
*
* 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 Xamarin.Forms;
using System.Linq.Expressions;
using System.Collections.Generic;
using NControlDemo.Classes;
using NControlDemo.FormsApp.IoC;
using NControlDemo.Helpers;
using NControlDemo.FormsApp.ViewModels;
using NControlDemo.FormsApp.Mvvm;
namespace NControlDemo.FormsApp.Views
{
/// <summary>
/// Base view.
/// </summary>
public abstract class BaseContentsView<TViewModel>: ContentPage, IView
where TViewModel : BaseViewModel
{
#region Private Members
/// <summary>
/// The view decorator.
/// </summary>
private readonly ViewDecorator<TViewModel> _viewDecorator;
/// <summary>
/// Main relative layout
/// </summary>
private readonly RelativeLayout _layout;
/// <summary>
/// The property change listeners.
/// </summary>
private readonly List<PropertyChangeListener> _propertyChangeListeners = new List<PropertyChangeListener>();
#endregion
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
public BaseContentsView ()
{
// Image provider
ImageProvider = Container.Resolve<IImageProvider>();
// Set up viewmodel and viewmodel values
ViewModel = Container.Resolve<TViewModel> ();
BindingContext = ViewModel;
// Bind title
this.SetBinding (Page.TitleProperty, GetPropertyName (vm => vm.Title));
// Loading/Progress overlay
_layout = new RelativeLayout ();
var contents = CreateContents ();
// Activity overflay and indiciator
_viewDecorator = new ViewDecorator<TViewModel> (_layout, contents);
// Set our content to be the relative layout with progress overlays etc.
Content = _layout;
}
#endregion
#region Public Properties
/// <summary>
/// Returns the ViewModel
/// </summary>
public TViewModel ViewModel{get; private set;}
#endregion
#region View LifeCycle
/// <summary>
/// Raised when the view has appeared on screen.
/// </summary>
protected override async void OnAppearing()
{
base.OnAppearing();
await ViewModel.OnAppearingAsync();
_viewDecorator.OnAppearing ();
}
/// <summary>
/// Raises the disappearing event.
/// </summary>
protected override void OnDisappearing ()
{
base.OnDisappearing ();
ViewModel.OnDisappearingAsync ();
_viewDecorator.OnDisappearing ();
}
/// <summary>
/// Application developers can override this method to provide behavior when the back button is pressed.
/// </summary>
/// <returns>To be added.</returns>
/// <remarks>To be added.</remarks>
protected override bool OnBackButtonPressed()
{
if (ViewModel.BackButtonCommand != null &&
ViewModel.BackButtonCommand.CanExecute(null))
ViewModel.BackButtonCommand.Execute(null);
return true;
}
#endregion
#region Protected Members
/// <summary>
/// Gets the image provide.
/// </summary>
/// <value>The image provide.</value>
protected IImageProvider ImageProvider {get;private set;}
/// <summary>
/// Implement to create the layout on the page
/// </summary>
/// <returns>The layout.</returns>
protected abstract View CreateContents ();
/// <summary>
/// Sets the background image.
/// </summary>
/// <param name="imageType">Image type.</param>
protected void SetBackgroundImage(string imageName)
{
// Background image
var image = new Image {
Source = ImageProvider.GetImageSource(imageName),
Aspect = Aspect.AspectFill
};
_layout.Children.Add (image, Constraint.Constant(0),
Constraint.RelativeToParent((parent) => parent.Height - 568),
Constraint.RelativeToParent((parent) => parent.Width),
Constraint.Constant(568));
}
/// <summary>
/// Calls the notify property changed event if it is attached. By using some
/// Expression/Func magic we get compile time type checking on our property
/// names by using this method instead of calling the event with a string in code.
/// </summary>
/// <param name="property">Property.</param>
protected string GetPropertyName<TOwner>(Expression<Func<TOwner, object>> property)
{
return PropertyNameHelper.GetPropertyName<TOwner> (property);
}
/// <summary>
/// Calls the notify property changed event if it is attached. By using some
/// Expression/Func magic we get compile time type checking on our property
/// names by using this method instead of calling the event with a string in code.
/// </summary>
/// <param name="property">Property.</param>
protected string GetPropertyName(Expression<Func<TViewModel, object>> property)
{
return PropertyNameHelper.GetPropertyName<TViewModel> (property);
}
/// <summary>
/// Listens for property change.
/// </summary>
/// <param name="property">Property.</param>
/// <typeparam name="TViewModel">The 1st type parameter.</typeparam>
protected void ListenForPropertyChange<TObject>(Expression<Func<TObject, object>> property, TObject obj, Action callback)
{
var changeListener = new PropertyChangeListener();
changeListener.Listen<TObject>(property, obj, callback);
_propertyChangeListeners.Add(changeListener);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using WixSharp.CommonTasks;
using sys = System.IO;
namespace WixSharp.Bootstrapper
{
//Useful stuff to have a look at:
//http://neilsleightholm.blogspot.com.au/2012/05/wix-burn-tipstricks.html
//https://wixwpf.codeplex.com/
/// <summary>
/// Class for defining a WiX standard Burn-based bootstrapper. By default the bootstrapper is using WiX default WiX bootstrapper UI.
/// </summary>
/// <example>The following is an example of defining a bootstrapper for two msi files and .NET Web setup.
/// <code>
/// var bootstrapper =
/// new Bundle("My Product",
/// new PackageGroupRef("NetFx40Web"),
/// new MsiPackage("productA.msi"),
/// new MsiPackage("productB.msi"));
///
/// bootstrapper.AboutUrl = "https://github.com/oleg-shilo/wixsharp/";
/// bootstrapper.IconFile = "app_icon.ico";
/// bootstrapper.Version = new Version("1.0.0.0");
/// bootstrapper.UpgradeCode = new Guid("6f330b47-2577-43ad-9095-1861bb25889b");
/// bootstrapper.Application.LogoFile = "logo.png";
///
/// bootstrapper.Build();
/// </code>
/// </example>
public class Bundle : WixProject
{
/// <summary>
/// Initializes a new instance of the <see cref="Bootstrapper"/> class.
/// </summary>
public Bundle()
{
if (!Compiler.AutoGeneration.LegacyDefaultIdAlgorithm)
{
// in case of Bundle project just do nothing
}
this.Include(WixExtension.NetFx);
this.Include(WixExtension.Bal);
}
/// <summary>
/// Initializes a new instance of the <see cref="Bootstrapper" /> class.
/// </summary>
/// <param name="name">The name of the project. Typically it is the name of the product to be installed.</param>
/// <param name="items">The project installable items (e.g. directories, files, registry keys, Custom Actions).</param>
public Bundle(string name, params ChainItem[] items)
{
if (!Compiler.AutoGeneration.LegacyDefaultIdAlgorithm)
{
// in case of Bundle project just do nothing
}
this.Include(WixExtension.NetFx);
this.Include(WixExtension.Bal);
Name = name;
Chain.AddRange(items);
}
/// <summary>
/// The disable rollbackSpecifies whether the bundle will attempt to rollback packages executed in the chain.
/// If "true" is specified then when a vital package fails to install only that package will rollback and the chain will stop with the error.
/// The default is "false" which indicates all packages executed during the chain will be rollback to their previous state when a vital package fails.
/// </summary>
public bool? DisableRollback;
/// <summary>
/// Specifies whether the bundle will attempt to create a system restore point when executing the chain. If "true" is specified then a system restore
/// point will not be created. The default is "false" which indicates a system restore point will be created when the bundle is installed, uninstalled,
/// repaired, modified, etc. If the system restore point cannot be created, the bundle will log the issue and continue.
/// </summary>
public bool? DisableSystemRestore;
/// <summary>
/// Specifies whether the bundle will start installing packages while other packages are still being cached.
/// If "true", packages will start executing when a rollback boundary is encountered. The default is "false"
/// which dictates all packages must be cached before any packages will start to be installed.
/// </summary>
public bool? ParallelCache;
/// <summary>
/// The legal copyright found in the version resources of final bundle executable.
/// If this attribute is not provided the copyright will be set to "Copyright (c) [Bundle/@Manufacturer]. All rights reserved.".
/// </summary>
[Xml]
public string Copyright;
/// <summary>
/// A URL for more information about the bundle to display in Programs and Features (also known as Add/Remove Programs).
/// </summary>
[Xml]
public string AboutUrl;
/// <summary>
/// Whether Packages and Payloads not assigned to a container should be added to the default attached container or if they
/// should be external. The default is yes.
/// </summary>
[Xml]
public bool? Compressed;
/// <summary>
/// The condition of the bundle. If the condition is not met, the bundle will refuse to run. Conditions are checked before the
/// bootstrapper application is loaded (before detect), and thus can only reference built-in variables such as variables which
/// indicate the version of the OS.
/// </summary>
[Xml]
public string Condition;
/// <summary>
/// Parameters of digitally sign
/// </summary>
public DigitalSignatureBootstrapper DigitalSignature;
/// <summary>
/// Determines whether the bundle can be removed via the Programs and Features (also known as Add/Remove Programs). If the value is
/// "yes" then the "Uninstall" button will not be displayed. The default is "no" which ensures there is an "Uninstall" button to remove
/// the bundle. If the "DisableModify" attribute is also "yes" or "button" then the bundle will not be displayed in Programs and
/// Features and another mechanism (such as registering as a related bundle addon) must be used to ensure the bundle can be removed.
/// </summary>
[Xml]
public bool? DisableRemove;
/// <summary>
/// Determines whether the bundle can be modified via the Programs and Features (also known as Add/Remove Programs). If the value is
/// "button" then Programs and Features will show a single "Uninstall/Change" button. If the value is "yes" then Programs and Features
/// will only show the "Uninstall" button". If the value is "no", the default, then a "Change" button is shown. See the DisableRemove
/// attribute for information how to not display the bundle in Programs and Features.
/// </summary>
[Xml]
public string DisableModify;
/// <summary>
/// A telephone number for help to display in Programs and Features (also known as Add/Remove Programs).
/// </summary>
[Xml]
public string HelpTelephone;
/// <summary>
/// A URL to the help for the bundle to display in Programs and Features (also known as Add/Remove Programs).
/// </summary>
[Xml]
public string HelpUrl;
/// <summary>
/// Path to an icon that will replace the default icon in the final Bundle executable. This icon will also be displayed in Programs and Features (also known as Add/Remove Programs).
/// </summary>
[Xml(Name = "IconSourceFile")]
public string IconFile;
/// <summary>
/// The publisher of the bundle to display in Programs and Features (also known as Add/Remove Programs).
/// </summary>
[Xml]
public string Manufacturer;
/// <summary>
/// The name of the parent bundle to display in Installed Updates (also known as Add/Remove Programs). This name is used to nest or group bundles that will appear as updates. If the
/// parent name does not actually exist, a virtual parent is created automatically.
/// </summary>
[Xml]
public string ParentName;
/// <summary>
/// Path to a bitmap that will be shown as the bootstrapper application is being loaded. If this attribute is not specified, no splash screen will be displayed.
/// </summary>
[Xml(Name = "SplashScreenSourceFile")]
public string SplashScreenSource;
/// <summary>
/// Set this string to uniquely identify this bundle to its own BA, and to related bundles. The value of this string only matters to the BA, and its value has no direct
/// effect on engine functionality.
/// </summary>
[Xml]
public string Tag;
/// <summary>
/// A URL for updates of the bundle to display in Programs and Features (also known as Add/Remove Programs).
/// </summary>
[Xml]
public string UpdateUrl;
/// <summary>
/// Unique identifier for a family of bundles. If two bundles have the same UpgradeCode the bundle with the highest version will be installed.
/// </summary>
[Xml]
public Guid UpgradeCode = Guid.NewGuid();
/// <summary>
/// The suppress auto insertion of WixMbaPrereq* variables in the bundle definition (WixMbaPrereqPackageId and WixMbaPrereqLicenseUrl).
/// <para>BA is relying on two internal variables that reflect .NET version (and license) that BA requires at runtime. If user defines
/// custom Wix# based BA the required variables are inserted automatically, similarly to the standards WiX/Burn BA. However some other
/// bundle packages (e.g. new PackageGroupRef("NetFx40Web")) may also define these variables so some duplication/collision is possible.
/// To avoid this you can suppress variables auto-insertion and define them manually as needed.</para>
/// </summary>
///<example>The following is an example of suppressing auto-insertion:
/// <code>
/// var bootstrapper = new Bundle("My Product Suite",
/// new PackageGroupRef("NetFx40Web"),
/// new MsiPackage(productMsi)
/// {
/// Id = "MyProductPackageId",
/// DisplayInternalUI = true
/// });
///
/// bootstrapper.SuppressWixMbaPrereqVars = true;
/// </code>
/// </example>
public bool SuppressWixMbaPrereqVars = false;
/// <summary>
/// The version of the bundle. Newer versions upgrade earlier versions of the bundles with matching UpgradeCodes. If the bundle is registered in Programs and Features then this attribute will be displayed in the Programs and Features user interface.
/// </summary>
[Xml]
public Version Version;
/// <summary>
/// The sequence of the packages to be installed
/// </summary>
public List<ChainItem> Chain = new List<ChainItem>();
/// <summary>
/// The instance of the Bootstrapper application class application. By default it is a LicenseBootstrapperApplication object.
/// </summary>
public WixStandardBootstrapperApplication Application = new LicenseBootstrapperApplication();
/// <summary>
/// The generic items to be added to the WiX <c>Bundle</c> element during the build. A generic item must implement
/// <see cref="IGenericEntity"/> interface;
///<example>The following is an example of extending WixSharp Bundle with otherwise not supported Bal:Condition:
/// <code>
/// class BalCondition : IXmlBuilder
/// {
/// public string Condition;
/// public string Message;
///
/// public XContainer[] ToXml()
/// {
/// return new XContainer[] {
/// new XElement(WixExtension.Bal.ToXName("Condition"), Condition)
/// .SetAttribute("Message", Message) };
/// }
/// }
///
/// var bootstrapper = new Bundle("My Product Suite", ...
/// bootstrapper.GenericItems.Add(new BalCondition { Condition = "some condition", Message = "Warning: ....." });
/// </code>
/// </example>
/// </summary>
public List<IGenericEntity> GenericItems = new List<IGenericEntity>();
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
public XContainer[] ToXml()
{
var result = new List<XContainer>();
var root = new XElement("Bundle",
new XAttribute("Name", Name));
root.AddAttributes(this.Attributes);
root.Add(this.MapToXmlAttributes());
if (Application is ManagedBootstrapperApplication app)
{
if (app.PrimaryPackageId == null)
{
var lastPackage = Chain.OfType<WixSharp.Bootstrapper.Package>().LastOrDefault();
if (lastPackage != null)
{
lastPackage.EnsureId();
app.PrimaryPackageId = lastPackage.Id;
}
}
//addresses https://wixsharp.codeplex.com/workitem/149
if (!SuppressWixMbaPrereqVars)
{
WixVariables["WixMbaPrereqPackageId"] = "Netfx4Full";
WixVariables.Add("WixMbaPrereqLicenseUrl", "NetfxLicense.rtf");
}
}
//important to call AutoGenerateSources after PrimaryPackageId is set
Application.AutoGenerateSources(this.OutDir);
root.Add(Application.ToXml());
var all_variabes = new List<Variable>();
all_variabes.AddRange(this.Variables);
all_variabes.AddRange(Application.Variables);
if (Application is IWixSharpManagedBootstrapperApplication wsApp)
if (wsApp.DowngradeWarningMessage.IsNotEmpty())
all_variabes.Add(new Variable("DowngradeWarningMessage", wsApp.DowngradeWarningMessage));
Compiler.ProcessWixVariables(this, root);
var context = new ProcessingContext
{
Project = this,
Parent = this,
XParent = root,
};
foreach (IGenericEntity item in all_variabes)
item.Process(context);
foreach (IGenericEntity item in GenericItems)
item.Process(context);
var xChain = root.AddElement("Chain");
foreach (var item in this.Chain)
xChain.Add(item.ToXml());
xChain.SetAttribute("DisableRollback", DisableRollback);
xChain.SetAttribute("DisableSystemRestore", DisableSystemRestore);
xChain.SetAttribute("ParallelCache", ParallelCache);
result.Add(root);
return result.ToArray();
}
/// <summary>
/// The Bundle string variables.
/// </summary>
/// <para>The variables are defined as a named values map.</para>
/// <para>If you need to access the variable value from the Package
/// you will need to add the MsiProperty mapped to this variable.
/// </para>
/// <example>
/// <code>
/// new ManagedBootstrapperApplication("ManagedBA.dll")
/// {
/// Variables = "FullInstall=Yes; Silent=No".ToStringVariables()
/// }
/// ...
/// new MsiPackage(msiFile) { MsiProperties = "FULL=[FullInstall]" },
/// </code>
/// </example>
public Variable[] Variables = new Variable[0];
/// <summary>
/// Builds WiX Bootstrapper application from the specified <see cref="Bundle" /> project instance.
/// </summary>
/// <param name="path">The path to the bootstrapper to be build.</param>
/// <returns></returns>
public string Build(string path = null)
{
if (!Compiler.AutoGeneration.LegacyDefaultIdAlgorithm)
{
// in case of Bundle project just do nothing
}
var output = new StringBuilder();
Action<string> collect = line => output.AppendLine(line);
Compiler.OutputWriteLine += collect;
try
{
if (path == null)
return Compiler.Build(this);
else
return Compiler.Build(this, path);
}
finally
{
ValidateCompileOutput(output.ToString());
Compiler.OutputWriteLine -= collect;
}
}
void ValidateCompileOutput(string output)
{
if (!this.SuppressWixMbaPrereqVars && output.Contains("'WixMbaPrereqPackageId' is declared in more than one location."))
{
Compiler.OutputWriteLine("======================================================");
Compiler.OutputWriteLine("");
Compiler.OutputWriteLine("WARNING: It looks like one of the packages defines " +
"WixMbaPrereqPackageId/WixMbaPrereqLicenseUrl in addition to the definition " +
"auto-inserted by Wix# managed BA. If it is the case set your Bundle project " +
"SuppressWixMbaPrereqVars to 'true' to fix the problem.");
Compiler.OutputWriteLine("");
Compiler.OutputWriteLine("======================================================");
}
else if (this.SuppressWixMbaPrereqVars && output.Contains("The Windows Installer XML variable !(wix.WixMbaPrereqPackageId) is unknown."))
{
Compiler.OutputWriteLine("======================================================");
Compiler.OutputWriteLine("");
Compiler.OutputWriteLine("WARNING: It looks like generation of WixMbaPrereqPackageId/WixMbaPrereqLicenseUrl " +
"was suppressed while none of other packages defines it. " +
"If it is the case set your Bundle project SuppressWixMbaPrereqVars to false to fix the problem.");
Compiler.OutputWriteLine("");
Compiler.OutputWriteLine("======================================================");
}
}
/// <summary>
/// Builds the WiX source file and generates batch file capable of building
/// WiX/MSI bootstrapper with WiX toolset.
/// </summary>
/// <param name="path">The path to the batch file to be created.</param>
/// <returns></returns>
public string BuildCmd(string path = null)
{
if (path == null)
return Compiler.BuildCmd(this);
else
return Compiler.BuildCmd(this, path);
}
/// <summary>
/// Validates this Bundle project packages.
/// </summary>
public void Validate()
{
var msiPackages = this.Chain.Where(x => (x is MsiPackage) && (x as MsiPackage).DisplayInternalUI == true);
foreach (MsiPackage item in msiPackages)
{
try
{
if (Tasks.IsEmbeddedUIPackage(item.SourceFile))
{
Compiler.OutputWriteLine("");
Compiler.OutputWriteLine("WARNING: You have selected enabled DisplayInternalUI for EmbeddedUI-based '"
+ sys.Path.GetFileName(item.SourceFile) + "'. Currently Burn (WiX) " +
"doesn't support integration with EmbeddedUI packages. Read more here: https://github.com/oleg-shilo/wixsharp/wiki/Wix%23-Bootstrapper-(Burn)-integration-notes");
Compiler.OutputWriteLine("");
}
}
catch { }
}
}
internal void ResetAutoIdGeneration(bool supressWarning)
{
WixGuid.ConsistentGenerationStartValue = this.UpgradeCode;
WixEntity.ResetIdGenerator(supressWarning);
}
}
/// <summary>
/// An interface that needs can be implemented by Silent (no-UI) BA.
/// </summary>
public interface IWixSharpManagedBootstrapperApplication
{
/// <summary>
/// Gets or sets the downgrade warning message. The message is displayed when bundle
/// detects a newer version of primary package is installed and the setup is about to exit.
/// </summary>
/// <value>
/// The downgrade warning message.
/// </value>
string DowngradeWarningMessage { get; set; }
}
/*
<Bundle Name="My Product"
Version="1.0.0.0"
Manufacturer="OSH"
AboutUrl="https://github.com/oleg-shilo/wixsharp/"
IconSourceFile="app_icon.ico"
UpgradeCode="acaa3540-97e0-44e4-ae7a-28c20d410a60">
<BootstrapperApplicationRef Id="WixStandardBootstrapperApplication.RtfLicense">
<bal:WixStandardBootstrapperApplication LicenseFile="readme.txt" LocalizationFile="" LogoFile="app_icon.ico" />
</BootstrapperApplicationRef>
<Chain>
<!-- Install .Net 4 Full -->
<PackageGroupRef Id="NetFx40Web"/>
<!--<ExePackage
Id="Netfx4FullExe"
Cache="no"
Compressed="no"
PerMachine="yes"
Permanent="yes"
Vital="yes"
SourceFile="C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bootstrapper\Packages\DotNetFX40\dotNetFx40_Full_x86_x64.exe"
InstallCommand="/q /norestart /ChainingPackage FullX64Bootstrapper"
DetectCondition="NETFRAMEWORK35='#1'"
DownloadUrl="http://go.microsoft.com/fwlink/?LinkId=164193" />-->
<RollbackBoundary />
<MsiPackage SourceFile="E:\Projects\WixSharp\src\WixSharp.Samples\Wix# Samples\Managed Setup\ManagedSetup.msi" Vital="yes" />
</Chain>
</Bundle>
*/
}
| |
using System;
public class Ex {
public static int test () {
int ocount = 0;
checked {
ocount = 0;
try {
ulong a = UInt64.MaxValue - 1;
ulong t = a++;
} catch {
ocount++;
}
if (ocount != 0)
return 1;
ocount = 0;
try {
ulong a = UInt64.MaxValue;
ulong t = a++;
} catch {
ocount++;
}
if (ocount != 1)
return 2;
ocount = 0;
try {
long a = Int64.MaxValue - 1;
long t = a++;
} catch {
ocount++;
}
if (ocount != 0)
return 3;
try {
long a = Int64.MaxValue;
long t = a++;
} catch {
ocount++;
}
if (ocount != 1)
return 4;
ocount = 0;
try {
ulong a = UInt64.MaxValue - 1;
ulong t = a++;
} catch {
ocount++;
}
if (ocount != 0)
return 5;
try {
ulong a = UInt64.MaxValue;
ulong t = a++;
} catch {
ocount++;
}
if (ocount != 1)
return 6;
ocount = 0;
try {
long a = Int64.MinValue + 1;
long t = a--;
} catch {
ocount++;
}
if (ocount != 0)
return 7;
ocount = 0;
try {
long a = Int64.MinValue;
long t = a--;
} catch {
ocount++;
}
if (ocount != 1)
return 8;
ocount = 0;
try {
ulong a = UInt64.MinValue + 1;
ulong t = a--;
} catch {
ocount++;
}
if (ocount != 0)
return 9;
ocount = 0;
try {
ulong a = UInt64.MinValue;
ulong t = a--;
} catch {
ocount++;
}
if (ocount != 1)
return 10;
ocount = 0;
try {
int a = Int32.MinValue + 1;
int t = a--;
} catch {
ocount++;
}
if (ocount != 0)
return 11;
ocount = 0;
try {
int a = Int32.MinValue;
int t = a--;
} catch {
ocount++;
}
if (ocount != 1)
return 12;
ocount = 0;
try {
uint a = 1;
uint t = a--;
} catch {
ocount++;
}
if (ocount != 0)
return 13;
ocount = 0;
try {
uint a = 0;
uint t = a--;
} catch {
ocount++;
}
if (ocount != 1)
return 14;
ocount = 0;
try {
sbyte a = 126;
sbyte t = a++;
} catch {
ocount++;
}
if (ocount != 0)
return 15;
ocount = 0;
try {
sbyte a = 127;
sbyte t = a++;
} catch {
ocount++;
}
if (ocount != 1)
return 16;
ocount = 0;
try {
} catch {
ocount++;
}
if (ocount != 0)
return 17;
ocount = 0;
try {
int a = 1 << 29;
int t = a*2;
} catch {
ocount++;
}
if (ocount != 0)
return 18;
ocount = 0;
try {
int a = 1 << 30;
int t = a*2;
} catch {
ocount++;
}
if (ocount != 1)
return 19;
ocount = 0;
try {
ulong a = 0xffffffffff;
ulong t = a*0x0ffffff;
} catch {
ocount++;
}
if (ocount != 0)
return 20;
ocount = 0;
try {
ulong a = 0xffffffffff;
ulong t = a*0x0fffffff;
} catch {
ocount++;
}
if (ocount != 1)
return 21;
}
return 0;
}
public static int Main () {
return test();
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NetGore.World;
using NUnit.Framework;
using SFML.Graphics;
// ReSharper disable AccessToModifiedClosure
namespace NetGore.Tests.NetGore
{
[TestFixture]
public class SpatialTests
{
static readonly Vector2 SpatialSize = new Vector2(1024, 512);
static IEnumerable<Entity> CreateEntities(int amount, Vector2 minPos, Vector2 maxPos)
{
var ret = new Entity[amount];
for (var i = 0; i < amount; i++)
{
ret[i] = new TestEntity { Position = RandomHelper.NextVector2(minPos, maxPos) };
}
return ret;
}
static IEnumerable<ISpatialCollection> GetSpatials()
{
var a = new LinearSpatialCollection();
a.SetAreaSize(SpatialSize);
var b = new DynamicGridSpatialCollection();
b.SetAreaSize(SpatialSize);
var c = new StaticGridSpatialCollection();
c.SetAreaSize(SpatialSize);
return new ISpatialCollection[] { a, b };
}
#region Unit tests
[Test]
public void AddTest()
{
foreach (var spatial in GetSpatials())
{
var entity = new TestEntity();
spatial.Add(entity);
Assert.IsTrue(spatial.CollectionContains(entity), "Current spatial: " + spatial);
}
}
[Test]
public void GetEntitiesTest()
{
const int count = 25;
var min = new Vector2(32, 64);
var max = new Vector2(256, 128);
var diff = max - min;
foreach (var spatial in GetSpatials())
{
var entities = CreateEntities(count, min, max);
spatial.Add(entities);
foreach (var entity in entities)
{
Assert.IsTrue(spatial.CollectionContains(entity), "Current spatial: " + spatial);
}
var found = spatial.GetMany(new Rectangle(min.X, min.Y, diff.X, diff.Y));
Assert.AreEqual(count, found.Count());
}
}
[Test]
public void MoveTest()
{
foreach (var spatial in GetSpatials())
{
var entity = new TestEntity();
spatial.Add(entity);
Assert.IsTrue(spatial.CollectionContains(entity), "Current spatial: " + spatial);
entity.Position = new Vector2(128, 128);
Assert.IsTrue(spatial.Contains(new Vector2(128, 128)), "Current spatial: " + spatial);
Assert.IsFalse(spatial.Contains(new Vector2(256, 128)), "Current spatial: " + spatial);
Assert.IsFalse(spatial.Contains(new Vector2(128, 256)), "Current spatial: " + spatial);
}
}
[Test(Description = "Puts an emphasis on ensuring Move() works.")]
public void MovementTest01()
{
var moveSize = (int)(Math.Min(SpatialSize.X, SpatialSize.Y) / 4);
var halfMoveSize = new Vector2(moveSize) / 2f;
var r = new Random(654987645);
foreach (var spatial in GetSpatials())
{
var entities = new List<TestEntity>();
for (var i = 0; i < 20; i++)
{
var e = new TestEntity
{ Position = new Vector2(r.Next((int)SpatialSize.X), r.Next((int)SpatialSize.Y)), Size = new Vector2(32) };
entities.Add(e);
spatial.Add(e);
Assert.IsTrue(spatial.CollectionContains(e), "Spatial: {0}, i: {1}", spatial.GetType().Name, i);
Assert.IsTrue(spatial.Contains(e.Position, x => x == e));
}
for (var i = 0; i < 40; i++)
{
foreach (var e in entities)
{
var v = new Vector2(r.Next(moveSize), r.Next(moveSize)) - halfMoveSize;
var newPos = v + e.Position;
if (newPos.X < 0 || newPos.X >= SpatialSize.X - e.Size.X)
v.X = 0;
if (newPos.Y < 0 || newPos.Y >= SpatialSize.Y - e.Size.Y)
v.Y = 0;
e.Move(v);
Assert.IsTrue(spatial.CollectionContains(e), "Spatial: {0}, i: {1}", spatial.GetType().Name, i);
Assert.IsTrue(spatial.Contains(e.Position, x => x == e), "Spatial: {0}, i: {1}", spatial.GetType().Name, i);
}
}
}
}
[Test(Description = "Puts an emphasis on ensuring Teleport works.")]
public void MovementTest02()
{
var moveSize = (int)(Math.Min(SpatialSize.X, SpatialSize.Y) / 4);
var halfMoveSize = new Vector2(moveSize) / 2f;
var r = new Random(654987645);
foreach (var spatial in GetSpatials())
{
var entities = new List<TestEntity>();
for (var i = 0; i < 20; i++)
{
var e = new TestEntity
{ Position = new Vector2(r.Next((int)SpatialSize.X), r.Next((int)SpatialSize.Y)), Size = new Vector2(32) };
entities.Add(e);
spatial.Add(e);
Assert.IsTrue(spatial.CollectionContains(e), "Spatial: {0}, i: {1}", spatial.GetType().Name, i);
Assert.IsTrue(spatial.Contains(e.Position, x => x == e));
}
for (var i = 0; i < 40; i++)
{
foreach (var e in entities)
{
var v = new Vector2(r.Next(moveSize), r.Next(moveSize)) - halfMoveSize;
var newPos = v + e.Position;
if (newPos.X < 0)
newPos.X = 0;
else if (newPos.X >= SpatialSize.X - e.Size.X)
newPos.X = SpatialSize.X - e.Size.X;
if (newPos.Y < 0)
newPos.Y = 0;
else if (newPos.Y >= SpatialSize.Y - e.Size.Y)
newPos.Y = SpatialSize.Y - e.Size.Y;
e.Position = newPos;
Assert.IsTrue(spatial.CollectionContains(e), "Spatial: {0}, i: {1}", spatial.GetType().Name, i);
Assert.IsTrue(spatial.Contains(e.Position, x => x == e), "Spatial: {0}, i: {1}", spatial.GetType().Name, i);
}
}
}
}
[Test(Description = "Tests both Teleport and Move().")]
public void MovementTest03()
{
var moveSize = (int)(Math.Min(SpatialSize.X, SpatialSize.Y) / 4);
var halfMoveSize = new Vector2(moveSize) / 2f;
var r = new Random(654987645);
foreach (var spatial in GetSpatials())
{
var entities = new List<TestEntity>();
for (var i = 0; i < 20; i++)
{
var e = new TestEntity
{ Position = new Vector2(r.Next((int)SpatialSize.X), r.Next((int)SpatialSize.Y)), Size = new Vector2(32) };
entities.Add(e);
spatial.Add(e);
Assert.IsTrue(spatial.CollectionContains(e), "Spatial: {0}, i: {1}", spatial.GetType().Name, i);
Assert.IsTrue(spatial.Contains(e.Position, x => x == e));
}
for (var i = 0; i < 40; i++)
{
foreach (var e in entities)
{
var v = new Vector2(r.Next(moveSize), r.Next(moveSize)) - halfMoveSize;
var newPos = v + e.Position;
var teleport = r.Next(0, 2) == 0;
if (teleport)
{
if (newPos.X < 0)
newPos.X = 0;
else if (newPos.X >= SpatialSize.X - e.Size.X)
newPos.X = SpatialSize.X - e.Size.X;
if (newPos.Y < 0)
newPos.Y = 0;
else if (newPos.Y >= SpatialSize.Y - e.Size.Y)
newPos.Y = SpatialSize.Y - e.Size.Y;
e.Position = newPos;
}
else
{
if (newPos.X < 0 || newPos.X >= SpatialSize.X - e.Size.X)
v.X = 0;
if (newPos.Y < 0 || newPos.Y >= SpatialSize.Y - e.Size.Y)
v.Y = 0;
e.Move(v);
}
Assert.IsTrue(spatial.CollectionContains(e), "Spatial: {0}, i: {1}", spatial.GetType().Name, i);
Assert.IsTrue(spatial.Contains(e.Position, x => x == e), "Spatial: {0}, i: {1}", spatial.GetType().Name, i);
}
}
}
}
[Test]
public void RemoveTest()
{
foreach (var spatial in GetSpatials())
{
var entity = new TestEntity();
spatial.Add(entity);
Assert.IsTrue(spatial.CollectionContains(entity), "Current spatial: " + spatial);
spatial.Remove(entity);
Assert.IsFalse(spatial.CollectionContains(entity), "Current spatial: " + spatial);
}
}
#endregion
class TestEntity : Entity
{
/// <summary>
/// When overridden in the derived class, gets if this <see cref="Entity"/> will collide against
/// walls. If false, this <see cref="Entity"/> will pass through walls and completely ignore them.
/// </summary>
public override bool CollidesAgainstWalls
{
get { return true; }
}
}
}
}
| |
using System;
using System.Drawing;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using MonoTouch.CoreAnimation;
using MonoTouch.CoreGraphics;
namespace ODRefreshControl
{
public class ODRefreshControl : UIControl
{
CAShapeLayer _shapeLayer, _arrowLayer, _highlightLayer;
UIActivityIndicatorView activity;
bool _refreshing, _canRefresh, _ignoreInset, _ignoreOffset, _didSetInset, _hasSectionHeaders;
float _lastOffset;
UIScrollView scrollView;
UIEdgeInsets originalContentInset;
public Action Action { get; set; }
public bool Refreshing { get { return _refreshing; } }
public bool WasManuallyStarted { get; private set; }
public UIColor ActivityIndicatorViewColor
{
get
{
if (this.activity != null)
return this.activity.Color;
return null;
}
set
{
if (this.activity != null)
this.activity.Color = value;
}
}
public UIActivityIndicatorViewStyle ActivityIndicatorViewStyle
{
get
{
if (this.activity != null)
return this.activity.ActivityIndicatorViewStyle;
return UIActivityIndicatorViewStyle.Gray;
}
set
{
if (this.activity != null)
this.activity.ActivityIndicatorViewStyle = value;
}
}
private UIColor _tintColor;
public UIColor TintColor
{
get
{
return _tintColor;
}
set
{
_tintColor = value;
if (_shapeLayer != null)
_shapeLayer.FillColor = _tintColor.CGColor;
}
}
const float kTotalViewHeight = 400;
const float kOpenedViewHeight = 44;
const float kMinTopPadding = 9;
const float kMaxTopPadding = 5;
const float kMinTopRadius = 12.5f;
const float kMaxTopRadius = 16;
const float kMinBottomRadius = 3;
const float kMaxBottomRadius = 16;
const float kMinBottomPadding = 4;
const float kMaxBottomPadding = 6;
const float kMinArrowSize = 2;
const float kMaxArrowSize = 3;
const float kMinArrowRadius = 5;
const float kMaxArrowRadius = 7;
const float kMaxDistance = 53;
public ODRefreshControl(UIScrollView scrollView)
: this (scrollView, null)
{
}
public ODRefreshControl(UIScrollView scrollView, UIActivityIndicatorView activity)
: base (new RectangleF(0, -1 * (kTotalViewHeight + scrollView.ContentInset.Top), scrollView.Frame.Size.Width, kTotalViewHeight))
{
this.scrollView = scrollView;
this.originalContentInset = this.scrollView.ContentInset;
this.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
this.scrollView.AddSubview(this);
this.scrollView.AddObserver(this, new NSString("contentOffset"), NSKeyValueObservingOptions.New, IntPtr.Zero);
this.scrollView.AddObserver(this, new NSString("contentInset"), NSKeyValueObservingOptions.New, IntPtr.Zero);
if (activity == null)
activity = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.Gray);
this.activity = activity;
this.activity.Center = new PointF((float)Math.Floor(this.Frame.Size.Width / 2), (float)Math.Floor(this.Frame.Size.Height / 2));
this.activity.AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin;
this.activity.Alpha = 0;
this.activity.StartAnimating();
this.AddSubview(this.activity);
_refreshing = false;
_canRefresh = true;
_ignoreInset = false;
_ignoreOffset = false;
_didSetInset = false;
_hasSectionHeaders = false;
TintColor = UIColor.FromRGBA(155 / 255, 162 / 255, 172 / 255, 1.0f);
_shapeLayer = new CAShapeLayer();
_shapeLayer.FillColor = TintColor.CGColor;
_shapeLayer.StrokeColor = UIColor.DarkGray.ColorWithAlpha(0.5f).CGColor;
_shapeLayer.LineWidth = 0.5f;
_shapeLayer.ShadowColor = UIColor.Black.CGColor;
_shapeLayer.ShadowOffset = new SizeF(0, 1);
_shapeLayer.ShadowOpacity = 0.4f;
_shapeLayer.ShadowRadius = 0.5f;
this.Layer.AddSublayer(_shapeLayer);
_arrowLayer = new CAShapeLayer();
_arrowLayer.StrokeColor = UIColor.DarkGray.ColorWithAlpha(0.5f).CGColor;
_arrowLayer.LineWidth = 0.5f;
_arrowLayer.FillColor = UIColor.White.CGColor;
_shapeLayer.AddSublayer(_arrowLayer);
_highlightLayer = new CAShapeLayer();
_highlightLayer.FillColor = UIColor.White.ColorWithAlpha(0.2f).CGColor;
_shapeLayer.AddSublayer(_highlightLayer);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// remove observers
if (this.scrollView != null)
{
this.scrollView.RemoveObserver(this, new NSString("contentOffset"));
this.scrollView.RemoveObserver(this, new NSString("contentInset"));
this.scrollView = null;
}
}
base.Dispose(disposing);
}
public override void ObserveValue(NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context)
{
//base.ObserveValue(keyPath, ofObject, change, context);
if (keyPath.ToString().ToLower() == "contentInset".ToLower())
{
if (!_ignoreInset)
{
this.originalContentInset = (change["new"] as NSValue).UIEdgeInsetsValue;
this.Frame = new RectangleF(0, -1 * (kTotalViewHeight + this.scrollView.ContentInset.Top), this.scrollView.Frame.Size.Width, kTotalViewHeight);
}
return;
}
if (!this.Enabled || this._ignoreOffset)
return;
float offset = (change["new"] as NSValue).PointFValue.Y + this.originalContentInset.Top;
if (_refreshing)
{
if (offset != 0)
{
// keep thing pinned at the top
CATransaction.Begin();
CATransaction.SetValueForKey(NSNumber.FromBoolean(true), CATransaction.DisableActionsKey);
_shapeLayer.Position = new PointF(0, kMaxDistance + offset + kOpenedViewHeight);
CATransaction.Commit();
this.activity.Center = new PointF((float)Math.Floor(this.Frame.Size.Width / 2), (float)Math.Min(offset + this.Frame.Size.Height + Math.Floor(kOpenedViewHeight / 2), this.Frame.Size.Height - kOpenedViewHeight / 2));
_ignoreInset = true;
_ignoreOffset = true;
if (offset < 0)
{
// set the inset depending on the situation
if (offset >= kOpenedViewHeight * -1)
{
if (!this.scrollView.Dragging)
{
if (!_didSetInset)
{
_didSetInset = true;
_hasSectionHeaders = false;
if (this.scrollView is UITableView)
{
for (int i = 0; i < (this.scrollView as UITableView).NumberOfSections(); ++i)
{
if ((this.scrollView as UITableView).RectForHeaderInSection(i).Size.Height != 0)
{
_hasSectionHeaders = true;
break;
}
}
}
}
if (_hasSectionHeaders)
this.scrollView.ContentInset = new UIEdgeInsets(Math.Min(offset * -1, kOpenedViewHeight) + this.originalContentInset.Top, this.originalContentInset.Left, this.originalContentInset.Bottom, this.originalContentInset.Right);
else
this.scrollView.ContentInset = new UIEdgeInsets(kOpenedViewHeight + this.originalContentInset.Top, this.originalContentInset.Left, this.originalContentInset.Bottom, this.originalContentInset.Right);
}
else if(_didSetInset && _hasSectionHeaders)
{
this.scrollView.ContentInset = new UIEdgeInsets(-1 * offset + this.originalContentInset.Top, this.originalContentInset.Left, this.originalContentInset.Bottom, this.originalContentInset.Right);
}
}
}
else if (_hasSectionHeaders)
{
this.scrollView.ContentInset = this.originalContentInset;
}
_ignoreInset = false;
_ignoreOffset = false;
}
return;
}
else
{
// check if we can trigger a new refresh and if we can draw the control
bool dontDraw = false; // line 230
if (!_canRefresh)
{
if (offset >= 0)
{
// we can refresh again after the control is scrolled out of view
_canRefresh = true;
_didSetInset = false;
}
else
{
dontDraw = true;
}
}
else
{
if (offset >= 0)
{
// don't draw if the control is not visible
dontDraw = true;
}
}
if (offset > 0 && _lastOffset > offset && !this.scrollView.Tracking)
{
// if we are scrolling too fast, don't draw, and don't trigger unless the scrollView bounced back
// removed behavior Heath
//_canRefresh = false;
//dontDraw = true;
}
if (dontDraw)
{
_shapeLayer.Path = null;
_shapeLayer.ShadowPath = new CGPath(IntPtr.Zero);
_arrowLayer.Path = null;
_highlightLayer.Path = null;
_lastOffset = offset;
return;
}
}
_lastOffset = offset; // line 260
bool triggered = false;
CGPath path = new CGPath();
// calculate some useful points and values
float verticalShift = (float)Math.Max(0, -1 * ((kMaxTopRadius + kMaxBottomRadius + kMaxTopPadding + kMaxBottomPadding) + offset));
float distance = (float)Math.Min(kMaxDistance, (float)Math.Abs(verticalShift));
float percentage = 1 - (distance / kMaxDistance);
float currentTopPadding = lerp(kMinTopPadding, kMaxTopPadding, percentage);
float currentTopRadius = lerp(kMinTopRadius, kMaxTopRadius, percentage);
float currentBottomRadius = lerp(kMinBottomRadius, kMaxBottomRadius, percentage);
float currentBottomPadding = lerp(kMinBottomPadding, kMaxBottomPadding, percentage);
PointF bottomOrigin = new PointF((float)Math.Floor(this.Bounds.Size.Width / 2), this.Bounds.Size.Height - currentBottomPadding - currentBottomRadius);
PointF topOrigin = PointF.Empty;
if (distance == 0)
{
topOrigin = new PointF((float)Math.Floor(this.Bounds.Size.Width / 2), bottomOrigin.Y);
}
else
{
topOrigin = new PointF((float)Math.Floor(this.Bounds.Size.Width / 2), this.Bounds.Size.Height + offset + currentTopPadding + currentTopRadius);
if (percentage == 0)
{
bottomOrigin.Y -= (float)Math.Abs(verticalShift) - kMaxDistance;
triggered = true;
}
}
// top semicircle
path.AddArc(topOrigin.X, topOrigin.Y, currentTopRadius, 0, (float)Math.PI, true);
// left curve
PointF leftCp1 = new PointF(lerp((topOrigin.X - currentTopRadius), (bottomOrigin.X - currentBottomRadius), 0.1f), lerp(topOrigin.Y, bottomOrigin.Y, 0.2f));
PointF leftCp2 = new PointF(lerp((topOrigin.X - currentTopRadius), (bottomOrigin.X - currentBottomRadius), 0.9f), lerp(topOrigin.Y, bottomOrigin.Y, 0.2f));
PointF leftDestination = new PointF(bottomOrigin.X - currentBottomRadius, bottomOrigin.Y);
path.AddCurveToPoint(leftCp1, leftCp2, leftDestination);
// bottom semicircle
path.AddArc(bottomOrigin.X, bottomOrigin.Y, currentBottomRadius, (float)Math.PI, 0, true);
// right curve
PointF rightCp2 = new PointF(lerp((topOrigin.X + currentTopRadius), (bottomOrigin.X + currentBottomRadius), 0.1f), lerp(topOrigin.Y, bottomOrigin.Y, 0.2f));
PointF rightCp1 = new PointF(lerp((topOrigin.X + currentTopRadius), (bottomOrigin.X + currentBottomRadius), 0.9f), lerp(topOrigin.Y, bottomOrigin.Y, 0.2f));
PointF rightDestination = new PointF(bottomOrigin.X + currentTopRadius, topOrigin.Y);
path.AddCurveToPoint (rightCp1, rightCp2, rightDestination);
path.CloseSubpath();
if (!triggered) // line 309
{
// set paths
_shapeLayer.Path = path;
_shapeLayer.ShadowPath = path;
// add the arrow shape
float currentArrowSize = lerp(kMinArrowSize, kMaxArrowSize, percentage);
float currentArrowRadius = lerp(kMinArrowRadius, kMaxArrowRadius, percentage);
float arrowBigRadius = currentArrowRadius + (currentArrowSize / 2);
float arrowSmallRadius = currentArrowRadius - (currentArrowSize / 2);
CGPath arrowPath = new CGPath();
/*
arrowPath.AddArc(topOrigin.X, topOrigin.Y, arrowBigRadius, 0, 3 * (float)Math.PI, false);
arrowPath.AddLineToPoint(topOrigin.X, topOrigin.Y - arrowBigRadius - currentArrowSize);
arrowPath.AddLineToPoint(topOrigin.X + (2 * currentArrowSize), topOrigin.Y - arrowBigRadius + (currentArrowSize / 2));
arrowPath.AddLineToPoint(topOrigin.X, topOrigin.Y - arrowBigRadius + (2 * currentArrowSize));
arrowPath.AddLineToPoint(topOrigin.X, topOrigin.Y - arrowBigRadius + currentArrowSize);
arrowPath.AddArc(topOrigin.X, topOrigin.Y, arrowSmallRadius, 3 * (float)Math.PI, 0, true);
*/
arrowPath.AddArc (topOrigin.X, topOrigin.Y, arrowBigRadius, 0, 3 * (float) Math.PI / 2.0f, false);
arrowPath.AddLineToPoint (topOrigin.X, topOrigin.Y - arrowBigRadius - currentArrowSize);
arrowPath.AddLineToPoint (topOrigin.X + (2 * currentArrowSize), topOrigin.Y - arrowBigRadius + (currentArrowSize / 2.0f));
arrowPath.AddLineToPoint (topOrigin.X, topOrigin.Y - arrowBigRadius + (2 * currentArrowSize));
arrowPath.AddLineToPoint (topOrigin.X, topOrigin.Y - arrowBigRadius + currentArrowSize);
arrowPath.AddArc (topOrigin.X, topOrigin.Y, arrowSmallRadius, 3 * (float) Math.PI / 2.0f, 0, true);
arrowPath.CloseSubpath();
_arrowLayer.Path = arrowPath;
_arrowLayer.FillRule = CAShapeLayer.FillRuleEvenOdd;
arrowPath.Dispose();
// add the highlight shape
CGPath highlightPath = new CGPath();
highlightPath.AddArc(topOrigin.X, topOrigin.Y, currentTopRadius, 0, (float)Math.PI, true);
highlightPath.AddArc(topOrigin.X, topOrigin.Y + 1.25f, currentTopRadius, (float)Math.PI, 0, false);
_highlightLayer.Path = highlightPath;
_highlightLayer.FillRule = CAShapeLayer.FillRuleNonZero;
highlightPath.Dispose();
}
else
{
// start the shape disappearance animation
float radius = lerp(kMinBottomRadius, kMaxBottomRadius, 0.2f);
CABasicAnimation pathMorph = CABasicAnimation.FromKeyPath("path");
pathMorph.Duration = 0.15f;
pathMorph.FillMode = CAFillMode.Forwards;
pathMorph.RemovedOnCompletion = false;
CGPath toPath = new CGPath();
toPath.AddArc(topOrigin.X, topOrigin.Y, radius, 0, (float)Math.PI, true);
toPath.AddCurveToPoint(topOrigin.X - radius, topOrigin.Y, topOrigin.X - radius, topOrigin.Y, topOrigin.X - radius, topOrigin.Y);
toPath.AddArc(topOrigin.X, topOrigin.Y, radius, (float)Math.PI, 0, true);
toPath.AddCurveToPoint(topOrigin.X + radius, topOrigin.Y, topOrigin.X + radius, topOrigin.Y, topOrigin.X + radius, topOrigin.Y);
toPath.CloseSubpath();
pathMorph.To = new NSValue(toPath.Handle);
_shapeLayer.AddAnimation(pathMorph, null);
CABasicAnimation shadowPathMorph = CABasicAnimation.FromKeyPath("shadowPath");
shadowPathMorph.Duration = 0.15f;
shadowPathMorph.FillMode = CAFillMode.Forwards;
shadowPathMorph.RemovedOnCompletion = false;
shadowPathMorph.To = new NSValue(toPath.Handle);
_shapeLayer.AddAnimation(shadowPathMorph, null);
toPath.Dispose();
CABasicAnimation shapeAlphaAnimation = CABasicAnimation.FromKeyPath("opacity");
shapeAlphaAnimation.Duration = 0.1f;
shapeAlphaAnimation.BeginTime = CAAnimation.CurrentMediaTime() + 0.1f;
shapeAlphaAnimation.To = new NSNumber(0);
shapeAlphaAnimation.FillMode = CAFillMode.Forwards;
shapeAlphaAnimation.RemovedOnCompletion = false;
_shapeLayer.AddAnimation(shapeAlphaAnimation, null);
CABasicAnimation alphaAnimation = CABasicAnimation.FromKeyPath("opacity");
alphaAnimation.Duration = 0.1f;
alphaAnimation.To = new NSNumber (0);
alphaAnimation.FillMode = CAFillMode.Forwards;
alphaAnimation.RemovedOnCompletion = false;
_arrowLayer.AddAnimation(alphaAnimation, null);
_highlightLayer.AddAnimation(alphaAnimation, null);
CATransaction.Begin();
CATransaction.DisableActions = true;
activity.Layer.Transform = CATransform3D.MakeScale(0.1f, 0.1f, 1f);
CATransaction.Commit();
UIView.Animate (0.2f, 0.15f, UIViewAnimationOptions.CurveLinear, () => {
activity.Alpha = 1;
activity.Layer.Transform = CATransform3D.MakeScale(1, 1, 1);
}, null);
_refreshing = true;
_canRefresh = false;
this.SendActionForControlEvents(UIControlEvent.ValueChanged);
if (this.Action != null)
this.Action();
}
path.Dispose();
}
public void BeginRefreshing()
{
if (_refreshing)
return;
CABasicAnimation alphaAnimation = CABasicAnimation.FromKeyPath("opacity");
alphaAnimation.Duration = 0.0001f;
alphaAnimation.To = new NSNumber(0);
alphaAnimation.FillMode = CAFillMode.Forwards;
alphaAnimation.RemovedOnCompletion = false;
_shapeLayer.AddAnimation(alphaAnimation, null);
_arrowLayer.AddAnimation(alphaAnimation, null);
_highlightLayer.AddAnimation(alphaAnimation, null);
this.activity.Center = new PointF((float)Math.Floor(this.Frame.Size.Width / 2), (float)Math.Min(this.Frame.Size.Height + Math.Floor(kOpenedViewHeight / 2), this.Frame.Size.Height - kOpenedViewHeight / 2));
this.activity.Alpha = 1;
this.activity.Layer.Transform = CATransform3D.MakeScale (1, 1, 1);
PointF offset = this.scrollView.ContentOffset;
_ignoreInset = true;
this.scrollView.ContentInset = new UIEdgeInsets(kOpenedViewHeight + this.originalContentInset.Top, this.originalContentInset.Left, this.originalContentInset.Bottom, this.originalContentInset.Right);
_ignoreInset = false;
offset.Y -= kMaxDistance;
this.scrollView.SetContentOffset(offset, false);
_refreshing = true;
_canRefresh = false;
this.WasManuallyStarted = true;
if (this.Action != null)
this.Action();
}
public void EndRefreshing()
{
if (!_refreshing)
return;
_refreshing = false;
// create a temporary retain-cycle, so the scrollview won't be released
// halfway through the end animation.
// this allows for the refresh control to clean up the observer,
// in the case the scrollView is released while the animation is running
UIView.Animate (0.4, () => {
_ignoreInset = true;
this.scrollView.ContentInset = originalContentInset;
_ignoreInset = false;
activity.Alpha = 0;
activity.Layer.Transform = CATransform3D.MakeScale(0.1f, 0.1f, 1);
}, () => {
_shapeLayer.RemoveAllAnimations();
_shapeLayer.Path = null;
_shapeLayer.ShadowPath = new CGPath(IntPtr.Zero);
_shapeLayer.Position = PointF.Empty;
_arrowLayer.RemoveAllAnimations();
_arrowLayer.Path = null;
_highlightLayer.RemoveAllAnimations();
_highlightLayer.Path = null;
// we need to use the scrollview somehow in the end block,
// or it'll get released in the animation block. ?? not true for xamarin.ios ??
_ignoreInset = true;
this.scrollView.ContentInset = originalContentInset;
_ignoreInset = false;
this.WasManuallyStarted = false;
});
}
static float lerp (float a, float b, float p)
{
return a + (b - a) * p;
}
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder Utilities
// File : FilePath.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 12/06/2009
// Note : Copyright 2006-2009, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a class used to represent a file path. Support is
// included for treating the path as fixed or relative and for expanding
// environment variables in the path name.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.3.4.0 12/29/2006 EFW Created the code
// 1.8.0.0 06/21/2008 EFW Added handling of MSBuild variable references and
// reworked BasePath support to make it useable in
// a multi-project environment like Visual Studio.
//=============================================================================
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using IOPath = System.IO.Path;
using SandcastleBuilder.Utils.Design;
namespace SandcastleBuilder.Utils
{
/// <summary>
/// This class is used to represent a file path. Support is included for
/// treating the path as fixed or relative and for expanding environment
/// variables in the path name.
/// </summary>
[Serializable, DefaultProperty("Path"),
Editor(typeof(FilePathObjectEditor), typeof(UITypeEditor)),
TypeConverter(typeof(FilePathTypeConverter))]
public class FilePath : ICloneable
{
#region Private data members
//=====================================================================
// This is used to convert MSBuild variable references to normal
// environment variable references.
internal static Regex reMSBuildVar = new Regex(@"\$\((.*?)\)");
private IBasePathProvider basePathProvider; // Base path provider
private string filePath; // Instance path
private bool isFixedPath;
#endregion
#region Properties
//=====================================================================
/// <summary>
/// This is used to get the base path provider for the object.
/// </summary>
[Browsable(false), XmlIgnore]
public IBasePathProvider BasePathProvider
{
get { return basePathProvider; }
}
/// <summary>
/// This returns the base path for the object
/// </summary>
/// <value>If no <see cref="IBasePathProvider" /> has been specified,
/// this returns the current directory.</value>
[Browsable(false)]
public string BasePath
{
get
{
if(basePathProvider == null)
return Directory.GetCurrentDirectory();
return basePathProvider.BasePath;
}
}
/// <summary>
/// This is used to get or set the path to use.
/// </summary>
/// <value>When set, if the path is not rooted (a relative path),
/// <see cref="IsFixedPath"/> is set to false. If rooted (an absolute
/// path), it is not changed. This property always returns a fully
/// qualified path but without any environment variable expansions.
/// <p/>If set to a null or empty string, the file path is cleared and
/// is considered to be undefined.</value>
/// <note type="note">MSBuild environment variable references are
/// also supported (i.e. $(DXROOT), $(OutputPath), etc.). However,
/// they will only be resolved if the <see cref="BasePathProvider" />
/// resolves them.</note>
/// <example>
/// <code lang="cs">
/// FilePath path = new FilePath();
///
/// // Set it to a relative path
/// path.Path = @"..\..\Test.txt";
///
/// // Set it to an absolute path
/// path.Path = @"C:\My Documents\Info.doc";
///
/// // Set it to a path based on an environment variable
/// path.Path = @"%HOMEDRIVE%%HOMEPATH%\Favorites\*.*";
/// </code>
/// <code lang="vbnet">
/// Dim path As New FilePath()
///
/// ' Set it to a relative path
/// path.Path = "..\..\Test.txt"
///
/// ' Set it to an absolute path
/// path.Path = "C:\My Documents\Info.doc"
///
/// ' Set it to a path based on an environment variable
/// path.Path = "%HOMEDRIVE%%HOMEPATH%\Favorites\*.*"
/// </code>
/// </example>
[XmlIgnore, Description("The fully qualified path but without " +
"environment variable expansions"),
RefreshProperties(RefreshProperties.Repaint)]
public virtual string Path
{
get { return filePath; }
set
{
this.OnPersistablePathChanging(EventArgs.Empty);
if(value == null || value.Trim().Length == 0)
{
filePath = String.Empty; // Undefined
isFixedPath = false;
}
else
{
filePath = value.Trim();
// Perform custom path resolution and expand environment
// variables for the rooted check.
string tempPath = Environment.ExpandEnvironmentVariables(
(basePathProvider != null) ? basePathProvider.ResolvePath(filePath) :
filePath).Trim();
if(!IOPath.IsPathRooted(tempPath))
{
// Variables are not expanded
filePath = FilePath.RelativeToAbsolutePath(
this.BasePath, filePath);
isFixedPath = false;
}
}
this.OnPersistablePathChanged(EventArgs.Empty);
}
}
/// <summary>
/// This is used to retrieve the file path in a format suitable for
/// persisting to storage based on the current settings.
/// </summary>
/// <remarks>If <see cref="IsFixedPath"/> is true, an absolute path
/// is always returned. If false, the path is returned in a form that
/// is relative to the path stored in the <see cref="BasePath"/>
/// property.</remarks>
[Browsable(false), DefaultValue(""), Description("The file path as " +
"it should be persisted for storage based on the current settings")]
public virtual string PersistablePath
{
get
{
Match m = reMSBuildVar.Match(filePath);
// If fixed, blank, or starts with an environment variable,
// return it as-is.
if(isFixedPath || filePath.Length == 0 || filePath[0] == '%' ||
(m.Success && m.Index == 0))
return filePath;
return FilePath.AbsoluteToRelativePath(this.BasePath, filePath);
}
set { this.Path = value; }
}
/// <summary>
/// This read-only property can be used to determine whether or not
/// the file path exists.
/// </summary>
[Description("This indicates whether or not the file path exists")]
public virtual bool Exists
{
get
{
string fileSpec, checkPath = this.ToString();
int pos;
if(checkPath.IndexOfAny(new char[] { '*', '?' }) == -1)
return File.Exists(checkPath);
try
{
if(!Directory.Exists(IOPath.GetDirectoryName(checkPath)))
return false;
pos = checkPath.LastIndexOf('\\');
if(pos == -1)
{
fileSpec = checkPath;
checkPath = Directory.GetCurrentDirectory();
}
else
{
fileSpec = checkPath.Substring(pos + 1);
checkPath = checkPath.Substring(0, pos);
}
string[] files = Directory.GetFiles(checkPath, fileSpec);
return (files.Length != 0);
}
catch
{
// Ignore the exception
return false;
}
}
}
/// <summary>
/// This read-only property is used to display the fully qualified
/// path with environment variable expansions in the designer.
/// </summary>
[Description("The fully qualified path with environment variables " +
"expanded")]
public string ExpandedPath
{
get { return this.ToString(); }
}
/// <summary>
/// This is used to indicate whether or not the path will be treated
/// as a relative or fixed path when converted retrieved via the
/// <see cref="PersistablePath"/> property.
/// </summary>
/// <value>If true, the path is returned as a fixed path when
/// retrieved. If false, it is returned as a path relative to the
/// current value of the <see cref="BasePath"/> property.</value>
[DefaultValue(false), Description("If true, the path is returned " +
"as an absolute path by the PersistablePath property. If false, " +
"it is returned as a path relative to the value of the static " +
"BasePath property."), RefreshProperties(RefreshProperties.Repaint)]
public bool IsFixedPath
{
get { return isFixedPath; }
set
{
this.OnPersistablePathChanging(EventArgs.Empty);
isFixedPath = value;
this.OnPersistablePathChanged(EventArgs.Empty);
}
}
#endregion
#region Events
//=====================================================================
/// <summary>
/// This event is raised when the persistable path is about to be
/// changed.
/// </summary>
public event EventHandler PersistablePathChanging;
/// <summary>
/// This raises the <see cref="PersistablePathChanging" /> event
/// </summary>
/// <param name="e">The event arguments</param>
protected void OnPersistablePathChanging(EventArgs e)
{
var handler = PersistablePathChanging;
if(handler != null)
handler(this, e);
}
/// <summary>
/// This event is raised when the persistable path changes
/// </summary>
public event EventHandler PersistablePathChanged;
/// <summary>
/// This raises the <see cref="PersistablePathChanged" /> event
/// </summary>
/// <param name="e">The event arguments</param>
protected void OnPersistablePathChanged(EventArgs e)
{
var handler = PersistablePathChanged;
if(handler != null)
handler(this, e);
}
#endregion
#region Static methods and operators
//=====================================================================
/// <summary>
/// This is used to handle an implicit conversion from a
/// <see cref="FilePath"/> object to a string.
/// </summary>
/// <param name="filePath">The <see cref="FilePath"/> to convert.</param>
/// <returns>The file path as a relative or absolute path string
/// based on its current settings.</returns>
/// <example>
/// <code lang="cs">
/// FilePath filePath = new FilePath(@"%APPDATA%\TestApp\App.config");
///
/// // The FilePath object is automatically converted to a string
/// // representing the expanded, fully qualified path.
/// string pathString = filePath;
/// </code>
/// <code lang="vbnet">
/// Dim filePath As New FilePath("%APPDATA%\TestApp\App.config")
///
/// ' The FilePath object is automatically converted to a string
/// ' representing the expanded, fully qualified path.
/// Dim pathString As String = filePath
/// </code>
/// </example>
public static implicit operator String(FilePath filePath)
{
if(filePath == null)
return null;
return filePath.ToString();
}
/// <summary>
/// Overload for equal operator.
/// </summary>
/// <param name="firstPath">The first object to compare</param>
/// <param name="secondPath">The second object to compare</param>
/// <returns>True if equal, false if not.</returns>
public static bool operator == (FilePath firstPath, FilePath secondPath)
{
if((object)firstPath == null && (object)secondPath == null)
return true;
if((object)firstPath == null)
return false;
return firstPath.Equals(secondPath);
}
/// <summary>
/// Overload for not equal operator.
/// </summary>
/// <param name="firstPath">The first object to compare</param>
/// <param name="secondPath">The second object to compare</param>
/// <returns>True if not equal, false if they are.</returns>
public static bool operator != (FilePath firstPath, FilePath secondPath)
{
if((object)firstPath == null && (object)secondPath == null)
return false;
if(firstPath == null)
return true;
return !firstPath.Equals(secondPath);
}
/// <summary>
/// This returns the fully qualified path for the specified path.
/// This version allows wildcards in the filename part if present.
/// </summary>
/// <param name="path">The path to expand</param>
/// <returns>The fully qualified path name</returns>
/// <remarks>The <b>System.IO.Path</b> version of
/// <see cref="System.IO.Path.GetFullPath"/> will throw an exception
/// if the path contains wildcard characters. This version does not.
/// </remarks>
public static string GetFullPath(string path)
{
if(path == null)
return null;
if(!path.Contains("*") && !path.Contains("?"))
return IOPath.GetFullPath(path);
string fullPath = IOPath.GetFullPath(IOPath.GetDirectoryName(path));
return fullPath + IOPath.DirectorySeparatorChar +
IOPath.GetFileName(path);
}
/// <summary>
/// This helper method can be used to convert an absolute path to one
/// that is relative to the given base path.
/// </summary>
/// <param name="basePath">The base path</param>
/// <param name="absolutePath">An absolute path</param>
/// <returns>A path to the given absolute path that is relative to the
/// given base path.</returns>
/// <remarks>If the base path is null or empty, the current working
/// folder is used.</remarks>
/// <example>
/// <code lang="cs">
/// string basePath = @"E:\DotNet\CS\TestProject\Source";
/// string absolutePath = @"E:\DotNet\CS\TestProject\Doc\Help.html";
///
/// string relativePath = FilePath.AbsoluteToRelativePath(basePath,
/// absolutePath);
///
/// Console.WriteLine(relativePath);
///
/// // Results in: ..\Doc\Help.html
/// </code>
/// <code lang="vbnet">
/// Dim basePath As String = "E:\DotNet\CS\TestProject\Source"
/// Dim absolutePath As String = "E:\DotNet\CS\TestProject\Doc\Help.html"
///
/// Dim relativePath As String = _
/// FilePath.AbsoluteToRelativePath(basePath, absolutePath);
///
/// Console.WriteLine(relativePath)
///
/// ' Results in: ..\Doc\Help.html
/// </code>
/// </example>
public static string AbsoluteToRelativePath(string basePath,
string absolutePath)
{
bool hasBackslash = false;
string relPath;
int minLength, idx;
// If not specified, use the current folder as the base path
if(basePath == null || basePath.Trim().Length == 0)
basePath = Directory.GetCurrentDirectory();
else
basePath = IOPath.GetFullPath(basePath);
if(absolutePath == null)
absolutePath = String.Empty;
// Just in case, make sure the path is absolute
if(!IOPath.IsPathRooted(absolutePath))
absolutePath = FilePath.GetFullPath(absolutePath);
// Remove trailing backslashes for comparison
if(FolderPath.IsPathTerminated(basePath))
basePath = basePath.Substring(0, basePath.Length - 1);
if(FolderPath.IsPathTerminated(absolutePath))
{
absolutePath = absolutePath.Substring(0, absolutePath.Length - 1);
hasBackslash = true;
}
// Split the paths into their component parts
char[] separators = { IOPath.DirectorySeparatorChar,
IOPath.AltDirectorySeparatorChar, IOPath.VolumeSeparatorChar };
string[] baseParts = basePath.Split(separators);
string[] absParts = absolutePath.Split(separators);
// Find the common base path
minLength = Math.Min(baseParts.Length, absParts.Length);
for(idx = 0; idx < minLength; idx++)
if(String.Compare(baseParts[idx], absParts[idx],
StringComparison.OrdinalIgnoreCase) != 0)
break;
// Use the absolute path if there's nothing in common (i.e. they
// are on different drives or network shares.
if(idx == 0)
relPath = absolutePath;
else
{
// If equal to the base path, it doesn't have to go anywhere.
// Otherwise, work up from the base path to the common root.
if(idx == baseParts.Length)
relPath = String.Empty;
else
relPath = new String(' ', baseParts.Length - idx).Replace(
" ", ".." + IOPath.DirectorySeparatorChar);
// And finally, add the path from the common root to the absolute
// path.
relPath += String.Join(IOPath.DirectorySeparatorChar.ToString(),
absParts, idx, absParts.Length - idx);
}
return (hasBackslash) ? FolderPath.TerminatePath(relPath) : relPath;
}
/// <summary>
/// This helper method can be used to convert a relative path to an
/// absolute path based on the given base path.
/// </summary>
/// <param name="basePath">The base path</param>
/// <param name="relativePath">A relative path</param>
/// <returns>An absolute path</returns>
/// <remarks>If the base path is null or empty, the current working
/// folder is used.</remarks>
/// <example>
/// <code lang="cs">
/// string basePath = @"E:\DotNet\CS\TestProject\Source";
/// string relativePath = @"..\Doc\Help.html";
///
/// string absolutePath = FilePath.RelativeToAbsolutePath(basePath,
/// relativePath);
///
/// Console.WriteLine(absolutePath);
///
/// // Results in: E:\DotNet\CS\TestProject\Doc\Help.html
/// </code>
/// <code lang="vbnet">
/// Dim basePath As String = "E:\DotNet\CS\TestProject\Source"
/// Dim relativePath As String = "..\Doc\Help.html"
///
/// Dim absolutePath As String = _
/// FilePath.RelativeToAbsolutePath(basePath, relativePath);
///
/// Console.WriteLine(absolutePath)
///
/// ' Results in: E:\DotNet\CS\TestProject\Doc\Help.html
/// </code>
/// </example>
public static string RelativeToAbsolutePath(string basePath,
string relativePath)
{
int idx;
// If blank return the base path
if(String.IsNullOrEmpty(relativePath))
return basePath;
// Don't bother if already absolute
if(IOPath.IsPathRooted(relativePath))
return relativePath;
// If not specified, use the current folder as the base path
if(basePath == null || basePath.Trim().Length == 0)
basePath = Directory.GetCurrentDirectory();
else
basePath = IOPath.GetFullPath(basePath);
// Remove trailing backslashes for comparison
if(FolderPath.IsPathTerminated(basePath))
basePath = basePath.Substring(0, basePath.Length - 1);
if(relativePath == ".")
relativePath = String.Empty;
// Remove ".\" or "./" if it's there
if(relativePath.Length > 1 && relativePath[0] == '.' &&
(relativePath[1] == IOPath.DirectorySeparatorChar ||
relativePath[1] == IOPath.AltDirectorySeparatorChar))
relativePath = relativePath.Substring(2);
// Split the paths into their component parts
string[] baseParts = basePath.Split(IOPath.DirectorySeparatorChar);
string[] relParts = relativePath.Split(
IOPath.DirectorySeparatorChar);
// Figure out how far to move up from the relative path
for(idx = 0; idx < relParts.Length; ++idx)
if(relParts[idx] != "..")
break;
// If it's below the base path, just add it to the base path
if(idx == 0)
return FilePath.GetFullPath(basePath +
IOPath.DirectorySeparatorChar + relativePath);
string absPath = String.Join(
IOPath.DirectorySeparatorChar.ToString(), baseParts, 0,
Math.Max(0, baseParts.Length - idx));
absPath += IOPath.DirectorySeparatorChar + String.Join(
IOPath.DirectorySeparatorChar.ToString(), relParts, idx,
relParts.Length - idx);
return FilePath.GetFullPath(absPath);
}
#endregion
#region Private designer methods
//=====================================================================
/// <summary>
/// This is used to prevent the Path property from showing as modified
/// in the designer.
/// </summary>
/// <returns>Always returns false</returns>
/// <remarks>The <see cref="Path"/> property is mainly for display
/// purposes in the designer but can be used for making changes to
/// the expanded path if needed. The <see cref="PersistablePath"/>
/// property is used as the display value in the designer.</remarks>
private bool ShouldSerializePath()
{
return false;
}
#endregion
#region Constructors
//=====================================================================
/// <summary>
/// Default constructor. The file path is undefined.
/// </summary>
/// <param name="provider">The base base provider</param>
/// <overloads>There are three overloads for the constructor.</overloads>
public FilePath(IBasePathProvider provider)
{
basePathProvider = provider;
filePath = String.Empty;
}
/// <summary>
/// Constructor. Assign the specified path.
/// </summary>
/// <param name="path">A relative or absolute path.</param>
/// <param name="provider">The base base provider</param>
/// <remarks>Unless <see cref="IsFixedPath"/> is set to true,
/// the path is always treated as a relative path.</remarks>
public FilePath(string path, IBasePathProvider provider)
{
basePathProvider = provider;
this.Path = path;
}
/// <summary>
/// Constructor. Assign the specified path and fixed setting.
/// </summary>
/// <param name="path">A relative or absolute path.</param>
/// <param name="isFixed">True to treat the path as fixed, false
/// to treat it as a relative path.</param>
/// <param name="provider">The base base provider</param>
public FilePath(string path, bool isFixed, IBasePathProvider provider)
{
basePathProvider = provider;
this.Path = path;
isFixedPath = isFixed;
}
#endregion
#region ToString, GetHashCode, and Equals
//=====================================================================
/// <summary>
/// Convert the file path to a string
/// </summary>
/// <returns>A fixed or relative path based on the current settings</returns>
public override string ToString()
{
return Environment.ExpandEnvironmentVariables(
(basePathProvider != null) ? basePathProvider.ResolvePath(filePath) : filePath);
}
/// <summary>
/// Get a hash code for the file path object
/// </summary>
/// <returns>Returns the hash code of the <see cref="ToString" />
/// value converted to lowercase.</returns>
public override int GetHashCode()
{
return this.ToString().ToLower(CultureInfo.InvariantCulture).GetHashCode();
}
/// <summary>
/// This is overridden to allow proper comparison of file path objects.
/// </summary>
/// <param name="obj">The object to which this instance is
/// compared.</param>
/// <returns>Returns true if the object equals this instance, false
/// if it does not.</returns>
public override bool Equals(object obj)
{
if(obj == null || obj.GetType() != this.GetType())
return false;
FilePath otherPath = obj as FilePath;
return (String.Compare(this.Path, otherPath.Path,
StringComparison.OrdinalIgnoreCase) == 0 &&
this.IsFixedPath == otherPath.IsFixedPath);
}
#endregion
#region ICloneable Members
//=====================================================================
/// <summary>
/// This returns a clone of the object
/// </summary>
/// <returns>A clone of the object</returns>
public object Clone()
{
FilePath newFilePath = new FilePath(filePath, isFixedPath,
basePathProvider);
return newFilePath;
}
#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.Runtime.CompilerServices;
namespace System.Numerics
{
/// <summary>
/// Contains various methods useful for creating, manipulating, combining, and converting generic vectors with one another.
/// </summary>
public static partial class Vector
{
// JIT is not looking at the Vector class methods
// all methods here should be inlined and they must be implemented in terms of Vector<T> intrinsics
#region Select Methods
/// <summary>
/// Creates a new vector with elements selected between the two given source vectors, and based on a mask vector.
/// </summary>
/// <param name="condition">The integral mask vector used to drive selection.</param>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The new vector with elements selected based on the mask.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<Single> ConditionalSelect(Vector<int> condition, Vector<Single> left, Vector<Single> right)
{
return (Vector<Single>)Vector<Single>.ConditionalSelect((Vector<Single>)condition, left, right);
}
/// <summary>
/// Creates a new vector with elements selected between the two given source vectors, and based on a mask vector.
/// </summary>
/// <param name="condition">The integral mask vector used to drive selection.</param>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The new vector with elements selected based on the mask.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<double> ConditionalSelect(Vector<long> condition, Vector<double> left, Vector<double> right)
{
return (Vector<double>)Vector<double>.ConditionalSelect((Vector<double>)condition, left, right);
}
/// <summary>
/// Creates a new vector with elements selected between the two given source vectors, and based on a mask vector.
/// </summary>
/// <param name="condition">The mask vector used to drive selection.</param>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The new vector with elements selected based on the mask.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> ConditionalSelect<T>(Vector<T> condition, Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.ConditionalSelect(condition, left, right);
}
#endregion Select Methods
#region Comparison methods
#region Equals methods
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left and right were equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Equals<T>(Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.Equals(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether elements in the left and right floating point vectors were equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> Equals(Vector<Single> left, Vector<Single> right)
{
return (Vector<int>)Vector<Single>.Equals(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left and right were equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> Equals(Vector<int> left, Vector<int> right)
{
return Vector<int>.Equals(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether elements in the left and right floating point vectors were equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> Equals(Vector<double> left, Vector<double> right)
{
return (Vector<long>)Vector<double>.Equals(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left and right were equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> Equals(Vector<long> left, Vector<long> right)
{
return Vector<long>.Equals(left, right);
}
/// <summary>
/// Returns a boolean indicating whether each pair of elements in the given vectors are equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The first vector to compare.</param>
/// <returns>True if all elements are equal; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool EqualsAll<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left == right;
}
/// <summary>
/// Returns a boolean indicating whether any single pair of elements in the given vectors are equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if any element pairs are equal; False if no element pairs are equal.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool EqualsAny<T>(Vector<T> left, Vector<T> right) where T : struct
{
return !Vector<T>.Equals(left, right).Equals(Vector<T>.Zero);
}
#endregion Equals methods
#region Lessthan Methods
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were less than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> LessThan<T>(Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.LessThan(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether the elements in left were less than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant integral vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> LessThan(Vector<Single> left, Vector<Single> right)
{
return (Vector<int>)Vector<Single>.LessThan(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were less than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> LessThan(Vector<int> left, Vector<int> right)
{
return Vector<int>.LessThan(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether the elements in left were less than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant integral vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> LessThan(Vector<double> left, Vector<double> right)
{
return (Vector<long>)Vector<double>.LessThan(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were less than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> LessThan(Vector<long> left, Vector<long> right)
{
return Vector<long>.LessThan(left, right);
}
/// <summary>
/// Returns a boolean indicating whether all of the elements in left are less than their corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if all elements in left are less than their corresponding elements in right; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool LessThanAll<T>(Vector<T> left, Vector<T> right) where T : struct
{
Vector<int> cond = (Vector<int>)Vector<T>.LessThan(left, right);
return cond.Equals(Vector<int>.AllOnes);
}
/// <summary>
/// Returns a boolean indicating whether any element in left is less than its corresponding element in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if any elements in left are less than their corresponding elements in right; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool LessThanAny<T>(Vector<T> left, Vector<T> right) where T : struct
{
Vector<int> cond = (Vector<int>)Vector<T>.LessThan(left, right);
return !cond.Equals(Vector<int>.Zero);
}
#endregion LessthanMethods
#region Lessthanorequal methods
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were less than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> LessThanOrEqual<T>(Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.LessThanOrEqual(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether the elements in left were less than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant integral vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> LessThanOrEqual(Vector<Single> left, Vector<Single> right)
{
return (Vector<int>)Vector<Single>.LessThanOrEqual(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were less than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> LessThanOrEqual(Vector<int> left, Vector<int> right)
{
return Vector<int>.LessThanOrEqual(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were less than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> LessThanOrEqual(Vector<long> left, Vector<long> right)
{
return Vector<long>.LessThanOrEqual(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether the elements in left were less than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant integral vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> LessThanOrEqual(Vector<double> left, Vector<double> right)
{
return (Vector<long>)Vector<double>.LessThanOrEqual(left, right);
}
/// <summary>
/// Returns a boolean indicating whether all elements in left are less than or equal to their corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if all elements in left are less than or equal to their corresponding elements in right; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool LessThanOrEqualAll<T>(Vector<T> left, Vector<T> right) where T : struct
{
Vector<int> cond = (Vector<int>)Vector<T>.LessThanOrEqual(left, right);
return cond.Equals(Vector<int>.AllOnes);
}
/// <summary>
/// Returns a boolean indicating whether any element in left is less than or equal to its corresponding element in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if any elements in left are less than their corresponding elements in right; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool LessThanOrEqualAny<T>(Vector<T> left, Vector<T> right) where T : struct
{
Vector<int> cond = (Vector<int>)Vector<T>.LessThanOrEqual(left, right);
return !cond.Equals(Vector<int>.Zero);
}
#endregion Lessthanorequal methods
#region Greaterthan methods
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were greater than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> GreaterThan<T>(Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.GreaterThan(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether the elements in left were greater than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant integral vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> GreaterThan(Vector<Single> left, Vector<Single> right)
{
return (Vector<int>)Vector<Single>.GreaterThan(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were greater than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> GreaterThan(Vector<int> left, Vector<int> right)
{
return Vector<int>.GreaterThan(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether the elements in left were greater than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant integral vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> GreaterThan(Vector<double> left, Vector<double> right)
{
return (Vector<long>)Vector<double>.GreaterThan(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were greater than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> GreaterThan(Vector<long> left, Vector<long> right)
{
return Vector<long>.GreaterThan(left, right);
}
/// <summary>
/// Returns a boolean indicating whether all elements in left are greater than the corresponding elements in right.
/// elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if all elements in left are greater than their corresponding elements in right; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool GreaterThanAll<T>(Vector<T> left, Vector<T> right) where T : struct
{
Vector<int> cond = (Vector<int>)Vector<T>.GreaterThan(left, right);
return cond.Equals(Vector<int>.AllOnes);
}
/// <summary>
/// Returns a boolean indicating whether any element in left is greater than its corresponding element in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if any elements in left are greater than their corresponding elements in right; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool GreaterThanAny<T>(Vector<T> left, Vector<T> right) where T : struct
{
Vector<int> cond = (Vector<int>)Vector<T>.GreaterThan(left, right);
return !cond.Equals(Vector<int>.Zero);
}
#endregion Greaterthan methods
#region Greaterthanorequal methods
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were greater than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> GreaterThanOrEqual<T>(Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.GreaterThanOrEqual(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether the elements in left were greater than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant integral vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> GreaterThanOrEqual(Vector<Single> left, Vector<Single> right)
{
return (Vector<int>)Vector<Single>.GreaterThanOrEqual(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were greater than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> GreaterThanOrEqual(Vector<int> left, Vector<int> right)
{
return Vector<int>.GreaterThanOrEqual(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were greater than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> GreaterThanOrEqual(Vector<long> left, Vector<long> right)
{
return Vector<long>.GreaterThanOrEqual(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether the elements in left were greater than or equal to
/// their corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant integral vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> GreaterThanOrEqual(Vector<double> left, Vector<double> right)
{
return (Vector<long>)Vector<double>.GreaterThanOrEqual(left, right);
}
/// <summary>
/// Returns a boolean indicating whether all of the elements in left are greater than or equal to
/// their corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if all elements in left are greater than or equal to their corresponding elements in right; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool GreaterThanOrEqualAll<T>(Vector<T> left, Vector<T> right) where T : struct
{
Vector<int> cond = (Vector<int>)Vector<T>.GreaterThanOrEqual(left, right);
return cond.Equals(Vector<int>.AllOnes);
}
/// <summary>
/// Returns a boolean indicating whether any element in left is greater than or equal to its corresponding element in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if any elements in left are greater than or equal to their corresponding elements in right; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool GreaterThanOrEqualAny<T>(Vector<T> left, Vector<T> right) where T : struct
{
Vector<int> cond = (Vector<int>)Vector<T>.GreaterThanOrEqual(left, right);
return !cond.Equals(Vector<int>.Zero);
}
#endregion Greaterthanorequal methods
#endregion Comparison methods
#region Vector Math Methods
// Every operation must either be a JIT intrinsic or implemented over a JIT intrinsic
// as a thin wrapper
// Operations implemented over a JIT intrinsic should be inlined
// Methods that do not have a <T> type parameter are recognized as intrinsics
/// <summary>
/// Returns whether or not vector operations are subject to hardware acceleration through JIT intrinsic support.
/// </summary>
public static bool IsHardwareAccelerated
{
[Intrinsic]
get
{
return false;
}
}
// Vector<T>
// Basic Math
// All Math operations for Vector<T> are aggressively inlined here
/// <summary>
/// Returns a new vector whose elements are the absolute values of the given vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The absolute value vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Abs<T>(Vector<T> value) where T : struct
{
return Vector<T>.Abs(value);
}
/// <summary>
/// Returns a new vector whose elements are the minimum of each pair of elements in the two given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The minimum vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Min<T>(Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.Min(left, right);
}
/// <summary>
/// Returns a new vector whose elements are the maximum of each pair of elements in the two given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The maximum vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Max<T>(Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.Max(left, right);
}
// Specialized vector operations
/// <summary>
/// Returns the dot product of two vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The dot product.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static T Dot<T>(Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.DotProduct(left, right);
}
/// <summary>
/// Returns a new vector whose elements are the square roots of the given vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The square root vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> SquareRoot<T>(Vector<T> value) where T : struct
{
return Vector<T>.SquareRoot(value);
}
#endregion Vector Math Methods
#region Named Arithmetic Operators
/// <summary>
/// Creates a new vector whose values are the sum of each pair of elements from the two given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Add<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left + right;
}
/// <summary>
/// Creates a new vector whose values are the difference between each pairs of elements in the given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Subtract<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left - right;
}
/// <summary>
/// Creates a new vector whose values are the product of each pair of elements from the two given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Multiply<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left * right;
}
/// <summary>
/// Returns a new vector whose values are the values of the given vector each multiplied by a scalar value.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar factor.</param>
/// <returns>The scaled vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Multiply<T>(Vector<T> left, T right) where T : struct
{
return left * right;
}
/// <summary>
/// Returns a new vector whose values are the values of the given vector each multiplied by a scalar value.
/// </summary>
/// <param name="left">The scalar factor.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Multiply<T>(T left, Vector<T> right) where T : struct
{
return left * right;
}
/// <summary>
/// Returns a new vector whose values are the result of dividing the first vector's elements
/// by the corresponding elements in the second vector.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The divided vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Divide<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left / right;
}
/// <summary>
/// Returns a new vector whose elements are the given vector's elements negated.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Negate<T>(Vector<T> value) where T : struct
{
return -value;
}
#endregion Named Arithmetic Operators
#region Named Bitwise Operators
/// <summary>
/// Returns a new vector by performing a bitwise-and operation on each of the elements in the given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> BitwiseAnd<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left & right;
}
/// <summary>
/// Returns a new vector by performing a bitwise-or operation on each of the elements in the given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> BitwiseOr<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left | right;
}
/// <summary>
/// Returns a new vector whose elements are obtained by taking the one's complement of the given vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The one's complement vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> OnesComplement<T>(Vector<T> value) where T : struct
{
return ~value;
}
/// <summary>
/// Returns a new vector by performing a bitwise-exclusive-or operation on each of the elements in the given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Xor<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left ^ right;
}
/// <summary>
/// Returns a new vector by performing a bitwise-and-not operation on each of the elements in the given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> AndNot<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left & ~right;
}
#endregion Named Bitwise Operators
#region Conversion Methods
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of unsigned bytes.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<Byte> AsVectorByte<T>(Vector<T> value) where T : struct
{
return (Vector<Byte>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of signed bytes.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<SByte> AsVectorSByte<T>(Vector<T> value) where T : struct
{
return (Vector<SByte>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of 16-bit integers.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<UInt16> AsVectorUInt16<T>(Vector<T> value) where T : struct
{
return (Vector<UInt16>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of signed 16-bit integers.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<Int16> AsVectorInt16<T>(Vector<T> value) where T : struct
{
return (Vector<Int16>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of unsigned 32-bit integers.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<UInt32> AsVectorUInt32<T>(Vector<T> value) where T : struct
{
return (Vector<UInt32>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of signed 32-bit integers.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<Int32> AsVectorInt32<T>(Vector<T> value) where T : struct
{
return (Vector<Int32>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of unsigned 64-bit integers.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<UInt64> AsVectorUInt64<T>(Vector<T> value) where T : struct
{
return (Vector<UInt64>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of signed 64-bit integers.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<Int64> AsVectorInt64<T>(Vector<T> value) where T : struct
{
return (Vector<Int64>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of 32-bit floating point numbers.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<Single> AsVectorSingle<T>(Vector<T> value) where T : struct
{
return (Vector<Single>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of 64-bit floating point numbers.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<Double> AsVectorDouble<T>(Vector<T> value) where T : struct
{
return (Vector<Double>)value;
}
#endregion Conversion Methods
}
}
| |
//---------------------------------------------------------------------------
//
// File: ContentElementAutomationPeer.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Automation element for ContentElements
//
//---------------------------------------------------------------------------
using System; // Object
using System.Collections.Generic; // List<T>
using System.Windows.Input; // AccessKeyManager
using MS.Internal.PresentationCore; // SR
using System.Windows.Automation.Provider;
using System.Windows.Automation;
using MS.Internal.Automation;
namespace System.Windows.Automation.Peers
{
///
public class ContentElementAutomationPeer : AutomationPeer
{
///
public ContentElementAutomationPeer(ContentElement owner)
{
if (owner == null)
{
throw new ArgumentNullException("owner");
}
_owner = owner;
}
///
public ContentElement Owner
{
get
{
return _owner;
}
}
///<summary>
/// This static helper creates an AutomationPeer for the specified element and
/// caches it - that means the created peer is going to live long and shadow the
/// element for its lifetime. The peer will be used by Automation to proxy the element, and
/// to fire events to the Automation when something happens with the element.
/// The created peer is returned from this method and also from subsequent calls to this method
/// and <seealso cref="FromElement"/>. The type of the peer is determined by the
/// <seealso cref="UIElement.OnCreateAutomationPeer"/> virtual callback. If FrameworkContentElement does not
/// implement the callback, there will be no peer and this method will return 'null' (in other
/// words, there is no such thing as a 'default peer').
///</summary>
public static AutomationPeer CreatePeerForElement(ContentElement element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return element.CreateAutomationPeer();
}
///
public static AutomationPeer FromElement(ContentElement element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return element.GetAutomationPeer();
}
/// <summary>
/// <see cref="AutomationPeer.GetChildrenCore"/>
/// </summary>
override protected List<AutomationPeer> GetChildrenCore()
{
return null;
}
///
override public object GetPattern(PatternInterface patternInterface)
{
//Support synchronized input
if (patternInterface == PatternInterface.SynchronizedInput)
{
// Adaptor object is used here to avoid loading UIA assemblies in non-UIA scenarios.
if (_synchronizedInputPattern == null)
_synchronizedInputPattern = new SynchronizedInputAdaptor(_owner);
return _synchronizedInputPattern;
}
return null;
}
/// <summary>
/// <see cref="AutomationPeer.GetAutomationControlTypeCore"/>
/// </summary>
protected override AutomationControlType GetAutomationControlTypeCore()
{
return AutomationControlType.Custom;
}
/// <summary>
/// <see cref="AutomationPeer.GetAutomationIdCore"/>
/// </summary>
protected override string GetAutomationIdCore()
{
return AutomationProperties.GetAutomationId(_owner);
}
/// <summary>
/// <see cref="AutomationPeer.GetNameCore"/>
/// </summary>
protected override string GetNameCore()
{
return AutomationProperties.GetName(_owner);
}
/// <summary>
/// <see cref="AutomationPeer.GetHelpTextCore"/>
/// </summary>
protected override string GetHelpTextCore()
{
return AutomationProperties.GetHelpText(_owner);
}
/// <summary>
/// <see cref="AutomationPeer.GetBoundingRectangleCore"/>
/// </summary>
override protected Rect GetBoundingRectangleCore()
{
return Rect.Empty;
}
/// <summary>
/// <see cref="AutomationPeer.IsOffscreenCore"/>
/// </summary>
override protected bool IsOffscreenCore()
{
IsOffscreenBehavior behavior = AutomationProperties.GetIsOffscreenBehavior(_owner);
switch (behavior)
{
case IsOffscreenBehavior.Onscreen :
return false;
default:
return true;
}
}
/// <summary>
/// <see cref="AutomationPeer.GetOrientationCore"/>
/// </summary>
override protected AutomationOrientation GetOrientationCore()
{
return AutomationOrientation.None;
}
/// <summary>
/// <see cref="AutomationPeer.GetItemTypeCore"/>
/// </summary>
override protected string GetItemTypeCore()
{
return string.Empty;
}
/// <summary>
/// <see cref="AutomationPeer.GetClassNameCore"/>
/// </summary>
override protected string GetClassNameCore()
{
return string.Empty;
}
/// <summary>
/// <see cref="AutomationPeer.GetItemStatusCore"/>
/// </summary>
override protected string GetItemStatusCore()
{
return string.Empty;
}
/// <summary>
/// <see cref="AutomationPeer.IsRequiredForFormCore"/>
/// </summary>
override protected bool IsRequiredForFormCore()
{
return false;
}
/// <summary>
/// <see cref="AutomationPeer.IsKeyboardFocusableCore"/>
/// </summary>
override protected bool IsKeyboardFocusableCore()
{
return Keyboard.IsFocusable(_owner);
}
/// <summary>
/// <see cref="AutomationPeer.HasKeyboardFocusCore"/>
/// </summary>
override protected bool HasKeyboardFocusCore()
{
return _owner.IsKeyboardFocused;
}
/// <summary>
/// <see cref="AutomationPeer.IsEnabledCore"/>
/// </summary>
override protected bool IsEnabledCore()
{
return _owner.IsEnabled;
}
/// <summary>
/// <see cref="AutomationPeer.IsPasswordCore"/>
/// </summary>
override protected bool IsPasswordCore()
{
return false;
}
/// <summary>
/// <see cref="AutomationPeer.IsContentElementCore"/>
/// </summary>
override protected bool IsContentElementCore()
{
return true;
}
/// <summary>
/// <see cref="AutomationPeer.IsControlElementCore"/>
/// </summary>
override protected bool IsControlElementCore()
{
return false;
}
/// <summary>
/// <see cref="AutomationPeer.GetLabeledByCore"/>
/// </summary>
override protected AutomationPeer GetLabeledByCore()
{
return null;
}
/// <summary>
/// <see cref="AutomationPeer.GetAcceleratorKeyCore"/>
/// </summary>
override protected string GetAcceleratorKeyCore()
{
return string.Empty;
}
/// <summary>
/// <see cref="AutomationPeer.GetAccessKeyCore"/>
/// </summary>
override protected string GetAccessKeyCore()
{
return AccessKeyManager.InternalGetAccessKeyCharacter(_owner);
}
/// <summary>
/// <see cref="AutomationPeer.GetClickablePointCore"/>
/// </summary>
override protected Point GetClickablePointCore()
{
return new Point(double.NaN, double.NaN);
}
/// <summary>
/// <see cref="AutomationPeer.SetFocusCore"/>
/// </summary>
override protected void SetFocusCore()
{
if (!_owner.Focus())
throw new InvalidOperationException(SR.Get(SRID.SetFocusFailed));
}
///
internal override Rect GetVisibleBoundingRectCore()
{
return GetBoundingRectangle();
}
private ContentElement _owner;
private SynchronizedInputAdaptor _synchronizedInputPattern;
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using System.Linq.Expressions;
using Sitecore.Data;
namespace Glass.Mapper.Sc.Configuration.Fluent
{
/// <summary>
/// Used to populate the property with data from a Sitecore field
/// </summary>
/// <typeparam name="T"></typeparam>
public class SitecoreField<T> : AbstractPropertyBuilder<T, SitecoreFieldConfiguration>
{
/// <summary>
/// Initializes a new instance of the <see cref="SitecoreField{T}"/> class.
/// </summary>
/// <param name="ex">The ex.</param>
public SitecoreField(Expression<Func<T, object>> ex)
: base(ex)
{
Configuration.FieldName = Configuration.PropertyInfo.Name;
}
/// <summary>
/// Indicate that the field can be used with Code First
/// </summary>
public SitecoreField<T> IsCodeFirst()
{
Configuration.CodeFirst = true;
return this;
}
/// <summary>
/// The ID of the field to load or create in code first
/// </summary>
/// <param name="id">The id.</param>
/// <returns>SitecoreField{`0}.</returns>
public SitecoreField<T> FieldId(string id)
{
return FieldId(new ID(id));
}
/// <summary>
/// The ID of the field to load or create in code first
/// </summary>
/// <param name="id">The id.</param>
/// <returns>SitecoreField{`0}.</returns>
public SitecoreField<T> FieldId(Guid id)
{
return FieldId(new ID(id));
}
/// <summary>
/// The ID of the field to load or create in code first
/// </summary>
/// <param name="id">The id.</param>
/// <returns>SitecoreField{`0}.</returns>
public SitecoreField<T> FieldId(ID id)
{
Configuration.FieldId = id;
return this;
}
/// <summary>
/// The name of the field to use if it is different to the property name
/// </summary>
/// <param name="name">The name.</param>
/// <returns>SitecoreField{`0}.</returns>
public SitecoreField<T> FieldName(string name)
{
Configuration.FieldName = name;
return this;
}
/// <summary>
/// The source for a code first field
/// </summary>
/// <param name="fieldSource">The field source.</param>
/// <returns>SitecoreField{`0}.</returns>
public SitecoreField<T> FieldSource(string fieldSource)
{
Configuration.FieldSource = fieldSource;
return this;
}
/// <summary>
/// The title for a code first field
/// </summary>
/// <param name="fieldTitle">The field title.</param>
/// <returns>SitecoreField{`0}.</returns>
public SitecoreField<T> FieldTitle(string fieldTitle)
{
Configuration.FieldTitle = fieldTitle;
return this;
}
/// <summary>
/// The Sitecore field type for a code first field
/// </summary>
/// <param name="fieldType">Type of the field.</param>
/// <returns>SitecoreField{`0}.</returns>
public SitecoreField<T> FieldType(SitecoreFieldType fieldType)
{
Configuration.FieldType = fieldType;
return this;
}
/// <summary>
/// The field should be shared between languages
/// </summary>
public SitecoreField<T> IsShared()
{
Configuration.IsShared = true;
return this;
}
/// <summary>
/// The field should be shared between versions
/// </summary>
public SitecoreField<T> IsUnversioned()
{
Configuration.IsUnversioned = true;
return this;
}
/// <summary>
/// The Sitecore custom field type for a code first field
/// </summary>
/// <param name="fieldType">Type of the field.</param>
/// <returns>SitecoreField{`0}.</returns>
public SitecoreField<T> CustomFieldType(string fieldType)
{
Configuration.CustomFieldType = fieldType;
return this;
}
/// <summary>
/// Options to override the behaviour of certain fields.
/// </summary>
/// <param name="setting">The setting.</param>
/// <returns>SitecoreField{`0}.</returns>
public SitecoreField<T> Setting(SitecoreFieldSettings setting)
{
Configuration.Setting = setting;
return this;
}
/// <summary>
/// The name of the section the field should appear in
/// </summary>
/// <param name="sectionName">Name of the section.</param>
/// <returns>SitecoreField{`0}.</returns>
public SitecoreField<T> SectionName(string sectionName)
{
Configuration.SectionName = sectionName;
return this;
}
/// <summary>
/// Indicate that the field can not be written to Sitecore
/// </summary>
/// <returns>SitecoreField{`0}.</returns>
public SitecoreField<T> ReadOnly()
{
Configuration.ReadOnly = true;
return this;
}
/// <summary>
/// Fields the sort order.
/// </summary>
/// <param name="order">The order.</param>
/// <returns>SitecoreField{`0}.</returns>
public SitecoreField<T> FieldSortOrder(int order)
{
Configuration.FieldSortOrder = order;
return this;
}
/// <summary>
/// Sections the sort order.
/// </summary>
/// <param name="order">The order.</param>
/// <returns>SitecoreField{`0}.</returns>
public SitecoreField<T> SectionSortOrder(int order)
{
Configuration.SectionSortOrder = order;
return this;
}
/// <summary>
/// Validations the error text.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>SitecoreField{`0}.</returns>
public SitecoreField<T> ValidationErrorText(string text)
{
Configuration.ValidationErrorText = text;
return this;
}
/// <summary>
/// Validations the regular expression.
/// </summary>
/// <param name="regex">The regex.</param>
/// <returns>SitecoreField{`0}.</returns>
public SitecoreField<T> ValidationRegularExpression(string regex)
{
Configuration.ValidationRegularExpression = regex;
return this;
}
/// <summary>
/// Determines whether this instance is required.
/// </summary>
public SitecoreField<T> IsRequired()
{
Configuration.IsRequired = true;
return this;
}
}
}
| |
//
// 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 Microsoft.Azure;
using Microsoft.WindowsAzure.Commands.Compute.Automation.Models;
using Microsoft.WindowsAzure.Management.Compute;
using Microsoft.WindowsAzure.Management.Compute.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.WindowsAzure.Commands.Compute.Automation
{
[Cmdlet(VerbsCommon.New, "AzureComputeParameterObject", DefaultParameterSetName = "CreateParameterObjectByFullName")]
[OutputType(typeof(object))]
public partial class NewAzureComputeParameterObjectCmdlet : ComputeAutomationBaseCmdlet
{
[Parameter(ParameterSetName = "CreateParameterObjectByFriendlyName", Mandatory = true, Position = 0)]
[ValidateSet(
"DeploymentChangeConfigurationParameters",
"DeploymentCreateParameters",
"DeploymentDeleteRoleInstanceParameters",
"DeploymentExtension",
"DeploymentExtensionConfiguration",
"DeploymentExtensionList",
"DeploymentGetPackageParameters",
"DeploymentNamedRole",
"DeploymentNamedRoleList",
"DeploymentRollbackUpdateOrUpgradeParameters",
"DeploymentSwapParameters",
"DeploymentUpdateStatusParameters",
"DeploymentUpgradeParameters",
"DeploymentWalkUpgradeDomainParameters",
"DNSServerDNSAddParameters",
"DNSServerDNSUpdateParameters",
"ExtensionImageExtensionCertificateConfiguration",
"ExtensionImageExtensionEndpointConfiguration",
"ExtensionImageExtensionLocalResourceConfiguration",
"ExtensionImageExtensionLocalResourceConfigurationList",
"ExtensionImageInputEndpoint",
"ExtensionImageInputEndpointList",
"ExtensionImageInternalEndpoint",
"ExtensionImageInternalEndpointList",
"ExtensionImageRegisterParameters",
"ExtensionImageUpdateParameters",
"HostedServiceAddExtensionParameters",
"HostedServiceCreateParameters",
"HostedServiceUpdateParameters",
"LoadBalancerCreateParameters",
"LoadBalancerFrontendIPConfiguration",
"LoadBalancerUpdateParameters",
"ServiceCertificateCreateParameters",
"ServiceCertificateDeleteParameters",
"ServiceCertificateGetParameters",
"VirtualMachineCaptureOSImageParameters",
"VirtualMachineCaptureVMImageParameters",
"VirtualMachineConfigurationSet",
"VirtualMachineConfigurationSetList",
"VirtualMachineCreateDeploymentParameters",
"VirtualMachineCreateParameters",
"VirtualMachineDataDiskConfiguration",
"VirtualMachineDataDiskConfigurationList",
"VirtualMachineDataVirtualHardDisk",
"VirtualMachineDataVirtualHardDiskList",
"VirtualMachineDiskCreateParameters",
"VirtualMachineDiskUpdateParameters",
"VirtualMachineDiskVirtualMachineDataDiskCreateParameters",
"VirtualMachineDiskVirtualMachineDataDiskUpdateParameters",
"VirtualMachineDnsServer",
"VirtualMachineDnsServerList",
"VirtualMachineDnsSettings",
"VirtualMachineDomainJoinCredentials",
"VirtualMachineDomainJoinProvisioning",
"VirtualMachineDomainJoinSettings",
"VirtualMachineInputEndpoint",
"VirtualMachineInputEndpointList",
"VirtualMachineLoadBalancer",
"VirtualMachineLoadBalancerList",
"VirtualMachineNetworkInterface",
"VirtualMachineNetworkInterfaceList",
"VirtualMachineOSDiskConfiguration",
"VirtualMachineOSImageComputeImageAttributes",
"VirtualMachineOSImageCreateParameters",
"VirtualMachineOSImageMarketplaceImageAttributes",
"VirtualMachineOSImagePlan",
"VirtualMachineOSImageReplicateParameters",
"VirtualMachineOSImageUpdateParameters",
"VirtualMachineOSVirtualHardDisk",
"VirtualMachinePublicIP",
"VirtualMachinePublicIPList",
"VirtualMachineResourceExtensionReference",
"VirtualMachineResourceExtensionReferenceList",
"VirtualMachineRole",
"VirtualMachineRoleList",
"VirtualMachineShutdownParameters",
"VirtualMachineShutdownRolesParameters",
"VirtualMachineSshSettingKeyPair",
"VirtualMachineSshSettingKeyPairList",
"VirtualMachineSshSettingPublicKey",
"VirtualMachineSshSettingPublicKeyList",
"VirtualMachineSshSettings",
"VirtualMachineStartRolesParameters",
"VirtualMachineStoredCertificateSettings",
"VirtualMachineStoredCertificateSettingsList",
"VirtualMachineUpdateLoadBalancedSetParameters",
"VirtualMachineUpdateParameters",
"VirtualMachineVMImageComputeImageAttributes",
"VirtualMachineVMImageCreateParameters",
"VirtualMachineVMImageDataDiskConfigurationCreateParameters",
"VirtualMachineVMImageDataDiskConfigurationCreateParametersList",
"VirtualMachineVMImageDataDiskConfigurationUpdateParameters",
"VirtualMachineVMImageDataDiskConfigurationUpdateParametersList",
"VirtualMachineVMImageInput",
"VirtualMachineVMImageMarketplaceImageAttributes",
"VirtualMachineVMImageOSDiskConfigurationCreateParameters",
"VirtualMachineVMImageOSDiskConfigurationUpdateParameters",
"VirtualMachineVMImagePlan",
"VirtualMachineVMImageReplicateParameters",
"VirtualMachineVMImageUpdateParameters",
"VirtualMachineWindowsRemoteManagementListener",
"VirtualMachineWindowsRemoteManagementListenerList",
"VirtualMachineWindowsRemoteManagementSettings"
)]
public string FriendlyName { get; set; }
[Parameter(ParameterSetName = "CreateParameterObjectByFullName", Mandatory = true, Position = 0)]
[ValidateSet(
"Microsoft.WindowsAzure.Management.Compute.Models.ComputeImageAttributes",
"Microsoft.WindowsAzure.Management.Compute.Models.ConfigurationSet",
"Microsoft.WindowsAzure.Management.Compute.Models.ConfigurationSet.PublicIP",
"Microsoft.WindowsAzure.Management.Compute.Models.DataDiskConfiguration",
"Microsoft.WindowsAzure.Management.Compute.Models.DataDiskConfigurationCreateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.DataDiskConfigurationUpdateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.DataVirtualHardDisk",
"Microsoft.WindowsAzure.Management.Compute.Models.DeploymentChangeConfigurationParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.DeploymentCreateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.DeploymentDeleteRoleInstanceParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.DeploymentGetPackageParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.DeploymentRollbackUpdateOrUpgradeParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.DeploymentSwapParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.DeploymentUpdateStatusParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.DeploymentUpgradeParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.DeploymentWalkUpgradeDomainParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.DNSAddParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.DnsServer",
"Microsoft.WindowsAzure.Management.Compute.Models.DnsSettings",
"Microsoft.WindowsAzure.Management.Compute.Models.DNSUpdateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.DomainJoinCredentials",
"Microsoft.WindowsAzure.Management.Compute.Models.DomainJoinProvisioning",
"Microsoft.WindowsAzure.Management.Compute.Models.DomainJoinSettings",
"Microsoft.WindowsAzure.Management.Compute.Models.ExtensionCertificateConfiguration",
"Microsoft.WindowsAzure.Management.Compute.Models.ExtensionConfiguration",
"Microsoft.WindowsAzure.Management.Compute.Models.ExtensionConfiguration.Extension",
"Microsoft.WindowsAzure.Management.Compute.Models.ExtensionConfiguration.NamedRole",
"Microsoft.WindowsAzure.Management.Compute.Models.ExtensionEndpointConfiguration",
"Microsoft.WindowsAzure.Management.Compute.Models.ExtensionEndpointConfiguration.InputEndpoint",
"Microsoft.WindowsAzure.Management.Compute.Models.ExtensionEndpointConfiguration.InternalEndpoint",
"Microsoft.WindowsAzure.Management.Compute.Models.ExtensionImageRegisterParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.ExtensionImageUpdateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.ExtensionLocalResourceConfiguration",
"Microsoft.WindowsAzure.Management.Compute.Models.FrontendIPConfiguration",
"Microsoft.WindowsAzure.Management.Compute.Models.HostedServiceAddExtensionParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.HostedServiceCreateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.HostedServiceUpdateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.InputEndpoint",
"Microsoft.WindowsAzure.Management.Compute.Models.LoadBalancer",
"Microsoft.WindowsAzure.Management.Compute.Models.LoadBalancerCreateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.LoadBalancerUpdateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.MarketplaceImageAttributes",
"Microsoft.WindowsAzure.Management.Compute.Models.NetworkInterface",
"Microsoft.WindowsAzure.Management.Compute.Models.OSDiskConfiguration",
"Microsoft.WindowsAzure.Management.Compute.Models.OSDiskConfigurationCreateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.OSDiskConfigurationUpdateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.OSVirtualHardDisk",
"Microsoft.WindowsAzure.Management.Compute.Models.Plan",
"Microsoft.WindowsAzure.Management.Compute.Models.ResourceExtensionReference",
"Microsoft.WindowsAzure.Management.Compute.Models.Role",
"Microsoft.WindowsAzure.Management.Compute.Models.ServiceCertificateCreateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.ServiceCertificateDeleteParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.ServiceCertificateGetParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.SshSettingKeyPair",
"Microsoft.WindowsAzure.Management.Compute.Models.SshSettingPublicKey",
"Microsoft.WindowsAzure.Management.Compute.Models.SshSettings",
"Microsoft.WindowsAzure.Management.Compute.Models.StoredCertificateSettings",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineCaptureOSImageParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineCaptureVMImageParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineCreateDeploymentParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineCreateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineDataDiskCreateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineDataDiskUpdateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineDiskCreateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineDiskUpdateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineOSImageCreateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineOSImageReplicateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineOSImageUpdateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineShutdownParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineShutdownRolesParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineStartRolesParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineUpdateLoadBalancedSetParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineUpdateLoadBalancedSetParameters.InputEndpoint",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineUpdateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineVMImageCreateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineVMImageReplicateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineVMImageUpdateParameters",
"Microsoft.WindowsAzure.Management.Compute.Models.VMImageInput",
"Microsoft.WindowsAzure.Management.Compute.Models.WindowsRemoteManagementListener",
"Microsoft.WindowsAzure.Management.Compute.Models.WindowsRemoteManagementSettings",
"System.Collections.Generic.List<ConfigurationSet.PublicIP>",
"System.Collections.Generic.List<ConfigurationSet>",
"System.Collections.Generic.List<DataDiskConfiguration>",
"System.Collections.Generic.List<DataDiskConfigurationCreateParameters>",
"System.Collections.Generic.List<DataDiskConfigurationUpdateParameters>",
"System.Collections.Generic.List<DataVirtualHardDisk>",
"System.Collections.Generic.List<DnsServer>",
"System.Collections.Generic.List<ExtensionConfiguration.Extension>",
"System.Collections.Generic.List<ExtensionConfiguration.NamedRole>",
"System.Collections.Generic.List<ExtensionEndpointConfiguration.InputEndpoint>",
"System.Collections.Generic.List<ExtensionEndpointConfiguration.InternalEndpoint>",
"System.Collections.Generic.List<ExtensionLocalResourceConfiguration>",
"System.Collections.Generic.List<InputEndpoint>",
"System.Collections.Generic.List<LoadBalancer>",
"System.Collections.Generic.List<NetworkInterface>",
"System.Collections.Generic.List<ResourceExtensionReference>",
"System.Collections.Generic.List<Role>",
"System.Collections.Generic.List<SshSettingKeyPair>",
"System.Collections.Generic.List<SshSettingPublicKey>",
"System.Collections.Generic.List<StoredCertificateSettings>",
"System.Collections.Generic.List<VirtualMachineUpdateLoadBalancedSetParameters.InputEndpoint>",
"System.Collections.Generic.List<WindowsRemoteManagementListener>"
)]
public string FullName { get; set; }
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
ExecuteClientAction(() =>
{
if (ParameterSetName == "CreateParameterObjectByFriendlyName")
{
switch (FriendlyName)
{
case "DeploymentChangeConfigurationParameters" : WriteObject(new DeploymentChangeConfigurationParameters()); break;
case "DeploymentCreateParameters" : WriteObject(new DeploymentCreateParameters()); break;
case "DeploymentDeleteRoleInstanceParameters" : WriteObject(new DeploymentDeleteRoleInstanceParameters()); break;
case "DeploymentExtension" : WriteObject(new ExtensionConfiguration.Extension()); break;
case "DeploymentExtensionConfiguration" : WriteObject(new ExtensionConfiguration()); break;
case "DeploymentExtensionList" : WriteObject(new List<ExtensionConfiguration.Extension>()); break;
case "DeploymentGetPackageParameters" : WriteObject(new DeploymentGetPackageParameters()); break;
case "DeploymentNamedRole" : WriteObject(new ExtensionConfiguration.NamedRole()); break;
case "DeploymentNamedRoleList" : WriteObject(new List<ExtensionConfiguration.NamedRole>()); break;
case "DeploymentRollbackUpdateOrUpgradeParameters" : WriteObject(new DeploymentRollbackUpdateOrUpgradeParameters()); break;
case "DeploymentSwapParameters" : WriteObject(new DeploymentSwapParameters()); break;
case "DeploymentUpdateStatusParameters" : WriteObject(new DeploymentUpdateStatusParameters()); break;
case "DeploymentUpgradeParameters" : WriteObject(new DeploymentUpgradeParameters()); break;
case "DeploymentWalkUpgradeDomainParameters" : WriteObject(new DeploymentWalkUpgradeDomainParameters()); break;
case "DNSServerDNSAddParameters" : WriteObject(new DNSAddParameters()); break;
case "DNSServerDNSUpdateParameters" : WriteObject(new DNSUpdateParameters()); break;
case "ExtensionImageExtensionCertificateConfiguration" : WriteObject(new ExtensionCertificateConfiguration()); break;
case "ExtensionImageExtensionEndpointConfiguration" : WriteObject(new ExtensionEndpointConfiguration()); break;
case "ExtensionImageExtensionLocalResourceConfiguration" : WriteObject(new ExtensionLocalResourceConfiguration()); break;
case "ExtensionImageExtensionLocalResourceConfigurationList" : WriteObject(new List<ExtensionLocalResourceConfiguration>()); break;
case "ExtensionImageInputEndpoint" : WriteObject(new ExtensionEndpointConfiguration.InputEndpoint()); break;
case "ExtensionImageInputEndpointList" : WriteObject(new List<ExtensionEndpointConfiguration.InputEndpoint>()); break;
case "ExtensionImageInternalEndpoint" : WriteObject(new ExtensionEndpointConfiguration.InternalEndpoint()); break;
case "ExtensionImageInternalEndpointList" : WriteObject(new List<ExtensionEndpointConfiguration.InternalEndpoint>()); break;
case "ExtensionImageRegisterParameters" : WriteObject(new ExtensionImageRegisterParameters()); break;
case "ExtensionImageUpdateParameters" : WriteObject(new ExtensionImageUpdateParameters()); break;
case "HostedServiceAddExtensionParameters" : WriteObject(new HostedServiceAddExtensionParameters()); break;
case "HostedServiceCreateParameters" : WriteObject(new HostedServiceCreateParameters()); break;
case "HostedServiceUpdateParameters" : WriteObject(new HostedServiceUpdateParameters()); break;
case "LoadBalancerCreateParameters" : WriteObject(new LoadBalancerCreateParameters()); break;
case "LoadBalancerFrontendIPConfiguration" : WriteObject(new FrontendIPConfiguration()); break;
case "LoadBalancerUpdateParameters" : WriteObject(new LoadBalancerUpdateParameters()); break;
case "ServiceCertificateCreateParameters" : WriteObject(new ServiceCertificateCreateParameters()); break;
case "ServiceCertificateDeleteParameters" : WriteObject(new ServiceCertificateDeleteParameters()); break;
case "ServiceCertificateGetParameters" : WriteObject(new ServiceCertificateGetParameters()); break;
case "VirtualMachineCaptureOSImageParameters" : WriteObject(new VirtualMachineCaptureOSImageParameters()); break;
case "VirtualMachineCaptureVMImageParameters" : WriteObject(new VirtualMachineCaptureVMImageParameters()); break;
case "VirtualMachineConfigurationSet" : WriteObject(new ConfigurationSet()); break;
case "VirtualMachineConfigurationSetList" : WriteObject(new List<ConfigurationSet>()); break;
case "VirtualMachineCreateDeploymentParameters" : WriteObject(new VirtualMachineCreateDeploymentParameters()); break;
case "VirtualMachineCreateParameters" : WriteObject(new VirtualMachineCreateParameters()); break;
case "VirtualMachineDataDiskConfiguration" : WriteObject(new DataDiskConfiguration()); break;
case "VirtualMachineDataDiskConfigurationList" : WriteObject(new List<DataDiskConfiguration>()); break;
case "VirtualMachineDataVirtualHardDisk" : WriteObject(new DataVirtualHardDisk()); break;
case "VirtualMachineDataVirtualHardDiskList" : WriteObject(new List<DataVirtualHardDisk>()); break;
case "VirtualMachineDiskCreateParameters" : WriteObject(new VirtualMachineDiskCreateParameters()); break;
case "VirtualMachineDiskUpdateParameters" : WriteObject(new VirtualMachineDiskUpdateParameters()); break;
case "VirtualMachineDiskVirtualMachineDataDiskCreateParameters" : WriteObject(new VirtualMachineDataDiskCreateParameters()); break;
case "VirtualMachineDiskVirtualMachineDataDiskUpdateParameters" : WriteObject(new VirtualMachineDataDiskUpdateParameters()); break;
case "VirtualMachineDnsServer" : WriteObject(new DnsServer()); break;
case "VirtualMachineDnsServerList" : WriteObject(new List<DnsServer>()); break;
case "VirtualMachineDnsSettings" : WriteObject(new DnsSettings()); break;
case "VirtualMachineDomainJoinCredentials" : WriteObject(new DomainJoinCredentials()); break;
case "VirtualMachineDomainJoinProvisioning" : WriteObject(new DomainJoinProvisioning()); break;
case "VirtualMachineDomainJoinSettings" : WriteObject(new DomainJoinSettings()); break;
case "VirtualMachineInputEndpoint" : WriteObject(new InputEndpoint()); break;
case "VirtualMachineInputEndpointList" : WriteObject(new List<InputEndpoint>()); break;
case "VirtualMachineLoadBalancer" : WriteObject(new LoadBalancer()); break;
case "VirtualMachineLoadBalancerList" : WriteObject(new List<LoadBalancer>()); break;
case "VirtualMachineNetworkInterface" : WriteObject(new NetworkInterface()); break;
case "VirtualMachineNetworkInterfaceList" : WriteObject(new List<NetworkInterface>()); break;
case "VirtualMachineOSDiskConfiguration" : WriteObject(new OSDiskConfiguration()); break;
case "VirtualMachineOSImageComputeImageAttributes" : WriteObject(new ComputeImageAttributes()); break;
case "VirtualMachineOSImageCreateParameters" : WriteObject(new VirtualMachineOSImageCreateParameters()); break;
case "VirtualMachineOSImageMarketplaceImageAttributes" : WriteObject(new MarketplaceImageAttributes()); break;
case "VirtualMachineOSImagePlan" : WriteObject(new Plan()); break;
case "VirtualMachineOSImageReplicateParameters" : WriteObject(new VirtualMachineOSImageReplicateParameters()); break;
case "VirtualMachineOSImageUpdateParameters" : WriteObject(new VirtualMachineOSImageUpdateParameters()); break;
case "VirtualMachineOSVirtualHardDisk" : WriteObject(new OSVirtualHardDisk()); break;
case "VirtualMachinePublicIP" : WriteObject(new ConfigurationSet.PublicIP()); break;
case "VirtualMachinePublicIPList" : WriteObject(new List<ConfigurationSet.PublicIP>()); break;
case "VirtualMachineResourceExtensionReference" : WriteObject(new ResourceExtensionReference()); break;
case "VirtualMachineResourceExtensionReferenceList" : WriteObject(new List<ResourceExtensionReference>()); break;
case "VirtualMachineRole" : WriteObject(new Role()); break;
case "VirtualMachineRoleList" : WriteObject(new List<Role>()); break;
case "VirtualMachineShutdownParameters" : WriteObject(new VirtualMachineShutdownParameters()); break;
case "VirtualMachineShutdownRolesParameters" : WriteObject(new VirtualMachineShutdownRolesParameters()); break;
case "VirtualMachineSshSettingKeyPair" : WriteObject(new SshSettingKeyPair()); break;
case "VirtualMachineSshSettingKeyPairList" : WriteObject(new List<SshSettingKeyPair>()); break;
case "VirtualMachineSshSettingPublicKey" : WriteObject(new SshSettingPublicKey()); break;
case "VirtualMachineSshSettingPublicKeyList" : WriteObject(new List<SshSettingPublicKey>()); break;
case "VirtualMachineSshSettings" : WriteObject(new SshSettings()); break;
case "VirtualMachineStartRolesParameters" : WriteObject(new VirtualMachineStartRolesParameters()); break;
case "VirtualMachineStoredCertificateSettings" : WriteObject(new StoredCertificateSettings()); break;
case "VirtualMachineStoredCertificateSettingsList" : WriteObject(new List<StoredCertificateSettings>()); break;
case "VirtualMachineUpdateLoadBalancedSetParameters" : WriteObject(new VirtualMachineUpdateLoadBalancedSetParameters()); break;
case "VirtualMachineUpdateParameters" : WriteObject(new VirtualMachineUpdateParameters()); break;
case "VirtualMachineVMImageComputeImageAttributes" : WriteObject(new ComputeImageAttributes()); break;
case "VirtualMachineVMImageCreateParameters" : WriteObject(new VirtualMachineVMImageCreateParameters()); break;
case "VirtualMachineVMImageDataDiskConfigurationCreateParameters" : WriteObject(new DataDiskConfigurationCreateParameters()); break;
case "VirtualMachineVMImageDataDiskConfigurationCreateParametersList" : WriteObject(new List<DataDiskConfigurationCreateParameters>()); break;
case "VirtualMachineVMImageDataDiskConfigurationUpdateParameters" : WriteObject(new DataDiskConfigurationUpdateParameters()); break;
case "VirtualMachineVMImageDataDiskConfigurationUpdateParametersList" : WriteObject(new List<DataDiskConfigurationUpdateParameters>()); break;
case "VirtualMachineVMImageInput" : WriteObject(new VMImageInput()); break;
case "VirtualMachineVMImageMarketplaceImageAttributes" : WriteObject(new MarketplaceImageAttributes()); break;
case "VirtualMachineVMImageOSDiskConfigurationCreateParameters" : WriteObject(new OSDiskConfigurationCreateParameters()); break;
case "VirtualMachineVMImageOSDiskConfigurationUpdateParameters" : WriteObject(new OSDiskConfigurationUpdateParameters()); break;
case "VirtualMachineVMImagePlan" : WriteObject(new Plan()); break;
case "VirtualMachineVMImageReplicateParameters" : WriteObject(new VirtualMachineVMImageReplicateParameters()); break;
case "VirtualMachineVMImageUpdateParameters" : WriteObject(new VirtualMachineVMImageUpdateParameters()); break;
case "VirtualMachineWindowsRemoteManagementListener" : WriteObject(new WindowsRemoteManagementListener()); break;
case "VirtualMachineWindowsRemoteManagementListenerList" : WriteObject(new List<WindowsRemoteManagementListener>()); break;
case "VirtualMachineWindowsRemoteManagementSettings" : WriteObject(new WindowsRemoteManagementSettings()); break;
default : WriteWarning("Cannot find the type by FriendlyName = '" + FriendlyName + "'."); break;
}
}
else if (ParameterSetName == "CreateParameterObjectByFullName")
{
switch (FullName)
{
case "Microsoft.WindowsAzure.Management.Compute.Models.ComputeImageAttributes" : WriteObject(new ComputeImageAttributes()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.ConfigurationSet" : WriteObject(new ConfigurationSet()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.ConfigurationSet.PublicIP" : WriteObject(new ConfigurationSet.PublicIP()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DataDiskConfiguration" : WriteObject(new DataDiskConfiguration()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DataDiskConfigurationCreateParameters" : WriteObject(new DataDiskConfigurationCreateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DataDiskConfigurationUpdateParameters" : WriteObject(new DataDiskConfigurationUpdateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DataVirtualHardDisk" : WriteObject(new DataVirtualHardDisk()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DeploymentChangeConfigurationParameters" : WriteObject(new DeploymentChangeConfigurationParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DeploymentCreateParameters" : WriteObject(new DeploymentCreateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DeploymentDeleteRoleInstanceParameters" : WriteObject(new DeploymentDeleteRoleInstanceParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DeploymentGetPackageParameters" : WriteObject(new DeploymentGetPackageParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DeploymentRollbackUpdateOrUpgradeParameters" : WriteObject(new DeploymentRollbackUpdateOrUpgradeParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DeploymentSwapParameters" : WriteObject(new DeploymentSwapParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DeploymentUpdateStatusParameters" : WriteObject(new DeploymentUpdateStatusParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DeploymentUpgradeParameters" : WriteObject(new DeploymentUpgradeParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DeploymentWalkUpgradeDomainParameters" : WriteObject(new DeploymentWalkUpgradeDomainParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DNSAddParameters" : WriteObject(new DNSAddParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DnsServer" : WriteObject(new DnsServer()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DnsSettings" : WriteObject(new DnsSettings()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DNSUpdateParameters" : WriteObject(new DNSUpdateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DomainJoinCredentials" : WriteObject(new DomainJoinCredentials()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DomainJoinProvisioning" : WriteObject(new DomainJoinProvisioning()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.DomainJoinSettings" : WriteObject(new DomainJoinSettings()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.ExtensionCertificateConfiguration" : WriteObject(new ExtensionCertificateConfiguration()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.ExtensionConfiguration" : WriteObject(new ExtensionConfiguration()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.ExtensionConfiguration.Extension" : WriteObject(new ExtensionConfiguration.Extension()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.ExtensionConfiguration.NamedRole" : WriteObject(new ExtensionConfiguration.NamedRole()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.ExtensionEndpointConfiguration" : WriteObject(new ExtensionEndpointConfiguration()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.ExtensionEndpointConfiguration.InputEndpoint" : WriteObject(new ExtensionEndpointConfiguration.InputEndpoint()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.ExtensionEndpointConfiguration.InternalEndpoint" : WriteObject(new ExtensionEndpointConfiguration.InternalEndpoint()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.ExtensionImageRegisterParameters" : WriteObject(new ExtensionImageRegisterParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.ExtensionImageUpdateParameters" : WriteObject(new ExtensionImageUpdateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.ExtensionLocalResourceConfiguration" : WriteObject(new ExtensionLocalResourceConfiguration()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.FrontendIPConfiguration" : WriteObject(new FrontendIPConfiguration()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.HostedServiceAddExtensionParameters" : WriteObject(new HostedServiceAddExtensionParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.HostedServiceCreateParameters" : WriteObject(new HostedServiceCreateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.HostedServiceUpdateParameters" : WriteObject(new HostedServiceUpdateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.InputEndpoint" : WriteObject(new InputEndpoint()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.LoadBalancer" : WriteObject(new LoadBalancer()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.LoadBalancerCreateParameters" : WriteObject(new LoadBalancerCreateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.LoadBalancerUpdateParameters" : WriteObject(new LoadBalancerUpdateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.MarketplaceImageAttributes" : WriteObject(new MarketplaceImageAttributes()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.NetworkInterface" : WriteObject(new NetworkInterface()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.OSDiskConfiguration" : WriteObject(new OSDiskConfiguration()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.OSDiskConfigurationCreateParameters" : WriteObject(new OSDiskConfigurationCreateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.OSDiskConfigurationUpdateParameters" : WriteObject(new OSDiskConfigurationUpdateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.OSVirtualHardDisk" : WriteObject(new OSVirtualHardDisk()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.Plan" : WriteObject(new Plan()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.ResourceExtensionReference" : WriteObject(new ResourceExtensionReference()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.Role" : WriteObject(new Role()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.ServiceCertificateCreateParameters" : WriteObject(new ServiceCertificateCreateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.ServiceCertificateDeleteParameters" : WriteObject(new ServiceCertificateDeleteParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.ServiceCertificateGetParameters" : WriteObject(new ServiceCertificateGetParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.SshSettingKeyPair" : WriteObject(new SshSettingKeyPair()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.SshSettingPublicKey" : WriteObject(new SshSettingPublicKey()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.SshSettings" : WriteObject(new SshSettings()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.StoredCertificateSettings" : WriteObject(new StoredCertificateSettings()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineCaptureOSImageParameters" : WriteObject(new VirtualMachineCaptureOSImageParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineCaptureVMImageParameters" : WriteObject(new VirtualMachineCaptureVMImageParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineCreateDeploymentParameters" : WriteObject(new VirtualMachineCreateDeploymentParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineCreateParameters" : WriteObject(new VirtualMachineCreateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineDataDiskCreateParameters" : WriteObject(new VirtualMachineDataDiskCreateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineDataDiskUpdateParameters" : WriteObject(new VirtualMachineDataDiskUpdateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineDiskCreateParameters" : WriteObject(new VirtualMachineDiskCreateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineDiskUpdateParameters" : WriteObject(new VirtualMachineDiskUpdateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineOSImageCreateParameters" : WriteObject(new VirtualMachineOSImageCreateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineOSImageReplicateParameters" : WriteObject(new VirtualMachineOSImageReplicateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineOSImageUpdateParameters" : WriteObject(new VirtualMachineOSImageUpdateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineShutdownParameters" : WriteObject(new VirtualMachineShutdownParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineShutdownRolesParameters" : WriteObject(new VirtualMachineShutdownRolesParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineStartRolesParameters" : WriteObject(new VirtualMachineStartRolesParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineUpdateLoadBalancedSetParameters" : WriteObject(new VirtualMachineUpdateLoadBalancedSetParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineUpdateLoadBalancedSetParameters.InputEndpoint" : WriteObject(new VirtualMachineUpdateLoadBalancedSetParameters.InputEndpoint()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineUpdateParameters" : WriteObject(new VirtualMachineUpdateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineVMImageCreateParameters" : WriteObject(new VirtualMachineVMImageCreateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineVMImageReplicateParameters" : WriteObject(new VirtualMachineVMImageReplicateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VirtualMachineVMImageUpdateParameters" : WriteObject(new VirtualMachineVMImageUpdateParameters()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.VMImageInput" : WriteObject(new VMImageInput()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.WindowsRemoteManagementListener" : WriteObject(new WindowsRemoteManagementListener()); break;
case "Microsoft.WindowsAzure.Management.Compute.Models.WindowsRemoteManagementSettings" : WriteObject(new WindowsRemoteManagementSettings()); break;
case "System.Collections.Generic.List<ConfigurationSet.PublicIP>" : WriteObject(new List<ConfigurationSet.PublicIP>()); break;
case "System.Collections.Generic.List<ConfigurationSet>" : WriteObject(new List<ConfigurationSet>()); break;
case "System.Collections.Generic.List<DataDiskConfiguration>" : WriteObject(new List<DataDiskConfiguration>()); break;
case "System.Collections.Generic.List<DataDiskConfigurationCreateParameters>" : WriteObject(new List<DataDiskConfigurationCreateParameters>()); break;
case "System.Collections.Generic.List<DataDiskConfigurationUpdateParameters>" : WriteObject(new List<DataDiskConfigurationUpdateParameters>()); break;
case "System.Collections.Generic.List<DataVirtualHardDisk>" : WriteObject(new List<DataVirtualHardDisk>()); break;
case "System.Collections.Generic.List<DnsServer>" : WriteObject(new List<DnsServer>()); break;
case "System.Collections.Generic.List<ExtensionConfiguration.Extension>" : WriteObject(new List<ExtensionConfiguration.Extension>()); break;
case "System.Collections.Generic.List<ExtensionConfiguration.NamedRole>" : WriteObject(new List<ExtensionConfiguration.NamedRole>()); break;
case "System.Collections.Generic.List<ExtensionEndpointConfiguration.InputEndpoint>" : WriteObject(new List<ExtensionEndpointConfiguration.InputEndpoint>()); break;
case "System.Collections.Generic.List<ExtensionEndpointConfiguration.InternalEndpoint>" : WriteObject(new List<ExtensionEndpointConfiguration.InternalEndpoint>()); break;
case "System.Collections.Generic.List<ExtensionLocalResourceConfiguration>" : WriteObject(new List<ExtensionLocalResourceConfiguration>()); break;
case "System.Collections.Generic.List<InputEndpoint>" : WriteObject(new List<InputEndpoint>()); break;
case "System.Collections.Generic.List<LoadBalancer>" : WriteObject(new List<LoadBalancer>()); break;
case "System.Collections.Generic.List<NetworkInterface>" : WriteObject(new List<NetworkInterface>()); break;
case "System.Collections.Generic.List<ResourceExtensionReference>" : WriteObject(new List<ResourceExtensionReference>()); break;
case "System.Collections.Generic.List<Role>" : WriteObject(new List<Role>()); break;
case "System.Collections.Generic.List<SshSettingKeyPair>" : WriteObject(new List<SshSettingKeyPair>()); break;
case "System.Collections.Generic.List<SshSettingPublicKey>" : WriteObject(new List<SshSettingPublicKey>()); break;
case "System.Collections.Generic.List<StoredCertificateSettings>" : WriteObject(new List<StoredCertificateSettings>()); break;
case "System.Collections.Generic.List<VirtualMachineUpdateLoadBalancedSetParameters.InputEndpoint>" : WriteObject(new List<VirtualMachineUpdateLoadBalancedSetParameters.InputEndpoint>()); break;
case "System.Collections.Generic.List<WindowsRemoteManagementListener>" : WriteObject(new List<WindowsRemoteManagementListener>()); break;
default : WriteWarning("Cannot find the type by FullName = '" + FullName + "'."); break;
}
}
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Logging;
using portal.Models;
using portal.Services;
using portal.ViewModels.Account;
namespace portal.Controllers
{
[Authorize]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<AccountController>();
}
//
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/Register
[HttpGet]
[AllowAnonymous]
public IActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
// "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
_logger.LogInformation(4, "User logged out.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
}
//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null)
{
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
var email = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
if (User.IsSignedIn())
{
return RedirectToAction(nameof(ManageController.Index), "Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GeneratePasswordResetTokenAsync(user);
//var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Reset Password",
// "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");
//return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
//
// GET: /Account/SendCode
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return View("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/VerifyCode
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(7, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError("", "Invalid code.");
return View(model);
}
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
#endregion
}
}
| |
// 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.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim
{
internal partial class CSharpProjectShim : ICSharpProjectSite
{
/// <summary>
/// When the project property page calls GetValidStartupClasses on us, it assumes
/// the strings passed to it are in the native C# language service's string table
/// and never frees them. To avoid leaking our strings, we allocate them on the
/// native heap for each call and keep the pointers here. On subsequent calls
/// or on disposal, we free the old strings before allocating the new ones.
/// </summary>
private IntPtr[] _startupClasses = null;
public void GetCompiler(out ICSCompiler compiler, out ICSInputSet inputSet)
{
compiler = this;
inputSet = this;
}
public bool CheckInputFileTimes(System.Runtime.InteropServices.ComTypes.FILETIME output)
{
throw new NotImplementedException();
}
public void BuildProject(object progress)
{
throw new NotImplementedException();
}
public void Unused()
{
throw new NotImplementedException();
}
public void OnSourceFileAdded(string filename)
{
var extension = Path.GetExtension(filename);
// The Workflow MSBuild targets and CompileWorkflowTask choose to pass the .xoml files to the language
// service as if they were actual C# files. We should just ignore them.
if (extension.Equals(".xoml", StringComparison.OrdinalIgnoreCase))
{
AddUntrackedFile(filename);
return;
}
// TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325
//var sourceCodeKind = extension.Equals(".csx", StringComparison.OrdinalIgnoreCase)
// ? SourceCodeKind.Script
// : SourceCodeKind.Regular;
var sourceCodeKind = SourceCodeKind.Regular;
IVsHierarchy foundHierarchy;
uint itemId;
if (ErrorHandler.Succeeded(_projectRoot.GetHierarchyAndItemID(filename, out foundHierarchy, out itemId)))
{
Debug.Assert(foundHierarchy == this.Hierarchy);
}
else
{
// Unfortunately, the project system does pass us some files which aren't part of
// the project as far as the hierarchy and itemid are concerned. We'll just used
// VSITEMID.Nil for them.
foundHierarchy = null;
itemId = (uint)VSConstants.VSITEMID.Nil;
}
AddFile(filename, sourceCodeKind, itemId, CanUseTextBuffer);
}
public void OnSourceFileRemoved(string filename)
{
RemoveFile(filename);
}
public int OnResourceFileAdded(string filename, string resourceName, bool embedded)
{
return VSConstants.S_OK;
}
public int OnResourceFileRemoved(string filename)
{
return VSConstants.S_OK;
}
public int OnImportAdded(string filename, string project)
{
// OnImportAdded is superseded by OnImportAddedEx. We maintain back-compat by treating
// it as a non-NoPIA reference.
return OnImportAddedEx(filename, project, CompilerOptions.OPTID_IMPORTS);
}
public int OnImportAddedEx(string filename, string project, CompilerOptions optionID)
{
filename = FileUtilities.NormalizeAbsolutePath(filename);
if (optionID != CompilerOptions.OPTID_IMPORTS && optionID != CompilerOptions.OPTID_IMPORTSUSINGNOPIA)
{
throw new ArgumentException("optionID was an unexpected value.", "optionID");
}
bool embedInteropTypes = optionID == CompilerOptions.OPTID_IMPORTSUSINGNOPIA;
var properties = new MetadataReferenceProperties(embedInteropTypes: embedInteropTypes);
return AddMetadataReferenceAndTryConvertingToProjectReferenceIfPossible(filename, properties);
}
public void OnImportRemoved(string filename, string project)
{
filename = FileUtilities.NormalizeAbsolutePath(filename);
RemoveMetadataReference(filename);
}
public void OnOutputFileChanged(string filename)
{
// We have nothing to do here (yet)
}
public void OnActiveConfigurationChanged(string configName)
{
// We have nothing to do here (yet)
}
public void OnProjectLoadCompletion()
{
// Despite the name, this is not necessarily called when the project has actually been
// completely loaded. If you plan on using this, be careful!
}
protected virtual bool CanUseTextBuffer(ITextBuffer textBuffer)
{
return true;
}
public abstract int CreateCodeModel(object parent, out EnvDTE.CodeModel codeModel);
public abstract int CreateFileCodeModel(string fileName, object parent, out EnvDTE.FileCodeModel ppFileCodeModel);
public void OnModuleAdded(string filename)
{
throw new NotImplementedException();
}
public void OnModuleRemoved(string filename)
{
throw new NotImplementedException();
}
public int GetValidStartupClasses(IntPtr[] classNames, ref int count)
{
// If classNames is NULL, then we need to populate the number of valid startup
// classes only
var project = Workspace.CurrentSolution.GetProject(Id);
var compilation = project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var entryPoints = GetEntryPoints(project, compilation);
if (classNames == null)
{
count = entryPoints.Count();
return VSConstants.S_OK;
}
else
{
// We return s_false if we have more entrypoints than places in the array.
var entryPointNames = entryPoints.Select(e => e.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat.WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted))).ToArray();
if (entryPointNames.Length > classNames.Length)
{
return VSConstants.S_FALSE;
}
// The old language service stored startup class names in its string table,
// so the property page never freed them. To avoid leaking memory, we're
// going to allocate our strings on the native heap and keep the pointers to them.
// Subsequent calls to this function will free the old strings and allocate the
// new ones. The last set of marshalled strings is freed in the destructor.
if (_startupClasses != null)
{
foreach (var @class in _startupClasses)
{
Marshal.FreeHGlobal(@class);
}
}
_startupClasses = entryPointNames.Select(Marshal.StringToHGlobalUni).ToArray();
Array.Copy(_startupClasses, classNames, _startupClasses.Length);
count = entryPointNames.Length;
return VSConstants.S_OK;
}
}
private IEnumerable<INamedTypeSymbol> GetEntryPoints(Project project, Compilation compilation)
{
return EntryPointFinder.FindEntryPoints(compilation.Assembly.GlobalNamespace);
}
public void OnAliasesChanged(string file, string project, int previousAliasesCount, string[] previousAliases, int currentAliasesCount, string[] currentAliases)
{
UpdateMetadataReferenceAliases(file, ImmutableArray.CreateRange(currentAliases));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.Pipeline;
using Azure.Storage.Blobs.Models;
namespace Azure.Storage.Blobs.ChangeFeed
{
internal class LazyLoadingBlobStream : Stream
{
/// <summary>
/// BlobClient to make download calls with.
/// </summary>
private readonly BlobClient _blobClient;
/// <summary>
/// The offset within the blob of the next block we will download.
/// </summary>
private long _offset;
/// <summary>
/// The number of bytes we'll download with each download call.
/// </summary>
private readonly long _blockSize;
/// <summary>
/// Underlying Stream.
/// </summary>
private Stream _stream;
/// <summary>
/// If this LazyLoadingBlobStream has been initalized.
/// </summary>
private bool _initalized;
/// <summary>
/// The number of bytes in the last download call.
/// </summary>
private long _lastDownloadBytes;
/// <summary>
/// The current length of the blob.
/// </summary>
private long _blobLength;
public LazyLoadingBlobStream(BlobClient blobClient, long offset, long blockSize)
{
_blobClient = blobClient;
_offset = offset;
_blockSize = blockSize;
_initalized = false;
}
/// <summary>
/// Constructor for mocking.
/// </summary>
public LazyLoadingBlobStream() { }
/// <inheritdoc/>
public override int Read(
byte[] buffer,
int offset,
int count)
=> ReadInternal(
async: false,
buffer,
offset,
count).EnsureCompleted();
/// <inheritdoc/>
public override async Task<int> ReadAsync(
byte[] buffer,
int offset,
int count,
CancellationToken cancellationToken)
=> await ReadInternal(
async: true,
buffer,
offset,
count,
cancellationToken).ConfigureAwait(false);
/// <summary>
/// Initalizes this LazyLoadingBlobStream.
/// <returns>The number of bytes that were downloaded in the first download request.</returns>
/// </summary>
private async Task Initalize(bool async, CancellationToken cancellationToken)
{
await DownloadBlock(async, cancellationToken).ConfigureAwait(false);
_initalized = true;
}
/// <summary>
/// Downloads the next block.
/// <returns>Number of bytes that were downloaded</returns>
/// </summary>
private async Task DownloadBlock(bool async, CancellationToken cancellationToken)
{
Response<BlobDownloadInfo> response;
HttpRange range = new HttpRange(_offset, _blockSize);
response = async
? await _blobClient.DownloadAsync(range, cancellationToken: cancellationToken).ConfigureAwait(false)
: _blobClient.Download(range);
_stream = response.Value.Content;
_offset += response.Value.ContentLength;
_lastDownloadBytes = response.Value.ContentLength;
_blobLength = GetBlobLength(response);
}
/// <summary>
/// Shared sync and async Read implementation.
/// </summary>
private async Task<int> ReadInternal(
bool async,
byte[] buffer,
int offset,
int count,
CancellationToken cancellationToken = default)
{
ValidateReadParameters(buffer, offset, count);
if (!_initalized)
{
await Initalize(async, cancellationToken: cancellationToken).ConfigureAwait(false);
if (_lastDownloadBytes == 0)
{
return 0;
}
}
int totalCopiedBytes = 0;
do
{
int copiedBytes = async
? await _stream.ReadAsync(buffer, offset, count).ConfigureAwait(false)
: _stream.Read(buffer, offset, count);
offset += copiedBytes;
count -= copiedBytes;
totalCopiedBytes += copiedBytes;
// We've run out of bytes in the current block.
if (copiedBytes == 0)
{
// We hit the end of the blob with the last download call.
if (_offset == _blobLength)
{
return totalCopiedBytes;
}
// Download the next block
else
{
await DownloadBlock(async, cancellationToken).ConfigureAwait(false);
}
}
}
while (count > 0);
return totalCopiedBytes;
}
private static void ValidateReadParameters(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException($"{nameof(buffer)}", $"{nameof(buffer)} cannot be null.");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException($"{nameof(offset)} cannot be less than 0.");
}
if (offset > buffer.Length)
{
throw new ArgumentOutOfRangeException($"{nameof(offset)} cannot exceed {nameof(buffer)} length.");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException($"{nameof(count)} cannot be less than 0.");
}
if (offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException($"{nameof(offset)} + {nameof(count)} cannot exceed {nameof(buffer)} length.");
}
}
private static long GetBlobLength(Response<BlobDownloadInfo> response)
{
string lengthString = response.Value.Details.ContentRange;
string[] split = lengthString.Split('/');
return Convert.ToInt64(split[1], CultureInfo.InvariantCulture);
}
/// <inheritdoc/>
public override bool CanRead => true;
/// <inheritdoc/>
public override bool CanSeek => false;
/// <inheritdoc/>
public override bool CanWrite => throw new NotSupportedException();
public override long Length => throw new NotSupportedException();
/// <inheritdoc/>
public override long Position {
get => _stream.Position;
set => throw new NotSupportedException();
}
/// <inheritdoc/>
public override void Flush()
{
}
/// <inheritdoc/>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <inheritdoc/>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <inheritdoc/>
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
protected override void Dispose(bool disposing) => _stream.Dispose();
}
}
| |
// Copyright 2012 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Annotations;
using NodaTime.TimeZones.Cldr;
using NodaTime.Utility;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
namespace NodaTime.TimeZones.IO
{
/// <summary>
/// Provides the raw data exposed by <see cref="TzdbDateTimeZoneSource"/>.
/// </summary>
internal sealed class TzdbStreamData
{
private static readonly Dictionary<TzdbStreamFieldId, Action<Builder, TzdbStreamField>> FieldHandlers =
new Dictionary<TzdbStreamFieldId, Action<Builder, TzdbStreamField>>
{
[TzdbStreamFieldId.StringPool] = (builder, field) => builder.HandleStringPoolField(field),
[TzdbStreamFieldId.TimeZone] = (builder, field) => builder.HandleZoneField(field),
[TzdbStreamFieldId.TzdbIdMap] = (builder, field) => builder.HandleTzdbIdMapField(field),
[TzdbStreamFieldId.TzdbVersion] = (builder, field) => builder.HandleTzdbVersionField(field),
[TzdbStreamFieldId.CldrSupplementalWindowsZones] = (builder, field) => builder.HandleSupplementalWindowsZonesField(field),
[TzdbStreamFieldId.ZoneLocations] = (builder, field) => builder.HandleZoneLocationsField(field),
[TzdbStreamFieldId.Zone1970Locations] = (builder, field) => builder.HandleZone1970LocationsField(field)
};
private const int AcceptedVersion = 0;
private readonly IReadOnlyList<string> stringPool;
private readonly IDictionary<string, TzdbStreamField> zoneFields;
/// <summary>
/// Returns the TZDB version string.
/// </summary>
public string TzdbVersion { get; }
/// <summary>
/// Returns the TZDB ID dictionary (alias to canonical ID).
/// </summary>
public ReadOnlyDictionary<string, string> TzdbIdMap { get; }
/// <summary>
/// Returns the Windows mapping dictionary. (As the type is immutable, it can be exposed directly
/// to callers.)
/// </summary>
public WindowsZones WindowsMapping { get; }
/// <summary>
/// Returns the zone locations for the source, or null if no location data is available.
/// </summary>
public ReadOnlyCollection<TzdbZoneLocation>? ZoneLocations { get; }
/// <summary>
/// Returns the "zone 1970" locations for the source, or null if no such location data is available.
/// </summary>
public ReadOnlyCollection<TzdbZone1970Location>? Zone1970Locations { get; }
[VisibleForTesting]
internal TzdbStreamData(Builder builder)
{
stringPool = CheckNotNull(builder.stringPool, "string pool");
var mutableIdMap = CheckNotNull(builder.tzdbIdMap, "TZDB alias map");
TzdbVersion = CheckNotNull(builder.tzdbVersion, "TZDB version");
WindowsMapping = CheckNotNull(builder.windowsMapping, "CLDR Supplemental Windows Zones");
zoneFields = builder.zoneFields;
ZoneLocations = builder.zoneLocations;
Zone1970Locations = builder.zone1970Locations;
// Add in the canonical IDs as mappings to themselves.
foreach (var id in zoneFields.Keys)
{
mutableIdMap[id] = id;
}
TzdbIdMap = new ReadOnlyDictionary<string, string>(mutableIdMap);
}
/// <summary>
/// Creates the <see cref="DateTimeZone"/> for the given canonical ID, which will definitely
/// be one of the values of the TzdbAliases dictionary.
/// </summary>
/// <param name="id">ID for the returned zone, which may be an alias.</param>
/// <param name="canonicalId">Canonical ID for zone data</param>
public DateTimeZone CreateZone(string id, string canonicalId)
{
Preconditions.CheckNotNull(id, nameof(id));
Preconditions.CheckNotNull(canonicalId, nameof(canonicalId));
using (var stream = zoneFields[canonicalId].CreateStream())
{
var reader = new DateTimeZoneReader(stream, stringPool);
// Skip over the ID before the zone data itself
reader.ReadString();
var type = (DateTimeZoneWriter.DateTimeZoneType) reader.ReadByte();
return type switch
{
DateTimeZoneWriter.DateTimeZoneType.Fixed => FixedDateTimeZone.Read(reader, id),
DateTimeZoneWriter.DateTimeZoneType.Precalculated =>
CachedDateTimeZone.ForZone(PrecalculatedDateTimeZone.Read(reader, id)),
_ => throw new InvalidNodaDataException($"Unknown time zone type {type}")
};
}
}
// Like Preconditions.CheckNotNull, but specifically for incomplete data.
private static T CheckNotNull<T>(T? input, string name) where T : class
{
if (input is null)
{
throw new InvalidNodaDataException($"Incomplete TZDB data. Missing field: {name}");
}
return input;
}
internal static TzdbStreamData FromStream(Stream stream)
{
Preconditions.CheckNotNull(stream, nameof(stream));
// Using statement to satisfy FxCop, but dispose won't do anything anyway, because
// we deliberately leave the stream open.
using (var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true))
{
int version = reader.ReadInt32();
if (version != AcceptedVersion)
{
throw new InvalidNodaDataException($"Unable to read stream with version {version}");
}
}
Builder builder = new Builder();
foreach (var field in TzdbStreamField.ReadFields(stream))
{
// Only handle fields we know about
if (FieldHandlers.TryGetValue(field.Id, out Action<Builder, TzdbStreamField> handler))
{
handler(builder, field);
}
}
return new TzdbStreamData(builder);
}
/// <summary>
/// Mutable builder class used during parsing.
/// </summary>
[VisibleForTesting]
internal class Builder
{
internal IReadOnlyList<string>? stringPool;
internal string? tzdbVersion;
// Note: deliberately mutable, as this is useful later when we map the canonical IDs to themselves.
// This is a mapping of the aliases from TZDB, at this point.
internal IDictionary<string, string>? tzdbIdMap;
internal ReadOnlyCollection<TzdbZoneLocation>? zoneLocations;
internal ReadOnlyCollection<TzdbZone1970Location>? zone1970Locations;
internal WindowsZones? windowsMapping;
internal readonly IDictionary<string, TzdbStreamField> zoneFields = new Dictionary<string, TzdbStreamField>();
internal void HandleStringPoolField(TzdbStreamField field)
{
CheckSingleField(field, stringPool);
using (var stream = field.CreateStream())
{
var reader = new DateTimeZoneReader(stream, null);
int count = reader.ReadCount();
var stringPoolArray = new string[count];
for (int i = 0; i < count; i++)
{
stringPoolArray[i] = reader.ReadString();
}
stringPool = stringPoolArray;
}
}
internal void HandleZoneField(TzdbStreamField field)
{
CheckStringPoolPresence(field);
// Just read the ID from the zone - we don't parse the data yet.
// (We could, but we might as well be lazy.)
using (var stream = field.CreateStream())
{
var reader = new DateTimeZoneReader(stream, stringPool);
string id = reader.ReadString();
if (zoneFields.ContainsKey(id))
{
throw new InvalidNodaDataException($"Multiple definitions for zone {id}");
}
zoneFields[id] = field;
}
}
internal void HandleTzdbVersionField(TzdbStreamField field)
{
CheckSingleField(field, tzdbVersion);
tzdbVersion = field.ExtractSingleValue(reader => reader.ReadString(), null);
}
internal void HandleTzdbIdMapField(TzdbStreamField field)
{
CheckSingleField(field, tzdbIdMap);
tzdbIdMap = field.ExtractSingleValue(reader => reader.ReadDictionary(), stringPool);
}
internal void HandleSupplementalWindowsZonesField(TzdbStreamField field)
{
CheckSingleField(field, windowsMapping);
windowsMapping = field.ExtractSingleValue(WindowsZones.Read, stringPool);
}
internal void HandleZoneLocationsField(TzdbStreamField field)
{
CheckSingleField(field, zoneLocations);
CheckStringPoolPresence(field);
using (var stream = field.CreateStream())
{
var reader = new DateTimeZoneReader(stream, stringPool);
var count = reader.ReadCount();
var array = new TzdbZoneLocation[count];
for (int i = 0; i < count; i++)
{
array[i] = TzdbZoneLocation.Read(reader);
}
zoneLocations = Array.AsReadOnly(array);
}
}
internal void HandleZone1970LocationsField(TzdbStreamField field)
{
CheckSingleField(field, zone1970Locations);
CheckStringPoolPresence(field);
using (var stream = field.CreateStream())
{
var reader = new DateTimeZoneReader(stream, stringPool);
var count = reader.ReadCount();
var array = new TzdbZone1970Location[count];
for (int i = 0; i < count; i++)
{
array[i] = TzdbZone1970Location.Read(reader);
}
zone1970Locations = Array.AsReadOnly(array);
}
}
private static void CheckSingleField(TzdbStreamField field, object? expectedNullField)
{
if (expectedNullField != null)
{
throw new InvalidNodaDataException($"Multiple fields of ID {field.Id}");
}
}
private void CheckStringPoolPresence(TzdbStreamField field)
{
if (stringPool is null)
{
throw new InvalidNodaDataException($"String pool must be present before field {field.Id}");
}
}
}
}
}
| |
/*
* REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
*
* The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using HETSAPI.Models;
namespace HETSAPI.Models
{
/// <summary>
/// The Ministry of Transportion and Infrastructure REGION.
/// </summary>
[MetaDataExtension (Description = "The Ministry of Transportion and Infrastructure REGION.")]
public partial class Region : AuditableEntity, IEquatable<Region>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public Region()
{
this.Id = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Region" /> class.
/// </summary>
/// <param name="Id">A system-generated unique identifier for a Region (required).</param>
/// <param name="MinistryRegionID">A system generated unique identifier. NOT GENERATED IN THIS SYSTEM. (required).</param>
/// <param name="Name">The name of a Minsitry Region. (required).</param>
/// <param name="StartDate">The DATE the business information came into effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM (required).</param>
/// <param name="RegionNumber">A code that uniquely defines a Region..</param>
/// <param name="EndDate">The DATE the business information ceased to be in effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM.</param>
public Region(int Id, int MinistryRegionID, string Name, DateTime StartDate, int? RegionNumber = null, DateTime? EndDate = null)
{
this.Id = Id;
this.MinistryRegionID = MinistryRegionID;
this.Name = Name;
this.StartDate = StartDate;
this.RegionNumber = RegionNumber;
this.EndDate = EndDate;
}
/// <summary>
/// A system-generated unique identifier for a Region
/// </summary>
/// <value>A system-generated unique identifier for a Region</value>
[MetaDataExtension (Description = "A system-generated unique identifier for a Region")]
public int Id { get; set; }
/// <summary>
/// A system generated unique identifier. NOT GENERATED IN THIS SYSTEM.
/// </summary>
/// <value>A system generated unique identifier. NOT GENERATED IN THIS SYSTEM.</value>
[MetaDataExtension (Description = "A system generated unique identifier. NOT GENERATED IN THIS SYSTEM.")]
public int MinistryRegionID { get; set; }
/// <summary>
/// The name of a Minsitry Region.
/// </summary>
/// <value>The name of a Minsitry Region.</value>
[MetaDataExtension (Description = "The name of a Minsitry Region.")]
[MaxLength(150)]
public string Name { get; set; }
/// <summary>
/// The DATE the business information came into effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM
/// </summary>
/// <value>The DATE the business information came into effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM</value>
[MetaDataExtension (Description = "The DATE the business information came into effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM")]
public DateTime StartDate { get; set; }
/// <summary>
/// A code that uniquely defines a Region.
/// </summary>
/// <value>A code that uniquely defines a Region.</value>
[MetaDataExtension (Description = "A code that uniquely defines a Region.")]
public int? RegionNumber { get; set; }
/// <summary>
/// The DATE the business information ceased to be in effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM
/// </summary>
/// <value>The DATE the business information ceased to be in effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM</value>
[MetaDataExtension (Description = "The DATE the business information ceased to be in effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM")]
public DateTime? EndDate { 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 Region {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" MinistryRegionID: ").Append(MinistryRegionID).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" StartDate: ").Append(StartDate).Append("\n");
sb.Append(" RegionNumber: ").Append(RegionNumber).Append("\n");
sb.Append(" EndDate: ").Append(EndDate).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((Region)obj);
}
/// <summary>
/// Returns true if Region instances are equal
/// </summary>
/// <param name="other">Instance of Region to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Region other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.Id == other.Id ||
this.Id.Equals(other.Id)
) &&
(
this.MinistryRegionID == other.MinistryRegionID ||
this.MinistryRegionID.Equals(other.MinistryRegionID)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.StartDate == other.StartDate ||
this.StartDate != null &&
this.StartDate.Equals(other.StartDate)
) &&
(
this.RegionNumber == other.RegionNumber ||
this.RegionNumber != null &&
this.RegionNumber.Equals(other.RegionNumber)
) &&
(
this.EndDate == other.EndDate ||
this.EndDate != null &&
this.EndDate.Equals(other.EndDate)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + this.Id.GetHashCode();
hash = hash * 59 + this.MinistryRegionID.GetHashCode(); if (this.Name != null)
{
hash = hash * 59 + this.Name.GetHashCode();
}
if (this.StartDate != null)
{
hash = hash * 59 + this.StartDate.GetHashCode();
} if (this.RegionNumber != null)
{
hash = hash * 59 + this.RegionNumber.GetHashCode();
}
if (this.EndDate != null)
{
hash = hash * 59 + this.EndDate.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(Region left, Region right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(Region left, Region right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 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.Threading;
using System.Globalization;
using NUnit.Framework;
using NUnit.Framework.Constraints;
using NUnit.Framework.Internal.Execution;
using System.Security.Principal;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Summary description for TestExecutionContextTests.
/// </summary>
[TestFixture][Property("Question", "Why?")]
public class TestExecutionContextTests
{
TestExecutionContext fixtureContext;
TestExecutionContext setupContext;
#if !PORTABLE && !NETSTANDARD1_6
string originalDirectory;
IPrincipal originalPrincipal;
#endif
[OneTimeSetUp]
public void OneTimeSetUp()
{
fixtureContext = TestExecutionContext.CurrentContext;
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
// TODO: We put some tests in one time teardown to verify that
// the context is still valid. It would be better if these tests
// were placed in a second-level test, invoked from this test class.
TestExecutionContext ec = TestExecutionContext.CurrentContext;
Assert.That(ec.CurrentTest.Name, Is.EqualTo("TestExecutionContextTests"));
Assert.That(ec.CurrentTest.FullName,
Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests"));
Assert.That(fixtureContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty);
Assert.That(fixtureContext.CurrentTest.Properties.Get("Question"), Is.EqualTo("Why?"));
}
/// <summary>
/// Since we are testing the mechanism that saves and
/// restores contexts, we save manually here
/// </summary>
[SetUp]
public void Initialize()
{
setupContext = new TestExecutionContext(TestExecutionContext.CurrentContext);
#if !PORTABLE && !NETSTANDARD1_6
originalCulture = CultureInfo.CurrentCulture;
originalUICulture = CultureInfo.CurrentUICulture;
#endif
#if !PORTABLE && !NETSTANDARD1_6
originalDirectory = Environment.CurrentDirectory;
originalPrincipal = Thread.CurrentPrincipal;
#endif
}
[TearDown]
public void Cleanup()
{
#if !PORTABLE && !NETSTANDARD1_6
Thread.CurrentThread.CurrentCulture = originalCulture;
Thread.CurrentThread.CurrentUICulture = originalUICulture;
#endif
#if !PORTABLE && !NETSTANDARD1_6
Environment.CurrentDirectory = originalDirectory;
Thread.CurrentPrincipal = originalPrincipal;
#endif
Assert.That(
TestExecutionContext.CurrentContext.CurrentTest.FullName,
Is.EqualTo(setupContext.CurrentTest.FullName),
"Context at TearDown failed to match that saved from SetUp");
}
#region CurrentTest
[Test]
public void FixtureSetUpCanAccessFixtureName()
{
Assert.That(fixtureContext.CurrentTest.Name, Is.EqualTo("TestExecutionContextTests"));
}
[Test]
public void FixtureSetUpCanAccessFixtureFullName()
{
Assert.That(fixtureContext.CurrentTest.FullName,
Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests"));
}
[Test]
public void FixtureSetUpHasNullMethodName()
{
Assert.That(fixtureContext.CurrentTest.MethodName, Is.Null);
}
[Test]
public void FixtureSetUpCanAccessFixtureId()
{
Assert.That(fixtureContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty);
}
[Test]
public void FixtureSetUpCanAccessFixtureProperties()
{
Assert.That(fixtureContext.CurrentTest.Properties.Get("Question"), Is.EqualTo("Why?"));
}
[Test]
public void SetUpCanAccessTestName()
{
Assert.That(setupContext.CurrentTest.Name, Is.EqualTo("SetUpCanAccessTestName"));
}
[Test]
public void SetUpCanAccessTestFullName()
{
Assert.That(setupContext.CurrentTest.FullName,
Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.SetUpCanAccessTestFullName"));
}
[Test]
public void SetUpCanAccessTestMethodName()
{
Assert.That(setupContext.CurrentTest.MethodName,
Is.EqualTo("SetUpCanAccessTestMethodName"));
}
[Test]
public void SetUpCanAccessTestId()
{
Assert.That(setupContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty);
}
[Test]
[Property("Answer", 42)]
public void SetUpCanAccessTestProperties()
{
Assert.That(setupContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42));
}
[Test]
public void TestCanAccessItsOwnName()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Name, Is.EqualTo("TestCanAccessItsOwnName"));
}
[Test]
public void TestCanAccessItsOwnFullName()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.FullName,
Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.TestCanAccessItsOwnFullName"));
}
[Test]
public void TestCanAccessItsOwnMethodName()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.MethodName,
Is.EqualTo("TestCanAccessItsOwnMethodName"));
}
[Test]
public void TestCanAccessItsOwnId()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty);
}
#if !PORTABLE && !NETSTANDARD1_6
[Test]
public void TestHasWorkerWhenParallel()
{
var worker = TestExecutionContext.CurrentContext.TestWorker;
var isRunningUnderTestWorker = TestExecutionContext.CurrentContext.Dispatcher is ParallelWorkItemDispatcher;
Assert.That(worker != null || !isRunningUnderTestWorker);
}
#endif
[Test]
[Property("Answer", 42)]
public void TestCanAccessItsOwnProperties()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42));
}
#endregion
#region CurrentCulture and CurrentUICulture
#if !PORTABLE && !NETSTANDARD1_6
CultureInfo originalCulture;
CultureInfo originalUICulture;
[Test]
public void FixtureSetUpContextReflectsCurrentCulture()
{
Assert.That(fixtureContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture));
}
[Test]
public void FixtureSetUpContextReflectsCurrentUICulture()
{
Assert.That(fixtureContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture));
}
[Test]
public void SetUpContextReflectsCurrentCulture()
{
Assert.That(setupContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture));
}
[Test]
public void SetUpContextReflectsCurrentUICulture()
{
Assert.That(setupContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture));
}
[Test]
public void TestContextReflectsCurrentCulture()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture));
}
[Test]
public void TestContextReflectsCurrentUICulture()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture));
}
[Test]
public void SetAndRestoreCurrentCulture()
{
var context = new TestExecutionContext(setupContext);
try
{
CultureInfo otherCulture =
new CultureInfo(originalCulture.Name == "fr-FR" ? "en-GB" : "fr-FR");
context.CurrentCulture = otherCulture;
Assert.AreEqual(otherCulture, CultureInfo.CurrentCulture, "Culture was not set");
Assert.AreEqual(otherCulture, context.CurrentCulture, "Culture not in new context");
Assert.AreEqual(setupContext.CurrentCulture, originalCulture, "Original context should not change");
}
finally
{
setupContext.EstablishExecutionEnvironment();
}
Assert.AreEqual(CultureInfo.CurrentCulture, originalCulture, "Culture was not restored");
Assert.AreEqual(setupContext.CurrentCulture, originalCulture, "Culture not in final context");
}
[Test]
public void SetAndRestoreCurrentUICulture()
{
var context = new TestExecutionContext(setupContext);
try
{
CultureInfo otherCulture =
new CultureInfo(originalUICulture.Name == "fr-FR" ? "en-GB" : "fr-FR");
context.CurrentUICulture = otherCulture;
Assert.AreEqual(otherCulture, CultureInfo.CurrentUICulture, "UICulture was not set");
Assert.AreEqual(otherCulture, context.CurrentUICulture, "UICulture not in new context");
Assert.AreEqual(setupContext.CurrentUICulture, originalUICulture, "Original context should not change");
}
finally
{
setupContext.EstablishExecutionEnvironment();
}
Assert.AreEqual(CultureInfo.CurrentUICulture, originalUICulture, "UICulture was not restored");
Assert.AreEqual(setupContext.CurrentUICulture, originalUICulture, "UICulture not in final context");
}
#endif
#endregion
#region CurrentPrincipal
#if !PORTABLE && !NETSTANDARD1_6
[Test]
public void FixtureSetUpContextReflectsCurrentPrincipal()
{
Assert.That(fixtureContext.CurrentPrincipal, Is.EqualTo(Thread.CurrentPrincipal));
}
[Test]
public void SetUpContextReflectsCurrentPrincipal()
{
Assert.That(setupContext.CurrentPrincipal, Is.EqualTo(Thread.CurrentPrincipal));
}
[Test]
public void TestContextReflectsCurrentPrincipal()
{
Assert.That(TestExecutionContext.CurrentContext.CurrentPrincipal, Is.EqualTo(Thread.CurrentPrincipal));
}
[Test]
public void SetAndRestoreCurrentPrincipal()
{
var context = new TestExecutionContext(setupContext);
try
{
GenericIdentity identity = new GenericIdentity("foo");
context.CurrentPrincipal = new GenericPrincipal(identity, new string[0]);
Assert.AreEqual("foo", Thread.CurrentPrincipal.Identity.Name, "Principal was not set");
Assert.AreEqual("foo", context.CurrentPrincipal.Identity.Name, "Principal not in new context");
Assert.AreEqual(setupContext.CurrentPrincipal, originalPrincipal, "Original context should not change");
}
finally
{
setupContext.EstablishExecutionEnvironment();
}
Assert.AreEqual(Thread.CurrentPrincipal, originalPrincipal, "Principal was not restored");
Assert.AreEqual(setupContext.CurrentPrincipal, originalPrincipal, "Principal not in final context");
}
#endif
#endregion
#region ValueFormatter
[Test]
public void SetAndRestoreValueFormatter()
{
var context = new TestExecutionContext(setupContext);
var originalFormatter = context.CurrentValueFormatter;
try
{
ValueFormatter f = val => "dummy";
context.AddFormatter(next => f);
Assert.That(context.CurrentValueFormatter, Is.EqualTo(f));
context.EstablishExecutionEnvironment();
Assert.That(MsgUtils.FormatValue(123), Is.EqualTo("dummy"));
}
finally
{
setupContext.EstablishExecutionEnvironment();
}
Assert.That(TestExecutionContext.CurrentContext.CurrentValueFormatter, Is.EqualTo(originalFormatter));
Assert.That(MsgUtils.FormatValue(123), Is.EqualTo("123"));
}
#endregion
#region SingleThreaded
[Test]
public void SingleThreadedDefaultsToFalse()
{
Assert.False(new TestExecutionContext().IsSingleThreaded);
}
[Test]
public void SingleThreadedIsInherited()
{
var parent = new TestExecutionContext();
parent.IsSingleThreaded = true;
Assert.True(new TestExecutionContext(parent).IsSingleThreaded);
}
#endregion
#region ExecutionStatus
[Test]
public void ExecutionStatusIsPushedToHigherContext()
{
var topContext = new TestExecutionContext();
var bottomContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext)));
bottomContext.ExecutionStatus = TestExecutionStatus.StopRequested;
Assert.That(topContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.StopRequested));
}
[Test]
public void ExecutionStatusIsPulledFromHigherContext()
{
var topContext = new TestExecutionContext();
var bottomContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext)));
topContext.ExecutionStatus = TestExecutionStatus.AbortRequested;
Assert.That(bottomContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.AbortRequested));
}
[Test]
public void ExecutionStatusIsPromulgatedAcrossBranches()
{
var topContext = new TestExecutionContext();
var leftContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext)));
var rightContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext)));
leftContext.ExecutionStatus = TestExecutionStatus.StopRequested;
Assert.That(rightContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.StopRequested));
}
#endregion
#region Cross-domain Tests
#if !PORTABLE && !NETSTANDARD1_6
[Test]
public void CanCreateObjectInAppDomain()
{
AppDomain domain = AppDomain.CreateDomain(
"TestCanCreateAppDomain",
AppDomain.CurrentDomain.Evidence,
AssemblyHelper.GetDirectoryName(Assembly.GetExecutingAssembly()),
null,
false);
var obj = domain.CreateInstanceAndUnwrap("nunit.framework.tests", "NUnit.Framework.Internal.TestExecutionContextTests+TestClass");
Assert.NotNull(obj);
}
[Serializable]
private class TestClass
{
}
#endif
#endregion
}
#if !PORTABLE && !NETSTANDARD1_6
[TestFixture]
public class TextExecutionContextInAppDomain
{
private RunsInAppDomain _runsInAppDomain;
[SetUp]
public void SetUp()
{
var domain = AppDomain.CreateDomain("TestDomain", null, AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.RelativeSearchPath, false);
_runsInAppDomain = domain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName,
"NUnit.Framework.Internal.RunsInAppDomain") as RunsInAppDomain;
Assert.That(_runsInAppDomain, Is.Not.Null);
}
[Test]
[Description("Issue 71 - NUnit swallows console output from AppDomains created within tests")]
public void CanWriteToConsoleInAppDomain()
{
_runsInAppDomain.WriteToConsole();
}
[Test]
[Description("Issue 210 - TestContext.WriteLine in an AppDomain causes an error")]
public void CanWriteToTestContextInAppDomain()
{
_runsInAppDomain.WriteToTestContext();
}
}
internal class RunsInAppDomain : MarshalByRefObject
{
public void WriteToConsole()
{
Console.WriteLine("RunsInAppDomain.WriteToConsole");
}
public void WriteToTestContext()
{
TestContext.WriteLine("RunsInAppDomain.WriteToTestContext");
}
}
#endif
}
| |
// Copyright 2016 Google Inc. 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.
using UnityEngine;
using UnityEngine.UI;
using System;
public class DemoInputManager : MonoBehaviour {
// Build for iOS, or for a pre-native integration Unity version, for Android, and running on-device.
#if UNITY_IOS || (!UNITY_HAS_GOOGLEVR && !UNITY_5_6_OR_NEWER && UNITY_ANDROID && !UNITY_EDITOR)
void Start() {
GameObject messageCanvas = transform.Find("MessageCanvas").gameObject;
messageCanvas.SetActive(false);
}
#endif // UNITY_IOS || (!UNITY_HAS_GOOGLEVR && !UNITY_5_6_OR_NEWER && UNITY_ANDROID && !UNITY_EDITOR)
// Cardboard / Daydream switching does not apply to pre-native integration versions
// of Unity, or platforms other than Android, since those are Cardboard-only.
#if UNITY_HAS_GOOGLEVR && UNITY_ANDROID
private const string MESSAGE_CANVAS_NAME = "MessageCanvas";
private const string MESSAGE_TEXT_NAME = "MessageText";
private const string LASER_GAMEOBJECT_NAME = "Laser";
private const string CONTROLLER_CONNECTING_MESSAGE = "Controller connecting...";
private const string CONTROLLER_DISCONNECTED_MESSAGE = "Controller disconnected";
private const string CONTROLLER_SCANNING_MESSAGE = "Controller scanning...";
private const string EMPTY_VR_SDK_WARNING_MESSAGE =
"Please enable a VR SDK in Player Settings > Virtual Reality Supported\n";
// Java class, method, and field constants.
private const int ANDROID_MIN_DAYDREAM_API = 24;
private const string FIELD_SDK_INT = "SDK_INT";
private const string PACKAGE_BUILD_VERSION = "android.os.Build$VERSION";
private const string PACKAGE_DAYDREAM_API_CLASS = "com.google.vr.ndk.base.DaydreamApi";
private const string PACKAGE_UNITY_PLAYER = "com.unity3d.player.UnityPlayer";
private const string METHOD_CURRENT_ACTIVITY = "currentActivity";
private const string METHOD_IS_DAYDREAM_READY = "isDaydreamReadyPlatform";
private bool isDaydream = false;
public static string CARDBOARD_DEVICE_NAME = "cardboard";
public static string DAYDREAM_DEVICE_NAME = "daydream";
[Tooltip("Reference to GvrControllerMain")]
public GameObject controllerMain;
public static string CONTROLLER_MAIN_PROP_NAME = "controllerMain";
[Tooltip("Reference to GvrControllerPointer")]
public GameObject controllerPointer;
public static string CONTROLLER_POINTER_PROP_NAME = "controllerPointer";
[Tooltip("Reference to GvrReticlePointer")]
public GameObject reticlePointer;
public static string RETICLE_POINTER_PROP_NAME = "reticlePointer";
public GameObject messageCanvas;
public Text messageText;
#if UNITY_EDITOR
public enum EmulatedPlatformType {
Daydream,
Cardboard
}
// Cardboard by default if there is no native integration.
[Tooltip("Emulated GVR Platform")]
public EmulatedPlatformType gvrEmulatedPlatformType = EmulatedPlatformType.Daydream;
public static string EMULATED_PLATFORM_PROP_NAME = "gvrEmulatedPlatformType";
#endif // UNITY_EDITOR
void Start() {
Input.backButtonLeavesApp = true;
if (messageCanvas == null) {
messageCanvas = transform.Find(MESSAGE_CANVAS_NAME).gameObject;
if (messageCanvas != null) {
messageText = messageCanvas.transform.Find(MESSAGE_TEXT_NAME).GetComponent<Text>();
}
}
#if UNITY_EDITOR
if (playerSettingsHasDaydream() || playerSettingsHasCardboard()) {
// The list is populated with valid VR SDK(s), pick the first one.
gvrEmulatedPlatformType =
(UnityEngine.VR.VRSettings.supportedDevices[0] == DAYDREAM_DEVICE_NAME) ?
EmulatedPlatformType.Daydream :
EmulatedPlatformType.Cardboard;
}
isDaydream = (gvrEmulatedPlatformType == EmulatedPlatformType.Daydream);
#else
// First loaded device in Player Settings.
string vrDeviceName = UnityEngine.VR.VRSettings.loadedDeviceName;
if (vrDeviceName != CARDBOARD_DEVICE_NAME &&
vrDeviceName != DAYDREAM_DEVICE_NAME) {
Debug.Log(string.Format("Loaded device was {0} must be one of {1} or {2}",
vrDeviceName, DAYDREAM_DEVICE_NAME, CARDBOARD_DEVICE_NAME));
return;
}
// On a non-Daydream ready phone, fall back to Cardboard if it's present in the
// list of enabled VR SDKs.
if (!IsDeviceDaydreamReady() && playerSettingsHasCardboard()) {
vrDeviceName = CARDBOARD_DEVICE_NAME;
}
isDaydream = (vrDeviceName == DAYDREAM_DEVICE_NAME);
#endif // UNITY_EDITOR
SetVRInputMechanism();
}
// Runtime switching enabled only in-editor.
void Update() {
UpdateStatusMessage();
#if UNITY_EDITOR
UpdateEmulatedPlatformIfPlayerSettingsChanged();
if ((isDaydream && gvrEmulatedPlatformType == EmulatedPlatformType.Daydream) ||
(!isDaydream && gvrEmulatedPlatformType == EmulatedPlatformType.Cardboard)) {
return;
}
isDaydream = (gvrEmulatedPlatformType == EmulatedPlatformType.Daydream);
SetVRInputMechanism();
#endif // UNITY_EDITOR
}
void LateUpdate() {
GvrViewer.Instance.UpdateState();
// Exit when (X) is tapped.
if (Input.GetKeyDown(KeyCode.Escape)) {
Application.Quit();
}
}
public static bool playerSettingsHasDaydream() {
string[] playerSettingsVrSdks = UnityEngine.VR.VRSettings.supportedDevices;
return Array.Exists<string>(playerSettingsVrSdks,
element => element.Equals(DemoInputManager.DAYDREAM_DEVICE_NAME));
}
public static bool playerSettingsHasCardboard() {
string[] playerSettingsVrSdks = UnityEngine.VR.VRSettings.supportedDevices;
return Array.Exists<string>(playerSettingsVrSdks,
element => element.Equals(DemoInputManager.CARDBOARD_DEVICE_NAME));
}
#if UNITY_EDITOR
private void UpdateEmulatedPlatformIfPlayerSettingsChanged() {
if (!playerSettingsHasDaydream() && !playerSettingsHasCardboard()) {
return;
}
// Player Settings > VR SDK list may have changed at runtime. The emulated platform
// may not have been manually updated if that's the case.
if (gvrEmulatedPlatformType == EmulatedPlatformType.Daydream &&
!playerSettingsHasDaydream()) {
gvrEmulatedPlatformType = EmulatedPlatformType.Cardboard;
} else if (gvrEmulatedPlatformType == EmulatedPlatformType.Cardboard &&
!playerSettingsHasCardboard()) {
gvrEmulatedPlatformType = EmulatedPlatformType.Daydream;
}
}
#endif // UNITY_EDITOR
#if !UNITY_EDITOR // Running on an Android device.
private static bool IsDeviceDaydreamReady() {
// Check API level.
using (var version = new AndroidJavaClass(PACKAGE_BUILD_VERSION)) {
if (version.GetStatic<int>(FIELD_SDK_INT) < ANDROID_MIN_DAYDREAM_API) {
return false;
}
}
// API level > 24, check whether the device is Daydream-ready..
AndroidJavaObject androidActivity = null;
try {
using (AndroidJavaObject unityPlayer = new AndroidJavaClass(PACKAGE_UNITY_PLAYER)) {
androidActivity = unityPlayer.GetStatic<AndroidJavaObject>(METHOD_CURRENT_ACTIVITY);
}
} catch (AndroidJavaException e) {
Debug.LogError("Exception while connecting to the Activity: " + e);
return false;
}
AndroidJavaClass daydreamApiClass = new AndroidJavaClass(PACKAGE_DAYDREAM_API_CLASS);
if (daydreamApiClass == null || androidActivity == null) {
return false;
}
return daydreamApiClass.CallStatic<bool>(METHOD_IS_DAYDREAM_READY, androidActivity);
}
#endif // !UNITY_EDITOR
private void UpdateStatusMessage() {
if (messageText == null || messageCanvas == null) {
return;
}
bool isVrSdkListEmpty = !playerSettingsHasCardboard() && !playerSettingsHasDaydream();
if (!isDaydream) {
if (messageCanvas.activeSelf) {
messageText.text = EMPTY_VR_SDK_WARNING_MESSAGE;
messageCanvas.SetActive(false || isVrSdkListEmpty);
}
return;
}
string vrSdkWarningMessage = isVrSdkListEmpty ? EMPTY_VR_SDK_WARNING_MESSAGE : "";
string controllerMessage = "";
GvrPointerGraphicRaycaster graphicRaycaster =
messageCanvas.GetComponent<GvrPointerGraphicRaycaster>();
// This is an example of how to process the controller's state to display a status message.
switch (GvrController.State) {
case GvrConnectionState.Connected:
break;
case GvrConnectionState.Disconnected:
controllerMessage = CONTROLLER_DISCONNECTED_MESSAGE;
messageText.color = Color.white;
break;
case GvrConnectionState.Scanning:
controllerMessage = CONTROLLER_SCANNING_MESSAGE;
messageText.color = Color.cyan;
break;
case GvrConnectionState.Connecting:
controllerMessage = CONTROLLER_CONNECTING_MESSAGE;
messageText.color = Color.yellow;
break;
case GvrConnectionState.Error:
controllerMessage = "ERROR: " + GvrController.ErrorDetails;
messageText.color = Color.red;
break;
default:
// Shouldn't happen.
Debug.LogError("Invalid controller state: " + GvrController.State);
break;
}
messageText.text = string.Format("{0}{1}", vrSdkWarningMessage, controllerMessage);
if (graphicRaycaster != null) {
graphicRaycaster.enabled =
!isVrSdkListEmpty || GvrController.State != GvrConnectionState.Connected;
}
messageCanvas.SetActive(isVrSdkListEmpty ||
(GvrController.State != GvrConnectionState.Connected));
}
private void SetVRInputMechanism() {
SetGazeInputActive(!isDaydream);
SetControllerInputActive(isDaydream);
}
private void SetGazeInputActive(bool active) {
if (reticlePointer == null) {
return;
}
reticlePointer.SetActive(active);
// Update the pointer type only if this is currently activated.
if (!active) {
return;
}
GvrReticlePointer pointer =
reticlePointer.GetComponent<GvrReticlePointer>();
if (pointer != null) {
pointer.SetAsMainPointer();
}
}
private void SetControllerInputActive(bool active) {
if (controllerMain != null) {
controllerMain.SetActive(active);
}
if (controllerPointer == null) {
return;
}
controllerPointer.SetActive(active);
// Update the pointer type only if this is currently activated.
if (!active) {
return;
}
GvrLaserPointer pointer =
controllerPointer.GetComponentInChildren<GvrLaserPointer>(true);
if (pointer != null) {
pointer.SetAsMainPointer();
}
}
#endif // UNITY_HAS_GOOGLEVR && UNITY_ANDROID
}
| |
// 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.Data.ProviderBase;
using System.Diagnostics;
namespace System.Data.Common
{
internal sealed class DataRecordInternal : DbDataRecord
{
private SchemaInfo[] _schemaInfo;
private object[] _values;
private FieldNameLookup _fieldNameLookup;
// copy all runtime data information
internal DataRecordInternal(SchemaInfo[] schemaInfo, object[] values, FieldNameLookup fieldNameLookup)
{
Debug.Assert(null != schemaInfo, "invalid attempt to instantiate DataRecordInternal with null schema information");
Debug.Assert(null != values, "invalid attempt to instantiate DataRecordInternal with null value[]");
_schemaInfo = schemaInfo;
_values = values;
_fieldNameLookup = fieldNameLookup;
}
internal void SetSchemaInfo(SchemaInfo[] schemaInfo)
{
Debug.Assert(null == _schemaInfo, "invalid attempt to override DataRecordInternal schema information");
_schemaInfo = schemaInfo;
}
public override int FieldCount
{
get
{
return _schemaInfo.Length;
}
}
public override int GetValues(object[] values)
{
if (null == values)
{
throw ADP.ArgumentNull("values");
}
int copyLen = (values.Length < _schemaInfo.Length) ? values.Length : _schemaInfo.Length;
for (int i = 0; i < copyLen; i++)
{
values[i] = _values[i];
}
return copyLen;
}
public override string GetName(int i)
{
return _schemaInfo[i].name;
}
public override object GetValue(int i)
{
return _values[i];
}
public override string GetDataTypeName(int i)
{
return _schemaInfo[i].typeName;
}
public override Type GetFieldType(int i)
{
return _schemaInfo[i].type;
}
public override int GetOrdinal(string name)
{
return _fieldNameLookup.GetOrdinal(name);
}
public override object this[int i]
{
get
{
return GetValue(i);
}
}
public override object this[string name]
{
get
{
return GetValue(GetOrdinal(name));
}
}
public override bool GetBoolean(int i)
{
return ((bool)_values[i]);
}
public override byte GetByte(int i)
{
return ((byte)_values[i]);
}
public override long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIndex, int length)
{
int cbytes = 0;
int ndataIndex;
byte[] data = (byte[])_values[i];
cbytes = data.Length;
// since arrays can't handle 64 bit values and this interface doesn't
// allow chunked access to data, a dataIndex outside the rang of Int32
// is invalid
if (dataIndex > Int32.MaxValue)
{
throw ADP.InvalidSourceBufferIndex(cbytes, dataIndex, "dataIndex");
}
ndataIndex = (int)dataIndex;
// if no buffer is passed in, return the number of characters we have
if (null == buffer)
return cbytes;
try
{
if (ndataIndex < cbytes)
{
// help the user out in the case where there's less data than requested
if ((ndataIndex + length) > cbytes)
cbytes = cbytes - ndataIndex;
else
cbytes = length;
}
// until arrays are 64 bit, we have to do these casts
Buffer.BlockCopy(data, ndataIndex, buffer, bufferIndex, (int)cbytes);
}
catch (Exception e)
{
if (ADP.IsCatchableExceptionType(e))
{
cbytes = data.Length;
if (length < 0)
throw ADP.InvalidDataLength(length);
// if bad buffer index, throw
if (bufferIndex < 0 || bufferIndex >= buffer.Length)
throw ADP.InvalidDestinationBufferIndex(length, bufferIndex, "bufferIndex");
// if bad data index, throw
if (dataIndex < 0 || dataIndex >= cbytes)
throw ADP.InvalidSourceBufferIndex(length, dataIndex, "dataIndex");
// if there is not enough room in the buffer for data
if (cbytes + bufferIndex > buffer.Length)
throw ADP.InvalidBufferSizeOrIndex(cbytes, bufferIndex);
}
throw;
}
return cbytes;
}
public override char GetChar(int i)
{
return ((string)_values[i])[0];
}
public override long GetChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length)
{
var s = (string)_values[i];
int cchars = s.Length;
// since arrays can't handle 64 bit values and this interface doesn't
// allow chunked access to data, a dataIndex outside the rang of Int32
// is invalid
if (dataIndex > Int32.MaxValue)
{
throw ADP.InvalidSourceBufferIndex(cchars, dataIndex, "dataIndex");
}
int ndataIndex = (int)dataIndex;
// if no buffer is passed in, return the number of characters we have
if (null == buffer)
return cchars;
try
{
if (ndataIndex < cchars)
{
// help the user out in the case where there's less data than requested
if ((ndataIndex + length) > cchars)
cchars = cchars - ndataIndex;
else
cchars = length;
}
s.CopyTo(ndataIndex, buffer, bufferIndex, cchars);
}
catch (Exception e)
{
if (ADP.IsCatchableExceptionType(e))
{
cchars = s.Length;
if (length < 0)
throw ADP.InvalidDataLength(length);
// if bad buffer index, throw
if (bufferIndex < 0 || bufferIndex >= buffer.Length)
throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, "bufferIndex");
// if bad data index, throw
if (ndataIndex < 0 || ndataIndex >= cchars)
throw ADP.InvalidSourceBufferIndex(cchars, dataIndex, "dataIndex");
// if there is not enough room in the buffer for data
if (cchars + bufferIndex > buffer.Length)
throw ADP.InvalidBufferSizeOrIndex(cchars, bufferIndex);
}
throw;
}
return cchars;
}
public override Guid GetGuid(int i)
{
return ((Guid)_values[i]);
}
public override Int16 GetInt16(int i)
{
return ((Int16)_values[i]);
}
public override Int32 GetInt32(int i)
{
return ((Int32)_values[i]);
}
public override Int64 GetInt64(int i)
{
return ((Int64)_values[i]);
}
public override float GetFloat(int i)
{
return ((float)_values[i]);
}
public override double GetDouble(int i)
{
return ((double)_values[i]);
}
public override string GetString(int i)
{
return ((string)_values[i]);
}
public override Decimal GetDecimal(int i)
{
return ((Decimal)_values[i]);
}
public override DateTime GetDateTime(int i)
{
return ((DateTime)_values[i]);
}
public override bool IsDBNull(int i)
{
object o = _values[i];
return (null == o || o is DBNull);
}
//
// ICustomTypeDescriptor
//
}
// this doesn't change per record, only alloc once
internal struct SchemaInfo
{
public string name;
public string typeName;
public Type type;
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TestMapping.cs" company="OBeautifulCode">
// Copyright (c) OBeautifulCode 2018. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace OBeautifulCode.Serialization.Test
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using OBeautifulCode.Equality.Recipes;
using OBeautifulCode.Serialization.Bson;
#pragma warning disable SA1201 // Elements should appear in the correct order
[Serializable]
public class TestMapping
{
public string StringProperty { get; set; }
public TestEnumeration EnumProperty { get; set; }
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Need to test an array.")]
public TestEnumeration[] EnumArray { get; set; }
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Need to test an array.")]
public string[] NonEnumArray { get; set; }
public Guid GuidProperty { get; set; }
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "int", Justification = "Name is correct.")]
public int IntProperty { get; set; }
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public Dictionary<AnotherEnumeration, int> EnumIntMap { get; set; }
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public Dictionary<string, int> StringIntMap { get; set; }
public Tuple<int, int> IntIntTuple { get; set; }
public DateTime DateTimePropertyUtc { get; set; }
public DateTime DateTimePropertyLocal { get; set; }
public DateTime DateTimePropertyUnspecified { get; set; }
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Just need a type to test.")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public int[] IntArray { get; set; }
}
[Serializable]
public class TestWithId
{
public string Id { get; set; }
}
[Serializable]
public class TestWithInheritor
{
public string Id { get; set; }
public string Name { get; set; }
}
[Serializable]
public class TestWithInheritorExtraProperty : TestWithInheritor
{
public string AnotherName { get; set; }
}
[SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces", Justification = "Here for testing.")]
public interface ITestConfigureActionFromInterface
{
}
[SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces", Justification = "Here for testing.")]
public interface ITestConfigureActionFromAuto
{
}
[Serializable]
public class TestConfigureActionFromInterface : ITestConfigureActionFromInterface
{
}
[Serializable]
public class TestConfigureActionFromAuto : ITestConfigureActionFromAuto
{
}
[Serializable]
public abstract class TestConfigureActionBaseFromSub
{
}
[Serializable]
public abstract class TestConfigureActionBaseFromAuto
{
}
[Serializable]
public class TestConfigureActionInheritedSub : TestConfigureActionBaseFromSub
{
}
[Serializable]
public class TestConfigureActionInheritedAuto : TestConfigureActionBaseFromAuto
{
}
[Serializable]
public class TestConfigureActionSingle
{
}
[Serializable]
public class TestTracking
{
}
[Serializable]
public class TestWrappedFields
{
public DateTime? NullableDateTimeNull { get; set; }
public DateTime? NullableDateTimeWithValue { get; set; }
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public ICollection<DateTime> CollectionOfDateTime { get; set; }
public AnotherEnumeration? NullableEnumNull { get; set; }
public AnotherEnumeration? NullableEnumWithValue { get; set; }
public IEnumerable<AnotherEnumeration> EnumerableOfEnum { get; set; }
}
[Serializable]
public class TestCollectionFields
{
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public ReadOnlyCollection<DateTime> ReadOnlyCollectionDateTime { get; set; }
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public ICollection<string> ICollectionDateTime { get; set; }
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public IList<AnotherEnumeration> IListEnum { get; set; }
public IReadOnlyList<string> IReadOnlyListString { get; set; }
public IReadOnlyCollection<DateTime> IReadOnlyCollectionGuid { get; set; }
[SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Justification = "Just need a type to test.")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public List<DateTime> ListDateTime { get; set; }
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Just need a type to test.")]
public Collection<Guid> CollectionGuid { get; set; }
}
[Serializable]
public class TestWithReadOnlyCollectionOfBaseClass
{
public IReadOnlyCollection<TestBase> TestCollection { get; set; }
public TestImplementationOne RootOne { get; set; }
public TestImplementationTwo RootTwo { get; set; }
}
[Serializable]
public class TestWithReadOnlyCollectionOfBaseClassConfig : BsonSerializationConfigurationBase
{
protected override IReadOnlyCollection<TypeToRegisterForBson> TypesToRegisterForBson => new TypeToRegisterForBson[]
{
new TypeToRegisterForBson(typeof(TestBase), MemberTypesToInclude.None, RelatedTypesToInclude.AncestorsAndDescendants, null, null),
new TypeToRegisterForBson(typeof(TestWithReadOnlyCollectionOfBaseClass), MemberTypesToInclude.None, RelatedTypesToInclude.AncestorsAndDescendants, null, null),
};
}
[Serializable]
public abstract class TestBase
{
public string Message { get; set; }
public static bool operator ==(
TestBase item1,
TestBase item2)
{
if (ReferenceEquals(item1, item2))
{
return true;
}
if (ReferenceEquals(item1, null) || ReferenceEquals(item2, null))
{
return false;
}
var result = item1.Equals((object)item2);
return result;
}
public static bool operator !=(
TestBase item1,
TestBase item2)
=> !(item1 == item2);
public bool Equals(
TestBase other)
=> this == other;
/// <inheritdoc />
public abstract override bool Equals(
object obj);
/// <inheritdoc />
public abstract override int GetHashCode();
}
[Serializable]
public class TestImplementationOne : TestBase
{
public string One { get; set; }
public static bool operator ==(
TestImplementationOne item1,
TestImplementationOne item2)
{
if (ReferenceEquals(item1, item2))
{
return true;
}
if (ReferenceEquals(item1, null) || ReferenceEquals(item2, null))
{
return false;
}
var result =
(item1.Message == item2.Message) &&
(item1.One == item2.One);
return result;
}
public static bool operator !=(
TestImplementationOne item1,
TestImplementationOne item2)
=> !(item1 == item2);
public bool Equals(TestImplementationOne other) => this == other;
public override bool Equals(object obj) => this == (obj as TestImplementationOne);
public override int GetHashCode() =>
HashCodeHelper.Initialize()
.Hash(this.Message)
.Hash(this.One)
.Value;
}
[Serializable]
public class TestImplementationTwo : TestBase
{
public string Two { get; set; }
public static bool operator ==(
TestImplementationTwo item1,
TestImplementationTwo item2)
{
if (ReferenceEquals(item1, item2))
{
return true;
}
if (ReferenceEquals(item1, null) || ReferenceEquals(item2, null))
{
return false;
}
var result =
(item1.Message == item2.Message) &&
(item1.Two == item2.Two);
return result;
}
public static bool operator !=(
TestImplementationTwo item1,
TestImplementationTwo item2)
=> !(item1 == item2);
public bool Equals(TestImplementationTwo other) => this == other;
public override bool Equals(object obj) => this == (obj as TestImplementationTwo);
public override int GetHashCode() =>
HashCodeHelper.Initialize()
.Hash(this.Message)
.Hash(this.Two)
.Value;
}
[Serializable]
public struct TestStruct
{
}
[Serializable]
public enum TestEnumeration
{
/// <summary>
/// No value specified.
/// </summary>
None,
/// <summary>
/// First value.
/// </summary>
TestFirst,
/// <summary>
/// Second value.
/// </summary>
TestSecond,
/// <summary>
/// Third value.
/// </summary>
TestThird,
}
[Serializable]
public enum AnotherEnumeration
{
/// <summary>
/// No value specified.
/// </summary>
None,
/// <summary>
/// First value.
/// </summary>
AnotherFirst,
/// <summary>
/// Second value.
/// </summary>
AnotherSecond,
}
[Serializable]
public class Investigation
{
public IReadOnlyCollection<IDeduceWhoLetTheDogsOut> Investigators { get; set; }
}
public interface IDeduceWhoLetTheDogsOut
{
string WhoLetTheDogsOut();
}
[Serializable]
public class NamedInvestigator : IDeduceWhoLetTheDogsOut
{
public NamedInvestigator(string name, int yearsOfPractice)
{
this.Name = name;
this.YearsOfPractice = yearsOfPractice;
}
public string Name { get; private set; }
public int YearsOfPractice { get; private set; }
public string WhoLetTheDogsOut()
{
return $"I don't know. I, {this.Name} quit!";
}
}
[Serializable]
public class AnonymousInvestigator : IDeduceWhoLetTheDogsOut
{
public AnonymousInvestigator(int fee)
{
this.Fee = fee;
}
public int Fee { get; private set; }
public string WhoLetTheDogsOut()
{
return FormattableString.Invariant($"Dunno. You owe me ${this.Fee}");
}
}
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Onlys", Justification = "Spelling/name is correct.")]
[Serializable]
public abstract class ClassWithGetterOnlysBase
{
public AnotherEnumeration GetMyEnumOnlyBase { get; }
public string GetMyStringOnlyBase { get; }
public abstract AnotherEnumeration GetMyEnumFromBase { get; }
public abstract string GetMyStringFromBase { get; }
}
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Onlys", Justification = "Spelling/name is correct.")]
[Serializable]
public class ClassWithGetterOnlys : ClassWithGetterOnlysBase
{
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This is strictly for testing.")]
public AnotherEnumeration GetMyEnumFromThis => AnotherEnumeration.AnotherFirst;
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This is strictly for testing.")]
public string GetMyStringFromThis => "TurtleBusiness";
public override AnotherEnumeration GetMyEnumFromBase => AnotherEnumeration.AnotherSecond;
public override string GetMyStringFromBase => "MonkeyBusiness";
}
[Serializable]
public class ClassWithPrivateSetter
{
public ClassWithPrivateSetter(string privateValue)
{
this.PrivateValue = privateValue;
}
public string PrivateValue { get; private set; }
public static bool operator ==(
ClassWithPrivateSetter item1,
ClassWithPrivateSetter item2)
{
if (ReferenceEquals(item1, item2))
{
return true;
}
if (ReferenceEquals(item1, null) || ReferenceEquals(item2, null))
{
return false;
}
var result = item1.PrivateValue == item2.PrivateValue;
return result;
}
public static bool operator !=(
ClassWithPrivateSetter item1,
ClassWithPrivateSetter item2)
=> !(item1 == item2);
public bool Equals(ClassWithPrivateSetter other) => this == other;
public override bool Equals(object obj) => this == (obj as ClassWithPrivateSetter);
public override int GetHashCode() =>
HashCodeHelper.Initialize()
.Hash(this.PrivateValue)
.Value;
}
[Serializable]
public class VanillaClass : IEquatable<VanillaClass>
{
public string Something { get; set; }
public static bool operator ==(
VanillaClass item1,
VanillaClass item2)
{
if (ReferenceEquals(item1, item2))
{
return true;
}
if (ReferenceEquals(item1, null) || ReferenceEquals(item2, null))
{
return false;
}
var result = item1.Something == item2.Something;
return result;
}
public static bool operator !=(
VanillaClass item1,
VanillaClass item2)
=> !(item1 == item2);
public bool Equals(VanillaClass other) => this == other;
public override bool Equals(object obj) => this == (obj as VanillaClass);
public override int GetHashCode() =>
HashCodeHelper.Initialize()
.Hash(this.Something)
.Value;
}
[SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames", Justification = "Spelling/name is correct.")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags", Justification = "Spelling/name is correct.")]
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "Spelling/name is correct.")]
[Flags]
[Serializable]
public enum FlagsEnumeration
{
/// <summary>
/// None value.
/// </summary>
None,
/// <summary>
/// Second value.
/// </summary>
SecondValue,
/// <summary>
/// Third value.
/// </summary>
ThirdValue,
}
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags", Justification = "Spelling/name is correct.")]
[Serializable]
public class ClassWithFlagsEnums
{
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags", Justification = "Spelling/name is correct.")]
public FlagsEnumeration Flags { get; set; }
}
[Serializable]
public abstract class Field
{
protected Field(
string id)
{
this.Id = id;
}
public string Id { get; private set; }
public abstract FieldDataKind FieldDataKind { get; }
public string Title { get; set; }
}
[Serializable]
public abstract class DecimalField : Field
{
protected DecimalField(string id)
: base(id)
{
}
public int NumberOfDecimalPlaces { get; set; }
}
[Serializable]
public class CurrencyField : DecimalField
{
public CurrencyField(string id)
: base(id)
{
}
public override FieldDataKind FieldDataKind
{
get
{
var result = this.NumberOfDecimalPlaces == 0
? FieldDataKind.CurrencyWithoutDecimals
: FieldDataKind.CurrencyWithDecimals;
return result;
}
}
}
[Serializable]
public class NumberField : DecimalField
{
public NumberField(string id)
: base(id)
{
}
public override FieldDataKind FieldDataKind
{
get
{
var result = this.NumberOfDecimalPlaces == 0
? FieldDataKind.NumberWithoutDecimals
: FieldDataKind.NumberWithDecimals;
return result;
}
}
}
[Serializable]
public class YearField : NumberField
{
public YearField(string id)
: base(id)
{
}
public override FieldDataKind FieldDataKind => FieldDataKind.Year;
}
[Serializable]
public enum FieldDataKind
{
CurrencyWithDecimals,
CurrencyWithoutDecimals,
NumberWithDecimals,
NumberWithoutDecimals,
Text,
Date,
Year,
}
#pragma warning restore SA1201 // Elements should appear in the correct order
}
| |
//-----------------------------------------------------------------------------
// <copyright file="MailBnfHelper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------
namespace System.Net.Mime
{
using System;
using System.Text;
using System.Net.Mail;
using System.Globalization;
using System.Collections.Generic;
using System.Diagnostics;
internal static class MailBnfHelper
{
// characters allowed in atoms
internal static bool[] Atext = new bool[128];
// characters allowed in quoted strings (not including unicode)
internal static bool[] Qtext = new bool[128];
// characters allowed in domain literals
internal static bool[] Dtext = new bool[128];
// characters allowed in header names
internal static bool[] Ftext = new bool[128];
// characters allowed in tokens
internal static bool[] Ttext = new bool[128];
// characters allowed inside of comments
internal static bool[] Ctext = new bool[128];
internal static readonly int Ascii7bitMaxValue = 127;
internal static readonly char Quote = '\"';
internal static readonly char Space = ' ';
internal static readonly char Tab = '\t';
internal static readonly char CR = '\r';
internal static readonly char LF = '\n';
internal static readonly char StartComment = '(';
internal static readonly char EndComment = ')';
internal static readonly char Backslash = '\\';
internal static readonly char At = '@';
internal static readonly char EndAngleBracket = '>';
internal static readonly char StartAngleBracket = '<';
internal static readonly char StartSquareBracket = '[';
internal static readonly char EndSquareBracket = ']';
internal static readonly char Comma = ',';
internal static readonly char Dot = '.';
internal static readonly IList<char> Whitespace;
static MailBnfHelper()
{
// NOTE: all of the specs outlined here are defined in "MailBNF.cs" as to what they are
// and what they mean. They are defined in RFC 2822 in more detail. By default, every
// value in the array is false and only those values which are allowed in that particular set
// are then set to true. The numbers annotating each definition below are the range of ASCII
// values which are allowed in that definition.
// all allowed whitespace characters
Whitespace = new List<char>();
Whitespace.Add(Tab);
Whitespace.Add(Space);
Whitespace.Add(CR);
Whitespace.Add(LF);
// atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~"
for (int i = '0'; i <= '9'; i++) { Atext[i] = true; }
for (int i = 'A'; i <= 'Z'; i++) { Atext[i] = true; }
for (int i = 'a'; i <= 'z'; i++) { Atext[i] = true; }
Atext['!'] = true;
Atext['#'] = true;
Atext['$'] = true;
Atext['%'] = true;
Atext['&'] = true;
Atext['\''] = true;
Atext['*'] = true;
Atext['+'] = true;
Atext['-'] = true;
Atext['/'] = true;
Atext['='] = true;
Atext['?'] = true;
Atext['^'] = true;
Atext['_'] = true;
Atext['`'] = true;
Atext['{'] = true;
Atext['|'] = true;
Atext['}'] = true;
Atext['~'] = true;
// fqtext = %d1-9 / %d11 / %d12 / %d14-33 / %d35-91 / %d93-127
for (int i = 1; i <= 9; i++) { Qtext[i] = true; }
Qtext[11] = true;
Qtext[12] = true;
for (int i = 14; i <= 33; i++) { Qtext[i] = true; }
for (int i = 35; i <= 91; i++) { Qtext[i] = true; }
for (int i = 93; i <= 127; i++) { Qtext[i] = true; }
// fdtext = %d1-8 / %d11 / %d12 / %d14-31 / %d33-90 / %d94-127
for (int i = 1; i <= 8; i++) { Dtext[i] = true; }
Dtext[11] = true;
Dtext[12] = true;
for (int i = 14; i <= 31; i++) { Dtext[i] = true; }
for (int i = 33; i <= 90; i++) { Dtext[i] = true; }
for (int i = 94; i <= 127; i++) { Dtext[i] = true; }
// ftext = %d33-57 / %d59-126
for (int i = 33; i <= 57; i++) { Ftext[i] = true; }
for (int i = 59; i <= 126; i++) { Ftext[i] = true; }
// ttext = %d33-126 except '()<>@,;:\"/[]?='
for (int i = 33; i <= 126; i++) { Ttext[i] = true; }
Ttext['('] = false;
Ttext[')'] = false;
Ttext['<'] = false;
Ttext['>'] = false;
Ttext['@'] = false;
Ttext[','] = false;
Ttext[';'] = false;
Ttext[':'] = false;
Ttext['\\'] = false;
Ttext['"'] = false;
Ttext['/'] = false;
Ttext['['] = false;
Ttext[']'] = false;
Ttext['?'] = false;
Ttext['='] = false;
// ctext- %d1-8 / %d11 / %d12 / %d14-31 / %33-39 / %42-91 / %93-127
for (int i = 1; i <= 8; i++) { Ctext[i] = true; }
Ctext[11] = true;
Ctext[12] = true;
for (int i = 14; i <= 31; i++) { Ctext[i] = true; }
for (int i = 33; i <= 39; i++) { Ctext[i] = true; }
for (int i = 42; i <= 91; i++) { Ctext[i] = true; }
for (int i = 93; i <= 127; i++) { Ctext[i] = true; }
}
internal static bool SkipCFWS(string data, ref int offset)
{
int comments = 0;
for (;offset < data.Length ;offset++)
{
if (data[offset] > 127)
throw new FormatException(SR.GetString(SR.MailHeaderFieldInvalidCharacter, data[offset]));
else if (data[offset] == '\\' && comments > 0)
offset += 2;
else if (data[offset] == '(')
comments++;
else if (data[offset] == ')')
comments--;
else if (data[offset] != ' ' && data[offset] != '\t' && comments == 0)
return true;
if (comments < 0) {
throw new FormatException(SR.GetString(SR.MailHeaderFieldInvalidCharacter, data[offset]));
}
}
//returns false if end of string
return false;
}
internal static void ValidateHeaderName(string data){
int offset = 0;
for (; offset < data.Length; offset++)
{
if (data[offset] > Ftext.Length || !Ftext[data[offset]])
throw new FormatException(SR.GetString(SR.InvalidHeaderName));
}
if (offset == 0)
throw new FormatException(SR.GetString(SR.InvalidHeaderName));
}
internal static string ReadQuotedString(string data, ref int offset, StringBuilder builder){
return ReadQuotedString(data, ref offset, builder, false, false);
}
internal static string ReadQuotedString(string data, ref int offset, StringBuilder builder, bool doesntRequireQuotes, bool permitUnicodeInDisplayName)
{
// assume first char is the opening quote
if(!doesntRequireQuotes){
++offset;
}
int start = offset;
StringBuilder localBuilder = (builder != null ? builder : new StringBuilder());
for (; offset < data.Length; offset++)
{
if (data[offset] == '\\')
{
localBuilder.Append(data, start, offset - start);
start = ++offset;
}
else if (data[offset] == '"')
{
localBuilder.Append(data, start, offset - start);
offset++;
return (builder != null ? null : localBuilder.ToString());
}
else if (data[offset] == '=' &&
data.Length > offset + 3 &&
data[offset + 1] == '\r' &&
data[offset + 2] == '\n' &&
(data[offset + 3] == ' ' || data[offset + 3] == '\t'))
{
//it's a soft crlf so it's ok
offset += 3;
}
else if (permitUnicodeInDisplayName)
{
//if data contains unicode and unicode is permitted, then
//it is valid in a quoted string in a header.
if (data[offset] <= Ascii7bitMaxValue && !Qtext[data[offset]])
throw new FormatException(SR.GetString(SR.MailHeaderFieldInvalidCharacter, data[offset]));
}
//not permitting unicode, in which case unicode is a formatting error
else if (data[offset] > Ascii7bitMaxValue || !Qtext[data[offset]])
{
throw new FormatException(SR.GetString(SR.MailHeaderFieldInvalidCharacter, data[offset]));
}
}
if(doesntRequireQuotes){
localBuilder.Append(data, start, offset - start);
return (builder != null ? null : localBuilder.ToString());
}
throw new FormatException(SR.GetString(SR.MailHeaderFieldMalformedHeader));
}
internal static string ReadParameterAttribute(string data, ref int offset, StringBuilder builder)
{
if (!SkipCFWS(data, ref offset))
return null; //
return ReadToken(data, ref offset, null);
}
internal static string ReadToken(string data, ref int offset, StringBuilder builder)
{
int start = offset;
for (; offset < data.Length; offset++)
{
if (data[offset] > Ascii7bitMaxValue)
{
throw new FormatException(SR.GetString(SR.MailHeaderFieldInvalidCharacter, data[offset]));
}
else if (!Ttext[data[offset]])
{
break;
}
}
if (start == offset) {
throw new FormatException(SR.GetString(SR.MailHeaderFieldInvalidCharacter, data[offset]));
}
return data.Substring(start, offset - start);
}
static string[] s_months = new string[] { null, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
internal static string GetDateTimeString(DateTime value, StringBuilder builder)
{
StringBuilder localBuilder = (builder != null ? builder : new StringBuilder());
localBuilder.Append(value.Day);
localBuilder.Append(' ');
localBuilder.Append(s_months[value.Month]);
localBuilder.Append(' ');
localBuilder.Append(value.Year);
localBuilder.Append(' ');
if (value.Hour <= 9) {
localBuilder.Append('0');
}
localBuilder.Append(value.Hour);
localBuilder.Append(':');
if (value.Minute <= 9) {
localBuilder.Append('0');
}
localBuilder.Append(value.Minute);
localBuilder.Append(':');
if (value.Second <= 9) {
localBuilder.Append('0');
}
localBuilder.Append(value.Second);
string offset = TimeZone.CurrentTimeZone.GetUtcOffset(value).ToString();
if (offset[0] != '-') {
localBuilder.Append(" +");
}
else {
localBuilder.Append(" ");
}
string[] offsetFields = offset.Split(':');
localBuilder.Append(offsetFields[0]);
localBuilder.Append(offsetFields[1]);
return (builder != null ? null : localBuilder.ToString());
}
internal static void GetTokenOrQuotedString(string data, StringBuilder builder, bool allowUnicode)
{
int offset = 0, start = 0;
for (; offset < data.Length; offset++)
{
if (CheckForUnicode(data[offset], allowUnicode))
{
continue;
}
if (!Ttext[data[offset]] || data[offset] == ' ')
{
builder.Append('"');
for (; offset < data.Length; offset++)
{
if (CheckForUnicode(data[offset], allowUnicode))
{
continue;
}
else if (IsFWSAt(data, offset)) // Allow FWS == "\r\n "
{
// No-op, skip these three chars
offset++;
offset++;
}
else if (!Qtext[data[offset]])
{
builder.Append(data, start, offset - start);
builder.Append('\\');
start = offset;
}
}
builder.Append(data, start, offset - start);
builder.Append('"');
return;
}
}
//always a quoted string if it was empty.
if(data.Length == 0){
builder.Append("\"\"");
}
// Token, no quotes needed
builder.Append(data);
}
private static bool CheckForUnicode(char ch, bool allowUnicode)
{
if (ch < Ascii7bitMaxValue)
{
return false;
}
if (!allowUnicode)
{
throw new FormatException(SR.GetString(SR.MailHeaderFieldInvalidCharacter, ch));
}
return true;
}
internal static bool HasCROrLF(string data){
for (int i = 0; i < data.Length; i++) {
if (data[i] == '\r' || data[i] == '\n'){
return true;
}
}
return false;
}
// Is there a FWS ("\r\n " or "\r\n\t") starting at the given index?
internal static bool IsFWSAt(string data, int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < data.Length);
return (data[index] == MailBnfHelper.CR
&& index + 2 < data.Length
&& data[index + 1] == MailBnfHelper.LF
&& (data[index + 2] == MailBnfHelper.Space
|| data[index + 2] == MailBnfHelper.Tab));
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Events;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using IdentityServer4.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;
namespace IdentityServer4.Quickstart.UI
{
/// <summary>
/// This controller processes the consent UI
/// </summary>
[SecurityHeaders]
[Authorize]
public class ConsentController : Controller
{
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly IResourceStore _resourceStore;
private readonly IEventService _events;
private readonly ILogger<ConsentController> _logger;
public ConsentController(
IIdentityServerInteractionService interaction,
IClientStore clientStore,
IResourceStore resourceStore,
IEventService events,
ILogger<ConsentController> logger)
{
_interaction = interaction;
_clientStore = clientStore;
_resourceStore = resourceStore;
_events = events;
_logger = logger;
}
/// <summary>
/// Shows the consent screen
/// </summary>
/// <param name="returnUrl"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> Index(string returnUrl)
{
var vm = await BuildViewModelAsync(returnUrl);
if (vm != null)
{
return View("Index", vm);
}
return View("Error");
}
/// <summary>
/// Handles the consent screen postback
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(ConsentInputModel model)
{
var result = await ProcessConsent(model);
if (result.IsRedirect)
{
if (await _clientStore.IsPkceClientAsync(result.ClientId))
{
// if the client is PKCE then we assume it's native, so this change in how to
// return the response is for better UX for the end user.
return View("Redirect", new RedirectViewModel { RedirectUrl = result.RedirectUri });
}
return Redirect(result.RedirectUri);
}
if (result.HasValidationError)
{
ModelState.AddModelError("", result.ValidationError);
}
if (result.ShowView)
{
return View("Index", result.ViewModel);
}
return View("Error");
}
/*****************************************/
/* helper APIs for the ConsentController */
/*****************************************/
private async Task<ProcessConsentResult> ProcessConsent(ConsentInputModel model)
{
var result = new ProcessConsentResult();
// validate return url is still valid
var request = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
if (request == null) return result;
ConsentResponse grantedConsent = null;
// user clicked 'no' - send back the standard 'access_denied' response
if (model.Button == "no")
{
grantedConsent = ConsentResponse.Denied;
// emit event
await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), result.ClientId, request.ScopesRequested));
}
// user clicked 'yes' - validate the data
else if (model.Button == "yes" && model != null)
{
// if the user consented to some scope, build the response model
if (model.ScopesConsented != null && model.ScopesConsented.Any())
{
var scopes = model.ScopesConsented;
if (ConsentOptions.EnableOfflineAccess == false)
{
scopes = scopes.Where(x => x != IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess);
}
grantedConsent = new ConsentResponse
{
RememberConsent = model.RememberConsent,
ScopesConsented = scopes.ToArray()
};
// emit event
await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested, grantedConsent.ScopesConsented, grantedConsent.RememberConsent));
}
else
{
result.ValidationError = ConsentOptions.MustChooseOneErrorMessage;
}
}
else
{
result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage;
}
if (grantedConsent != null)
{
// communicate outcome of consent back to identityserver
await _interaction.GrantConsentAsync(request, grantedConsent);
// indicate that's it ok to redirect back to authorization endpoint
result.RedirectUri = model.ReturnUrl;
result.ClientId = request.ClientId;
}
else
{
// we need to redisplay the consent UI
result.ViewModel = await BuildViewModelAsync(model.ReturnUrl, model);
}
return result;
}
private async Task<ConsentViewModel> BuildViewModelAsync(string returnUrl, ConsentInputModel model = null)
{
var request = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (request != null)
{
var client = await _clientStore.FindEnabledClientByIdAsync(request.ClientId);
if (client != null)
{
var resources = await _resourceStore.FindEnabledResourcesByScopeAsync(request.ScopesRequested);
if (resources != null && (resources.IdentityResources.Any() || resources.ApiResources.Any()))
{
return CreateConsentViewModel(model, returnUrl, request, client, resources);
}
else
{
_logger.LogError("No scopes matching: {0}", request.ScopesRequested.Aggregate((x, y) => x + ", " + y));
}
}
else
{
_logger.LogError("Invalid client id: {0}", request.ClientId);
}
}
else
{
_logger.LogError("No consent request matching request: {0}", returnUrl);
}
return null;
}
private ConsentViewModel CreateConsentViewModel(
ConsentInputModel model, string returnUrl,
AuthorizationRequest request,
Client client, Resources resources)
{
var vm = new ConsentViewModel
{
RememberConsent = model?.RememberConsent ?? true,
ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(),
ReturnUrl = returnUrl,
ClientName = client.ClientName ?? client.ClientId,
ClientUrl = client.ClientUri,
ClientLogoUrl = client.LogoUri,
AllowRememberConsent = client.AllowRememberConsent
};
vm.IdentityScopes = resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
vm.ResourceScopes = resources.ApiResources.SelectMany(x => x.Scopes).Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
if (ConsentOptions.EnableOfflineAccess && resources.OfflineAccess)
{
vm.ResourceScopes = vm.ResourceScopes.Union(new ScopeViewModel[] {
GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null)
});
}
return vm;
}
private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check)
{
return new ScopeViewModel
{
Name = identity.Name,
DisplayName = identity.DisplayName,
Description = identity.Description,
Emphasize = identity.Emphasize,
Required = identity.Required,
Checked = check || identity.Required
};
}
public ScopeViewModel CreateScopeViewModel(Scope scope, bool check)
{
return new ScopeViewModel
{
Name = scope.Name,
DisplayName = scope.DisplayName,
Description = scope.Description,
Emphasize = scope.Emphasize,
Required = scope.Required,
Checked = check || scope.Required
};
}
private ScopeViewModel GetOfflineAccessScope(bool check)
{
return new ScopeViewModel
{
Name = IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess,
DisplayName = ConsentOptions.OfflineAccessDisplayName,
Description = ConsentOptions.OfflineAccessDescription,
Emphasize = true,
Checked = check
};
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagve = Google.Ads.GoogleAds.V9.Enums;
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCampaignBudgetServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetCampaignBudgetRequestObject()
{
moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient> mockGrpcClient = new moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient>(moq::MockBehavior.Strict);
GetCampaignBudgetRequest request = new GetCampaignBudgetRequest
{
ResourceNameAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
};
gagvr::CampaignBudget expectedResponse = new gagvr::CampaignBudget
{
ResourceNameAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
Status = gagve::BudgetStatusEnum.Types.BudgetStatus.Enabled,
DeliveryMethod = gagve::BudgetDeliveryMethodEnum.Types.BudgetDeliveryMethod.Standard,
Period = gagve::BudgetPeriodEnum.Types.BudgetPeriod.Unspecified,
Type = gagve::BudgetTypeEnum.Types.BudgetType.Unspecified,
Id = -6774108720365892680L,
CampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
AmountMicros = -5708430407335026218L,
TotalAmountMicros = -8735537612243809071L,
ExplicitlyShared = true,
ReferenceCount = -8440758895662409664L,
HasRecommendedBudget = false,
RecommendedBudgetAmountMicros = -5174015606152417050L,
RecommendedBudgetEstimatedChangeWeeklyClicks = 5003538975719544582L,
RecommendedBudgetEstimatedChangeWeeklyCostMicros = 6886876539534848907L,
RecommendedBudgetEstimatedChangeWeeklyInteractions = -4068174795511900246L,
RecommendedBudgetEstimatedChangeWeeklyViews = -4598204636615893095L,
};
mockGrpcClient.Setup(x => x.GetCampaignBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignBudgetServiceClient client = new CampaignBudgetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignBudget response = client.GetCampaignBudget(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignBudgetRequestObjectAsync()
{
moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient> mockGrpcClient = new moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient>(moq::MockBehavior.Strict);
GetCampaignBudgetRequest request = new GetCampaignBudgetRequest
{
ResourceNameAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
};
gagvr::CampaignBudget expectedResponse = new gagvr::CampaignBudget
{
ResourceNameAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
Status = gagve::BudgetStatusEnum.Types.BudgetStatus.Enabled,
DeliveryMethod = gagve::BudgetDeliveryMethodEnum.Types.BudgetDeliveryMethod.Standard,
Period = gagve::BudgetPeriodEnum.Types.BudgetPeriod.Unspecified,
Type = gagve::BudgetTypeEnum.Types.BudgetType.Unspecified,
Id = -6774108720365892680L,
CampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
AmountMicros = -5708430407335026218L,
TotalAmountMicros = -8735537612243809071L,
ExplicitlyShared = true,
ReferenceCount = -8440758895662409664L,
HasRecommendedBudget = false,
RecommendedBudgetAmountMicros = -5174015606152417050L,
RecommendedBudgetEstimatedChangeWeeklyClicks = 5003538975719544582L,
RecommendedBudgetEstimatedChangeWeeklyCostMicros = 6886876539534848907L,
RecommendedBudgetEstimatedChangeWeeklyInteractions = -4068174795511900246L,
RecommendedBudgetEstimatedChangeWeeklyViews = -4598204636615893095L,
};
mockGrpcClient.Setup(x => x.GetCampaignBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignBudget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignBudgetServiceClient client = new CampaignBudgetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignBudget responseCallSettings = await client.GetCampaignBudgetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignBudget responseCancellationToken = await client.GetCampaignBudgetAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCampaignBudget()
{
moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient> mockGrpcClient = new moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient>(moq::MockBehavior.Strict);
GetCampaignBudgetRequest request = new GetCampaignBudgetRequest
{
ResourceNameAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
};
gagvr::CampaignBudget expectedResponse = new gagvr::CampaignBudget
{
ResourceNameAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
Status = gagve::BudgetStatusEnum.Types.BudgetStatus.Enabled,
DeliveryMethod = gagve::BudgetDeliveryMethodEnum.Types.BudgetDeliveryMethod.Standard,
Period = gagve::BudgetPeriodEnum.Types.BudgetPeriod.Unspecified,
Type = gagve::BudgetTypeEnum.Types.BudgetType.Unspecified,
Id = -6774108720365892680L,
CampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
AmountMicros = -5708430407335026218L,
TotalAmountMicros = -8735537612243809071L,
ExplicitlyShared = true,
ReferenceCount = -8440758895662409664L,
HasRecommendedBudget = false,
RecommendedBudgetAmountMicros = -5174015606152417050L,
RecommendedBudgetEstimatedChangeWeeklyClicks = 5003538975719544582L,
RecommendedBudgetEstimatedChangeWeeklyCostMicros = 6886876539534848907L,
RecommendedBudgetEstimatedChangeWeeklyInteractions = -4068174795511900246L,
RecommendedBudgetEstimatedChangeWeeklyViews = -4598204636615893095L,
};
mockGrpcClient.Setup(x => x.GetCampaignBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignBudgetServiceClient client = new CampaignBudgetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignBudget response = client.GetCampaignBudget(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignBudgetAsync()
{
moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient> mockGrpcClient = new moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient>(moq::MockBehavior.Strict);
GetCampaignBudgetRequest request = new GetCampaignBudgetRequest
{
ResourceNameAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
};
gagvr::CampaignBudget expectedResponse = new gagvr::CampaignBudget
{
ResourceNameAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
Status = gagve::BudgetStatusEnum.Types.BudgetStatus.Enabled,
DeliveryMethod = gagve::BudgetDeliveryMethodEnum.Types.BudgetDeliveryMethod.Standard,
Period = gagve::BudgetPeriodEnum.Types.BudgetPeriod.Unspecified,
Type = gagve::BudgetTypeEnum.Types.BudgetType.Unspecified,
Id = -6774108720365892680L,
CampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
AmountMicros = -5708430407335026218L,
TotalAmountMicros = -8735537612243809071L,
ExplicitlyShared = true,
ReferenceCount = -8440758895662409664L,
HasRecommendedBudget = false,
RecommendedBudgetAmountMicros = -5174015606152417050L,
RecommendedBudgetEstimatedChangeWeeklyClicks = 5003538975719544582L,
RecommendedBudgetEstimatedChangeWeeklyCostMicros = 6886876539534848907L,
RecommendedBudgetEstimatedChangeWeeklyInteractions = -4068174795511900246L,
RecommendedBudgetEstimatedChangeWeeklyViews = -4598204636615893095L,
};
mockGrpcClient.Setup(x => x.GetCampaignBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignBudget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignBudgetServiceClient client = new CampaignBudgetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignBudget responseCallSettings = await client.GetCampaignBudgetAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignBudget responseCancellationToken = await client.GetCampaignBudgetAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCampaignBudgetResourceNames()
{
moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient> mockGrpcClient = new moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient>(moq::MockBehavior.Strict);
GetCampaignBudgetRequest request = new GetCampaignBudgetRequest
{
ResourceNameAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
};
gagvr::CampaignBudget expectedResponse = new gagvr::CampaignBudget
{
ResourceNameAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
Status = gagve::BudgetStatusEnum.Types.BudgetStatus.Enabled,
DeliveryMethod = gagve::BudgetDeliveryMethodEnum.Types.BudgetDeliveryMethod.Standard,
Period = gagve::BudgetPeriodEnum.Types.BudgetPeriod.Unspecified,
Type = gagve::BudgetTypeEnum.Types.BudgetType.Unspecified,
Id = -6774108720365892680L,
CampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
AmountMicros = -5708430407335026218L,
TotalAmountMicros = -8735537612243809071L,
ExplicitlyShared = true,
ReferenceCount = -8440758895662409664L,
HasRecommendedBudget = false,
RecommendedBudgetAmountMicros = -5174015606152417050L,
RecommendedBudgetEstimatedChangeWeeklyClicks = 5003538975719544582L,
RecommendedBudgetEstimatedChangeWeeklyCostMicros = 6886876539534848907L,
RecommendedBudgetEstimatedChangeWeeklyInteractions = -4068174795511900246L,
RecommendedBudgetEstimatedChangeWeeklyViews = -4598204636615893095L,
};
mockGrpcClient.Setup(x => x.GetCampaignBudget(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignBudgetServiceClient client = new CampaignBudgetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignBudget response = client.GetCampaignBudget(request.ResourceNameAsCampaignBudgetName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignBudgetResourceNamesAsync()
{
moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient> mockGrpcClient = new moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient>(moq::MockBehavior.Strict);
GetCampaignBudgetRequest request = new GetCampaignBudgetRequest
{
ResourceNameAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
};
gagvr::CampaignBudget expectedResponse = new gagvr::CampaignBudget
{
ResourceNameAsCampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
Status = gagve::BudgetStatusEnum.Types.BudgetStatus.Enabled,
DeliveryMethod = gagve::BudgetDeliveryMethodEnum.Types.BudgetDeliveryMethod.Standard,
Period = gagve::BudgetPeriodEnum.Types.BudgetPeriod.Unspecified,
Type = gagve::BudgetTypeEnum.Types.BudgetType.Unspecified,
Id = -6774108720365892680L,
CampaignBudgetName = gagvr::CampaignBudgetName.FromCustomerCampaignBudget("[CUSTOMER_ID]", "[CAMPAIGN_BUDGET_ID]"),
AmountMicros = -5708430407335026218L,
TotalAmountMicros = -8735537612243809071L,
ExplicitlyShared = true,
ReferenceCount = -8440758895662409664L,
HasRecommendedBudget = false,
RecommendedBudgetAmountMicros = -5174015606152417050L,
RecommendedBudgetEstimatedChangeWeeklyClicks = 5003538975719544582L,
RecommendedBudgetEstimatedChangeWeeklyCostMicros = 6886876539534848907L,
RecommendedBudgetEstimatedChangeWeeklyInteractions = -4068174795511900246L,
RecommendedBudgetEstimatedChangeWeeklyViews = -4598204636615893095L,
};
mockGrpcClient.Setup(x => x.GetCampaignBudgetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignBudget>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignBudgetServiceClient client = new CampaignBudgetServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignBudget responseCallSettings = await client.GetCampaignBudgetAsync(request.ResourceNameAsCampaignBudgetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignBudget responseCancellationToken = await client.GetCampaignBudgetAsync(request.ResourceNameAsCampaignBudgetName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCampaignBudgetsRequestObject()
{
moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient> mockGrpcClient = new moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient>(moq::MockBehavior.Strict);
MutateCampaignBudgetsRequest request = new MutateCampaignBudgetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignBudgetOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateCampaignBudgetsResponse expectedResponse = new MutateCampaignBudgetsResponse
{
Results =
{
new MutateCampaignBudgetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignBudgets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignBudgetServiceClient client = new CampaignBudgetServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignBudgetsResponse response = client.MutateCampaignBudgets(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCampaignBudgetsRequestObjectAsync()
{
moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient> mockGrpcClient = new moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient>(moq::MockBehavior.Strict);
MutateCampaignBudgetsRequest request = new MutateCampaignBudgetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignBudgetOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateCampaignBudgetsResponse expectedResponse = new MutateCampaignBudgetsResponse
{
Results =
{
new MutateCampaignBudgetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignBudgetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignBudgetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignBudgetServiceClient client = new CampaignBudgetServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignBudgetsResponse responseCallSettings = await client.MutateCampaignBudgetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCampaignBudgetsResponse responseCancellationToken = await client.MutateCampaignBudgetsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCampaignBudgets()
{
moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient> mockGrpcClient = new moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient>(moq::MockBehavior.Strict);
MutateCampaignBudgetsRequest request = new MutateCampaignBudgetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignBudgetOperation(),
},
};
MutateCampaignBudgetsResponse expectedResponse = new MutateCampaignBudgetsResponse
{
Results =
{
new MutateCampaignBudgetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignBudgets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignBudgetServiceClient client = new CampaignBudgetServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignBudgetsResponse response = client.MutateCampaignBudgets(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCampaignBudgetsAsync()
{
moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient> mockGrpcClient = new moq::Mock<CampaignBudgetService.CampaignBudgetServiceClient>(moq::MockBehavior.Strict);
MutateCampaignBudgetsRequest request = new MutateCampaignBudgetsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignBudgetOperation(),
},
};
MutateCampaignBudgetsResponse expectedResponse = new MutateCampaignBudgetsResponse
{
Results =
{
new MutateCampaignBudgetResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignBudgetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignBudgetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignBudgetServiceClient client = new CampaignBudgetServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignBudgetsResponse responseCallSettings = await client.MutateCampaignBudgetsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCampaignBudgetsResponse responseCancellationToken = await client.MutateCampaignBudgetsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// 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.11.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsHead
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Linq;
using Microsoft.Rest.Azure;
/// <summary>
/// HttpSuccessOperations operations.
/// </summary>
internal partial class HttpSuccessOperations : IServiceOperations<AutoRestHeadTestService>, IHttpSuccessOperations
{
/// <summary>
/// Initializes a new instance of the HttpSuccessOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal HttpSuccessOperations(AutoRestHeadTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHeadTestService
/// </summary>
public AutoRestHeadTestService Client { get; private set; }
/// <summary>
/// Return 204 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<bool?>> Head204WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Head204", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/204").ToString();
List<string> queryParameters = new List<string>();
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("HEAD");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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);
}
}
// 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();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "NoContent") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "NotFound")))
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex = new CloudException(errorBody.Message);
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse<bool?>();
result.Request = httpRequest;
result.Response = httpResponse;
result.Body = (statusCode == HttpStatusCode.NoContent);
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>
/// Return 404 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<bool?>> Head404WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Head404", tracingParameters);
}
// Construct URL
var url = new Uri(this.Client.BaseUri, "/http/success/404").ToString();
List<string> queryParameters = new List<string>();
if (queryParameters.Count > 0)
{
url += "?" + string.Join("&", queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("HEAD");
httpRequest.RequestUri = new Uri(url);
// Set Headers
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);
}
}
// 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();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "NoContent") || statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "NotFound")))
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex = new CloudException(errorBody.Message);
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new AzureOperationResponse<bool?>();
result.Request = httpRequest;
result.Response = httpResponse;
result.Body = (statusCode == HttpStatusCode.NoContent);
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;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Security.Permissions {
using System.Security;
using System;
using SecurityElement = System.Security.SecurityElement;
using System.Security.Util;
using System.IO;
using System.Globalization;
using System.Diagnostics.Contracts;
[Serializable]
[Flags]
[System.Runtime.InteropServices.ComVisible(true)]
public enum EnvironmentPermissionAccess
{
NoAccess = 0x00,
Read = 0x01,
Write = 0x02,
AllAccess = 0x03,
}
[Serializable]
internal class EnvironmentStringExpressionSet : StringExpressionSet
{
public EnvironmentStringExpressionSet()
: base( true, null, false )
{
}
public EnvironmentStringExpressionSet( String str )
: base( true, str, false )
{
}
protected override StringExpressionSet CreateNewEmpty()
{
return new EnvironmentStringExpressionSet();
}
protected override bool StringSubsetString( String left, String right, bool ignoreCase )
{
return (ignoreCase?(String.Compare( left, right, StringComparison.OrdinalIgnoreCase) == 0):
(String.Compare( left, right, StringComparison.Ordinal) == 0));
}
protected override String ProcessWholeString( String str )
{
return str;
}
protected override String ProcessSingleString( String str )
{
return str;
}
public override string ToString()
{
// SafeCritical: we're not storing path information in the strings, so exposing them out is fine ...
// they're just the same strings that came in to the .ctor.
return base.UnsafeToString();
}
}
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
sealed public class EnvironmentPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
{
private StringExpressionSet m_read;
private StringExpressionSet m_write;
private bool m_unrestricted;
public EnvironmentPermission(PermissionState state)
{
if (state == PermissionState.Unrestricted)
m_unrestricted = true;
else if (state == PermissionState.None)
m_unrestricted = false;
else
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
}
public EnvironmentPermission( EnvironmentPermissionAccess flag, String pathList )
{
SetPathList( flag, pathList );
}
public void SetPathList( EnvironmentPermissionAccess flag, String pathList )
{
VerifyFlag( flag );
m_unrestricted = false;
if ((flag & EnvironmentPermissionAccess.Read) != 0)
m_read = null;
if ((flag & EnvironmentPermissionAccess.Write) != 0)
m_write = null;
AddPathList( flag, pathList );
}
public void AddPathList( EnvironmentPermissionAccess flag, String pathList )
{
VerifyFlag( flag );
if (FlagIsSet( flag, EnvironmentPermissionAccess.Read ))
{
if (m_read == null)
m_read = new EnvironmentStringExpressionSet();
m_read.AddExpressions( pathList );
}
if (FlagIsSet( flag, EnvironmentPermissionAccess.Write ))
{
if (m_write == null)
m_write = new EnvironmentStringExpressionSet();
m_write.AddExpressions( pathList );
}
}
public String GetPathList( EnvironmentPermissionAccess flag )
{
VerifyFlag( flag );
ExclusiveFlag( flag );
if (FlagIsSet( flag, EnvironmentPermissionAccess.Read ))
{
if (m_read == null)
{
return "";
}
return m_read.ToString();
}
if (FlagIsSet( flag, EnvironmentPermissionAccess.Write ))
{
if (m_write == null)
{
return "";
}
return m_write.ToString();
}
/* not reached */
return "";
}
private void VerifyFlag( EnvironmentPermissionAccess flag )
{
if ((flag & ~EnvironmentPermissionAccess.AllAccess) != 0)
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)flag));
Contract.EndContractBlock();
}
private void ExclusiveFlag( EnvironmentPermissionAccess flag )
{
if (flag == EnvironmentPermissionAccess.NoAccess)
{
throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") );
}
if (((int)flag & ((int)flag-1)) != 0)
{
throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") );
}
Contract.EndContractBlock();
}
private bool FlagIsSet( EnvironmentPermissionAccess flag, EnvironmentPermissionAccess question )
{
return (flag & question) != 0;
}
private bool IsEmpty()
{
return (!m_unrestricted &&
(this.m_read == null || this.m_read.IsEmpty()) &&
(this.m_write == null || this.m_write.IsEmpty()));
}
//------------------------------------------------------
//
// CODEACCESSPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
public bool IsUnrestricted()
{
return m_unrestricted;
}
//------------------------------------------------------
//
// IPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
public override bool IsSubsetOf(IPermission target)
{
if (target == null)
{
return this.IsEmpty();
}
try
{
EnvironmentPermission operand = (EnvironmentPermission)target;
if (operand.IsUnrestricted())
return true;
else if (this.IsUnrestricted())
return false;
else
return ((this.m_read == null || this.m_read.IsSubsetOf( operand.m_read )) &&
(this.m_write == null || this.m_write.IsSubsetOf( operand.m_write )));
}
catch (InvalidCastException)
{
throw new
ArgumentException(
Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
);
}
}
public override IPermission Intersect(IPermission target)
{
if (target == null)
{
return null;
}
else if (!VerifyType(target))
{
throw new
ArgumentException(
Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
);
}
else if (this.IsUnrestricted())
{
return target.Copy();
}
EnvironmentPermission operand = (EnvironmentPermission)target;
if (operand.IsUnrestricted())
{
return this.Copy();
}
StringExpressionSet intersectRead = this.m_read == null ? null : this.m_read.Intersect( operand.m_read );
StringExpressionSet intersectWrite = this.m_write == null ? null : this.m_write.Intersect( operand.m_write );
if ((intersectRead == null || intersectRead.IsEmpty()) &&
(intersectWrite == null || intersectWrite.IsEmpty()))
{
return null;
}
EnvironmentPermission intersectPermission = new EnvironmentPermission(PermissionState.None);
intersectPermission.m_unrestricted = false;
intersectPermission.m_read = intersectRead;
intersectPermission.m_write = intersectWrite;
return intersectPermission;
}
public override IPermission Union(IPermission other)
{
if (other == null)
{
return this.Copy();
}
else if (!VerifyType(other))
{
throw new
ArgumentException(
Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
);
}
EnvironmentPermission operand = (EnvironmentPermission)other;
if (this.IsUnrestricted() || operand.IsUnrestricted())
{
return new EnvironmentPermission( PermissionState.Unrestricted );
}
StringExpressionSet unionRead = this.m_read == null ? operand.m_read : this.m_read.Union( operand.m_read );
StringExpressionSet unionWrite = this.m_write == null ? operand.m_write : this.m_write.Union( operand.m_write );
if ((unionRead == null || unionRead.IsEmpty()) &&
(unionWrite == null || unionWrite.IsEmpty()))
{
return null;
}
EnvironmentPermission unionPermission = new EnvironmentPermission(PermissionState.None);
unionPermission.m_unrestricted = false;
unionPermission.m_read = unionRead;
unionPermission.m_write = unionWrite;
return unionPermission;
}
public override IPermission Copy()
{
EnvironmentPermission copy = new EnvironmentPermission(PermissionState.None);
if (this.m_unrestricted)
{
copy.m_unrestricted = true;
}
else
{
copy.m_unrestricted = false;
if (this.m_read != null)
{
copy.m_read = this.m_read.Copy();
}
if (this.m_write != null)
{
copy.m_write = this.m_write.Copy();
}
}
return copy;
}
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
{
return EnvironmentPermission.GetTokenIndex();
}
internal static int GetTokenIndex()
{
return BuiltInPermissionIndex.EnvironmentPermissionIndex;
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
namespace YAF.Lucene.Net.Index
{
/*
* 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 AttributeSource = YAF.Lucene.Net.Util.AttributeSource;
using IBits = YAF.Lucene.Net.Util.IBits;
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
/// <summary>
/// Abstract class for enumerating a subset of all terms.
/// <para/>
/// Term enumerations are always ordered by
/// <see cref="Comparer"/>. Each term in the enumeration is
/// greater than all that precede it.
/// <para/><c>Please note:</c> Consumers of this enumeration cannot
/// call <c>Seek()</c>, it is forward only; it throws
/// <see cref="System.NotSupportedException"/> when a seeking method
/// is called.
/// </summary>
public abstract class FilteredTermsEnum : TermsEnum
{
private BytesRef initialSeekTerm = null;
private bool doSeek;
private BytesRef actualTerm = null;
private readonly TermsEnum tenum;
/// <summary>
/// Return value, if term should be accepted or the iteration should
/// <see cref="END"/>. The <c>*_SEEK</c> values denote, that after handling the current term
/// the enum should call <see cref="NextSeekTerm(BytesRef)"/> and step forward. </summary>
/// <seealso cref="Accept(BytesRef)"/>
protected internal enum AcceptStatus
{
/// <summary>
/// Accept the term and position the enum at the next term. </summary>
YES,
/// <summary>
/// Accept the term and advance (<see cref="FilteredTermsEnum.NextSeekTerm(BytesRef)"/>)
/// to the next term.
/// </summary>
YES_AND_SEEK,
/// <summary>
/// Reject the term and position the enum at the next term. </summary>
NO,
/// <summary>
/// Reject the term and advance (<see cref="FilteredTermsEnum.NextSeekTerm(BytesRef)"/>)
/// to the next term.
/// </summary>
NO_AND_SEEK,
/// <summary>
/// Reject the term and stop enumerating. </summary>
END
}
/// <summary>
/// Return if term is accepted, not accepted or the iteration should ended
/// (and possibly seek).
/// </summary>
protected abstract AcceptStatus Accept(BytesRef term);
/// <summary>
/// Creates a filtered <see cref="TermsEnum"/> on a terms enum. </summary>
/// <param name="tenum"> the terms enumeration to filter. </param>
public FilteredTermsEnum(TermsEnum tenum)
: this(tenum, true)
{
}
/// <summary>
/// Creates a filtered <see cref="TermsEnum"/> on a terms enum. </summary>
/// <param name="tenum"> the terms enumeration to filter. </param>
/// <param name="startWithSeek"> start with seek </param>
public FilteredTermsEnum(TermsEnum tenum, bool startWithSeek)
{
Debug.Assert(tenum != null);
this.tenum = tenum;
doSeek = startWithSeek;
}
/// <summary>
/// Use this method to set the initial <see cref="BytesRef"/>
/// to seek before iterating. This is a convenience method for
/// subclasses that do not override <see cref="NextSeekTerm(BytesRef)"/>.
/// If the initial seek term is <c>null</c> (default),
/// the enum is empty.
/// <para/>You can only use this method, if you keep the default
/// implementation of <see cref="NextSeekTerm(BytesRef)"/>.
/// </summary>
protected void SetInitialSeekTerm(BytesRef term)
{
this.initialSeekTerm = term;
}
/// <summary>
/// On the first call to <see cref="Next()"/> or if <see cref="Accept(BytesRef)"/> returns
/// <see cref="AcceptStatus.YES_AND_SEEK"/> or <see cref="AcceptStatus.NO_AND_SEEK"/>,
/// this method will be called to eventually seek the underlying <see cref="TermsEnum"/>
/// to a new position.
/// On the first call, <paramref name="currentTerm"/> will be <c>null</c>, later
/// calls will provide the term the underlying enum is positioned at.
/// This method returns per default only one time the initial seek term
/// and then <c>null</c>, so no repositioning is ever done.
/// <para/>
/// Override this method, if you want a more sophisticated <see cref="TermsEnum"/>,
/// that repositions the iterator during enumeration.
/// If this method always returns <c>null</c> the enum is empty.
/// <para/><c>Please note:</c> this method should always provide a greater term
/// than the last enumerated term, else the behavior of this enum
/// violates the contract for <see cref="TermsEnum"/>s.
/// </summary>
protected virtual BytesRef NextSeekTerm(BytesRef currentTerm)
{
BytesRef t = initialSeekTerm;
initialSeekTerm = null;
return t;
}
/// <summary>
/// Returns the related attributes, the returned <see cref="AttributeSource"/>
/// is shared with the delegate <see cref="TermsEnum"/>.
/// </summary>
public override AttributeSource Attributes
{
get { return tenum.Attributes; }
}
public override BytesRef Term
{
get { return tenum.Term; }
}
public override IComparer<BytesRef> Comparer
{
get
{
return tenum.Comparer;
}
}
public override int DocFreq
{
get { return tenum.DocFreq; }
}
public override long TotalTermFreq
{
get { return tenum.TotalTermFreq; }
}
/// <summary>
/// this enum does not support seeking! </summary>
/// <exception cref="System.NotSupportedException"> In general, subclasses do not
/// support seeking. </exception>
public override bool SeekExact(BytesRef term)
{
throw new System.NotSupportedException(this.GetType().Name + " does not support seeking");
}
/// <summary>
/// this enum does not support seeking! </summary>
/// <exception cref="System.NotSupportedException"> In general, subclasses do not
/// support seeking. </exception>
public override SeekStatus SeekCeil(BytesRef term)
{
throw new System.NotSupportedException(this.GetType().Name + " does not support seeking");
}
/// <summary>
/// this enum does not support seeking! </summary>
/// <exception cref="System.NotSupportedException"> In general, subclasses do not
/// support seeking. </exception>
public override void SeekExact(long ord)
{
throw new System.NotSupportedException(this.GetType().Name + " does not support seeking");
}
public override long Ord
{
get { return tenum.Ord; }
}
public override DocsEnum Docs(IBits bits, DocsEnum reuse, DocsFlags flags)
{
return tenum.Docs(bits, reuse, flags);
}
public override DocsAndPositionsEnum DocsAndPositions(IBits bits, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags)
{
return tenum.DocsAndPositions(bits, reuse, flags);
}
/// <summary>
/// this enum does not support seeking! </summary>
/// <exception cref="System.NotSupportedException"> In general, subclasses do not
/// support seeking. </exception>
public override void SeekExact(BytesRef term, TermState state)
{
throw new System.NotSupportedException(this.GetType().Name + " does not support seeking");
}
/// <summary>
/// Returns the filtered enums term state
/// </summary>
public override TermState GetTermState()
{
Debug.Assert(tenum != null);
return tenum.GetTermState();
}
public override BytesRef Next()
{
//System.out.println("FTE.next doSeek=" + doSeek);
//new Throwable().printStackTrace(System.out);
for (; ; )
{
// Seek or forward the iterator
if (doSeek)
{
doSeek = false;
BytesRef t = NextSeekTerm(actualTerm);
//System.out.println(" seek to t=" + (t == null ? "null" : t.utf8ToString()) + " tenum=" + tenum);
// Make sure we always seek forward:
Debug.Assert(actualTerm == null || t == null || Comparer.Compare(t, actualTerm) > 0, "curTerm=" + actualTerm + " seekTerm=" + t);
if (t == null || tenum.SeekCeil(t) == SeekStatus.END)
{
// no more terms to seek to or enum exhausted
//System.out.println(" return null");
return null;
}
actualTerm = tenum.Term;
//System.out.println(" got term=" + actualTerm.utf8ToString());
}
else
{
actualTerm = tenum.Next();
if (actualTerm == null)
{
// enum exhausted
return null;
}
}
// check if term is accepted
switch (Accept(actualTerm))
{
case FilteredTermsEnum.AcceptStatus.YES_AND_SEEK:
doSeek = true;
// term accepted, but we need to seek so fall-through
goto case FilteredTermsEnum.AcceptStatus.YES;
case FilteredTermsEnum.AcceptStatus.YES:
// term accepted
return actualTerm;
case FilteredTermsEnum.AcceptStatus.NO_AND_SEEK:
// invalid term, seek next time
doSeek = true;
break;
case FilteredTermsEnum.AcceptStatus.END:
// we are supposed to end the enum
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 is1 distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HSSF.Record
{
using System;
using NUnit.Framework;
using NUnit.Framework.Constraints;
using NPOI.HSSF.Record;
using NPOI.HSSF.Record.CF;
using NPOI.SS.Formula;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Model;
using NPOI.HSSF.Util;
using NPOI.Util;
using NPOI.SS.UserModel;
using NPOI.SS.Formula.PTG;
/**
* Tests the serialization and deserialization of the TestCFRuleRecord
* class works correctly.
*
* @author Dmitriy Kumshayev
*/
[TestFixture]
public class TestCFRuleRecord
{
[Test]
public void TestConstructors()
{
IWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet();
CFRuleRecord rule1 = CFRuleRecord.Create((HSSFSheet)sheet, "7");
Assert.AreEqual(CFRuleRecord.CONDITION_TYPE_FORMULA, rule1.ConditionType);
Assert.AreEqual((byte)ComparisonOperator.NoComparison, rule1.ComparisonOperation);
Assert.IsNotNull(rule1.ParsedExpression1);
Assert.AreSame(Ptg.EMPTY_PTG_ARRAY, rule1.ParsedExpression2);
CFRuleRecord rule2 = CFRuleRecord.Create((HSSFSheet)sheet, (byte)ComparisonOperator.Between, "2", "5");
Assert.AreEqual(CFRuleRecord.CONDITION_TYPE_CELL_VALUE_IS, rule2.ConditionType);
Assert.AreEqual((byte)ComparisonOperator.Between, rule2.ComparisonOperation);
Assert.IsNotNull(rule2.ParsedExpression1);
Assert.IsNotNull(rule2.ParsedExpression2);
CFRuleRecord rule3 = CFRuleRecord.Create((HSSFSheet)sheet, (byte)ComparisonOperator.Equal, null, null);
Assert.AreEqual(CFRuleRecord.CONDITION_TYPE_CELL_VALUE_IS, rule3.ConditionType);
Assert.AreEqual((byte)ComparisonOperator.Equal, rule3.ComparisonOperation);
Assert.AreSame(Ptg.EMPTY_PTG_ARRAY, rule3.ParsedExpression2);
Assert.AreSame(Ptg.EMPTY_PTG_ARRAY, rule3.ParsedExpression2);
}
[Test]
public void TestCreateCFRuleRecord()
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();
CFRuleRecord record = CFRuleRecord.Create(sheet, "7");
TestCFRuleRecord1(record);
// Serialize
byte[] SerializedRecord = record.Serialize();
// Strip header
byte[] recordData = new byte[SerializedRecord.Length - 4];
Array.Copy(SerializedRecord, 4, recordData, 0, recordData.Length);
// DeSerialize
record = new CFRuleRecord(TestcaseRecordInputStream.Create(CFRuleRecord.sid, recordData));
// Serialize again
byte[] output = record.Serialize();
// Compare
Assert.AreEqual(recordData.Length + 4, output.Length, "Output size"); //includes sid+recordlength
for (int i = 0; i < recordData.Length; i++)
{
Assert.AreEqual(recordData[i], output[i + 4], "CFRuleRecord doesn't match");
}
}
private void TestCFRuleRecord1(CFRuleRecord record)
{
FontFormatting fontFormatting = new FontFormatting();
TestFontFormattingAccessors(fontFormatting);
Assert.IsFalse(record.ContainsFontFormattingBlock);
record.FontFormatting = (fontFormatting);
Assert.IsTrue(record.ContainsFontFormattingBlock);
BorderFormatting borderFormatting = new BorderFormatting();
TestBorderFormattingAccessors(borderFormatting);
Assert.IsFalse(record.ContainsBorderFormattingBlock);
record.BorderFormatting = (borderFormatting);
Assert.IsTrue(record.ContainsBorderFormattingBlock);
Assert.IsFalse(record.IsLeftBorderModified);
record.IsLeftBorderModified = (true);
Assert.IsTrue(record.IsLeftBorderModified);
Assert.IsFalse(record.IsRightBorderModified);
record.IsRightBorderModified = (true);
Assert.IsTrue(record.IsRightBorderModified);
Assert.IsFalse(record.IsTopBorderModified);
record.IsTopBorderModified = (true);
Assert.IsTrue(record.IsTopBorderModified);
Assert.IsFalse(record.IsBottomBorderModified);
record.IsBottomBorderModified = (true);
Assert.IsTrue(record.IsBottomBorderModified);
Assert.IsFalse(record.IsTopLeftBottomRightBorderModified);
record.IsTopLeftBottomRightBorderModified = (true);
Assert.IsTrue(record.IsTopLeftBottomRightBorderModified);
Assert.IsFalse(record.IsBottomLeftTopRightBorderModified);
record.IsBottomLeftTopRightBorderModified = (true);
Assert.IsTrue(record.IsBottomLeftTopRightBorderModified);
PatternFormatting patternFormatting = new PatternFormatting();
TestPatternFormattingAccessors(patternFormatting);
Assert.IsFalse(record.ContainsPatternFormattingBlock);
record.PatternFormatting = (patternFormatting);
Assert.IsTrue(record.ContainsPatternFormattingBlock);
Assert.IsFalse(record.IsPatternBackgroundColorModified);
record.IsPatternBackgroundColorModified = (true);
Assert.IsTrue(record.IsPatternBackgroundColorModified);
Assert.IsFalse(record.IsPatternColorModified);
record.IsPatternColorModified = (true);
Assert.IsTrue(record.IsPatternColorModified);
Assert.IsFalse(record.IsPatternStyleModified);
record.IsPatternStyleModified = (true);
Assert.IsTrue(record.IsPatternStyleModified);
}
private void TestPatternFormattingAccessors(PatternFormatting patternFormatting)
{
patternFormatting.FillBackgroundColor = (HSSFColor.Green.Index);
Assert.AreEqual(HSSFColor.Green.Index, patternFormatting.FillBackgroundColor);
patternFormatting.FillForegroundColor = (HSSFColor.Indigo.Index);
Assert.AreEqual(HSSFColor.Indigo.Index, patternFormatting.FillForegroundColor);
patternFormatting.FillPattern = FillPattern.Diamonds;
Assert.AreEqual(FillPattern.Diamonds, patternFormatting.FillPattern);
}
private void TestBorderFormattingAccessors(BorderFormatting borderFormatting)
{
borderFormatting.IsBackwardDiagonalOn = (false);
Assert.IsFalse(borderFormatting.IsBackwardDiagonalOn);
borderFormatting.IsBackwardDiagonalOn = (true);
Assert.IsTrue(borderFormatting.IsBackwardDiagonalOn);
borderFormatting.BorderBottom = BorderStyle.Dotted;
Assert.AreEqual(BorderStyle.Dotted, borderFormatting.BorderBottom);
borderFormatting.BorderDiagonal = (BorderStyle.Medium);
Assert.AreEqual(BorderStyle.Medium, borderFormatting.BorderDiagonal);
borderFormatting.BorderLeft = (BorderStyle.MediumDashDotDot);
Assert.AreEqual(BorderStyle.MediumDashDotDot, borderFormatting.BorderLeft);
borderFormatting.BorderRight = (BorderStyle.MediumDashed);
Assert.AreEqual(BorderStyle.MediumDashed, borderFormatting.BorderRight);
borderFormatting.BorderTop = (BorderStyle.Hair);
Assert.AreEqual(BorderStyle.Hair, borderFormatting.BorderTop);
borderFormatting.BottomBorderColor = (HSSFColor.Aqua.Index);
Assert.AreEqual(HSSFColor.Aqua.Index, borderFormatting.BottomBorderColor);
borderFormatting.DiagonalBorderColor = (HSSFColor.Red.Index);
Assert.AreEqual(HSSFColor.Red.Index, borderFormatting.DiagonalBorderColor);
Assert.IsFalse(borderFormatting.IsForwardDiagonalOn);
borderFormatting.IsForwardDiagonalOn = (true);
Assert.IsTrue(borderFormatting.IsForwardDiagonalOn);
borderFormatting.LeftBorderColor = (HSSFColor.Black.Index);
Assert.AreEqual(HSSFColor.Black.Index, borderFormatting.LeftBorderColor);
borderFormatting.RightBorderColor = (HSSFColor.Blue.Index);
Assert.AreEqual(HSSFColor.Blue.Index, borderFormatting.RightBorderColor);
borderFormatting.TopBorderColor = (HSSFColor.Gold.Index);
Assert.AreEqual(HSSFColor.Gold.Index, borderFormatting.TopBorderColor);
}
private void TestFontFormattingAccessors(FontFormatting fontFormatting)
{
// Check for defaults
Assert.IsFalse(fontFormatting.IsEscapementTypeModified);
Assert.IsFalse(fontFormatting.IsFontCancellationModified);
Assert.IsFalse(fontFormatting.IsFontOutlineModified);
Assert.IsFalse(fontFormatting.IsFontShadowModified);
Assert.IsFalse(fontFormatting.IsFontStyleModified);
Assert.IsFalse(fontFormatting.IsUnderlineTypeModified);
Assert.IsFalse(fontFormatting.IsFontWeightModified);
Assert.IsFalse(fontFormatting.IsBold);
Assert.IsFalse(fontFormatting.IsItalic);
Assert.IsFalse(fontFormatting.IsOutlineOn);
Assert.IsFalse(fontFormatting.IsShadowOn);
Assert.IsFalse(fontFormatting.IsStruckout);
Assert.AreEqual(FontSuperScript.None, fontFormatting.EscapementType);
Assert.AreEqual(-1, fontFormatting.FontColorIndex);
Assert.AreEqual(-1, fontFormatting.FontHeight);
Assert.AreEqual(0, fontFormatting.FontWeight);
Assert.AreEqual(FontUnderlineType.None, fontFormatting.UnderlineType);
fontFormatting.IsBold = (true);
Assert.IsTrue(fontFormatting.IsBold);
fontFormatting.IsBold = (false);
Assert.IsFalse(fontFormatting.IsBold);
fontFormatting.EscapementType = FontSuperScript.Sub;
Assert.AreEqual(FontSuperScript.Sub, fontFormatting.EscapementType);
fontFormatting.EscapementType = FontSuperScript.Super;
Assert.AreEqual(FontSuperScript.Super, fontFormatting.EscapementType);
fontFormatting.EscapementType = FontSuperScript.None;
Assert.AreEqual(FontSuperScript.None, fontFormatting.EscapementType);
fontFormatting.IsEscapementTypeModified = (false);
Assert.IsFalse(fontFormatting.IsEscapementTypeModified);
fontFormatting.IsEscapementTypeModified = (true);
Assert.IsTrue(fontFormatting.IsEscapementTypeModified);
fontFormatting.IsFontWeightModified = (false);
Assert.IsFalse(fontFormatting.IsFontWeightModified);
fontFormatting.IsFontWeightModified = (true);
Assert.IsTrue(fontFormatting.IsFontWeightModified);
fontFormatting.IsFontCancellationModified = (false);
Assert.IsFalse(fontFormatting.IsFontCancellationModified);
fontFormatting.IsFontCancellationModified = (true);
Assert.IsTrue(fontFormatting.IsFontCancellationModified);
fontFormatting.FontColorIndex = ((short)10);
Assert.AreEqual(10, fontFormatting.FontColorIndex);
fontFormatting.FontHeight = (100);
Assert.AreEqual(100, fontFormatting.FontHeight);
fontFormatting.IsFontOutlineModified = (false);
Assert.IsFalse(fontFormatting.IsFontOutlineModified);
fontFormatting.IsFontOutlineModified = (true);
Assert.IsTrue(fontFormatting.IsFontOutlineModified);
fontFormatting.IsFontShadowModified = (false);
Assert.IsFalse(fontFormatting.IsFontShadowModified);
fontFormatting.IsFontShadowModified = (true);
Assert.IsTrue(fontFormatting.IsFontShadowModified);
fontFormatting.IsFontStyleModified = (false);
Assert.IsFalse(fontFormatting.IsFontStyleModified);
fontFormatting.IsFontStyleModified = (true);
Assert.IsTrue(fontFormatting.IsFontStyleModified);
fontFormatting.IsItalic = (false);
Assert.IsFalse(fontFormatting.IsItalic);
fontFormatting.IsItalic = (true);
Assert.IsTrue(fontFormatting.IsItalic);
fontFormatting.IsOutlineOn = (false);
Assert.IsFalse(fontFormatting.IsOutlineOn);
fontFormatting.IsOutlineOn = (true);
Assert.IsTrue(fontFormatting.IsOutlineOn);
fontFormatting.IsShadowOn = (false);
Assert.IsFalse(fontFormatting.IsShadowOn);
fontFormatting.IsShadowOn = (true);
Assert.IsTrue(fontFormatting.IsShadowOn);
fontFormatting.IsStruckout = (false);
Assert.IsFalse(fontFormatting.IsStruckout);
fontFormatting.IsStruckout = (true);
Assert.IsTrue(fontFormatting.IsStruckout);
fontFormatting.UnderlineType = FontUnderlineType.DoubleAccounting;
Assert.AreEqual(FontUnderlineType.DoubleAccounting, fontFormatting.UnderlineType);
fontFormatting.IsUnderlineTypeModified = (false);
Assert.IsFalse(fontFormatting.IsUnderlineTypeModified);
fontFormatting.IsUnderlineTypeModified = (true);
Assert.IsTrue(fontFormatting.IsUnderlineTypeModified);
}
[Test]
public void TestWrite() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();
CFRuleRecord rr = CFRuleRecord.Create(sheet, (byte)ComparisonOperator.Between, "5", "10");
PatternFormatting patternFormatting = new PatternFormatting();
patternFormatting.FillPattern = FillPattern.Bricks;
rr.PatternFormatting=(patternFormatting);
byte[] data = rr.Serialize();
Assert.AreEqual(26, data.Length);
Assert.AreEqual(3, LittleEndian.GetShort(data, 6));
Assert.AreEqual(3, LittleEndian.GetShort(data, 8));
int flags = LittleEndian.GetInt(data, 10);
Assert.AreEqual(0x00380000, flags & 0x00380000,"unused flags should be 111");
Assert.AreEqual(0, flags & 0x03C00000,"undocumented flags should be 0000"); // Otherwise Excel s unhappy
// check all remaining flag bits (some are not well understood yet)
Assert.AreEqual(0x203FFFFF, flags);
}
private static byte[] DATA_REFN = {
// formula extracted from bugzilla 45234 att 22141
1, 3,
9, // formula 1 length
0, 0, 0, unchecked((byte)-1), unchecked((byte)-1), 63, 32, 2, unchecked((byte)-128), 0, 0, 0, 5,
// formula 1: "=B3=1" (formula is relative to B4)
76, unchecked((byte)-1), unchecked((byte)-1), 0, unchecked((byte)-64), // tRefN(B1)
30, 1, 0,
11,
};
/**
* tRefN and tAreaN tokens must be preserved when re-serializing conditional format formulas
*/
[Test]
public void TestReserializeRefNTokens()
{
RecordInputStream is1 = TestcaseRecordInputStream.Create (CFRuleRecord.sid, DATA_REFN);
CFRuleRecord rr = new CFRuleRecord(is1);
Ptg[] ptgs = rr.ParsedExpression1;
Assert.AreEqual(3, ptgs.Length);
if (ptgs[0] is RefPtg) {
throw new AssertionException("Identified bug 45234");
}
Assert.AreEqual(typeof(RefNPtg), ptgs[0].GetType());
RefNPtg refNPtg = (RefNPtg) ptgs[0];
Assert.IsTrue(refNPtg.IsColRelative);
Assert.IsTrue(refNPtg.IsRowRelative);
byte[] data = rr.Serialize();
TestcaseRecordInputStream.ConfirmRecordEncoding(CFRuleRecord.sid, DATA_REFN, data);
}
[Test]
public void TestBug53691()
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet;
CFRuleRecord record = CFRuleRecord.Create(sheet, (byte)ComparisonOperator.Between, "2", "5") as CFRuleRecord;
CFRuleRecord clone = (CFRuleRecord)record.Clone();
byte[] SerializedRecord = record.Serialize();
byte[] SerializedClone = clone.Serialize();
Assert.That(SerializedRecord, new EqualConstraint(SerializedClone));
}
}
}
| |
// 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 Internal.NativeCrypto;
using System.Diagnostics;
using System.IO;
namespace System.Security.Cryptography
{
public sealed class DSACryptoServiceProvider : DSA, ICspAsymmetricAlgorithm
{
private int _keySize;
private readonly CspParameters _parameters;
private readonly bool _randomKeyContainer;
private SafeKeyHandle _safeKeyHandle;
private SafeProvHandle _safeProvHandle;
private SHA1 _sha1;
private static volatile CspProviderFlags s_useMachineKeyStore = 0;
/// <summary>
/// Initializes a new instance of the DSACryptoServiceProvider class.
/// </summary>
public DSACryptoServiceProvider()
: this(
new CspParameters(CapiHelper.DefaultDssProviderType,
null,
null,
s_useMachineKeyStore))
{
}
/// <summary>
/// Initializes a new instance of the DSACryptoServiceProvider class with the specified key size.
/// </summary>
/// <param name="dwKeySize">The size of the key for the asymmetric algorithm in bits.</param>
public DSACryptoServiceProvider(int dwKeySize)
: this(dwKeySize,
new CspParameters(CapiHelper.DefaultDssProviderType,
null,
null,
s_useMachineKeyStore))
{
}
/// <summary>
/// Initializes a new instance of the DSACryptoServiceProvider class with the specified parameters
/// for the cryptographic service provider (CSP).
/// </summary>
/// <param name="parameters">The parameters for the CSP.</param>
public DSACryptoServiceProvider(CspParameters parameters)
: this(0, parameters)
{
}
/// <summary>
/// Initializes a new instance of the DSACryptoServiceProvider class with the specified key size and parameters
/// for the cryptographic service provider (CSP).
/// </summary>
/// <param name="dwKeySize">The size of the key for the cryptographic algorithm in bits.</param>
/// <param name="parameters">The parameters for the CSP.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 is required by the FIPS 186-2 DSA spec.")]
public DSACryptoServiceProvider(int dwKeySize, CspParameters parameters)
{
if (dwKeySize < 0)
throw new ArgumentOutOfRangeException(nameof(dwKeySize), SR.ArgumentOutOfRange_NeedNonNegNum);
_parameters = CapiHelper.SaveCspParameters(
CapiHelper.CspAlgorithmType.Dss,
parameters,
s_useMachineKeyStore,
out _randomKeyContainer);
_keySize = dwKeySize;
_sha1 = SHA1.Create();
// If this is not a random container we generate, create it eagerly
// in the constructor so we can report any errors now.
if (!_randomKeyContainer)
{
// Force-read the SafeKeyHandle property, which will summon it into existence.
SafeKeyHandle localHandle = SafeKeyHandle;
Debug.Assert(localHandle != null);
}
}
private SafeProvHandle SafeProvHandle
{
get
{
if (_safeProvHandle == null)
{
lock (_parameters)
{
if (_safeProvHandle == null)
{
SafeProvHandle hProv = CapiHelper.CreateProvHandle(_parameters, _randomKeyContainer);
Debug.Assert(hProv != null);
Debug.Assert(!hProv.IsInvalid);
Debug.Assert(!hProv.IsClosed);
_safeProvHandle = hProv;
}
}
return _safeProvHandle;
}
return _safeProvHandle;
}
set
{
lock (_parameters)
{
SafeProvHandle current = _safeProvHandle;
if (ReferenceEquals(value, current))
{
return;
}
if (current != null)
{
SafeKeyHandle keyHandle = _safeKeyHandle;
_safeKeyHandle = null;
keyHandle?.Dispose();
current.Dispose();
}
_safeProvHandle = value;
}
}
}
private SafeKeyHandle SafeKeyHandle
{
get
{
if (_safeKeyHandle == null)
{
lock (_parameters)
{
if (_safeKeyHandle == null)
{
SafeKeyHandle hKey = CapiHelper.GetKeyPairHelper(
CapiHelper.CspAlgorithmType.Dss,
_parameters,
_keySize,
SafeProvHandle);
Debug.Assert(hKey != null);
Debug.Assert(!hKey.IsInvalid);
Debug.Assert(!hKey.IsClosed);
_safeKeyHandle = hKey;
}
}
}
return _safeKeyHandle;
}
set
{
lock (_parameters)
{
SafeKeyHandle current = _safeKeyHandle;
if (ReferenceEquals(value, current))
{
return;
}
_safeKeyHandle = value;
current?.Dispose();
}
}
}
/// <summary>
/// Gets a CspKeyContainerInfo object that describes additional information about a cryptographic key pair.
/// </summary>
public CspKeyContainerInfo CspKeyContainerInfo
{
get
{
// Desktop compat: Read the SafeKeyHandle property to force the key to load,
// because it might throw here.
SafeKeyHandle localHandle = SafeKeyHandle;
Debug.Assert(localHandle != null);
return new CspKeyContainerInfo(_parameters, _randomKeyContainer);
}
}
public override int KeySize
{
get
{
byte[] keySize = CapiHelper.GetKeyParameter(SafeKeyHandle, Constants.CLR_KEYLEN);
_keySize = (keySize[0] | (keySize[1] << 8) | (keySize[2] << 16) | (keySize[3] << 24));
return _keySize;
}
}
public override KeySizes[] LegalKeySizes
{
get
{
return new[] { new KeySizes(512, 1024, 64) }; // per FIPS 186-2
}
}
/// <summary>
/// Gets or sets a value indicating whether the key should be persisted in the cryptographic
/// service provider (CSP).
/// </summary>
public bool PersistKeyInCsp
{
get
{
return CapiHelper.GetPersistKeyInCsp(SafeProvHandle);
}
set
{
bool oldPersistKeyInCsp = this.PersistKeyInCsp;
if (value == oldPersistKeyInCsp)
{
return; // Do nothing
}
CapiHelper.SetPersistKeyInCsp(SafeProvHandle, value);
}
}
/// <summary>
/// Gets a value that indicates whether the DSACryptoServiceProvider object contains
/// only a public key.
/// </summary>
public bool PublicOnly
{
get
{
byte[] publicKey = CapiHelper.GetKeyParameter(SafeKeyHandle, Constants.CLR_PUBLICKEYONLY);
return (publicKey[0] == 1);
}
}
/// <summary>
/// Gets or sets a value indicating whether the key should be persisted in the computer's
/// key store instead of the user profile store.
/// </summary>
public static bool UseMachineKeyStore
{
get
{
return (s_useMachineKeyStore == CspProviderFlags.UseMachineKeyStore);
}
set
{
s_useMachineKeyStore = (value ? CspProviderFlags.UseMachineKeyStore : 0);
}
}
public override string KeyExchangeAlgorithm => null;
public override string SignatureAlgorithm => "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed)
{
_safeKeyHandle.Dispose();
}
if (_safeProvHandle != null && !_safeProvHandle.IsClosed)
{
_safeProvHandle.Dispose();
}
}
/// <summary>
/// Exports a blob containing the key information associated with an DSACryptoServiceProvider object.
/// </summary>
public byte[] ExportCspBlob(bool includePrivateParameters)
{
return CapiHelper.ExportKeyBlob(includePrivateParameters, SafeKeyHandle);
}
public override DSAParameters ExportParameters(bool includePrivateParameters)
{
byte[] cspBlob = ExportCspBlob(includePrivateParameters);
byte[] cspPublicBlob = null;
if (includePrivateParameters)
{
byte bVersion = CapiHelper.GetKeyBlobHeaderVersion(cspBlob);
if (bVersion <= 2)
{
// Since DSSPUBKEY is used for either public or private key, we got X
// but not Y. To get Y, do another export and ask for public key blob.
cspPublicBlob = ExportCspBlob(false);
}
}
return cspBlob.ToDSAParameters(includePrivateParameters, cspPublicBlob);
}
/// <summary>
/// This method helps Acquire the default CSP and avoids the need for static SafeProvHandle
/// in CapiHelper class
/// </summary>
private SafeProvHandle AcquireSafeProviderHandle()
{
SafeProvHandle safeProvHandle;
CapiHelper.AcquireCsp(new CspParameters(CapiHelper.DefaultDssProviderType), out safeProvHandle);
return safeProvHandle;
}
/// <summary>
/// Imports a blob that represents DSA key information.
/// </summary>
/// <param name="keyBlob">A byte array that represents a DSA key blob.</param>
public void ImportCspBlob(byte[] keyBlob)
{
SafeKeyHandle safeKeyHandle;
if (IsPublic(keyBlob))
{
SafeProvHandle safeProvHandleTemp = AcquireSafeProviderHandle();
CapiHelper.ImportKeyBlob(safeProvHandleTemp, (CspProviderFlags)0, false, keyBlob, out safeKeyHandle);
// The property set will take care of releasing any already-existing resources.
SafeProvHandle = safeProvHandleTemp;
}
else
{
CapiHelper.ImportKeyBlob(SafeProvHandle, _parameters.Flags, false, keyBlob, out safeKeyHandle);
}
// The property set will take care of releasing any already-existing resources.
SafeKeyHandle = safeKeyHandle;
}
public override void ImportParameters(DSAParameters parameters)
{
byte[] keyBlob = parameters.ToKeyBlob();
ImportCspBlob(keyBlob);
}
/// <summary>
/// Computes the hash value of the specified input stream and signs the resulting hash value.
/// </summary>
/// <param name="inputStream">The input data for which to compute the hash.</param>
/// <returns>The DSA signature for the specified data.</returns>
public byte[] SignData(Stream inputStream)
{
byte[] hashVal = _sha1.ComputeHash(inputStream);
return SignHash(hashVal, null);
}
/// <summary>
/// Computes the hash value of the specified input stream and signs the resulting hash value.
/// </summary>
/// <param name="buffer">The input data for which to compute the hash.</param>
/// <returns>The DSA signature for the specified data.</returns>
public byte[] SignData(byte[] buffer)
{
byte[] hashVal = _sha1.ComputeHash(buffer);
return SignHash(hashVal, null);
}
/// <summary>
/// Signs a byte array from the specified start point to the specified end point.
/// </summary>
/// <param name="buffer">The input data to sign.</param>
/// <param name="offset">The offset into the array from which to begin using data.</param>
/// <param name="count">The number of bytes in the array to use as data.</param>
/// <returns>The DSA signature for the specified data.</returns>
public byte[] SignData(byte[] buffer, int offset, int count)
{
byte[] hashVal = _sha1.ComputeHash(buffer, offset, count);
return SignHash(hashVal, null);
}
/// <summary>
/// Verifies the specified signature data by comparing it to the signature computed for the specified data.
/// </summary>
/// <param name="rgbData">The data that was signed.</param>
/// <param name="rgbSignature">The signature data to be verified.</param>
/// <returns>true if the signature verifies as valid; otherwise, false.</returns>
public bool VerifyData(byte[] rgbData, byte[] rgbSignature)
{
byte[] hashVal = _sha1.ComputeHash(rgbData);
return VerifyHash(hashVal, null, rgbSignature);
}
/// <summary>
/// Creates the DSA signature for the specified data.
/// </summary>
/// <param name="rgbHash">The data to be signed.</param>
/// <returns>The digital signature for the specified data.</returns>
override public byte[] CreateSignature(byte[] rgbHash)
{
return SignHash(rgbHash, null);
}
override public bool VerifySignature(byte[] rgbHash, byte[] rgbSignature)
{
return VerifyHash(rgbHash, null, rgbSignature);
}
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
// we're sealed and the base should have checked this before calling us
Debug.Assert(data != null);
Debug.Assert(offset >= 0 && offset <= data.Length);
Debug.Assert(count >= 0 && count <= data.Length - offset);
Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name));
if (hashAlgorithm != HashAlgorithmName.SHA1)
{
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name);
}
return _sha1.ComputeHash(data, offset, count);
}
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
{
// we're sealed and the base should have checked this before calling us
Debug.Assert(data != null);
Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name));
if (hashAlgorithm != HashAlgorithmName.SHA1)
{
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name);
}
return _sha1.ComputeHash(data);
}
/// <summary>
/// Computes the signature for the specified hash value by encrypting it with the private key.
/// </summary>
/// <param name="rgbHash">The hash value of the data to be signed.</param>
/// <param name="str">The name of the hash algorithm used to create the hash value of the data.</param>
/// <returns>The DSA signature for the specified hash value.</returns>
public byte[] SignHash(byte[] rgbHash, string str)
{
if (rgbHash == null)
throw new ArgumentNullException(nameof(rgbHash));
if (PublicOnly)
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm);
if (rgbHash.Length != _sha1.HashSize / 8)
throw new CryptographicException(string.Format(SR.Cryptography_InvalidHashSize, "SHA1", _sha1.HashSize / 8));
return CapiHelper.SignValue(
SafeProvHandle,
SafeKeyHandle,
_parameters.KeyNumber,
CapiHelper.CALG_DSS_SIGN,
calgHash,
rgbHash);
}
/// <summary>
/// Verifies the specified signature data by comparing it to the signature computed for the specified hash value.
/// </summary>
/// <param name="rgbHash">The hash value of the data to be signed.</param>
/// <param name="str">The name of the hash algorithm used to create the hash value of the data.</param>
/// <param name="rgbSignature">The signature data to be verified.</param>
/// <returns>true if the signature verifies as valid; otherwise, false.</returns>
public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature)
{
if (rgbHash == null)
throw new ArgumentNullException(nameof(rgbHash));
if (rgbSignature == null)
throw new ArgumentNullException(nameof(rgbSignature));
int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm);
return CapiHelper.VerifySign(
SafeProvHandle,
SafeKeyHandle,
CapiHelper.CALG_DSS_SIGN,
calgHash,
rgbHash,
rgbSignature);
}
/// <summary>
/// Find whether a DSS key blob is public.
/// </summary>
private static bool IsPublic(byte[] keyBlob)
{
if (keyBlob == null)
{
throw new ArgumentNullException(nameof(keyBlob));
}
// The CAPI DSS public key representation consists of the following sequence:
// - BLOBHEADER (the first byte is bType)
// - DSSPUBKEY or DSSPUBKEY_VER3 (the first field is the magic field)
// The first byte should be PUBLICKEYBLOB
if (keyBlob[0] != CapiHelper.PUBLICKEYBLOB)
{
return false;
}
// Magic should be DSS_MAGIC or DSS_PUB_MAGIC_VER3
if ((keyBlob[11] != 0x31 && keyBlob[11] != 0x33) || keyBlob[10] != 0x53 || keyBlob[9] != 0x53 || keyBlob[8] != 0x44)
{
return false;
}
return true;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Security;
using BulletSharp.Math;
namespace BulletSharp
{
public class GimPair : IDisposable
{
internal IntPtr _native;
internal GimPair(IntPtr native)
{
_native = native;
}
public GimPair()
{
_native = GIM_PAIR_new();
}
public GimPair(GimPair p)
{
_native = GIM_PAIR_new2(p._native);
}
public GimPair(int index1, int index2)
{
_native = GIM_PAIR_new3(index1, index2);
}
public int Index1
{
get { return GIM_PAIR_getIndex1(_native); }
set { GIM_PAIR_setIndex1(_native, value); }
}
public int Index2
{
get { return GIM_PAIR_getIndex2(_native); }
set { GIM_PAIR_setIndex2(_native, value); }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_native != IntPtr.Zero)
{
GIM_PAIR_delete(_native);
_native = IntPtr.Zero;
}
}
~GimPair()
{
Dispose(false);
}
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr GIM_PAIR_new();
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr GIM_PAIR_new2(IntPtr p);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr GIM_PAIR_new3(int index1, int index2);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int GIM_PAIR_getIndex1(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int GIM_PAIR_getIndex2(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void GIM_PAIR_setIndex1(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void GIM_PAIR_setIndex2(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void GIM_PAIR_delete(IntPtr obj);
}
public class PairSet
{
internal IntPtr _native;
internal PairSet(IntPtr native)
{
_native = native;
}
/*
public PairSet()
{
_native = btPairSet_new();
}
*/
public void PushPair(int index1, int index2)
{
btPairSet_push_pair(_native, index1, index2);
}
public void PushPairInv(int index1, int index2)
{
btPairSet_push_pair_inv(_native, index1, index2);
}
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btPairSet_new();
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btPairSet_push_pair(IntPtr obj, int index1, int index2);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btPairSet_push_pair_inv(IntPtr obj, int index1, int index2);
}
public class GimBvhData : IDisposable
{
internal IntPtr _native;
internal GimBvhData(IntPtr native)
{
_native = native;
}
public GimBvhData()
{
_native = GIM_BVH_DATA_new();
}
public Aabb Bound
{
get { return new Aabb(GIM_BVH_DATA_getBound(_native), true); }
}
public int Data
{
get { return GIM_BVH_DATA_getData(_native); }
set { GIM_BVH_DATA_setData(_native, value); }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_native != IntPtr.Zero)
{
GIM_BVH_DATA_delete(_native);
_native = IntPtr.Zero;
}
}
~GimBvhData()
{
Dispose(false);
}
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr GIM_BVH_DATA_new();
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr GIM_BVH_DATA_getBound(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int GIM_BVH_DATA_getData(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void GIM_BVH_DATA_setData(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void GIM_BVH_DATA_delete(IntPtr obj);
}
public class GimBvhTreeNode : IDisposable
{
internal IntPtr _native;
internal GimBvhTreeNode(IntPtr native)
{
_native = native;
}
public GimBvhTreeNode()
{
_native = GIM_BVH_TREE_NODE_new();
}
public Aabb Bound
{
get { return new Aabb(GIM_BVH_TREE_NODE_getBound(_native), true); }
}
public int DataIndex
{
get { return GIM_BVH_TREE_NODE_getDataIndex(_native); }
set { GIM_BVH_TREE_NODE_setDataIndex(_native, value); }
}
public int EscapeIndex
{
get { return GIM_BVH_TREE_NODE_getEscapeIndex(_native); }
set { GIM_BVH_TREE_NODE_setEscapeIndex(_native, value); }
}
public bool IsLeafNode
{
get { return GIM_BVH_TREE_NODE_isLeafNode(_native); }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_native != IntPtr.Zero)
{
GIM_BVH_TREE_NODE_delete(_native);
_native = IntPtr.Zero;
}
}
~GimBvhTreeNode()
{
Dispose(false);
}
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr GIM_BVH_TREE_NODE_new();
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr GIM_BVH_TREE_NODE_getBound(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int GIM_BVH_TREE_NODE_getDataIndex(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int GIM_BVH_TREE_NODE_getEscapeIndex(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool GIM_BVH_TREE_NODE_isLeafNode(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void GIM_BVH_TREE_NODE_setDataIndex(IntPtr obj, int index);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void GIM_BVH_TREE_NODE_setEscapeIndex(IntPtr obj, int index);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void GIM_BVH_TREE_NODE_delete(IntPtr obj);
}
public class GimBvhDataArray
{
internal IntPtr _native;
internal GimBvhDataArray(IntPtr native)
{
_native = native;
}
/*
public GimBvhDataArray()
{
_native = GIM_BVH_DATA_ARRAY_new();
}
*/
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr GIM_BVH_DATA_ARRAY_new();
}
public class GimBvhTreeNodeArray
{
internal IntPtr _native;
internal GimBvhTreeNodeArray(IntPtr native)
{
_native = native;
}
/*
public GimBvhTreeNodeArray()
{
_native = GIM_BVH_TREE_NODE_ARRAY_new();
}
*/
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr GIM_BVH_TREE_NODE_ARRAY_new();
}
public class BvhTree : IDisposable
{
internal IntPtr _native;
internal BvhTree(IntPtr native)
{
_native = native;
}
public BvhTree()
{
_native = btBvhTree_new();
}
public void BuildTree(GimBvhDataArray primitiveBoxes)
{
btBvhTree_build_tree(_native, primitiveBoxes._native);
}
public void ClearNodes()
{
btBvhTree_clearNodes(_native);
}
public GimBvhTreeNode GetNodePointer()
{
return new GimBvhTreeNode(btBvhTree_get_node_pointer(_native));
}
public GimBvhTreeNode GetNodePointer(int index)
{
return new GimBvhTreeNode(btBvhTree_get_node_pointer2(_native, index));
}
public int GetEscapeNodeIndex(int nodeIndex)
{
return btBvhTree_getEscapeNodeIndex(_native, nodeIndex);
}
public int GetLeftNode(int nodeIndex)
{
return btBvhTree_getLeftNode(_native, nodeIndex);
}
public void GetNodeBound(int nodeIndex, Aabb bound)
{
btBvhTree_getNodeBound(_native, nodeIndex, bound._native);
}
public int GetNodeData(int nodeIndex)
{
return btBvhTree_getNodeData(_native, nodeIndex);
}
public int GetRightNode(int nodeIndex)
{
return btBvhTree_getRightNode(_native, nodeIndex);
}
public bool IsLeafNode(int nodeIndex)
{
return btBvhTree_isLeafNode(_native, nodeIndex);
}
public void SetNodeBound(int nodeIndex, Aabb bound)
{
btBvhTree_setNodeBound(_native, nodeIndex, bound._native);
}
public int NodeCount
{
get { return btBvhTree_getNodeCount(_native); }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_native != IntPtr.Zero)
{
btBvhTree_delete(_native);
_native = IntPtr.Zero;
}
}
~BvhTree()
{
Dispose(false);
}
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btBvhTree_new();
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btBvhTree_build_tree(IntPtr obj, IntPtr primitive_boxes);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btBvhTree_clearNodes(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btBvhTree_get_node_pointer(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btBvhTree_get_node_pointer2(IntPtr obj, int index);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btBvhTree_getEscapeNodeIndex(IntPtr obj, int nodeindex);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btBvhTree_getLeftNode(IntPtr obj, int nodeindex);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btBvhTree_getNodeBound(IntPtr obj, int nodeindex, IntPtr bound);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btBvhTree_getNodeCount(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btBvhTree_getNodeData(IntPtr obj, int nodeindex);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btBvhTree_getRightNode(IntPtr obj, int nodeindex);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btBvhTree_isLeafNode(IntPtr obj, int nodeindex);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btBvhTree_setNodeBound(IntPtr obj, int nodeindex, IntPtr bound);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btBvhTree_delete(IntPtr obj);
}
public class PrimitiveManagerBase : IDisposable
{
internal IntPtr _native;
internal PrimitiveManagerBase(IntPtr native)
{
_native = native;
}
public void GetPrimitiveBox(int primIndex, Aabb primbox)
{
btPrimitiveManagerBase_get_primitive_box(_native, primIndex, primbox._native);
}
/*
public void GetPrimitiveTriangle(int primIndex, PrimitiveTriangle triangle)
{
btPrimitiveManagerBase_get_primitive_triangle(_native, primIndex, triangle._native);
}
*/
public bool IsTrimesh
{
get { return btPrimitiveManagerBase_is_trimesh(_native); }
}
public int PrimitiveCount
{
get { return btPrimitiveManagerBase_get_primitive_count(_native); }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_native != IntPtr.Zero)
{
btPrimitiveManagerBase_delete(_native);
_native = IntPtr.Zero;
}
}
~PrimitiveManagerBase()
{
Dispose(false);
}
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btPrimitiveManagerBase_get_primitive_box(IntPtr obj, int prim_index, IntPtr primbox);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btPrimitiveManagerBase_get_primitive_count(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btPrimitiveManagerBase_get_primitive_triangle(IntPtr obj, int prim_index, IntPtr triangle);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btPrimitiveManagerBase_is_trimesh(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btPrimitiveManagerBase_delete(IntPtr obj);
}
public class GImpactBvh : IDisposable
{
internal IntPtr _native;
private PrimitiveManagerBase _primitiveManager;
internal GImpactBvh(IntPtr native)
{
_native = native;
}
public GImpactBvh()
{
_native = btGImpactBvh_new();
}
public GImpactBvh(PrimitiveManagerBase primitiveManager)
{
_native = btGImpactBvh_new2(primitiveManager._native);
_primitiveManager = primitiveManager;
}
/*
public bool BoxQuery(Aabb box, AlignedIntArray collidedResults)
{
return btGImpactBvh_boxQuery(_native, box._native, collidedResults._native);
}
public bool BoxQueryTrans(Aabb box, Matrix transform, AlignedIntArray collidedResults)
{
return btGImpactBvh_boxQueryTrans(_native, box._native, ref transform, collidedResults._native);
}
*/
public void BuildSet()
{
btGImpactBvh_buildSet(_native);
}
public static void FindCollision(GImpactBvh boxset1, Matrix trans1, GImpactBvh boxset2, Matrix trans2, PairSet collisionPairs)
{
btGImpactBvh_find_collision(boxset1._native, ref trans1, boxset2._native, ref trans2, collisionPairs._native);
}
public GimBvhTreeNode GetNodePointer()
{
return new GimBvhTreeNode(btGImpactBvh_get_node_pointer(_native));
}
public GimBvhTreeNode GetNodePointer(int index)
{
return new GimBvhTreeNode(btGImpactBvh_get_node_pointer2(_native, index));
}
public int GetEscapeNodeIndex(int nodeIndex)
{
return btGImpactBvh_getEscapeNodeIndex(_native, nodeIndex);
}
public int GetLeftNode(int nodeIndex)
{
return btGImpactBvh_getLeftNode(_native, nodeIndex);
}
public void GetNodeBound(int nodeIndex, Aabb bound)
{
btGImpactBvh_getNodeBound(_native, nodeIndex, bound._native);
}
public int GetNodeData(int nodeIndex)
{
return btGImpactBvh_getNodeData(_native, nodeIndex);
}
/*
public void GetNodeTriangle(int nodeIndex, PrimitiveTriangle triangle)
{
btGImpactBvh_getNodeTriangle(_native, nodeIndex, triangle._native);
}
*/
public int GetRightNode(int nodeIndex)
{
return btGImpactBvh_getRightNode(_native, nodeIndex);
}
public bool IsLeafNode(int nodeIndex)
{
return btGImpactBvh_isLeafNode(_native, nodeIndex);
}
/*
public bool RayQuery(Vector3 rayDir, Vector3 rayOrigin, AlignedIntArray collidedResults)
{
return btGImpactBvh_rayQuery(_native, ref rayDir, ref rayOrigin, collidedResults._native);
}
*/
public void SetNodeBound(int nodeIndex, Aabb bound)
{
btGImpactBvh_setNodeBound(_native, nodeIndex, bound._native);
}
public void Update()
{
btGImpactBvh_update(_native);
}
public Aabb GlobalBox
{
get { return new Aabb(btGImpactBvh_getGlobalBox(_native), true); }
}
public bool HasHierarchy
{
get { return btGImpactBvh_hasHierarchy(_native); }
}
public bool IsTrimesh
{
get { return btGImpactBvh_isTrimesh(_native); }
}
public int NodeCount
{
get { return btGImpactBvh_getNodeCount(_native); }
}
public PrimitiveManagerBase PrimitiveManager
{
get { return new PrimitiveManagerBase(btGImpactBvh_getPrimitiveManager(_native)); }
set { btGImpactBvh_setPrimitiveManager(_native, value._native); }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_native != IntPtr.Zero)
{
btGImpactBvh_delete(_native);
_native = IntPtr.Zero;
}
}
~GImpactBvh()
{
Dispose(false);
}
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btGImpactBvh_new();
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btGImpactBvh_new2(IntPtr primitive_manager);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btGImpactBvh_boxQuery(IntPtr obj, IntPtr box, IntPtr collided_results);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btGImpactBvh_boxQueryTrans(IntPtr obj, IntPtr box, [In] ref Matrix transform, IntPtr collided_results);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btGImpactBvh_buildSet(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btGImpactBvh_find_collision(IntPtr boxset1, [In] ref Matrix trans1, IntPtr boxset2, [In] ref Matrix trans2, IntPtr collision_pairs);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btGImpactBvh_get_node_pointer(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btGImpactBvh_get_node_pointer2(IntPtr obj, int index);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btGImpactBvh_getEscapeNodeIndex(IntPtr obj, int nodeindex);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btGImpactBvh_getGlobalBox(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btGImpactBvh_getLeftNode(IntPtr obj, int nodeindex);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btGImpactBvh_getNodeBound(IntPtr obj, int nodeindex, IntPtr bound);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btGImpactBvh_getNodeCount(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btGImpactBvh_getNodeData(IntPtr obj, int nodeindex);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btGImpactBvh_getNodeTriangle(IntPtr obj, int nodeindex, IntPtr triangle);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btGImpactBvh_getPrimitiveManager(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btGImpactBvh_getRightNode(IntPtr obj, int nodeindex);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btGImpactBvh_hasHierarchy(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btGImpactBvh_isLeafNode(IntPtr obj, int nodeindex);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btGImpactBvh_isTrimesh(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I1)]
static extern bool btGImpactBvh_rayQuery(IntPtr obj, [In] ref Vector3 ray_dir, [In] ref Vector3 ray_origin, IntPtr collided_results);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btGImpactBvh_setNodeBound(IntPtr obj, int nodeindex, IntPtr bound);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btGImpactBvh_setPrimitiveManager(IntPtr obj, IntPtr primitive_manager);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btGImpactBvh_update(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btGImpactBvh_delete(IntPtr obj);
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Net;
using System.IO;
namespace AdvancedRenamer.TheTVDB
{
[Flags]
public enum MirrorType
{
XmlFiles = 1,
BannerFiles = 2,
ZipFiles = 4
}
public class TvDBApi
{
#region Member Variables
private string _url = String.Empty;
private string _apiKey = String.Empty;
private string _lang = "en";
private static TvDBApi _instance = null;
private List<TvDBMirror> _mirrors = new List<TvDBMirror>();
#endregion
#region Properties
/// <summary>
/// The instance of the initalised API object
/// </summary>
public static TvDBApi Instance
{
get { return _instance; }
set { _instance = value; }
}
/// <summary>
/// The URL to access the API on
/// </summary>
public string ApiUrl
{
get { return _url; }
private set { _url = value; }
}
/// <summary>
/// The API key to use when accessing the TV db API.
/// </summary>
public string ApiKey
{
get { return _apiKey; }
private set { _apiKey = value; }
}
/// <summary>
/// The language to access the API in
/// </summary>
public string Language
{
get { return _lang; }
set { _lang = value; }
}
#endregion
public static TvDBApi Create(string url, string apiKey)
{
if (Instance == null)
Instance = new TvDBApi(url, apiKey);
return Instance;
}
/// <summary>
/// Private constructor for creating the API object
/// </summary>
/// <param name="url">The URL to access th API on</param>
/// <param name="apiKey">The API key to use when accessing the API</param>
private TvDBApi(string url, string apiKey)
{
ApiKey = apiKey;
ApiUrl = url;
DownloadMirrors();
}
/// <summary>
/// Gets the API mirror sites. This is an async download
/// </summary>
private void DownloadMirrors()
{
string url = ApiUrl + "/api/" + ApiKey + "/mirrors.xml";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Timeout = 5000;
req.BeginGetResponse(new AsyncCallback(DownloadMirrorsCallback), req);
}
/// <summary>
/// Async callback for the mirrors.xml download
/// </summary>
private void DownloadMirrorsCallback(IAsyncResult result)
{
HttpWebRequest req = (HttpWebRequest)result.AsyncState;
try
{
HttpWebResponse resp = (HttpWebResponse)req.EndGetResponse(result);
Stream stream = resp.GetResponseStream();
StreamReader r = new StreamReader(resp.GetResponseStream());
string xml = r.ReadToEnd();
r.Dispose();
ParseMirrors(xml);
}
catch (Exception e)
{
Console.Error.WriteLine("Failed to download or parse mirrors: " + e.Message);
}
}
/// <summary>
/// Parses the mirror sites Xml
/// </summary>
/// <param name="xml">The Xml containing the mirrors</param>
private bool ParseMirrors(string xml)
{
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(xml);
}
catch (XmlException e)
{
Console.Error.WriteLine("Failed to get TvDB mirrors: " + e.Message);
return false;
}
foreach (XmlNode mirrorNode in doc.GetElementsByTagName("Mirror"))
{
TvDBMirror mirror = new TvDBMirror
(
XmlConvert.ToInt32(mirrorNode["id"].InnerText),
mirrorNode["mirrorpath"].InnerText,
XmlConvert.ToUInt32(mirrorNode["typemask"].InnerText)
);
_mirrors.Add(mirror);
}
return _mirrors.Count > 0;
}
/// <summary>
/// Returns a random mirror that is capable of processing the
/// given type of request
/// </summary>
/// <param name="type">The type or request data that we will
/// retrieve from the mirror</param>
/// <returns>A random mirror</returns>
public TvDBMirror GetMirror(MirrorType type)
{
List<TvDBMirror> validMirrors = new List<TvDBMirror>();
foreach (TvDBMirror mirror in _mirrors)
{
if (mirror.ValidType(type))
validMirrors.Add(mirror);
}
if (validMirrors.Count > 0)
{
Random rnd = new Random();
return validMirrors[rnd.Next(validMirrors.Count)];
}
else
{
throw new TvDBException("No valid mirror for type: " + type.ToString());
}
}
/// <summary>
/// Returns the results of searching for a TV show name
/// </summary>
/// <param name="title">The title of the TV show</param>
/// <returns>A list of search results</returns>
public List<TvDBSearchResult> Search(string title)
{
string encTitle = System.Uri.EscapeUriString(title).Replace("%20", "+");
string url = ApiUrl + "/api/GetSeries.php?seriesname=" + encTitle;
string xml = GetFile(url);
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(xml);
}
catch (XmlException e)
{
Console.Error.WriteLine("Invalid search xml: " + e.Message);
return null;
}
List<TvDBSearchResult> results = new List<TvDBSearchResult>();
foreach (XmlNode seriesNode in doc.GetElementsByTagName("Series"))
{
try
{
TvDBSearchResult result = new TvDBSearchResult(seriesNode);
results.Add(result);
}
catch (Exception e)
{
Console.Error.WriteLine("Failed to parse Series node");
}
}
return results;
}
/// <summary>
/// Get the Xml that repesents a full TV show
/// </summary>
/// <param name="seriesID">The unique series ID</param>
/// <returns>The parsed TV show</returns>
public TvDBShow GetShow(int seriesID)
{
TvDBMirror mirror = GetMirror(MirrorType.XmlFiles);
if (mirror == null)
{
Console.Error.WriteLine("Failed to GetShow: No available mirrors");
return null;
}
string url = mirror.Url + "/api/" + ApiKey + "/series/" +
seriesID.ToString() + "/all/" + Language + ".xml";
string xml = GetFile(url);
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(xml);
XmlNodeList seriesNodes = doc.GetElementsByTagName("Series");
if (seriesNodes.Count != 1)
Console.Error.WriteLine("Series lookup returned " + seriesNodes.Count.ToString() + " nodes");
TvDBShow show = new TvDBShow(seriesNodes[0]);
foreach (XmlNode episodeNode in doc.GetElementsByTagName("Episode"))
{
show.AddEpisode(episodeNode);
}
return show;
}
catch (Exception e)
{
Console.Error.WriteLine("Failed to get show: " + e.Message);
}
return null;
}
/// <summary>
/// Downloads a remote file
/// </summary>
/// <param name="url">The URL to download</param>
/// <returns>The contents of the remote file</returns>
private string GetFile(string url)
{
Console.Out.WriteLine("Downloading: " + url);
try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Timeout = 5 * 1000;
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader r = new StreamReader(resp.GetResponseStream());
string xml = r.ReadToEnd();
r.Dispose();
return xml;
}
catch (Exception e)
{
Console.Error.WriteLine("Failed to download: " + e.Message);
return String.Empty;
}
}
}
/// <summary>
/// Encapsulates the details for a TV DB API mirror site
/// </summary>
public class TvDBMirror
{
#region Member Variables
private string _url = String.Empty;
private MirrorType _typeMask;
private int _id;
#endregion
#region Properties
/// <summary>
/// Gets or sEts the mirror URL
/// </summary>
public string Url
{
get { return _url; }
set { _url = value; }
}
/// <summary>
/// Gets or sets the type mask for the mirror
/// </summary>
public MirrorType TypeMask
{
get { return _typeMask; }
set { _typeMask = value; }
}
/// <summary>
/// Gets or sets the ID number for the mirror
/// </summary>
public int ID
{
get { return _id; }
set { _id = value; }
}
#endregion
public TvDBMirror(int id, string url, uint typeMask)
{
ID = id;
Url = url;
TypeMask = (MirrorType)typeMask;
}
public TvDBMirror(int id, string url, MirrorType typeMask)
{
ID = id;
TypeMask = typeMask;
Url = url;
}
/// <summary>
/// Checks if the mirror can handle requests for the given type of data
/// </summary>
/// <param name="type">The type of data to retreive from the mirror</param>
/// <returns>True if the mirror can handle the data, false otherwise</returns>
public bool ValidType(MirrorType type)
{
return ((TypeMask & type) == type);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos.Enums.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Enums {
/// <summary>Holder for reflection information generated from POGOProtos.Enums.proto</summary>
public static partial class POGOProtosEnumsReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos.Enums.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static POGOProtosEnumsReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChZQT0dPUHJvdG9zLkVudW1zLnByb3RvEhBQT0dPUHJvdG9zLkVudW1zKuwF",
"CgxBY3Rpdml0eVR5cGUSFAoQQUNUSVZJVFlfVU5LTk9XThAAEhoKFkFDVElW",
"SVRZX0NBVENIX1BPS0VNT04QARIhCh1BQ1RJVklUWV9DQVRDSF9MRUdFTkRf",
"UE9LRU1PThACEhkKFUFDVElWSVRZX0ZMRUVfUE9LRU1PThADEhgKFEFDVElW",
"SVRZX0RFRkVBVF9GT1JUEAQSGwoXQUNUSVZJVFlfRVZPTFZFX1BPS0VNT04Q",
"BRIWChJBQ1RJVklUWV9IQVRDSF9FR0cQBhIUChBBQ1RJVklUWV9XQUxLX0tN",
"EAcSHgoaQUNUSVZJVFlfUE9LRURFWF9FTlRSWV9ORVcQCBIeChpBQ1RJVklU",
"WV9DQVRDSF9GSVJTVF9USFJPVxAJEh0KGUFDVElWSVRZX0NBVENIX05JQ0Vf",
"VEhST1cQChIeChpBQ1RJVklUWV9DQVRDSF9HUkVBVF9USFJPVxALEiIKHkFD",
"VElWSVRZX0NBVENIX0VYQ0VMTEVOVF9USFJPVxAMEhwKGEFDVElWSVRZX0NB",
"VENIX0NVUlZFQkFMTBANEiUKIUFDVElWSVRZX0NBVENIX0ZJUlNUX0NBVENI",
"X09GX0RBWRAOEhwKGEFDVElWSVRZX0NBVENIX01JTEVTVE9ORRAPEhoKFkFD",
"VElWSVRZX1RSQUlOX1BPS0VNT04QEBIYChRBQ1RJVklUWV9TRUFSQ0hfRk9S",
"VBAREhwKGEFDVElWSVRZX1JFTEVBU0VfUE9LRU1PThASEiIKHkFDVElWSVRZ",
"X0hBVENIX0VHR19TTUFMTF9CT05VUxATEiMKH0FDVElWSVRZX0hBVENIX0VH",
"R19NRURJVU1fQk9OVVMQFBIiCh5BQ1RJVklUWV9IQVRDSF9FR0dfTEFSR0Vf",
"Qk9OVVMQFRIgChxBQ1RJVklUWV9ERUZFQVRfR1lNX0RFRkVOREVSEBYSHgoa",
"QUNUSVZJVFlfREVGRUFUX0dZTV9MRUFERVIQFyqhBwoJQmFkZ2VUeXBlEg8K",
"C0JBREdFX1VOU0VUEAASEwoPQkFER0VfVFJBVkVMX0tNEAESGQoVQkFER0Vf",
"UE9LRURFWF9FTlRSSUVTEAISFwoTQkFER0VfQ0FQVFVSRV9UT1RBTBADEhcK",
"E0JBREdFX0RFRkVBVEVEX0ZPUlQQBBIXChNCQURHRV9FVk9MVkVEX1RPVEFM",
"EAUSFwoTQkFER0VfSEFUQ0hFRF9UT1RBTBAGEhsKF0JBREdFX0VOQ09VTlRF",
"UkVEX1RPVEFMEAcSGwoXQkFER0VfUE9LRVNUT1BTX1ZJU0lURUQQCBIaChZC",
"QURHRV9VTklRVUVfUE9LRVNUT1BTEAkSGQoVQkFER0VfUE9LRUJBTExfVEhS",
"T1dOEAoSFgoSQkFER0VfQklHX01BR0lLQVJQEAsSGAoUQkFER0VfREVQTE9Z",
"RURfVE9UQUwQDBIbChdCQURHRV9CQVRUTEVfQVRUQUNLX1dPThANEh0KGUJB",
"REdFX0JBVFRMRV9UUkFJTklOR19XT04QDhIbChdCQURHRV9CQVRUTEVfREVG",
"RU5EX1dPThAPEhkKFUJBREdFX1BSRVNUSUdFX1JBSVNFRBAQEhoKFkJBREdF",
"X1BSRVNUSUdFX0RST1BQRUQQERIVChFCQURHRV9UWVBFX05PUk1BTBASEhcK",
"E0JBREdFX1RZUEVfRklHSFRJTkcQExIVChFCQURHRV9UWVBFX0ZMWUlORxAU",
"EhUKEUJBREdFX1RZUEVfUE9JU09OEBUSFQoRQkFER0VfVFlQRV9HUk9VTkQQ",
"FhITCg9CQURHRV9UWVBFX1JPQ0sQFxISCg5CQURHRV9UWVBFX0JVRxAYEhQK",
"EEJBREdFX1RZUEVfR0hPU1QQGRIUChBCQURHRV9UWVBFX1NURUVMEBoSEwoP",
"QkFER0VfVFlQRV9GSVJFEBsSFAoQQkFER0VfVFlQRV9XQVRFUhAcEhQKEEJB",
"REdFX1RZUEVfR1JBU1MQHRIXChNCQURHRV9UWVBFX0VMRUNUUklDEB4SFgoS",
"QkFER0VfVFlQRV9QU1lDSElDEB8SEgoOQkFER0VfVFlQRV9JQ0UQIBIVChFC",
"QURHRV9UWVBFX0RSQUdPThAhEhMKD0JBREdFX1RZUEVfREFSSxAiEhQKEEJB",
"REdFX1RZUEVfRkFJUlkQIxIXChNCQURHRV9TTUFMTF9SQVRUQVRBECQSEQoN",
"QkFER0VfUElLQUNIVRAlKpYBChNDYW1lcmFJbnRlcnBvbGF0aW9uEhIKDkNB",
"TV9JTlRFUlBfQ1VUEAASFQoRQ0FNX0lOVEVSUF9MSU5FQVIQARIVChFDQU1f",
"SU5URVJQX1NNT09USBACEiUKIUNBTV9JTlRFUlBfU01PT1RIX1JPVF9MSU5F",
"QVJfTU9WRRADEhYKEkNBTV9JTlRFUlBfREVQRU5EUxAEKvwDCgxDYW1lcmFU",
"YXJnZXQSFwoTQ0FNX1RBUkdFVF9BVFRBQ0tFUhAAEhwKGENBTV9UQVJHRVRf",
"QVRUQUNLRVJfRURHRRABEh4KGkNBTV9UQVJHRVRfQVRUQUNLRVJfR1JPVU5E",
"EAISFwoTQ0FNX1RBUkdFVF9ERUZFTkRFUhADEhwKGENBTV9UQVJHRVRfREVG",
"RU5ERVJfRURHRRAEEh4KGkNBTV9UQVJHRVRfREVGRU5ERVJfR1JPVU5EEAUS",
"IAocQ0FNX1RBUkdFVF9BVFRBQ0tFUl9ERUZFTkRFUhAGEiUKIUNBTV9UQVJH",
"RVRfQVRUQUNLRVJfREVGRU5ERVJfRURHRRAHEiAKHENBTV9UQVJHRVRfREVG",
"RU5ERVJfQVRUQUNLRVIQCBIlCiFDQU1fVEFSR0VUX0RFRkVOREVSX0FUVEFD",
"S0VSX0VER0UQCRInCiNDQU1fVEFSR0VUX0FUVEFDS0VSX0RFRkVOREVSX01J",
"UlJPUhALEikKJUNBTV9UQVJHRVRfU0hPVUxERVJfQVRUQUNLRVJfREVGRU5E",
"RVIQDBIwCixDQU1fVEFSR0VUX1NIT1VMREVSX0FUVEFDS0VSX0RFRkVOREVS",
"X01JUlJPUhANEiYKIkNBTV9UQVJHRVRfQVRUQUNLRVJfREVGRU5ERVJfV09S",
"TEQQDioeCgZHZW5kZXISCAoETUFMRRAAEgoKBkZFTUFMRRABKpQBChNIb2xv",
"SWFwSXRlbUNhdGVnb3J5EhUKEUlBUF9DQVRFR09SWV9OT05FEAASFwoTSUFQ",
"X0NBVEVHT1JZX0JVTkRMRRABEhYKEklBUF9DQVRFR09SWV9JVEVNUxACEhkK",
"FUlBUF9DQVRFR09SWV9VUEdSQURFUxADEhoKFklBUF9DQVRFR09SWV9QT0tF",
"Q09JTlMQBCrWAgoMSXRlbUNhdGVnb3J5EhYKEklURU1fQ0FURUdPUllfTk9O",
"RRAAEhoKFklURU1fQ0FURUdPUllfUE9LRUJBTEwQARIWChJJVEVNX0NBVEVH",
"T1JZX0ZPT0QQAhIaChZJVEVNX0NBVEVHT1JZX01FRElDSU5FEAMSFwoTSVRF",
"TV9DQVRFR09SWV9CT09TVBAEEhoKFklURU1fQ0FURUdPUllfVVRJTElURVMQ",
"BRIYChRJVEVNX0NBVEVHT1JZX0NBTUVSQRAGEhYKEklURU1fQ0FURUdPUllf",
"RElTSxAHEhsKF0lURU1fQ0FURUdPUllfSU5DVUJBVE9SEAgSGQoVSVRFTV9D",
"QVRFR09SWV9JTkNFTlNFEAkSGgoWSVRFTV9DQVRFR09SWV9YUF9CT09TVBAK",
"EiMKH0lURU1fQ0FURUdPUllfSU5WRU5UT1JZX1VQR1JBREUQCyqYBAoKSXRl",
"bUVmZmVjdBIUChBJVEVNX0VGRkVDVF9OT05FEAASHAoXSVRFTV9FRkZFQ1Rf",
"Q0FQX05PX0ZMRUUQ6AcSIAobSVRFTV9FRkZFQ1RfQ0FQX05PX01PVkVNRU5U",
"EOoHEh4KGUlURU1fRUZGRUNUX0NBUF9OT19USFJFQVQQ6wcSHwoaSVRFTV9F",
"RkZFQ1RfQ0FQX1RBUkdFVF9NQVgQ7AcSIAobSVRFTV9FRkZFQ1RfQ0FQX1RB",
"UkdFVF9TTE9XEO0HEiEKHElURU1fRUZGRUNUX0NBUF9DSEFOQ0VfTklHSFQQ",
"7gcSIwoeSVRFTV9FRkZFQ1RfQ0FQX0NIQU5DRV9UUkFJTkVSEO8HEicKIklU",
"RU1fRUZGRUNUX0NBUF9DSEFOQ0VfRklSU1RfVEhST1cQ8AcSIgodSVRFTV9F",
"RkZFQ1RfQ0FQX0NIQU5DRV9MRUdFTkQQ8QcSIQocSVRFTV9FRkZFQ1RfQ0FQ",
"X0NIQU5DRV9IRUFWWRDyBxIiCh1JVEVNX0VGRkVDVF9DQVBfQ0hBTkNFX1JF",
"UEVBVBDzBxInCiJJVEVNX0VGRkVDVF9DQVBfQ0hBTkNFX01VTFRJX1RIUk9X",
"EPQHEiIKHUlURU1fRUZGRUNUX0NBUF9DSEFOQ0VfQUxXQVlTEPUHEigKI0lU",
"RU1fRUZGRUNUX0NBUF9DSEFOQ0VfU0lOR0xFX1RIUk9XEPYHKkEKCFBsYXRm",
"b3JtEgkKBVVOU0VUEAASBwoDSU9TEAESCwoHQU5EUk9JRBACEgcKA09TWBAD",
"EgsKB1dJTkRPV1MQBCr6DAoPUG9rZW1vbkZhbWlseUlkEhAKDEZBTUlMWV9V",
"TlNFVBAAEhQKEEZBTUlMWV9CVUxCQVNBVVIQARIVChFGQU1JTFlfQ0hBUk1B",
"TkRFUhAEEhMKD0ZBTUlMWV9TUVVJUlRMRRAHEhMKD0ZBTUlMWV9DQVRFUlBJ",
"RRAKEhEKDUZBTUlMWV9XRUVETEUQDRIRCg1GQU1JTFlfUElER0VZEBASEgoO",
"RkFNSUxZX1JBVFRBVEEQExISCg5GQU1JTFlfU1BFQVJPVxAVEhAKDEZBTUlM",
"WV9FS0FOUxAXEhIKDkZBTUlMWV9QSUtBQ0hVEBkSFAoQRkFNSUxZX1NBTkRT",
"SFJFVxAbEhkKFUZBTUlMWV9OSURPUkFOX0ZFTUFMRRAdEhcKE0ZBTUlMWV9O",
"SURPUkFOX01BTEUQIBITCg9GQU1JTFlfQ0xFRkFJUlkQIxIRCg1GQU1JTFlf",
"VlVMUElYECUSFQoRRkFNSUxZX0pJR0dMWVBVRkYQJxIQCgxGQU1JTFlfWlVC",
"QVQQKRIRCg1GQU1JTFlfT0RESVNIECsSEAoMRkFNSUxZX1BBUkFTEC4SEgoO",
"RkFNSUxZX1ZFTk9OQVQQMBISCg5GQU1JTFlfRElHTEVUVBAyEhEKDUZBTUlM",
"WV9NRU9XVEgQNBISCg5GQU1JTFlfUFNZRFVDSxA2EhEKDUZBTUlMWV9NQU5L",
"RVkQOBIUChBGQU1JTFlfR1JPV0xJVEhFEDoSEgoORkFNSUxZX1BPTElXQUcQ",
"PBIPCgtGQU1JTFlfQUJSQRA/EhEKDUZBTUlMWV9NQUNIT1AQQhIVChFGQU1J",
"TFlfQkVMTFNQUk9VVBBFEhQKEEZBTUlMWV9URU5UQUNPT0wQSBISCg5GQU1J",
"TFlfR0VPRFVERRBKEhEKDUZBTUlMWV9QT05ZVEEQTRITCg9GQU1JTFlfU0xP",
"V1BPS0UQTxIUChBGQU1JTFlfTUFHTkVNSVRFEFESFAoQRkFNSUxZX0ZBUkZF",
"VENIRBBTEhAKDEZBTUlMWV9ET0RVTxBUEg8KC0ZBTUlMWV9TRUVMEFYSEQoN",
"RkFNSUxZX0dSSU1FUhBYEhMKD0ZBTUlMWV9TSEVMTERFUhBaEhEKDUZBTUlM",
"WV9HQVNUTFkQXBIPCgtGQU1JTFlfT05JWBBfEhIKDkZBTUlMWV9EUk9XWkVF",
"EGASEAoMRkFNSUxZX0hZUE5PEGESEQoNRkFNSUxZX0tSQUJCWRBiEhIKDkZB",
"TUlMWV9WT0xUT1JCEGQSFAoQRkFNSUxZX0VYRUdHQ1VURRBmEhEKDUZBTUlM",
"WV9DVUJPTkUQaBIUChBGQU1JTFlfSElUTU9OTEVFEGoSFQoRRkFNSUxZX0hJ",
"VE1PTkNIQU4QaxIUChBGQU1JTFlfTElDS0lUVU5HEGwSEgoORkFNSUxZX0tP",
"RkZJTkcQbRISCg5GQU1JTFlfUkhZSE9SThBvEhIKDkZBTUlMWV9DSEFOU0VZ",
"EHESEgoORkFNSUxZX1RBTkdFTEEQchIVChFGQU1JTFlfS0FOR0FTS0hBThBz",
"EhEKDUZBTUlMWV9IT1JTRUEQdBISCg5GQU1JTFlfR09MREVFThB2EhEKDUZB",
"TUlMWV9TVEFSWVUQeBISCg5GQU1JTFlfTVJfTUlNRRB6EhIKDkZBTUlMWV9T",
"Q1lUSEVSEHsSDwoLRkFNSUxZX0pZTlgQfBIVChFGQU1JTFlfRUxFQ1RBQlVa",
"WhB9EhEKDUZBTUlMWV9NQUdNQVIQfhIRCg1GQU1JTFlfUElOU0lSEH8SEgoN",
"RkFNSUxZX1RBVVJPUxCAARIUCg9GQU1JTFlfTUFHSUtBUlAQgQESEgoNRkFN",
"SUxZX0xBUFJBUxCDARIRCgxGQU1JTFlfRElUVE8QhAESEQoMRkFNSUxZX0VF",
"VkVFEIUBEhMKDkZBTUlMWV9QT1JZR09OEIkBEhMKDkZBTUlMWV9PTUFOWVRF",
"EIoBEhIKDUZBTUlMWV9LQUJVVE8QjAESFgoRRkFNSUxZX0FFUk9EQUNUWUwQ",
"jgESEwoORkFNSUxZX1NOT1JMQVgQjwESFAoPRkFNSUxZX0FSVElDVU5PEJAB",
"EhIKDUZBTUlMWV9aQVBET1MQkQESEwoORkFNSUxZX01PTFRSRVMQkgESEwoO",
"RkFNSUxZX0RSQVRJTkkQkwESEgoNRkFNSUxZX01FV1RXTxCWARIPCgpGQU1J",
"TFlfTUVXEJcBKpMQCglQb2tlbW9uSWQSDQoJTUlTU0lOR05PEAASDQoJQlVM",
"QkFTQVVSEAESCwoHSVZZU0FVUhACEgwKCFZFTlVTQVVSEAMSDgoKQ0hBUk1B",
"TkRFUhAEEg4KCkNIQVJNRUxFT04QBRINCglDSEFSSVpBUkQQBhIMCghTUVVJ",
"UlRMRRAHEg0KCVdBUlRPUlRMRRAIEg0KCUJMQVNUT0lTRRAJEgwKCENBVEVS",
"UElFEAoSCwoHTUVUQVBPRBALEg4KCkJVVFRFUkZSRUUQDBIKCgZXRUVETEUQ",
"DRIKCgZLQUtVTkEQDhIMCghCRUVEUklMTBAPEgoKBlBJREdFWRAQEg0KCVBJ",
"REdFT1RUTxAREgsKB1BJREdFT1QQEhILCgdSQVRUQVRBEBMSDAoIUkFUSUNB",
"VEUQFBILCgdTUEVBUk9XEBUSCgoGRkVBUk9XEBYSCQoFRUtBTlMQFxIJCgVB",
"UkJPSxAYEgsKB1BJS0FDSFUQGRIKCgZSQUlDSFUQGhINCglTQU5EU0hSRVcQ",
"GxINCglTQU5EU0xBU0gQHBISCg5OSURPUkFOX0ZFTUFMRRAdEgwKCE5JRE9S",
"SU5BEB4SDQoJTklET1FVRUVOEB8SEAoMTklET1JBTl9NQUxFECASDAoITklE",
"T1JJTk8QIRIMCghOSURPS0lORxAiEgwKCENMRUZBSVJZECMSDAoIQ0xFRkFC",
"TEUQJBIKCgZWVUxQSVgQJRINCglOSU5FVEFMRVMQJhIOCgpKSUdHTFlQVUZG",
"ECcSDgoKV0lHR0xZVFVGRhAoEgkKBVpVQkFUECkSCgoGR09MQkFUECoSCgoG",
"T0RESVNIECsSCQoFR0xPT00QLBINCglWSUxFUExVTUUQLRIJCgVQQVJBUxAu",
"EgwKCFBBUkFTRUNUEC8SCwoHVkVOT05BVBAwEgwKCFZFTk9NT1RIEDESCwoH",
"RElHTEVUVBAyEgsKB0RVR1RSSU8QMxIKCgZNRU9XVEgQNBILCgdQRVJTSUFO",
"EDUSCwoHUFNZRFVDSxA2EgsKB0dPTERVQ0sQNxIKCgZNQU5LRVkQOBIMCghQ",
"UklNRUFQRRA5Eg0KCUdST1dMSVRIRRA6EgwKCEFSQ0FOSU5FEDsSCwoHUE9M",
"SVdBRxA8Eg0KCVBPTElXSElSTBA9Eg0KCVBPTElXUkFUSBA+EggKBEFCUkEQ",
"PxILCgdLQURBQlJBEEASDAoIQUxBS0FaQU0QQRIKCgZNQUNIT1AQQhILCgdN",
"QUNIT0tFEEMSCwoHTUFDSEFNUBBEEg4KCkJFTExTUFJPVVQQRRIOCgpXRUVQ",
"SU5CRUxMEEYSDgoKVklDVFJFRUJFTBBHEg0KCVRFTlRBQ09PTBBIEg4KClRF",
"TlRBQ1JVRUwQSRILCgdHRU9EVURFEEoSDAoIR1JBVkVMRVIQSxIJCgVHT0xF",
"TRBMEgoKBlBPTllUQRBNEgwKCFJBUElEQVNIEE4SDAoIU0xPV1BPS0UQTxIL",
"CgdTTE9XQlJPEFASDQoJTUFHTkVNSVRFEFESDAoITUFHTkVUT04QUhINCglG",
"QVJGRVRDSEQQUxIJCgVET0RVTxBUEgoKBkRPRFJJTxBVEggKBFNFRUwQVhIL",
"CgdERVdHT05HEFcSCgoGR1JJTUVSEFgSBwoDTVVLEFkSDAoIU0hFTExERVIQ",
"WhIMCghDTE9ZU1RFUhBbEgoKBkdBU1RMWRBcEgsKB0hBVU5URVIQXRIKCgZH",
"RU5HQVIQXhIICgRPTklYEF8SCwoHRFJPV1pFRRBgEgkKBUhZUE5PEGESCgoG",
"S1JBQkJZEGISCwoHS0lOR0xFUhBjEgsKB1ZPTFRPUkIQZBINCglFTEVDVFJP",
"REUQZRINCglFWEVHR0NVVEUQZhINCglFWEVHR1VUT1IQZxIKCgZDVUJPTkUQ",
"aBILCgdNQVJPV0FLEGkSDQoJSElUTU9OTEVFEGoSDgoKSElUTU9OQ0hBThBr",
"Eg0KCUxJQ0tJVFVORxBsEgsKB0tPRkZJTkcQbRILCgdXRUVaSU5HEG4SCwoH",
"UkhZSE9SThBvEgoKBlJIWURPThBwEgsKB0NIQU5TRVkQcRILCgdUQU5HRUxB",
"EHISDgoKS0FOR0FTS0hBThBzEgoKBkhPUlNFQRB0EgoKBlNFQURSQRB1EgsK",
"B0dPTERFRU4QdhILCgdTRUFLSU5HEHcSCgoGU1RBUllVEHgSCwoHU1RBUk1J",
"RRB5EgsKB01SX01JTUUQehILCgdTQ1lUSEVSEHsSCAoESllOWBB8Eg4KCkVM",
"RUNUQUJVWloQfRIKCgZNQUdNQVIQfhIKCgZQSU5TSVIQfxILCgZUQVVST1MQ",
"gAESDQoITUFHSUtBUlAQgQESDQoIR1lBUkFET1MQggESCwoGTEFQUkFTEIMB",
"EgoKBURJVFRPEIQBEgoKBUVFVkVFEIUBEg0KCFZBUE9SRU9OEIYBEgwKB0pP",
"TFRFT04QhwESDAoHRkxBUkVPThCIARIMCgdQT1JZR09OEIkBEgwKB09NQU5Z",
"VEUQigESDAoHT01BU1RBUhCLARILCgZLQUJVVE8QjAESDQoIS0FCVVRPUFMQ",
"jQESDwoKQUVST0RBQ1RZTBCOARIMCgdTTk9STEFYEI8BEg0KCEFSVElDVU5P",
"EJABEgsKBlpBUERPUxCRARIMCgdNT0xUUkVTEJIBEgwKB0RSQVRJTkkQkwES",
"DgoJRFJBR09OQUlSEJQBEg4KCURSQUdPTklURRCVARILCgZNRVdUV08QlgES",
"CAoDTUVXEJcBKs4XCgtQb2tlbW9uTW92ZRIOCgpNT1ZFX1VOU0VUEAASEQoN",
"VEhVTkRFUl9TSE9DSxABEhAKDFFVSUNLX0FUVEFDSxACEgsKB1NDUkFUQ0gQ",
"AxIJCgVFTUJFUhAEEg0KCVZJTkVfV0hJUBAFEgoKBlRBQ0tMRRAGEg4KClJB",
"Wk9SX0xFQUYQBxINCglUQUtFX0RPV04QCBINCglXQVRFUl9HVU4QCRIICgRC",
"SVRFEAoSCQoFUE9VTkQQCxIPCgtET1VCTEVfU0xBUBAMEggKBFdSQVAQDRIO",
"CgpIWVBFUl9CRUFNEA4SCAoETElDSxAPEg4KCkRBUktfUFVMU0UQEBIICgRT",
"TU9HEBESCgoGU0xVREdFEBISDgoKTUVUQUxfQ0xBVxATEg0KCVZJQ0VfR1JJ",
"UBAUEg8KC0ZMQU1FX1dIRUVMEBUSDAoITUVHQUhPUk4QFhIPCgtXSU5HX0FU",
"VEFDSxAXEhAKDEZMQU1FVEhST1dFUhAYEhAKDFNVQ0tFUl9QVU5DSBAZEgcK",
"A0RJRxAaEgwKCExPV19LSUNLEBsSDgoKQ1JPU1NfQ0hPUBAcEg4KClBTWUNI",
"T19DVVQQHRILCgdQU1lCRUFNEB4SDgoKRUFSVEhRVUFLRRAfEg4KClNUT05F",
"X0VER0UQIBINCglJQ0VfUFVOQ0gQIRIPCgtIRUFSVF9TVEFNUBAiEg0KCURJ",
"U0NIQVJHRRAjEhAKDEZMQVNIX0NBTk5PThAkEggKBFBFQ0sQJRIOCgpEUklM",
"TF9QRUNLECYSDAoISUNFX0JFQU0QJxIMCghCTElaWkFSRBAoEg0KCUFJUl9T",
"TEFTSBApEg0KCUhFQVRfV0FWRRAqEg0KCVRXSU5FRURMRRArEg4KClBPSVNP",
"Tl9KQUIQLBIOCgpBRVJJQUxfQUNFEC0SDQoJRFJJTExfUlVOEC4SEgoOUEVU",
"QUxfQkxJWlpBUkQQLxIOCgpNRUdBX0RSQUlOEDASDAoIQlVHX0JVWloQMRIP",
"CgtQT0lTT05fRkFORxAyEg8KC05JR0hUX1NMQVNIEDMSCQoFU0xBU0gQNBIP",
"CgtCVUJCTEVfQkVBTRA1Eg4KClNVQk1JU1NJT04QNhIPCgtLQVJBVEVfQ0hP",
"UBA3Eg0KCUxPV19TV0VFUBA4EgwKCEFRVUFfSkVUEDkSDQoJQVFVQV9UQUlM",
"EDoSDQoJU0VFRF9CT01CEDsSDAoIUFNZU0hPQ0sQPBIOCgpST0NLX1RIUk9X",
"ED0SEQoNQU5DSUVOVF9QT1dFUhA+Eg0KCVJPQ0tfVE9NQhA/Eg4KClJPQ0tf",
"U0xJREUQQBINCglQT1dFUl9HRU0QQRIQCgxTSEFET1dfU05FQUsQQhIQCgxT",
"SEFET1dfUFVOQ0gQQxIPCgtTSEFET1dfQ0xBVxBEEhAKDE9NSU5PVVNfV0lO",
"RBBFEg8KC1NIQURPV19CQUxMEEYSEAoMQlVMTEVUX1BVTkNIEEcSDwoLTUFH",
"TkVUX0JPTUIQSBIOCgpTVEVFTF9XSU5HEEkSDQoJSVJPTl9IRUFEEEoSFAoQ",
"UEFSQUJPTElDX0NIQVJHRRBLEgkKBVNQQVJLEEwSEQoNVEhVTkRFUl9QVU5D",
"SBBNEgsKB1RIVU5ERVIQThIPCgtUSFVOREVSQk9MVBBPEgsKB1RXSVNURVIQ",
"UBIRCg1EUkFHT05fQlJFQVRIEFESEAoMRFJBR09OX1BVTFNFEFISDwoLRFJB",
"R09OX0NMQVcQUxITCg9ESVNBUk1JTkdfVk9JQ0UQVBIRCg1EUkFJTklOR19L",
"SVNTEFUSEgoOREFaWkxJTkdfR0xFQU0QVhINCglNT09OQkxBU1QQVxIOCgpQ",
"TEFZX1JPVUdIEFgSEAoMQ1JPU1NfUE9JU09OEFkSDwoLU0xVREdFX0JPTUIQ",
"WhIPCgtTTFVER0VfV0FWRRBbEg0KCUdVTktfU0hPVBBcEgwKCE1VRF9TSE9U",
"EF0SDQoJQk9ORV9DTFVCEF4SDAoIQlVMTERPWkUQXxIMCghNVURfQk9NQhBg",
"Eg8KC0ZVUllfQ1VUVEVSEGESDAoIQlVHX0JJVEUQYhIPCgtTSUdOQUxfQkVB",
"TRBjEg0KCVhfU0NJU1NPUhBkEhAKDEZMQU1FX0NIQVJHRRBlEg8KC0ZMQU1F",
"X0JVUlNUEGYSDgoKRklSRV9CTEFTVBBnEgkKBUJSSU5FEGgSDwoLV0FURVJf",
"UFVMU0UQaRIJCgVTQ0FMRBBqEg4KCkhZRFJPX1BVTVAQaxILCgdQU1lDSElD",
"EGwSDQoJUFNZU1RSSUtFEG0SDQoJSUNFX1NIQVJEEG4SDAoISUNZX1dJTkQQ",
"bxIQCgxGUk9TVF9CUkVBVEgQcBIKCgZBQlNPUkIQcRIOCgpHSUdBX0RSQUlO",
"EHISDgoKRklSRV9QVU5DSBBzEg4KClNPTEFSX0JFQU0QdBIOCgpMRUFGX0JM",
"QURFEHUSDgoKUE9XRVJfV0hJUBB2EgoKBlNQTEFTSBB3EggKBEFDSUQQeBIO",
"CgpBSVJfQ1VUVEVSEHkSDQoJSFVSUklDQU5FEHoSDwoLQlJJQ0tfQlJFQUsQ",
"exIHCgNDVVQQfBIJCgVTV0lGVBB9Eg8KC0hPUk5fQVRUQUNLEH4SCQoFU1RP",
"TVAQfxINCghIRUFEQlVUVBCAARIPCgpIWVBFUl9GQU5HEIEBEgkKBFNMQU0Q",
"ggESDgoJQk9EWV9TTEFNEIMBEgkKBFJFU1QQhAESDQoIU1RSVUdHTEUQhQES",
"FAoPU0NBTERfQkxBU1RPSVNFEIYBEhkKFEhZRFJPX1BVTVBfQkxBU1RPSVNF",
"EIcBEg8KCldSQVBfR1JFRU4QiAESDgoJV1JBUF9QSU5LEIkBEhUKEEZVUllf",
"Q1VUVEVSX0ZBU1QQyAESEgoNQlVHX0JJVEVfRkFTVBDJARIOCglCSVRFX0ZB",
"U1QQygESFgoRU1VDS0VSX1BVTkNIX0ZBU1QQywESFwoSRFJBR09OX0JSRUFU",
"SF9GQVNUEMwBEhcKElRIVU5ERVJfU0hPQ0tfRkFTVBDNARIPCgpTUEFSS19G",
"QVNUEM4BEhIKDUxPV19LSUNLX0ZBU1QQzwESFQoQS0FSQVRFX0NIT1BfRkFT",
"VBDQARIPCgpFTUJFUl9GQVNUENEBEhUKEFdJTkdfQVRUQUNLX0ZBU1QQ0gES",
"DgoJUEVDS19GQVNUENMBEg4KCUxJQ0tfRkFTVBDUARIVChBTSEFET1dfQ0xB",
"V19GQVNUENUBEhMKDlZJTkVfV0hJUF9GQVNUENYBEhQKD1JBWk9SX0xFQUZf",
"RkFTVBDXARISCg1NVURfU0hPVF9GQVNUENgBEhMKDklDRV9TSEFSRF9GQVNU",
"ENkBEhYKEUZST1NUX0JSRUFUSF9GQVNUENoBEhYKEVFVSUNLX0FUVEFDS19G",
"QVNUENsBEhEKDFNDUkFUQ0hfRkFTVBDcARIQCgtUQUNLTEVfRkFTVBDdARIP",
"CgpQT1VORF9GQVNUEN4BEg0KCENVVF9GQVNUEN8BEhQKD1BPSVNPTl9KQUJf",
"RkFTVBDgARIOCglBQ0lEX0ZBU1QQ4QESFAoPUFNZQ0hPX0NVVF9GQVNUEOIB",
"EhQKD1JPQ0tfVEhST1dfRkFTVBDjARIUCg9NRVRBTF9DTEFXX0ZBU1QQ5AES",
"FgoRQlVMTEVUX1BVTkNIX0ZBU1QQ5QESEwoOV0FURVJfR1VOX0ZBU1QQ5gES",
"EAoLU1BMQVNIX0ZBU1QQ5wESHQoYV0FURVJfR1VOX0ZBU1RfQkxBU1RPSVNF",
"EOgBEhIKDU1VRF9TTEFQX0ZBU1QQ6QESFgoRWkVOX0hFQURCVVRUX0ZBU1QQ",
"6gESEwoOQ09ORlVTSU9OX0ZBU1QQ6wESFgoRUE9JU09OX1NUSU5HX0ZBU1QQ",
"7AESEAoLQlVCQkxFX0ZBU1QQ7QESFgoRRkVJTlRfQVRUQUNLX0ZBU1QQ7gES",
"FAoPU1RFRUxfV0lOR19GQVNUEO8BEhMKDkZJUkVfRkFOR19GQVNUEPABEhQK",
"D1JPQ0tfU01BU0hfRkFTVBDxASqtAQoTUG9rZW1vbk1vdmVtZW50VHlwZRIT",
"Cg9NT1ZFTUVOVF9TVEFUSUMQABIRCg1NT1ZFTUVOVF9KVU1QEAESFQoRTU9W",
"RU1FTlRfVkVSVElDQUwQAhIUChBNT1ZFTUVOVF9QU1lDSElDEAMSFQoRTU9W",
"RU1FTlRfRUxFQ1RSSUMQBBITCg9NT1ZFTUVOVF9GTFlJTkcQBRIVChFNT1ZF",
"TUVOVF9IT1ZFUklORxAGKjYKDVBva2Vtb25SYXJpdHkSCgoGTk9STUFMEAAS",
"DQoJTEVHRU5EQVJZEAESCgoGTVlUSElDEAIq2gMKC1Bva2Vtb25UeXBlEhUK",
"EVBPS0VNT05fVFlQRV9OT05FEAASFwoTUE9LRU1PTl9UWVBFX05PUk1BTBAB",
"EhkKFVBPS0VNT05fVFlQRV9GSUdIVElORxACEhcKE1BPS0VNT05fVFlQRV9G",
"TFlJTkcQAxIXChNQT0tFTU9OX1RZUEVfUE9JU09OEAQSFwoTUE9LRU1PTl9U",
"WVBFX0dST1VORBAFEhUKEVBPS0VNT05fVFlQRV9ST0NLEAYSFAoQUE9LRU1P",
"Tl9UWVBFX0JVRxAHEhYKElBPS0VNT05fVFlQRV9HSE9TVBAIEhYKElBPS0VN",
"T05fVFlQRV9TVEVFTBAJEhUKEVBPS0VNT05fVFlQRV9GSVJFEAoSFgoSUE9L",
"RU1PTl9UWVBFX1dBVEVSEAsSFgoSUE9LRU1PTl9UWVBFX0dSQVNTEAwSGQoV",
"UE9LRU1PTl9UWVBFX0VMRUNUUklDEA0SGAoUUE9LRU1PTl9UWVBFX1BTWUNI",
"SUMQDhIUChBQT0tFTU9OX1RZUEVfSUNFEA8SFwoTUE9LRU1PTl9UWVBFX0RS",
"QUdPThAQEhUKEVBPS0VNT05fVFlQRV9EQVJLEBESFgoSUE9LRU1PTl9UWVBF",
"X0ZBSVJZEBIqNwoJVGVhbUNvbG9yEgsKB05FVVRSQUwQABIICgRCTFVFEAES",
"BwoDUkVEEAISCgoGWUVMTE9XEAMq5AEKDVR1dG9yaWFsU3RhdGUSEAoMTEVH",
"QUxfU0NSRUVOEAASFAoQQVZBVEFSX1NFTEVDVElPThABEhQKEEFDQ09VTlRf",
"Q1JFQVRJT04QAhITCg9QT0tFTU9OX0NBUFRVUkUQAxISCg5OQU1FX1NFTEVD",
"VElPThAEEhEKDVBPS0VNT05fQkVSUlkQBRIMCghVU0VfSVRFTRAGEiIKHkZJ",
"UlNUX1RJTUVfRVhQRVJJRU5DRV9DT01QTEVURRAHEhUKEVBPS0VTVE9QX1RV",
"VE9SSUFMEAgSEAoMR1lNX1RVVE9SSUFMEAliBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::POGOProtos.Enums.ActivityType), typeof(global::POGOProtos.Enums.BadgeType), typeof(global::POGOProtos.Enums.CameraInterpolation), typeof(global::POGOProtos.Enums.CameraTarget), typeof(global::POGOProtos.Enums.Gender), typeof(global::POGOProtos.Enums.HoloIapItemCategory), typeof(global::POGOProtos.Enums.ItemCategory), typeof(global::POGOProtos.Enums.ItemEffect), typeof(global::POGOProtos.Enums.Platform), typeof(global::POGOProtos.Enums.PokemonFamilyId), typeof(global::POGOProtos.Enums.PokemonId), typeof(global::POGOProtos.Enums.PokemonMove), typeof(global::POGOProtos.Enums.PokemonMovementType), typeof(global::POGOProtos.Enums.PokemonRarity), typeof(global::POGOProtos.Enums.PokemonType), typeof(global::POGOProtos.Enums.TeamColor), typeof(global::POGOProtos.Enums.TutorialState), }, null));
}
#endregion
}
#region Enums
public enum ActivityType {
[pbr::OriginalName("ACTIVITY_UNKNOWN")] ActivityUnknown = 0,
[pbr::OriginalName("ACTIVITY_CATCH_POKEMON")] ActivityCatchPokemon = 1,
[pbr::OriginalName("ACTIVITY_CATCH_LEGEND_POKEMON")] ActivityCatchLegendPokemon = 2,
[pbr::OriginalName("ACTIVITY_FLEE_POKEMON")] ActivityFleePokemon = 3,
[pbr::OriginalName("ACTIVITY_DEFEAT_FORT")] ActivityDefeatFort = 4,
[pbr::OriginalName("ACTIVITY_EVOLVE_POKEMON")] ActivityEvolvePokemon = 5,
[pbr::OriginalName("ACTIVITY_HATCH_EGG")] ActivityHatchEgg = 6,
[pbr::OriginalName("ACTIVITY_WALK_KM")] ActivityWalkKm = 7,
[pbr::OriginalName("ACTIVITY_POKEDEX_ENTRY_NEW")] ActivityPokedexEntryNew = 8,
[pbr::OriginalName("ACTIVITY_CATCH_FIRST_THROW")] ActivityCatchFirstThrow = 9,
[pbr::OriginalName("ACTIVITY_CATCH_NICE_THROW")] ActivityCatchNiceThrow = 10,
[pbr::OriginalName("ACTIVITY_CATCH_GREAT_THROW")] ActivityCatchGreatThrow = 11,
[pbr::OriginalName("ACTIVITY_CATCH_EXCELLENT_THROW")] ActivityCatchExcellentThrow = 12,
[pbr::OriginalName("ACTIVITY_CATCH_CURVEBALL")] ActivityCatchCurveball = 13,
[pbr::OriginalName("ACTIVITY_CATCH_FIRST_CATCH_OF_DAY")] ActivityCatchFirstCatchOfDay = 14,
[pbr::OriginalName("ACTIVITY_CATCH_MILESTONE")] ActivityCatchMilestone = 15,
[pbr::OriginalName("ACTIVITY_TRAIN_POKEMON")] ActivityTrainPokemon = 16,
[pbr::OriginalName("ACTIVITY_SEARCH_FORT")] ActivitySearchFort = 17,
[pbr::OriginalName("ACTIVITY_RELEASE_POKEMON")] ActivityReleasePokemon = 18,
[pbr::OriginalName("ACTIVITY_HATCH_EGG_SMALL_BONUS")] ActivityHatchEggSmallBonus = 19,
[pbr::OriginalName("ACTIVITY_HATCH_EGG_MEDIUM_BONUS")] ActivityHatchEggMediumBonus = 20,
[pbr::OriginalName("ACTIVITY_HATCH_EGG_LARGE_BONUS")] ActivityHatchEggLargeBonus = 21,
[pbr::OriginalName("ACTIVITY_DEFEAT_GYM_DEFENDER")] ActivityDefeatGymDefender = 22,
[pbr::OriginalName("ACTIVITY_DEFEAT_GYM_LEADER")] ActivityDefeatGymLeader = 23,
}
public enum BadgeType {
[pbr::OriginalName("BADGE_UNSET")] BadgeUnset = 0,
[pbr::OriginalName("BADGE_TRAVEL_KM")] BadgeTravelKm = 1,
[pbr::OriginalName("BADGE_POKEDEX_ENTRIES")] BadgePokedexEntries = 2,
[pbr::OriginalName("BADGE_CAPTURE_TOTAL")] BadgeCaptureTotal = 3,
[pbr::OriginalName("BADGE_DEFEATED_FORT")] BadgeDefeatedFort = 4,
[pbr::OriginalName("BADGE_EVOLVED_TOTAL")] BadgeEvolvedTotal = 5,
[pbr::OriginalName("BADGE_HATCHED_TOTAL")] BadgeHatchedTotal = 6,
[pbr::OriginalName("BADGE_ENCOUNTERED_TOTAL")] BadgeEncounteredTotal = 7,
[pbr::OriginalName("BADGE_POKESTOPS_VISITED")] BadgePokestopsVisited = 8,
[pbr::OriginalName("BADGE_UNIQUE_POKESTOPS")] BadgeUniquePokestops = 9,
[pbr::OriginalName("BADGE_POKEBALL_THROWN")] BadgePokeballThrown = 10,
[pbr::OriginalName("BADGE_BIG_MAGIKARP")] BadgeBigMagikarp = 11,
[pbr::OriginalName("BADGE_DEPLOYED_TOTAL")] BadgeDeployedTotal = 12,
[pbr::OriginalName("BADGE_BATTLE_ATTACK_WON")] BadgeBattleAttackWon = 13,
[pbr::OriginalName("BADGE_BATTLE_TRAINING_WON")] BadgeBattleTrainingWon = 14,
[pbr::OriginalName("BADGE_BATTLE_DEFEND_WON")] BadgeBattleDefendWon = 15,
[pbr::OriginalName("BADGE_PRESTIGE_RAISED")] BadgePrestigeRaised = 16,
[pbr::OriginalName("BADGE_PRESTIGE_DROPPED")] BadgePrestigeDropped = 17,
[pbr::OriginalName("BADGE_TYPE_NORMAL")] Normal = 18,
[pbr::OriginalName("BADGE_TYPE_FIGHTING")] Fighting = 19,
[pbr::OriginalName("BADGE_TYPE_FLYING")] Flying = 20,
[pbr::OriginalName("BADGE_TYPE_POISON")] Poison = 21,
[pbr::OriginalName("BADGE_TYPE_GROUND")] Ground = 22,
[pbr::OriginalName("BADGE_TYPE_ROCK")] Rock = 23,
[pbr::OriginalName("BADGE_TYPE_BUG")] Bug = 24,
[pbr::OriginalName("BADGE_TYPE_GHOST")] Ghost = 25,
[pbr::OriginalName("BADGE_TYPE_STEEL")] Steel = 26,
[pbr::OriginalName("BADGE_TYPE_FIRE")] Fire = 27,
[pbr::OriginalName("BADGE_TYPE_WATER")] Water = 28,
[pbr::OriginalName("BADGE_TYPE_GRASS")] Grass = 29,
[pbr::OriginalName("BADGE_TYPE_ELECTRIC")] Electric = 30,
[pbr::OriginalName("BADGE_TYPE_PSYCHIC")] Psychic = 31,
[pbr::OriginalName("BADGE_TYPE_ICE")] Ice = 32,
[pbr::OriginalName("BADGE_TYPE_DRAGON")] Dragon = 33,
[pbr::OriginalName("BADGE_TYPE_DARK")] Dark = 34,
[pbr::OriginalName("BADGE_TYPE_FAIRY")] Fairy = 35,
[pbr::OriginalName("BADGE_SMALL_RATTATA")] BadgeSmallRattata = 36,
[pbr::OriginalName("BADGE_PIKACHU")] BadgePikachu = 37,
}
public enum CameraInterpolation {
[pbr::OriginalName("CAM_INTERP_CUT")] CamInterpCut = 0,
[pbr::OriginalName("CAM_INTERP_LINEAR")] CamInterpLinear = 1,
[pbr::OriginalName("CAM_INTERP_SMOOTH")] CamInterpSmooth = 2,
[pbr::OriginalName("CAM_INTERP_SMOOTH_ROT_LINEAR_MOVE")] CamInterpSmoothRotLinearMove = 3,
[pbr::OriginalName("CAM_INTERP_DEPENDS")] CamInterpDepends = 4,
}
public enum CameraTarget {
[pbr::OriginalName("CAM_TARGET_ATTACKER")] CamTargetAttacker = 0,
[pbr::OriginalName("CAM_TARGET_ATTACKER_EDGE")] CamTargetAttackerEdge = 1,
[pbr::OriginalName("CAM_TARGET_ATTACKER_GROUND")] CamTargetAttackerGround = 2,
[pbr::OriginalName("CAM_TARGET_DEFENDER")] CamTargetDefender = 3,
[pbr::OriginalName("CAM_TARGET_DEFENDER_EDGE")] CamTargetDefenderEdge = 4,
[pbr::OriginalName("CAM_TARGET_DEFENDER_GROUND")] CamTargetDefenderGround = 5,
[pbr::OriginalName("CAM_TARGET_ATTACKER_DEFENDER")] CamTargetAttackerDefender = 6,
[pbr::OriginalName("CAM_TARGET_ATTACKER_DEFENDER_EDGE")] CamTargetAttackerDefenderEdge = 7,
[pbr::OriginalName("CAM_TARGET_DEFENDER_ATTACKER")] CamTargetDefenderAttacker = 8,
[pbr::OriginalName("CAM_TARGET_DEFENDER_ATTACKER_EDGE")] CamTargetDefenderAttackerEdge = 9,
[pbr::OriginalName("CAM_TARGET_ATTACKER_DEFENDER_MIRROR")] CamTargetAttackerDefenderMirror = 11,
[pbr::OriginalName("CAM_TARGET_SHOULDER_ATTACKER_DEFENDER")] CamTargetShoulderAttackerDefender = 12,
[pbr::OriginalName("CAM_TARGET_SHOULDER_ATTACKER_DEFENDER_MIRROR")] CamTargetShoulderAttackerDefenderMirror = 13,
[pbr::OriginalName("CAM_TARGET_ATTACKER_DEFENDER_WORLD")] CamTargetAttackerDefenderWorld = 14,
}
public enum Gender {
[pbr::OriginalName("MALE")] Male = 0,
[pbr::OriginalName("FEMALE")] Female = 1,
}
public enum HoloIapItemCategory {
[pbr::OriginalName("IAP_CATEGORY_NONE")] IapCategoryNone = 0,
[pbr::OriginalName("IAP_CATEGORY_BUNDLE")] IapCategoryBundle = 1,
[pbr::OriginalName("IAP_CATEGORY_ITEMS")] IapCategoryItems = 2,
[pbr::OriginalName("IAP_CATEGORY_UPGRADES")] IapCategoryUpgrades = 3,
[pbr::OriginalName("IAP_CATEGORY_POKECOINS")] IapCategoryPokecoins = 4,
}
public enum ItemCategory {
[pbr::OriginalName("ITEM_CATEGORY_NONE")] None = 0,
[pbr::OriginalName("ITEM_CATEGORY_POKEBALL")] Pokeball = 1,
[pbr::OriginalName("ITEM_CATEGORY_FOOD")] Food = 2,
[pbr::OriginalName("ITEM_CATEGORY_MEDICINE")] Medicine = 3,
[pbr::OriginalName("ITEM_CATEGORY_BOOST")] Boost = 4,
[pbr::OriginalName("ITEM_CATEGORY_UTILITES")] Utilites = 5,
[pbr::OriginalName("ITEM_CATEGORY_CAMERA")] Camera = 6,
[pbr::OriginalName("ITEM_CATEGORY_DISK")] Disk = 7,
[pbr::OriginalName("ITEM_CATEGORY_INCUBATOR")] Incubator = 8,
[pbr::OriginalName("ITEM_CATEGORY_INCENSE")] Incense = 9,
[pbr::OriginalName("ITEM_CATEGORY_XP_BOOST")] XpBoost = 10,
[pbr::OriginalName("ITEM_CATEGORY_INVENTORY_UPGRADE")] InventoryUpgrade = 11,
}
public enum ItemEffect {
[pbr::OriginalName("ITEM_EFFECT_NONE")] None = 0,
[pbr::OriginalName("ITEM_EFFECT_CAP_NO_FLEE")] CapNoFlee = 1000,
[pbr::OriginalName("ITEM_EFFECT_CAP_NO_MOVEMENT")] CapNoMovement = 1002,
[pbr::OriginalName("ITEM_EFFECT_CAP_NO_THREAT")] CapNoThreat = 1003,
[pbr::OriginalName("ITEM_EFFECT_CAP_TARGET_MAX")] CapTargetMax = 1004,
[pbr::OriginalName("ITEM_EFFECT_CAP_TARGET_SLOW")] CapTargetSlow = 1005,
[pbr::OriginalName("ITEM_EFFECT_CAP_CHANCE_NIGHT")] CapChanceNight = 1006,
[pbr::OriginalName("ITEM_EFFECT_CAP_CHANCE_TRAINER")] CapChanceTrainer = 1007,
[pbr::OriginalName("ITEM_EFFECT_CAP_CHANCE_FIRST_THROW")] CapChanceFirstThrow = 1008,
[pbr::OriginalName("ITEM_EFFECT_CAP_CHANCE_LEGEND")] CapChanceLegend = 1009,
[pbr::OriginalName("ITEM_EFFECT_CAP_CHANCE_HEAVY")] CapChanceHeavy = 1010,
[pbr::OriginalName("ITEM_EFFECT_CAP_CHANCE_REPEAT")] CapChanceRepeat = 1011,
[pbr::OriginalName("ITEM_EFFECT_CAP_CHANCE_MULTI_THROW")] CapChanceMultiThrow = 1012,
[pbr::OriginalName("ITEM_EFFECT_CAP_CHANCE_ALWAYS")] CapChanceAlways = 1013,
[pbr::OriginalName("ITEM_EFFECT_CAP_CHANCE_SINGLE_THROW")] CapChanceSingleThrow = 1014,
}
public enum Platform {
[pbr::OriginalName("UNSET")] Unset = 0,
[pbr::OriginalName("IOS")] Ios = 1,
[pbr::OriginalName("ANDROID")] Android = 2,
[pbr::OriginalName("OSX")] Osx = 3,
[pbr::OriginalName("WINDOWS")] Windows = 4,
}
public enum PokemonFamilyId {
[pbr::OriginalName("FAMILY_UNSET")] FamilyUnset = 0,
[pbr::OriginalName("FAMILY_BULBASAUR")] FamilyBulbasaur = 1,
[pbr::OriginalName("FAMILY_CHARMANDER")] FamilyCharmander = 4,
[pbr::OriginalName("FAMILY_SQUIRTLE")] FamilySquirtle = 7,
[pbr::OriginalName("FAMILY_CATERPIE")] FamilyCaterpie = 10,
[pbr::OriginalName("FAMILY_WEEDLE")] FamilyWeedle = 13,
[pbr::OriginalName("FAMILY_PIDGEY")] FamilyPidgey = 16,
[pbr::OriginalName("FAMILY_RATTATA")] FamilyRattata = 19,
[pbr::OriginalName("FAMILY_SPEAROW")] FamilySpearow = 21,
[pbr::OriginalName("FAMILY_EKANS")] FamilyEkans = 23,
[pbr::OriginalName("FAMILY_PIKACHU")] FamilyPikachu = 25,
[pbr::OriginalName("FAMILY_SANDSHREW")] FamilySandshrew = 27,
[pbr::OriginalName("FAMILY_NIDORAN_FEMALE")] FamilyNidoranFemale = 29,
[pbr::OriginalName("FAMILY_NIDORAN_MALE")] FamilyNidoranMale = 32,
[pbr::OriginalName("FAMILY_CLEFAIRY")] FamilyClefairy = 35,
[pbr::OriginalName("FAMILY_VULPIX")] FamilyVulpix = 37,
[pbr::OriginalName("FAMILY_JIGGLYPUFF")] FamilyJigglypuff = 39,
[pbr::OriginalName("FAMILY_ZUBAT")] FamilyZubat = 41,
[pbr::OriginalName("FAMILY_ODDISH")] FamilyOddish = 43,
[pbr::OriginalName("FAMILY_PARAS")] FamilyParas = 46,
[pbr::OriginalName("FAMILY_VENONAT")] FamilyVenonat = 48,
[pbr::OriginalName("FAMILY_DIGLETT")] FamilyDiglett = 50,
[pbr::OriginalName("FAMILY_MEOWTH")] FamilyMeowth = 52,
[pbr::OriginalName("FAMILY_PSYDUCK")] FamilyPsyduck = 54,
[pbr::OriginalName("FAMILY_MANKEY")] FamilyMankey = 56,
[pbr::OriginalName("FAMILY_GROWLITHE")] FamilyGrowlithe = 58,
[pbr::OriginalName("FAMILY_POLIWAG")] FamilyPoliwag = 60,
[pbr::OriginalName("FAMILY_ABRA")] FamilyAbra = 63,
[pbr::OriginalName("FAMILY_MACHOP")] FamilyMachop = 66,
[pbr::OriginalName("FAMILY_BELLSPROUT")] FamilyBellsprout = 69,
[pbr::OriginalName("FAMILY_TENTACOOL")] FamilyTentacool = 72,
[pbr::OriginalName("FAMILY_GEODUDE")] FamilyGeodude = 74,
[pbr::OriginalName("FAMILY_PONYTA")] FamilyPonyta = 77,
[pbr::OriginalName("FAMILY_SLOWPOKE")] FamilySlowpoke = 79,
[pbr::OriginalName("FAMILY_MAGNEMITE")] FamilyMagnemite = 81,
[pbr::OriginalName("FAMILY_FARFETCHD")] FamilyFarfetchd = 83,
[pbr::OriginalName("FAMILY_DODUO")] FamilyDoduo = 84,
[pbr::OriginalName("FAMILY_SEEL")] FamilySeel = 86,
[pbr::OriginalName("FAMILY_GRIMER")] FamilyGrimer = 88,
[pbr::OriginalName("FAMILY_SHELLDER")] FamilyShellder = 90,
[pbr::OriginalName("FAMILY_GASTLY")] FamilyGastly = 92,
[pbr::OriginalName("FAMILY_ONIX")] FamilyOnix = 95,
[pbr::OriginalName("FAMILY_DROWZEE")] FamilyDrowzee = 96,
[pbr::OriginalName("FAMILY_HYPNO")] FamilyHypno = 97,
[pbr::OriginalName("FAMILY_KRABBY")] FamilyKrabby = 98,
[pbr::OriginalName("FAMILY_VOLTORB")] FamilyVoltorb = 100,
[pbr::OriginalName("FAMILY_EXEGGCUTE")] FamilyExeggcute = 102,
[pbr::OriginalName("FAMILY_CUBONE")] FamilyCubone = 104,
[pbr::OriginalName("FAMILY_HITMONLEE")] FamilyHitmonlee = 106,
[pbr::OriginalName("FAMILY_HITMONCHAN")] FamilyHitmonchan = 107,
[pbr::OriginalName("FAMILY_LICKITUNG")] FamilyLickitung = 108,
[pbr::OriginalName("FAMILY_KOFFING")] FamilyKoffing = 109,
[pbr::OriginalName("FAMILY_RHYHORN")] FamilyRhyhorn = 111,
[pbr::OriginalName("FAMILY_CHANSEY")] FamilyChansey = 113,
[pbr::OriginalName("FAMILY_TANGELA")] FamilyTangela = 114,
[pbr::OriginalName("FAMILY_KANGASKHAN")] FamilyKangaskhan = 115,
[pbr::OriginalName("FAMILY_HORSEA")] FamilyHorsea = 116,
[pbr::OriginalName("FAMILY_GOLDEEN")] FamilyGoldeen = 118,
[pbr::OriginalName("FAMILY_STARYU")] FamilyStaryu = 120,
[pbr::OriginalName("FAMILY_MR_MIME")] FamilyMrMime = 122,
[pbr::OriginalName("FAMILY_SCYTHER")] FamilyScyther = 123,
[pbr::OriginalName("FAMILY_JYNX")] FamilyJynx = 124,
[pbr::OriginalName("FAMILY_ELECTABUZZ")] FamilyElectabuzz = 125,
[pbr::OriginalName("FAMILY_MAGMAR")] FamilyMagmar = 126,
[pbr::OriginalName("FAMILY_PINSIR")] FamilyPinsir = 127,
[pbr::OriginalName("FAMILY_TAUROS")] FamilyTauros = 128,
[pbr::OriginalName("FAMILY_MAGIKARP")] FamilyMagikarp = 129,
[pbr::OriginalName("FAMILY_LAPRAS")] FamilyLapras = 131,
[pbr::OriginalName("FAMILY_DITTO")] FamilyDitto = 132,
[pbr::OriginalName("FAMILY_EEVEE")] FamilyEevee = 133,
[pbr::OriginalName("FAMILY_PORYGON")] FamilyPorygon = 137,
[pbr::OriginalName("FAMILY_OMANYTE")] FamilyOmanyte = 138,
[pbr::OriginalName("FAMILY_KABUTO")] FamilyKabuto = 140,
[pbr::OriginalName("FAMILY_AERODACTYL")] FamilyAerodactyl = 142,
[pbr::OriginalName("FAMILY_SNORLAX")] FamilySnorlax = 143,
[pbr::OriginalName("FAMILY_ARTICUNO")] FamilyArticuno = 144,
[pbr::OriginalName("FAMILY_ZAPDOS")] FamilyZapdos = 145,
[pbr::OriginalName("FAMILY_MOLTRES")] FamilyMoltres = 146,
[pbr::OriginalName("FAMILY_DRATINI")] FamilyDratini = 147,
[pbr::OriginalName("FAMILY_MEWTWO")] FamilyMewtwo = 150,
[pbr::OriginalName("FAMILY_MEW")] FamilyMew = 151,
}
public enum PokemonId {
[pbr::OriginalName("MISSINGNO")] Missingno = 0,
[pbr::OriginalName("BULBASAUR")] Bulbasaur = 1,
[pbr::OriginalName("IVYSAUR")] Ivysaur = 2,
[pbr::OriginalName("VENUSAUR")] Venusaur = 3,
[pbr::OriginalName("CHARMANDER")] Charmander = 4,
[pbr::OriginalName("CHARMELEON")] Charmeleon = 5,
[pbr::OriginalName("CHARIZARD")] Charizard = 6,
[pbr::OriginalName("SQUIRTLE")] Squirtle = 7,
[pbr::OriginalName("WARTORTLE")] Wartortle = 8,
[pbr::OriginalName("BLASTOISE")] Blastoise = 9,
[pbr::OriginalName("CATERPIE")] Caterpie = 10,
[pbr::OriginalName("METAPOD")] Metapod = 11,
[pbr::OriginalName("BUTTERFREE")] Butterfree = 12,
[pbr::OriginalName("WEEDLE")] Weedle = 13,
[pbr::OriginalName("KAKUNA")] Kakuna = 14,
[pbr::OriginalName("BEEDRILL")] Beedrill = 15,
[pbr::OriginalName("PIDGEY")] Pidgey = 16,
[pbr::OriginalName("PIDGEOTTO")] Pidgeotto = 17,
[pbr::OriginalName("PIDGEOT")] Pidgeot = 18,
[pbr::OriginalName("RATTATA")] Rattata = 19,
[pbr::OriginalName("RATICATE")] Raticate = 20,
[pbr::OriginalName("SPEAROW")] Spearow = 21,
[pbr::OriginalName("FEAROW")] Fearow = 22,
[pbr::OriginalName("EKANS")] Ekans = 23,
[pbr::OriginalName("ARBOK")] Arbok = 24,
[pbr::OriginalName("PIKACHU")] Pikachu = 25,
[pbr::OriginalName("RAICHU")] Raichu = 26,
[pbr::OriginalName("SANDSHREW")] Sandshrew = 27,
[pbr::OriginalName("SANDSLASH")] Sandslash = 28,
[pbr::OriginalName("NIDORAN_FEMALE")] NidoranFemale = 29,
[pbr::OriginalName("NIDORINA")] Nidorina = 30,
[pbr::OriginalName("NIDOQUEEN")] Nidoqueen = 31,
[pbr::OriginalName("NIDORAN_MALE")] NidoranMale = 32,
[pbr::OriginalName("NIDORINO")] Nidorino = 33,
[pbr::OriginalName("NIDOKING")] Nidoking = 34,
[pbr::OriginalName("CLEFAIRY")] Clefairy = 35,
[pbr::OriginalName("CLEFABLE")] Clefable = 36,
[pbr::OriginalName("VULPIX")] Vulpix = 37,
[pbr::OriginalName("NINETALES")] Ninetales = 38,
[pbr::OriginalName("JIGGLYPUFF")] Jigglypuff = 39,
[pbr::OriginalName("WIGGLYTUFF")] Wigglytuff = 40,
[pbr::OriginalName("ZUBAT")] Zubat = 41,
[pbr::OriginalName("GOLBAT")] Golbat = 42,
[pbr::OriginalName("ODDISH")] Oddish = 43,
[pbr::OriginalName("GLOOM")] Gloom = 44,
[pbr::OriginalName("VILEPLUME")] Vileplume = 45,
[pbr::OriginalName("PARAS")] Paras = 46,
[pbr::OriginalName("PARASECT")] Parasect = 47,
[pbr::OriginalName("VENONAT")] Venonat = 48,
[pbr::OriginalName("VENOMOTH")] Venomoth = 49,
[pbr::OriginalName("DIGLETT")] Diglett = 50,
[pbr::OriginalName("DUGTRIO")] Dugtrio = 51,
[pbr::OriginalName("MEOWTH")] Meowth = 52,
[pbr::OriginalName("PERSIAN")] Persian = 53,
[pbr::OriginalName("PSYDUCK")] Psyduck = 54,
[pbr::OriginalName("GOLDUCK")] Golduck = 55,
[pbr::OriginalName("MANKEY")] Mankey = 56,
[pbr::OriginalName("PRIMEAPE")] Primeape = 57,
[pbr::OriginalName("GROWLITHE")] Growlithe = 58,
[pbr::OriginalName("ARCANINE")] Arcanine = 59,
[pbr::OriginalName("POLIWAG")] Poliwag = 60,
[pbr::OriginalName("POLIWHIRL")] Poliwhirl = 61,
[pbr::OriginalName("POLIWRATH")] Poliwrath = 62,
[pbr::OriginalName("ABRA")] Abra = 63,
[pbr::OriginalName("KADABRA")] Kadabra = 64,
[pbr::OriginalName("ALAKAZAM")] Alakazam = 65,
[pbr::OriginalName("MACHOP")] Machop = 66,
[pbr::OriginalName("MACHOKE")] Machoke = 67,
[pbr::OriginalName("MACHAMP")] Machamp = 68,
[pbr::OriginalName("BELLSPROUT")] Bellsprout = 69,
[pbr::OriginalName("WEEPINBELL")] Weepinbell = 70,
[pbr::OriginalName("VICTREEBEL")] Victreebel = 71,
[pbr::OriginalName("TENTACOOL")] Tentacool = 72,
[pbr::OriginalName("TENTACRUEL")] Tentacruel = 73,
[pbr::OriginalName("GEODUDE")] Geodude = 74,
[pbr::OriginalName("GRAVELER")] Graveler = 75,
[pbr::OriginalName("GOLEM")] Golem = 76,
[pbr::OriginalName("PONYTA")] Ponyta = 77,
[pbr::OriginalName("RAPIDASH")] Rapidash = 78,
[pbr::OriginalName("SLOWPOKE")] Slowpoke = 79,
[pbr::OriginalName("SLOWBRO")] Slowbro = 80,
[pbr::OriginalName("MAGNEMITE")] Magnemite = 81,
[pbr::OriginalName("MAGNETON")] Magneton = 82,
[pbr::OriginalName("FARFETCHD")] Farfetchd = 83,
[pbr::OriginalName("DODUO")] Doduo = 84,
[pbr::OriginalName("DODRIO")] Dodrio = 85,
[pbr::OriginalName("SEEL")] Seel = 86,
[pbr::OriginalName("DEWGONG")] Dewgong = 87,
[pbr::OriginalName("GRIMER")] Grimer = 88,
[pbr::OriginalName("MUK")] Muk = 89,
[pbr::OriginalName("SHELLDER")] Shellder = 90,
[pbr::OriginalName("CLOYSTER")] Cloyster = 91,
[pbr::OriginalName("GASTLY")] Gastly = 92,
[pbr::OriginalName("HAUNTER")] Haunter = 93,
[pbr::OriginalName("GENGAR")] Gengar = 94,
[pbr::OriginalName("ONIX")] Onix = 95,
[pbr::OriginalName("DROWZEE")] Drowzee = 96,
[pbr::OriginalName("HYPNO")] Hypno = 97,
[pbr::OriginalName("KRABBY")] Krabby = 98,
[pbr::OriginalName("KINGLER")] Kingler = 99,
[pbr::OriginalName("VOLTORB")] Voltorb = 100,
[pbr::OriginalName("ELECTRODE")] Electrode = 101,
[pbr::OriginalName("EXEGGCUTE")] Exeggcute = 102,
[pbr::OriginalName("EXEGGUTOR")] Exeggutor = 103,
[pbr::OriginalName("CUBONE")] Cubone = 104,
[pbr::OriginalName("MAROWAK")] Marowak = 105,
[pbr::OriginalName("HITMONLEE")] Hitmonlee = 106,
[pbr::OriginalName("HITMONCHAN")] Hitmonchan = 107,
[pbr::OriginalName("LICKITUNG")] Lickitung = 108,
[pbr::OriginalName("KOFFING")] Koffing = 109,
[pbr::OriginalName("WEEZING")] Weezing = 110,
[pbr::OriginalName("RHYHORN")] Rhyhorn = 111,
[pbr::OriginalName("RHYDON")] Rhydon = 112,
[pbr::OriginalName("CHANSEY")] Chansey = 113,
[pbr::OriginalName("TANGELA")] Tangela = 114,
[pbr::OriginalName("KANGASKHAN")] Kangaskhan = 115,
[pbr::OriginalName("HORSEA")] Horsea = 116,
[pbr::OriginalName("SEADRA")] Seadra = 117,
[pbr::OriginalName("GOLDEEN")] Goldeen = 118,
[pbr::OriginalName("SEAKING")] Seaking = 119,
[pbr::OriginalName("STARYU")] Staryu = 120,
[pbr::OriginalName("STARMIE")] Starmie = 121,
[pbr::OriginalName("MR_MIME")] MrMime = 122,
[pbr::OriginalName("SCYTHER")] Scyther = 123,
[pbr::OriginalName("JYNX")] Jynx = 124,
[pbr::OriginalName("ELECTABUZZ")] Electabuzz = 125,
[pbr::OriginalName("MAGMAR")] Magmar = 126,
[pbr::OriginalName("PINSIR")] Pinsir = 127,
[pbr::OriginalName("TAUROS")] Tauros = 128,
[pbr::OriginalName("MAGIKARP")] Magikarp = 129,
[pbr::OriginalName("GYARADOS")] Gyarados = 130,
[pbr::OriginalName("LAPRAS")] Lapras = 131,
[pbr::OriginalName("DITTO")] Ditto = 132,
[pbr::OriginalName("EEVEE")] Eevee = 133,
[pbr::OriginalName("VAPOREON")] Vaporeon = 134,
[pbr::OriginalName("JOLTEON")] Jolteon = 135,
[pbr::OriginalName("FLAREON")] Flareon = 136,
[pbr::OriginalName("PORYGON")] Porygon = 137,
[pbr::OriginalName("OMANYTE")] Omanyte = 138,
[pbr::OriginalName("OMASTAR")] Omastar = 139,
[pbr::OriginalName("KABUTO")] Kabuto = 140,
[pbr::OriginalName("KABUTOPS")] Kabutops = 141,
[pbr::OriginalName("AERODACTYL")] Aerodactyl = 142,
[pbr::OriginalName("SNORLAX")] Snorlax = 143,
[pbr::OriginalName("ARTICUNO")] Articuno = 144,
[pbr::OriginalName("ZAPDOS")] Zapdos = 145,
[pbr::OriginalName("MOLTRES")] Moltres = 146,
[pbr::OriginalName("DRATINI")] Dratini = 147,
[pbr::OriginalName("DRAGONAIR")] Dragonair = 148,
[pbr::OriginalName("DRAGONITE")] Dragonite = 149,
[pbr::OriginalName("MEWTWO")] Mewtwo = 150,
[pbr::OriginalName("MEW")] Mew = 151,
}
public enum PokemonMove {
[pbr::OriginalName("MOVE_UNSET")] MoveUnset = 0,
[pbr::OriginalName("THUNDER_SHOCK")] ThunderShock = 1,
[pbr::OriginalName("QUICK_ATTACK")] QuickAttack = 2,
[pbr::OriginalName("SCRATCH")] Scratch = 3,
[pbr::OriginalName("EMBER")] Ember = 4,
[pbr::OriginalName("VINE_WHIP")] VineWhip = 5,
[pbr::OriginalName("TACKLE")] Tackle = 6,
[pbr::OriginalName("RAZOR_LEAF")] RazorLeaf = 7,
[pbr::OriginalName("TAKE_DOWN")] TakeDown = 8,
[pbr::OriginalName("WATER_GUN")] WaterGun = 9,
[pbr::OriginalName("BITE")] Bite = 10,
[pbr::OriginalName("POUND")] Pound = 11,
[pbr::OriginalName("DOUBLE_SLAP")] DoubleSlap = 12,
[pbr::OriginalName("WRAP")] Wrap = 13,
[pbr::OriginalName("HYPER_BEAM")] HyperBeam = 14,
[pbr::OriginalName("LICK")] Lick = 15,
[pbr::OriginalName("DARK_PULSE")] DarkPulse = 16,
[pbr::OriginalName("SMOG")] Smog = 17,
[pbr::OriginalName("SLUDGE")] Sludge = 18,
[pbr::OriginalName("METAL_CLAW")] MetalClaw = 19,
[pbr::OriginalName("VICE_GRIP")] ViceGrip = 20,
[pbr::OriginalName("FLAME_WHEEL")] FlameWheel = 21,
[pbr::OriginalName("MEGAHORN")] Megahorn = 22,
[pbr::OriginalName("WING_ATTACK")] WingAttack = 23,
[pbr::OriginalName("FLAMETHROWER")] Flamethrower = 24,
[pbr::OriginalName("SUCKER_PUNCH")] SuckerPunch = 25,
[pbr::OriginalName("DIG")] Dig = 26,
[pbr::OriginalName("LOW_KICK")] LowKick = 27,
[pbr::OriginalName("CROSS_CHOP")] CrossChop = 28,
[pbr::OriginalName("PSYCHO_CUT")] PsychoCut = 29,
[pbr::OriginalName("PSYBEAM")] Psybeam = 30,
[pbr::OriginalName("EARTHQUAKE")] Earthquake = 31,
[pbr::OriginalName("STONE_EDGE")] StoneEdge = 32,
[pbr::OriginalName("ICE_PUNCH")] IcePunch = 33,
[pbr::OriginalName("HEART_STAMP")] HeartStamp = 34,
[pbr::OriginalName("DISCHARGE")] Discharge = 35,
[pbr::OriginalName("FLASH_CANNON")] FlashCannon = 36,
[pbr::OriginalName("PECK")] Peck = 37,
[pbr::OriginalName("DRILL_PECK")] DrillPeck = 38,
[pbr::OriginalName("ICE_BEAM")] IceBeam = 39,
[pbr::OriginalName("BLIZZARD")] Blizzard = 40,
[pbr::OriginalName("AIR_SLASH")] AirSlash = 41,
[pbr::OriginalName("HEAT_WAVE")] HeatWave = 42,
[pbr::OriginalName("TWINEEDLE")] Twineedle = 43,
[pbr::OriginalName("POISON_JAB")] PoisonJab = 44,
[pbr::OriginalName("AERIAL_ACE")] AerialAce = 45,
[pbr::OriginalName("DRILL_RUN")] DrillRun = 46,
[pbr::OriginalName("PETAL_BLIZZARD")] PetalBlizzard = 47,
[pbr::OriginalName("MEGA_DRAIN")] MegaDrain = 48,
[pbr::OriginalName("BUG_BUZZ")] BugBuzz = 49,
[pbr::OriginalName("POISON_FANG")] PoisonFang = 50,
[pbr::OriginalName("NIGHT_SLASH")] NightSlash = 51,
[pbr::OriginalName("SLASH")] Slash = 52,
[pbr::OriginalName("BUBBLE_BEAM")] BubbleBeam = 53,
[pbr::OriginalName("SUBMISSION")] Submission = 54,
[pbr::OriginalName("KARATE_CHOP")] KarateChop = 55,
[pbr::OriginalName("LOW_SWEEP")] LowSweep = 56,
[pbr::OriginalName("AQUA_JET")] AquaJet = 57,
[pbr::OriginalName("AQUA_TAIL")] AquaTail = 58,
[pbr::OriginalName("SEED_BOMB")] SeedBomb = 59,
[pbr::OriginalName("PSYSHOCK")] Psyshock = 60,
[pbr::OriginalName("ROCK_THROW")] RockThrow = 61,
[pbr::OriginalName("ANCIENT_POWER")] AncientPower = 62,
[pbr::OriginalName("ROCK_TOMB")] RockTomb = 63,
[pbr::OriginalName("ROCK_SLIDE")] RockSlide = 64,
[pbr::OriginalName("POWER_GEM")] PowerGem = 65,
[pbr::OriginalName("SHADOW_SNEAK")] ShadowSneak = 66,
[pbr::OriginalName("SHADOW_PUNCH")] ShadowPunch = 67,
[pbr::OriginalName("SHADOW_CLAW")] ShadowClaw = 68,
[pbr::OriginalName("OMINOUS_WIND")] OminousWind = 69,
[pbr::OriginalName("SHADOW_BALL")] ShadowBall = 70,
[pbr::OriginalName("BULLET_PUNCH")] BulletPunch = 71,
[pbr::OriginalName("MAGNET_BOMB")] MagnetBomb = 72,
[pbr::OriginalName("STEEL_WING")] SteelWing = 73,
[pbr::OriginalName("IRON_HEAD")] IronHead = 74,
[pbr::OriginalName("PARABOLIC_CHARGE")] ParabolicCharge = 75,
[pbr::OriginalName("SPARK")] Spark = 76,
[pbr::OriginalName("THUNDER_PUNCH")] ThunderPunch = 77,
[pbr::OriginalName("THUNDER")] Thunder = 78,
[pbr::OriginalName("THUNDERBOLT")] Thunderbolt = 79,
[pbr::OriginalName("TWISTER")] Twister = 80,
[pbr::OriginalName("DRAGON_BREATH")] DragonBreath = 81,
[pbr::OriginalName("DRAGON_PULSE")] DragonPulse = 82,
[pbr::OriginalName("DRAGON_CLAW")] DragonClaw = 83,
[pbr::OriginalName("DISARMING_VOICE")] DisarmingVoice = 84,
[pbr::OriginalName("DRAINING_KISS")] DrainingKiss = 85,
[pbr::OriginalName("DAZZLING_GLEAM")] DazzlingGleam = 86,
[pbr::OriginalName("MOONBLAST")] Moonblast = 87,
[pbr::OriginalName("PLAY_ROUGH")] PlayRough = 88,
[pbr::OriginalName("CROSS_POISON")] CrossPoison = 89,
[pbr::OriginalName("SLUDGE_BOMB")] SludgeBomb = 90,
[pbr::OriginalName("SLUDGE_WAVE")] SludgeWave = 91,
[pbr::OriginalName("GUNK_SHOT")] GunkShot = 92,
[pbr::OriginalName("MUD_SHOT")] MudShot = 93,
[pbr::OriginalName("BONE_CLUB")] BoneClub = 94,
[pbr::OriginalName("BULLDOZE")] Bulldoze = 95,
[pbr::OriginalName("MUD_BOMB")] MudBomb = 96,
[pbr::OriginalName("FURY_CUTTER")] FuryCutter = 97,
[pbr::OriginalName("BUG_BITE")] BugBite = 98,
[pbr::OriginalName("SIGNAL_BEAM")] SignalBeam = 99,
[pbr::OriginalName("X_SCISSOR")] XScissor = 100,
[pbr::OriginalName("FLAME_CHARGE")] FlameCharge = 101,
[pbr::OriginalName("FLAME_BURST")] FlameBurst = 102,
[pbr::OriginalName("FIRE_BLAST")] FireBlast = 103,
[pbr::OriginalName("BRINE")] Brine = 104,
[pbr::OriginalName("WATER_PULSE")] WaterPulse = 105,
[pbr::OriginalName("SCALD")] Scald = 106,
[pbr::OriginalName("HYDRO_PUMP")] HydroPump = 107,
[pbr::OriginalName("PSYCHIC")] Psychic = 108,
[pbr::OriginalName("PSYSTRIKE")] Psystrike = 109,
[pbr::OriginalName("ICE_SHARD")] IceShard = 110,
[pbr::OriginalName("ICY_WIND")] IcyWind = 111,
[pbr::OriginalName("FROST_BREATH")] FrostBreath = 112,
[pbr::OriginalName("ABSORB")] Absorb = 113,
[pbr::OriginalName("GIGA_DRAIN")] GigaDrain = 114,
[pbr::OriginalName("FIRE_PUNCH")] FirePunch = 115,
[pbr::OriginalName("SOLAR_BEAM")] SolarBeam = 116,
[pbr::OriginalName("LEAF_BLADE")] LeafBlade = 117,
[pbr::OriginalName("POWER_WHIP")] PowerWhip = 118,
[pbr::OriginalName("SPLASH")] Splash = 119,
[pbr::OriginalName("ACID")] Acid = 120,
[pbr::OriginalName("AIR_CUTTER")] AirCutter = 121,
[pbr::OriginalName("HURRICANE")] Hurricane = 122,
[pbr::OriginalName("BRICK_BREAK")] BrickBreak = 123,
[pbr::OriginalName("CUT")] Cut = 124,
[pbr::OriginalName("SWIFT")] Swift = 125,
[pbr::OriginalName("HORN_ATTACK")] HornAttack = 126,
[pbr::OriginalName("STOMP")] Stomp = 127,
[pbr::OriginalName("HEADBUTT")] Headbutt = 128,
[pbr::OriginalName("HYPER_FANG")] HyperFang = 129,
[pbr::OriginalName("SLAM")] Slam = 130,
[pbr::OriginalName("BODY_SLAM")] BodySlam = 131,
[pbr::OriginalName("REST")] Rest = 132,
[pbr::OriginalName("STRUGGLE")] Struggle = 133,
[pbr::OriginalName("SCALD_BLASTOISE")] ScaldBlastoise = 134,
[pbr::OriginalName("HYDRO_PUMP_BLASTOISE")] HydroPumpBlastoise = 135,
[pbr::OriginalName("WRAP_GREEN")] WrapGreen = 136,
[pbr::OriginalName("WRAP_PINK")] WrapPink = 137,
[pbr::OriginalName("FURY_CUTTER_FAST")] FuryCutterFast = 200,
[pbr::OriginalName("BUG_BITE_FAST")] BugBiteFast = 201,
[pbr::OriginalName("BITE_FAST")] BiteFast = 202,
[pbr::OriginalName("SUCKER_PUNCH_FAST")] SuckerPunchFast = 203,
[pbr::OriginalName("DRAGON_BREATH_FAST")] DragonBreathFast = 204,
[pbr::OriginalName("THUNDER_SHOCK_FAST")] ThunderShockFast = 205,
[pbr::OriginalName("SPARK_FAST")] SparkFast = 206,
[pbr::OriginalName("LOW_KICK_FAST")] LowKickFast = 207,
[pbr::OriginalName("KARATE_CHOP_FAST")] KarateChopFast = 208,
[pbr::OriginalName("EMBER_FAST")] EmberFast = 209,
[pbr::OriginalName("WING_ATTACK_FAST")] WingAttackFast = 210,
[pbr::OriginalName("PECK_FAST")] PeckFast = 211,
[pbr::OriginalName("LICK_FAST")] LickFast = 212,
[pbr::OriginalName("SHADOW_CLAW_FAST")] ShadowClawFast = 213,
[pbr::OriginalName("VINE_WHIP_FAST")] VineWhipFast = 214,
[pbr::OriginalName("RAZOR_LEAF_FAST")] RazorLeafFast = 215,
[pbr::OriginalName("MUD_SHOT_FAST")] MudShotFast = 216,
[pbr::OriginalName("ICE_SHARD_FAST")] IceShardFast = 217,
[pbr::OriginalName("FROST_BREATH_FAST")] FrostBreathFast = 218,
[pbr::OriginalName("QUICK_ATTACK_FAST")] QuickAttackFast = 219,
[pbr::OriginalName("SCRATCH_FAST")] ScratchFast = 220,
[pbr::OriginalName("TACKLE_FAST")] TackleFast = 221,
[pbr::OriginalName("POUND_FAST")] PoundFast = 222,
[pbr::OriginalName("CUT_FAST")] CutFast = 223,
[pbr::OriginalName("POISON_JAB_FAST")] PoisonJabFast = 224,
[pbr::OriginalName("ACID_FAST")] AcidFast = 225,
[pbr::OriginalName("PSYCHO_CUT_FAST")] PsychoCutFast = 226,
[pbr::OriginalName("ROCK_THROW_FAST")] RockThrowFast = 227,
[pbr::OriginalName("METAL_CLAW_FAST")] MetalClawFast = 228,
[pbr::OriginalName("BULLET_PUNCH_FAST")] BulletPunchFast = 229,
[pbr::OriginalName("WATER_GUN_FAST")] WaterGunFast = 230,
[pbr::OriginalName("SPLASH_FAST")] SplashFast = 231,
[pbr::OriginalName("WATER_GUN_FAST_BLASTOISE")] WaterGunFastBlastoise = 232,
[pbr::OriginalName("MUD_SLAP_FAST")] MudSlapFast = 233,
[pbr::OriginalName("ZEN_HEADBUTT_FAST")] ZenHeadbuttFast = 234,
[pbr::OriginalName("CONFUSION_FAST")] ConfusionFast = 235,
[pbr::OriginalName("POISON_STING_FAST")] PoisonStingFast = 236,
[pbr::OriginalName("BUBBLE_FAST")] BubbleFast = 237,
[pbr::OriginalName("FEINT_ATTACK_FAST")] FeintAttackFast = 238,
[pbr::OriginalName("STEEL_WING_FAST")] SteelWingFast = 239,
[pbr::OriginalName("FIRE_FANG_FAST")] FireFangFast = 240,
[pbr::OriginalName("ROCK_SMASH_FAST")] RockSmashFast = 241,
}
public enum PokemonMovementType {
[pbr::OriginalName("MOVEMENT_STATIC")] MovementStatic = 0,
[pbr::OriginalName("MOVEMENT_JUMP")] MovementJump = 1,
[pbr::OriginalName("MOVEMENT_VERTICAL")] MovementVertical = 2,
[pbr::OriginalName("MOVEMENT_PSYCHIC")] MovementPsychic = 3,
[pbr::OriginalName("MOVEMENT_ELECTRIC")] MovementElectric = 4,
[pbr::OriginalName("MOVEMENT_FLYING")] MovementFlying = 5,
[pbr::OriginalName("MOVEMENT_HOVERING")] MovementHovering = 6,
}
public enum PokemonRarity {
[pbr::OriginalName("NORMAL")] Normal = 0,
[pbr::OriginalName("LEGENDARY")] Legendary = 1,
[pbr::OriginalName("MYTHIC")] Mythic = 2,
}
public enum PokemonType {
[pbr::OriginalName("POKEMON_TYPE_NONE")] None = 0,
[pbr::OriginalName("POKEMON_TYPE_NORMAL")] Normal = 1,
[pbr::OriginalName("POKEMON_TYPE_FIGHTING")] Fighting = 2,
[pbr::OriginalName("POKEMON_TYPE_FLYING")] Flying = 3,
[pbr::OriginalName("POKEMON_TYPE_POISON")] Poison = 4,
[pbr::OriginalName("POKEMON_TYPE_GROUND")] Ground = 5,
[pbr::OriginalName("POKEMON_TYPE_ROCK")] Rock = 6,
[pbr::OriginalName("POKEMON_TYPE_BUG")] Bug = 7,
[pbr::OriginalName("POKEMON_TYPE_GHOST")] Ghost = 8,
[pbr::OriginalName("POKEMON_TYPE_STEEL")] Steel = 9,
[pbr::OriginalName("POKEMON_TYPE_FIRE")] Fire = 10,
[pbr::OriginalName("POKEMON_TYPE_WATER")] Water = 11,
[pbr::OriginalName("POKEMON_TYPE_GRASS")] Grass = 12,
[pbr::OriginalName("POKEMON_TYPE_ELECTRIC")] Electric = 13,
[pbr::OriginalName("POKEMON_TYPE_PSYCHIC")] Psychic = 14,
[pbr::OriginalName("POKEMON_TYPE_ICE")] Ice = 15,
[pbr::OriginalName("POKEMON_TYPE_DRAGON")] Dragon = 16,
[pbr::OriginalName("POKEMON_TYPE_DARK")] Dark = 17,
[pbr::OriginalName("POKEMON_TYPE_FAIRY")] Fairy = 18,
}
public enum TeamColor {
[pbr::OriginalName("NEUTRAL")] Neutral = 0,
[pbr::OriginalName("BLUE")] Blue = 1,
[pbr::OriginalName("RED")] Red = 2,
[pbr::OriginalName("YELLOW")] Yellow = 3,
}
public enum TutorialState {
[pbr::OriginalName("LEGAL_SCREEN")] LegalScreen = 0,
[pbr::OriginalName("AVATAR_SELECTION")] AvatarSelection = 1,
[pbr::OriginalName("ACCOUNT_CREATION")] AccountCreation = 2,
[pbr::OriginalName("POKEMON_CAPTURE")] PokemonCapture = 3,
[pbr::OriginalName("NAME_SELECTION")] NameSelection = 4,
[pbr::OriginalName("POKEMON_BERRY")] PokemonBerry = 5,
[pbr::OriginalName("USE_ITEM")] UseItem = 6,
[pbr::OriginalName("FIRST_TIME_EXPERIENCE_COMPLETE")] FirstTimeExperienceComplete = 7,
[pbr::OriginalName("POKESTOP_TUTORIAL")] PokestopTutorial = 8,
[pbr::OriginalName("GYM_TUTORIAL")] GymTutorial = 9,
}
#endregion
}
#endregion Designer generated code
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace PersonalizedSearchResultsWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
// 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.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
[OuterLoop]
public partial class ParallelQueryCombinationTests
{
private const int DefaultStart = 8;
private const int DefaultSize = 16;
private const int CountFactor = 8;
private const int GroupFactor = 8;
private static IEnumerable<LabeledOperation> UnorderedRangeSources()
{
// The difference between this and the existing sources is more control is needed over the range creation.
// Specifically, start/count won't be known until the nesting level is resolved at runtime.
yield return Label("ParallelEnumerable.Range", (start, count, ignore) => ParallelEnumerable.Range(start, count));
yield return Label("Enumerable.Range", (start, count, ignore) => Enumerable.Range(start, count).AsParallel());
yield return Label("Array", (start, count, ignore) => UnorderedSources.GetRangeArray(start, count).AsParallel());
yield return Label("Partitioner", (start, count, ignore) => Partitioner.Create(UnorderedSources.GetRangeArray(start, count)).AsParallel());
yield return Label("List", (start, count, ignore) => UnorderedSources.GetRangeArray(start, count).ToList().AsParallel());
yield return Label("ReadOnlyCollection", (start, count, ignore) => new ReadOnlyCollection<int>(UnorderedSources.GetRangeArray(start, count).ToList()).AsParallel());
}
private static IEnumerable<LabeledOperation> RangeSources()
{
foreach (LabeledOperation source in UnorderedRangeSources())
{
foreach (LabeledOperation ordering in new[] { AsOrdered }.Concat(OrderOperators()))
{
yield return source.Append(ordering);
}
}
}
private static IEnumerable<LabeledOperation> OrderOperators()
{
yield return Label("OrderBy", (start, count, source) => source(start, count).OrderBy(x => -x, ReverseComparer.Instance));
yield return Label("OrderByDescending", (start, count, source) => source(start, count).OrderByDescending(x => x, ReverseComparer.Instance));
yield return Label("ThenBy", (start, count, source) => source(start, count).OrderBy(x => 0).ThenBy(x => -x, ReverseComparer.Instance));
yield return Label("ThenByDescending", (start, count, source) => source(start, count).OrderBy(x => 0).ThenByDescending(x => x, ReverseComparer.Instance));
}
public static IEnumerable<object[]> OrderFailingOperators()
{
LabeledOperation source = UnorderedRangeSources().First();
foreach (LabeledOperation operation in new[] {
Label("OrderBy", (start, count, s) => s(start, count).OrderBy<int, int>(x => {throw new DeliberateTestException(); })),
Label("OrderBy-Comparer", (start, count, s) => s(start, count).OrderBy(x => x, new FailingComparer())),
Label("OrderByDescending", (start, count, s) => s(start, count).OrderByDescending<int, int>(x => {throw new DeliberateTestException(); })),
Label("OrderByDescending-Comparer", (start, count, s) => s(start, count).OrderByDescending(x => x, new FailingComparer())),
Label("ThenBy", (start, count, s) => s(start, count).OrderBy(x => 0).ThenBy<int, int>(x => {throw new DeliberateTestException(); })),
Label("ThenBy-Comparer", (start, count, s) => s(start, count).OrderBy(x => 0).ThenBy(x => x, new FailingComparer())),
Label("ThenByDescending", (start, count, s) => s(start, count).OrderBy(x => 0).ThenByDescending<int, int>(x => {throw new DeliberateTestException(); })),
Label("ThenByDescending-Comparer", (start, count, s) => s(start, count).OrderBy(x => 0).ThenByDescending(x => x, new FailingComparer())),
})
{
yield return new object[] { source, operation };
}
foreach (LabeledOperation operation in OrderOperators())
{
yield return new object[] { Failing, operation };
}
}
private static IEnumerable<LabeledOperation> UnaryOperations()
{
yield return Label("Cast", (start, count, source) => source(start, count).Cast<int>());
yield return Label("DefaultIfEmpty", (start, count, source) => source(start, count).DefaultIfEmpty());
yield return Label("Distinct", (start, count, source) => source(start * 2, count * 2).Select(x => x / 2).Distinct(new ModularCongruenceComparer(count)));
yield return Label("OfType", (start, count, source) => source(start, count).OfType<int>());
yield return Label("Reverse", (start, count, source) => source(start, count).Select(x => (start + count - 1) - (x - start)).Reverse());
yield return Label("GroupBy", (start, count, source) => source(start, count * CountFactor).GroupBy(x => (x - start) % count, new ModularCongruenceComparer(count)).Select(g => g.Key + start));
yield return Label("GroupBy-ElementSelector", (start, count, source) => source(start, count * CountFactor).GroupBy(x => x % count, y => y + 1, new ModularCongruenceComparer(count)).Select(g => g.Min() - 1));
yield return Label("GroupBy-ResultSelector", (start, count, source) => source(start, count * CountFactor).GroupBy(x => (x - start) % count, (key, g) => key + start, new ModularCongruenceComparer(count)));
yield return Label("GroupBy-ElementSelector-ResultSelector", (start, count, source) => source(start, count * CountFactor).GroupBy(x => x % count, y => y + 1, (key, g) => g.Min() - 1, new ModularCongruenceComparer(count)));
yield return Label("Select", (start, count, source) => source(start - count, count).Select(x => x + count));
yield return Label("Select-Index", (start, count, source) => source(start - count, count).Select((x, index) => x + count));
yield return Label("SelectMany", (start, count, source) => source(0, (count - 1) / CountFactor + 1).SelectMany(x => Enumerable.Range(start + x * CountFactor, Math.Min(CountFactor, count - x * CountFactor))));
yield return Label("SelectMany-Index", (start, count, source) => source(0, (count - 1) / CountFactor + 1).SelectMany((x, index) => Enumerable.Range(start + x * CountFactor, Math.Min(CountFactor, count - x * CountFactor))));
yield return Label("SelectMany-ResultSelector", (start, count, source) => source(0, (count - 1) / CountFactor + 1).SelectMany(x => Enumerable.Range(0, Math.Min(CountFactor, count - x * CountFactor)), (group, element) => start + group * CountFactor + element));
yield return Label("SelectMany-Index-ResultSelector", (start, count, source) => source(0, (count - 1) / CountFactor + 1).SelectMany((x, index) => Enumerable.Range(0, Math.Min(CountFactor, count - x * CountFactor)), (group, element) => start + group * CountFactor + element));
yield return Label("Where", (start, count, source) => source(start - count / 2, count * 2).Where(x => x >= start && x < start + count));
yield return Label("Where-Index", (start, count, source) => source(start - count / 2, count * 2).Where((x, index) => x >= start && x < start + count));
}
public static IEnumerable<object[]> UnaryUnorderedOperators()
{
foreach (LabeledOperation source in UnorderedRangeSources())
{
foreach (LabeledOperation operation in UnaryOperations())
{
yield return new object[] { source, operation };
}
}
}
private static IEnumerable<LabeledOperation> SkipTakeOperations()
{
// Take/Skip-based operations require ordered input, or will disobey
// the [start, start + count) convention expected in tests.
yield return Label("Skip", (start, count, source) => source(start - count, count * 2).Skip(count));
yield return Label("SkipWhile", (start, count, source) => source(start - count, count * 2).SkipWhile(x => x < start));
yield return Label("SkipWhile-Index", (start, count, source) => source(start - count, count * 2).SkipWhile((x, index) => x < start));
yield return Label("Take", (start, count, source) => source(start, count * 2).Take(count));
yield return Label("TakeWhile", (start, count, source) => source(start, count * 2).TakeWhile(x => x < start + count));
yield return Label("TakeWhile-Index", (start, count, source) => source(start, count * 2).TakeWhile((x, index) => x < start + count));
}
public static IEnumerable<object[]> SkipTakeOperators()
{
foreach (LabeledOperation source in RangeSources())
{
foreach (LabeledOperation operation in SkipTakeOperations())
{
yield return new object[] { source, operation };
}
}
}
public static IEnumerable<object[]> UnaryOperators()
{
// Apply an ordered source to each operation
foreach (LabeledOperation source in RangeSources())
{
foreach (LabeledOperation operation in UnaryOperations())
{
yield return new object[] { source, operation };
}
}
// Apply ordering to the output of each operation
foreach (LabeledOperation source in UnorderedRangeSources())
{
foreach (LabeledOperation operation in UnaryOperations())
{
foreach (LabeledOperation ordering in OrderOperators())
{
yield return new object[] { source, operation.Append(ordering) };
}
}
}
foreach (object[] parms in SkipTakeOperators())
{
yield return parms;
}
}
public static IEnumerable<object[]> UnaryFailingOperators()
{
foreach (LabeledOperation operation in new[] {
Label("Distinct", (start, count, s) => s(start, count).Distinct(new FailingEqualityComparer<int>())),
Label("GroupBy", (start, count, s) => s(start, count).GroupBy<int, int>(x => {throw new DeliberateTestException(); }).Select(g => g.Key)),
Label("GroupBy-Comparer", (start, count, s) => s(start, count).GroupBy(x => x, new FailingEqualityComparer<int>()).Select(g => g.Key)),
Label("GroupBy-ElementSelector", (start, count, s) => s(start, count).GroupBy<int, int, int>(x => x, x => { throw new DeliberateTestException(); }).Select(g => g.Key)),
Label("GroupBy-ResultSelector", (start, count, s) => s(start, count).GroupBy<int, int, int, int>(x => x, x => x, (x, g) => { throw new DeliberateTestException(); })),
Label("Select", (start, count, s) => s(start, count).Select<int, int>(x => {throw new DeliberateTestException(); })),
Label("Select-Index", (start, count, s) => s(start, count).Select<int, int>((x, index) => {throw new DeliberateTestException(); })),
Label("SelectMany", (start, count, s) => s(start, count).SelectMany<int, int>(x => {throw new DeliberateTestException(); })),
Label("SelectMany-Index", (start, count, s) => s(start, count).SelectMany<int, int>((x, index) => {throw new DeliberateTestException(); })),
Label("SelectMany-ResultSelector", (start, count, s) => s(start, count).SelectMany<int, int, int>(x => Enumerable.Range(x, 2), (group, elem) => { throw new DeliberateTestException(); })),
Label("SelectMany-Index-ResultSelector", (start, count, s) => s(start, count).SelectMany<int, int, int>((x, index) => Enumerable.Range(x, 2), (group, elem) => { throw new DeliberateTestException(); })),
Label("SkipWhile", (start, count, s) => s(start, count).SkipWhile(x => {throw new DeliberateTestException(); })),
Label("SkipWhile-Index", (start, count, s) => s(start, count).SkipWhile((x, index) => {throw new DeliberateTestException(); })),
Label("TakeWhile", (start, count, s) => s(start, count).TakeWhile(x => {throw new DeliberateTestException(); })),
Label("TakeWhile-Index", (start, count, s) => s(start, count).SkipWhile((x, index) => {throw new DeliberateTestException(); })),
Label("Where", (start, count, s) => s(start, count).Where(x => {throw new DeliberateTestException(); })),
Label("Where-Index", (start, count, s) => s(start, count).Where((x, index) => {throw new DeliberateTestException(); })),
})
{
foreach (LabeledOperation source in UnorderedRangeSources())
{
yield return new object[] { source, operation };
}
}
foreach (LabeledOperation operation in UnaryOperations().Concat(SkipTakeOperations()))
{
yield return new object[] { Failing, operation };
}
}
private static IEnumerable<LabeledOperation> BinaryOperations(LabeledOperation otherSource)
{
String label = otherSource.ToString();
Operation other = otherSource.Item;
yield return Label("Concat-Right:" + label, (start, count, source) => source(start, count / 2).Concat(other(start + count / 2, count / 2 + count % 2)));
yield return Label("Concat-Left:" + label, (start, count, source) => other(start, count / 2).Concat(source(start + count / 2, count / 2 + count % 2)));
// Comparator needs to cover _source_ size, as which of two "equal" items is returned is undefined for unordered collections.
yield return Label("Except-Right:" + label, (start, count, source) => source(start, count + count / 2).Except(other(start + count, count), new ModularCongruenceComparer(count * 2)));
yield return Label("Except-Left:" + label, (start, count, source) => other(start, count + count / 2).Except(source(start + count, count), new ModularCongruenceComparer(count * 2)));
yield return Label("GroupJoin-Right:" + label, (start, count, source) => source(start, count).GroupJoin(other(start, count * CountFactor), x => x, y => y % count, (x, g) => g.Min(), new ModularCongruenceComparer(count)));
yield return Label("GroupJoin-Left:" + label, (start, count, source) => other(start, count).GroupJoin(source(start, count * CountFactor), x => x, y => y % count, (x, g) => g.Min(), new ModularCongruenceComparer(count)));
// Comparator needs to cover _source_ size, as which of two "equal" items is returned is undefined.
yield return Label("Intersect-Right:" + label, (start, count, source) => source(start, count + count / 2).Intersect(other(start - count / 2, count + count / 2), new ModularCongruenceComparer(count * 2)));
yield return Label("Intersect-Left:" + label, (start, count, source) => other(start, count + count / 2).Intersect(source(start - count / 2, count + count / 2), new ModularCongruenceComparer(count * 2)));
yield return Label("Join-Right:" + label, (start, count, source) => source(0, count).Join(other(start, count), x => x, y => y - start, (x, y) => x + start, new ModularCongruenceComparer(count)));
yield return Label("Join-Left:" + label, (start, count, source) => other(0, count).Join(source(start, count), x => x, y => y - start, (x, y) => x + start, new ModularCongruenceComparer(count)));
yield return Label("Union-Right:" + label, (start, count, source) => source(start, count * 3 / 4).Union(other(start + count / 2, count / 2 + count % 2), new ModularCongruenceComparer(count)));
yield return Label("Union-Left:" + label, (start, count, source) => other(start, count * 3 / 4).Union(source(start + count / 2, count / 2 + count % 2), new ModularCongruenceComparer(count)));
// When both sources are unordered any element can be matched to any other, so a different check is required.
yield return Label("Zip-Unordered-Right:" + label, (start, count, source) => source(0, count).Zip(other(start * 2, count), (x, y) => x + start));
yield return Label("Zip-Unordered-Left:" + label, (start, count, source) => other(start * 2, count).Zip(source(0, count), (x, y) => y + start));
}
public static IEnumerable<object[]> BinaryUnorderedOperators()
{
LabeledOperation otherSource = UnorderedRangeSources().First();
foreach (LabeledOperation source in UnorderedRangeSources())
{
// Operations having multiple paths to check.
foreach (LabeledOperation operation in BinaryOperations(otherSource))
{
yield return new object[] { source, operation };
}
}
}
public static IEnumerable<object[]> BinaryOperators()
{
LabeledOperation unordered = UnorderedRangeSources().First();
foreach (LabeledOperation source in RangeSources())
{
// Each binary can work differently, depending on which of the two source queries (or both) is ordered.
// For most, only the ordering of the first query is important
foreach (LabeledOperation operation in BinaryOperations(unordered).Where(op => !(op.ToString().StartsWith("Union") || op.ToString().StartsWith("Zip")) && op.ToString().Contains("Right")))
{
yield return new object[] { source, operation };
}
// Concat currently doesn't play nice if only the right query is ordered via OrderBy et al. Issue #1332
// For Concat, since either one can be ordered the other side has to be tested
//foreach (var operation in BinaryOperations().Where(op => op.ToString().Contains("Concat") && op.ToString().Contains("Left")))
//{
// yield return new object[] { source, operation };
//}
// Zip is the same as Concat, but has a special check for matching indices (as compared to unordered)
foreach (LabeledOperation operation in Zip_Ordered_Operation(unordered))
{
yield return new object[] { source, operation };
}
// Union is an odd duck that (currently) orders only the portion that came from an ordered source.
foreach (LabeledOperation operation in BinaryOperations(RangeSources().First()).Where(op => op.ToString().StartsWith("Union")))
{
yield return new object[] { source, operation };
}
}
// Ordering the output should always be safe
foreach (object[] parameters in BinaryUnorderedOperators())
{
foreach (LabeledOperation ordering in OrderOperators())
{
yield return new[] { parameters[0], ((LabeledOperation)parameters[1]).Append(ordering) };
}
}
}
public static IEnumerable<object[]> BinaryFailingOperators()
{
LabeledOperation failing = Label("Failing", (start, count, s) => s(start, count).Select<int, int>(x => { throw new DeliberateTestException(); }));
LabeledOperation source = UnorderedRangeSources().First();
foreach (LabeledOperation operation in BinaryOperations(UnorderedRangeSources().First()))
{
foreach (LabeledOperation other in UnorderedRangeSources())
{
yield return new object[] { other.Append(failing), operation };
}
yield return new object[] { Failing, operation };
}
foreach (LabeledOperation operation in new[]
{
Label("Except-Fail", (start, count, s) => s(start, count).Except(source.Item(start, count), new FailingEqualityComparer<int>())),
Label("GroupJoin-Fail", (start, count, s) => s(start, count).GroupJoin(source.Item(start, count), x => x, y => y, (x, g) => x, new FailingEqualityComparer<int>())),
Label("Intersect-Fail", (start, count, s) => s(start, count).Intersect(source.Item(start, count), new FailingEqualityComparer<int>())),
Label("Join-Fail", (start, count, s) => s(start, count).Join(source.Item(start, count), x => x, y => y, (x, y) => x, new FailingEqualityComparer<int>())),
Label("Union-Fail", (start, count, s) => s(start, count).Union(source.Item(start, count), new FailingEqualityComparer<int>())),
Label("Zip-Fail", (start, count, s) => s(start, count).Zip<int, int, int>(source.Item(start, count), (x, y) => { throw new DeliberateTestException(); })),
})
{
yield return new object[] { source, operation };
}
}
#region operators
private static LabeledOperation Failing = Label("ThrowOnFirstEnumeration", (start, count, source) => Enumerables<int>.ThrowOnEnumeration().AsParallel());
private static LabeledOperation AsOrdered = Label("AsOrdered", (start, count, source) => source(start, count).AsOrdered());
private static Func<CancellationToken, LabeledOperation> WithCancellation = token => Label("WithCancellation", (start, count, source) => source(start, count).WithCancellation(token));
// There are two implementations here to help check that the 1st element is matched to the 1st element.
private static Func<LabeledOperation, IEnumerable<LabeledOperation>> Zip_Ordered_Operation = sOther => new[] {
Label("Zip-Ordered-Right:" + sOther.ToString(), (start, count, source) => source(0, count).Zip(sOther.Item(start * 2, count), (x, y) => (x + y) / 2)),
Label("Zip-Ordered-Left:" + sOther.ToString(), (start, count, source) => sOther.Item(start * 2, count).Zip(source(0, count), (x, y) => (x + y) / 2))
};
#endregion operators
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ArgData.Entities;
using ArgData.IO;
namespace ArgData
{
/// <summary>
/// Reads preferences from the F1PREFS.DAT file.
/// </summary>
public class PreferencesReader
{
private readonly PreferencesFile _preferencesFile;
/// <summary>
/// Creates a PreferencesReader for the specified F1PREFS.DAT file.
/// </summary>
/// <param name="preferencesFile">PreferencesFile to read from.</param>
/// <returns>PreferencesReader.</returns>
public PreferencesReader(PreferencesFile preferencesFile)
{
if (preferencesFile == null) { throw new ArgumentNullException(nameof(preferencesFile)); }
_preferencesFile = preferencesFile;
}
/// <summary>
/// Creates a PreferencesReader for the specified F1PREFS.DAT file.
/// </summary>
/// <param name="preferencesFile">PreferencesFile to read from.</param>
/// <returns>PreferencesReader.</returns>
public static PreferencesReader For(PreferencesFile preferencesFile)
{
return new PreferencesReader(preferencesFile);
}
/// <summary>
/// Gets the relative path and name of the name file that is auto-loaded by the game.
/// </summary>
/// <returns>Relative path and name of name file. If no file is set to auto-load, returns null.</returns>
public string GetAutoLoadedNameFile()
{
return ReadPathPropertyWithActivation(
PreferencesContants.AutoLoadNameFileActivatedPosition,
PreferencesContants.AutoLoadNameFilePathPosition,
PreferencesContants.AutoLoadNameFileLength);
}
/// <summary>
/// Gets the relative path and name of the setup file that is auto-loaded by the game.
/// </summary>
/// <returns>Relative path and name of the setup file. If no file is set to auto-load, returns null.</returns>
public string GetAutoLoadedSetupFile()
{
return ReadPathPropertyWithActivation(
PreferencesContants.AutoLoadSetupFileActivatedPosition,
PreferencesContants.AutoLoadSetupFilePathPosition,
PreferencesContants.AutoLoadSetupFileLength);
}
private string ReadPathPropertyWithActivation(int activatedPosition, int pathPosition, int length)
{
using (var reader = new BinaryReader(StreamProvider.Invoke(_preferencesFile.Path)))
{
reader.BaseStream.Position = activatedPosition;
byte activated = reader.ReadByte();
if (activated == 0)
return null;
reader.BaseStream.Position = pathPosition;
byte[] data = reader.ReadBytes(length);
return GetTextFromBytes(data);
}
}
private static string GetTextFromBytes(IEnumerable<byte> nameData)
{
byte[] nameBytes = nameData.TakeWhile(b => b != 0).ToArray();
string name = Encoding.ASCII.GetString(nameBytes);
return name;
}
/// <summary>
/// Default FileStream provider. Can be overridden in tests.
/// </summary>
internal Func<string, Stream> StreamProvider = FileStreamProvider.Open;
}
/// <summary>
/// Writes preferences to the F1PREFS.DAT file.
/// </summary>
public class PreferencesWriter
{
private readonly PreferencesFile _preferencesFile;
/// <summary>
/// Creates a PreferencesWriter for the specified F1PREFS.DAT file.
/// </summary>
/// <param name="preferencesFile">PreferencesFile to read from.</param>
/// <returns>PreferencesWriter.</returns>
public PreferencesWriter(PreferencesFile preferencesFile)
{
if (preferencesFile == null) { throw new ArgumentNullException(nameof(preferencesFile)); }
_preferencesFile = preferencesFile;
}
/// <summary>
/// Creates a PreferencesWriter for the specified F1PREFS.DAT file.
/// </summary>
/// <param name="preferencesFile">PreferencesFile to read from.</param>
/// <returns>PreferencesWriter.</returns>
public static PreferencesWriter For(PreferencesFile preferencesFile)
{
return new PreferencesWriter(preferencesFile);
}
/// <summary>
/// Sets the auto-loaded name file.
/// </summary>
/// <param name="nameFilePath">Relative path to F1GP installation. Max 31 chars.</param>
public void SetAutoLoadedNameFile(string nameFilePath)
{
if (string.IsNullOrEmpty(nameFilePath))
throw new ArgumentNullException(nameof(nameFilePath));
if (nameFilePath.Length > 31)
throw new ArgumentOutOfRangeException($"The path '{nameFilePath}' exceeds the max length of 31 chars.");
string pathToWrite = nameFilePath.PadRight(PreferencesContants.AutoLoadNameFileLength, '\0');
byte[] pathBytes = Encoding.ASCII.GetBytes(pathToWrite);
using (var writer = new BinaryWriter(StreamProvider.Invoke(_preferencesFile.Path)))
{
writer.BaseStream.Position = PreferencesContants.AutoLoadNameFileActivatedPosition;
writer.Write((byte)255);
writer.BaseStream.Position = PreferencesContants.AutoLoadNameFilePathPosition;
writer.Write(pathBytes);
}
ChecksumCalculator.UpdateChecksum(_preferencesFile.Path);
}
/// <summary>
/// Sets the auto-loaded setup file.
/// </summary>
/// <param name="setupFilePath">Relative path to F1GP installation. Max 31 chars.</param>
public void SetAutoLoadedSetupFile(string setupFilePath)
{
if (string.IsNullOrEmpty(setupFilePath))
throw new ArgumentNullException(nameof(setupFilePath));
if (setupFilePath.Length > 31)
throw new ArgumentOutOfRangeException($"The path '{setupFilePath}' exceeds the max length of 31 chars.");
string pathToWrite = setupFilePath.PadRight(PreferencesContants.AutoLoadSetupFileLength, '\0');
byte[] pathBytes = Encoding.ASCII.GetBytes(pathToWrite);
using (var writer = new BinaryWriter(StreamProvider.Invoke(_preferencesFile.Path)))
{
writer.BaseStream.Position = PreferencesContants.AutoLoadSetupFileActivatedPosition;
writer.Write((byte)255);
writer.BaseStream.Position = PreferencesContants.AutoLoadSetupFilePathPosition;
writer.Write(pathBytes);
}
ChecksumCalculator.UpdateChecksum(_preferencesFile.Path);
}
/// <summary>
/// Disables auto-loading of any name file in the game.
/// </summary>
public void DisableAutoLoadedNameFile()
{
string pathToWrite = "".PadRight(PreferencesContants.AutoLoadNameFileLength, '\0');
byte[] pathBytes = Encoding.ASCII.GetBytes(pathToWrite);
using (var writer = new BinaryWriter(StreamProvider.Invoke(_preferencesFile.Path)))
{
writer.BaseStream.Position = PreferencesContants.AutoLoadNameFileActivatedPosition;
writer.Write((byte)0);
writer.BaseStream.Position = PreferencesContants.AutoLoadNameFilePathPosition;
writer.Write(pathBytes);
}
ChecksumCalculator.UpdateChecksum(_preferencesFile.Path);
}
/// <summary>
/// Disables auto-loading of any setup file in the game.
/// </summary>
public void DisableAutoLoadedSetupFile()
{
string pathToWrite = "".PadRight(PreferencesContants.AutoLoadSetupFileLength, '\0');
byte[] pathBytes = Encoding.ASCII.GetBytes(pathToWrite);
using (var writer = new BinaryWriter(StreamProvider.Invoke(_preferencesFile.Path)))
{
writer.BaseStream.Position = PreferencesContants.AutoLoadSetupFileActivatedPosition;
writer.Write((byte)0);
writer.BaseStream.Position = PreferencesContants.AutoLoadSetupFilePathPosition;
writer.Write(pathBytes);
}
ChecksumCalculator.UpdateChecksum(_preferencesFile.Path);
}
/// <summary>
/// Default FileStream provider. Can be overridden in tests.
/// </summary>
internal Func<string, Stream> StreamProvider = FileStreamProvider.OpenWriter;
}
internal static class PreferencesContants
{
internal const int PreferencesFileLength = 1166;
internal const int AutoLoadNameFileActivatedPosition = 1130;
internal const int AutoLoadNameFilePathPosition = 1034;
internal const int AutoLoadNameFileLength = 30;
internal const int AutoLoadSetupFileActivatedPosition = 1131;
internal const int AutoLoadSetupFilePathPosition = 1066;
internal const int AutoLoadSetupFileLength = 30;
}
}
| |
using System.Collections.Generic;
using Raccoon.Graphics;
using Raccoon.Util;
namespace Raccoon.Fonts {
public abstract class FontRenderMap : System.IDisposable {
#region Constructors
public FontRenderMap() {
}
#endregion Constructors
#region Public Properties
public Texture Texture { get; protected set; }
public float LineHeight { get; protected set; }
public float Ascender { get; protected set; }
public float Descender { get; protected set; }
public float UnderlinePosition { get; protected set; }
public float UnderlineThickness { get; protected set; }
public float NominalWidth { get; set; }
public float NominalHeight { get; set; }
public abstract bool HasKerning { get; }
public uint DefaultErrorCharacter { get; set; } = '?';
public Size GlyphSlotSize { get { return new Size((float) NominalWidth, (float) NominalHeight); } }
public Dictionary<uint, Glyph> Glyphs { get; } = new Dictionary<uint, Glyph>();
/// <summary>
/// Default shader to be applied when using this map.
/// </summary>
public abstract Shader Shader { get; }
/// <summary>
/// Font size (in pixels/em).
/// </summary>
public float Size { get { return NominalWidth; } }
public bool IsDisposed { get; private set; }
#endregion Public Properties
#region Internal Properties
internal uint References { get; private set; } = 1;
#endregion Internal Properties
#region Public Methods
public virtual void Setup(float size) {
}
public virtual Text.RenderData PrepareTextRenderData(string text, out double textEmWidth, out double textEmHeight) {
return BuildText(text, out textEmWidth, out textEmHeight);
}
public abstract void Reload();
public abstract IShaderParameters CreateShaderParameters();
public override string ToString() {
return $"Line Height: {LineHeight}, Ascender: {Ascender}, Descender: {Descender}, UnderlinePosition: {UnderlinePosition}, UnderlineThickness: {UnderlineThickness}, NominalWidth: {NominalWidth}, NominalHeight: {NominalHeight}, HasKerning? {HasKerning.ToPrettyString()}, DefaultErrorCharacter: {DefaultErrorCharacter}, GlyphSlotSize: {GlyphSlotSize}, Glyphs: {Glyphs.Count}";
}
public void Dispose() {
if (IsDisposed) {
return;
}
References -= 1;
if (References > 0) {
return;
}
IsDisposed = true;
Disposed();
}
#endregion Public Methods
#region Protected Methods
protected abstract double Kerning(uint leftGlyph, uint rightGlyph);
protected Glyph RegisterGlyph(
uint charCode,
Rectangle sourceArea,
double bearingX,
double bearingY,
double width,
double height,
double advanceX,
double advanceY
) {
Glyph glyph = new Glyph(
sourceArea,
bearingX,
bearingY,
width,
height,
advanceX,
advanceY
);
Glyphs.Add(charCode, glyph);
return glyph;
}
protected double ConvertEmToPx(double em, double fontTargetSize) {
return em * fontTargetSize;
}
protected float ConvertEmToPx(float em, float fontTargetSize) {
return em * fontTargetSize;
}
protected double ConvertPxToEm(double px, double fontTargetSize) {
return px / fontTargetSize;
}
protected float ConvertPxToEm(float px, float fontTargetSize) {
return px / fontTargetSize;
}
protected abstract void Disposed();
#endregion Protected Methods
#region Private Methods
private Text.RenderData BuildText(string text, out double textEmWidth, out double textEmHeight) {
int extraSpace = text.Count("\t") * Math.Max(0, Font.TabulationWhitespacesSize - 1);
Text.RenderData textRenderData = new Text.RenderData(text.Length + extraSpace);
textEmWidth = textEmHeight = 0.0;
double kern,
penX = 0f,
penY = Math.Abs(Ascender);
bool isEndOfLine = false;
int renderTimes;
// TODO: add support to unicode characters?
for (int i = 0; i < text.Length; i++) {
char charCode = text[i];
if (charCode == '\n') { // new line
penY += LineHeight;
continue;
} else if (charCode == '\r') { // carriage return
// do nothing, just ignore
// TODO: maybe add an option to detect when carriage return handling is needed (MAC OS 9 or older, maybe?)
continue;
} else if (i + 1 == text.Length
|| text[i + 1] == '\n'
|| (i + 2 < text.Length && text[i + 1] == '\r' && text[i + 2] == '\n')
) {
isEndOfLine = true;
}
if (charCode == '\t') { // tabulation
// will render a tabulation representation using whitespaces
charCode = ' ';
renderTimes = Font.TabulationWhitespacesSize;
} else {
renderTimes = 1;
}
if (!Glyphs.TryGetValue(charCode, out Glyph glyph)) {
// glyph not found, just render default symbol
glyph = Glyphs[DefaultErrorCharacter];
}
for (int j = 0; j < renderTimes; j++) {
#region Underrun
if (penX == 0.0) {
penX -= glyph.BearingX;
}
#endregion Underrun
textRenderData.AppendGlyph(
penX + glyph.BearingX,
penY + glyph.BearingY,
glyph.SourceArea,
charCode,
glyph
);
penX += glyph.AdvanceX;
penY += glyph.AdvanceY;
#region Kerning with Next Repeated Character
// Adjust for kerning between this character and the next (if repeatTimes > 1)
if (HasKerning && !isEndOfLine && renderTimes > 1) {
kern = Kerning(charCode, charCode);
if (Math.Abs(kern) > glyph.AdvanceX * 5.0) {
kern = 0;
}
penX += kern;
}
#endregion Kerning with Next Repeated Character
}
#region Kerning with Next Character
// Adjust for kerning between this character and the next.
if (HasKerning && !isEndOfLine) {
char nextCharCode = text[i + 1];
kern = Kerning(charCode, nextCharCode);
if (Math.Abs(kern) > glyph.AdvanceX * 5.0) {
kern = 0;
}
penX += kern;
}
#endregion Kerning with Next Character
if (isEndOfLine) {
isEndOfLine = false;
if (penX > textEmWidth) {
textEmWidth = penX;
}
penX = 0.0;
}
}
textEmHeight = penY + Descender;
return textRenderData;
}
#endregion Private Methods
#region Internal Methods
internal void AddReferenceCount() {
if (IsDisposed) {
return;
}
References += 1;
}
#endregion Internal Methods
#region Class Glyph
public class Glyph {
public Glyph(
Rectangle sourceArea,
double bearingX,
double bearingY,
double width,
double height,
double advanceX,
double advanceY
) {
SourceArea = sourceArea;
BearingX = bearingX;
BearingY = bearingY;
Width = width;
Height = height;
AdvanceX = advanceX;
AdvanceY = advanceY;
}
public Rectangle SourceArea { get; }
public double BearingX { get; }
public double BearingY { get; }
public double Width { get; }
public double Height { get; }
public double AdvanceX { get; }
public double AdvanceY { get; }
public override string ToString() {
return $"Source Area: {SourceArea}, BearingX: {BearingX}, BearingY: {BearingY}, Width: {Width}, Height: {Height}, AdvanceX: {AdvanceX}, AdvanceY: {AdvanceY}";
}
}
#endregion Class Glyph
}
}
| |
/* Copyright (c) Peter Palotas 2007
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
* * Neither the name of the copyright holder 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.
*
* $Id: UsageInfo.cs 7 2007-08-04 12:02:15Z palotas $
*/
using System;
using SCG = System.Collections.Generic;
using System.Text;
using C5;
using System.Diagnostics;
using Plossum.Resources;
using System.Globalization;
namespace Plossum.CommandLine
{
/// <summary>
/// Represents the properties of a <see cref="CommandLineManagerAttribute"/> (or rather the object to which its
/// applied) that describe the command line syntax.
/// </summary>
/// <remarks>This class is the only way to programatically set usage descriptions, group names and similar, which
/// is required if globalization of the usage description is desired. Users can not instantiate objects of this
/// class, but they are retrieved by the <see cref="CommandLineParser.UsageInfo"/> property.</remarks>
public sealed class UsageInfo
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="UsageInfo"/> class.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="optionStyles">The option styles.</param>
/// <param name="parser">The parser.</param>
internal UsageInfo(SCG.IEnumerable<KeyValuePair<string, IOption>> options, OptionStyles optionStyles, CommandLineParser parser)
{
mParser = parser;
foreach (KeyValuePair<string, IOption> entry in options)
{
Option option = entry.Value as Option;
if (option != null)
{
if (option.Group != null)
{
if (!mGroups.Contains(option.Group.Id))
{
mGroups.Add(option.Group.Id, new OptionGroupInfo(this, option.Group, optionStyles));
}
}
else
{
Debug.Assert(!mOptions.Contains(option.Name));
mOptions.Add(option.Name, new OptionInfo(this, option, optionStyles));
}
}
}
}
#endregion
#region Public properties
/// <summary>
/// Gets or sets the name of the application.
/// </summary>
/// <value>The name of the application.</value>
public string ApplicationName
{
get { return mParser.ApplicationName; }
set { mParser.ApplicationName = value; }
}
/// <summary>
/// Gets or sets the application version.
/// </summary>
/// <value>The application version.</value>
public string ApplicationVersion
{
get { return mParser.ApplicationVersion; }
set { mParser.ApplicationVersion = value; }
}
/// <summary>
/// Gets or sets the application copyright.
/// </summary>
/// <value>The application copyright.</value>
public string ApplicationCopyright
{
get { return mParser.ApplicationCopyright; }
set { mParser.ApplicationCopyright = value; }
}
/// <summary>
/// Gets or sets the application description.
/// </summary>
/// <value>The application description.</value>
public string ApplicationDescription
{
get { return mParser.ApplicationDescription; }
set { mParser.ApplicationDescription = value; }
}
/// <summary>
/// Gets an enumeration of <see cref="OptionInfo"/> objects describing the options of this
/// command line manager that are <i>not</i> part of any option group.
/// </summary>
/// <value>an enumeration of <see cref="OptionInfo"/> objects describing the options of this
/// command line manager that are <i>not</i> part of any option group.</value>
public SCG.IEnumerable<OptionInfo> Options
{
get { return mOptions.Values; }
}
/// <summary>
/// Gets an enumeration of the <see cref="OptionGroupInfo"/> objects describin the option groups
/// of this command line manager.
/// </summary>
/// <value>an enumeration of the <see cref="OptionGroupInfo"/> objects describin the option groups
/// of this command line manager.</value>
public SCG.IEnumerable<OptionGroupInfo> Groups
{
get { return mGroups.Values; }
}
/// <summary>
/// Gets or sets the column spacing to use for any string formatting involving multiple columns.
/// </summary>
/// <value>The column spacing used for any string formatting involving multiple columns.</value>
public int ColumnSpacing
{
get { return mColumnSpacing; }
set
{
if (value < 0)
throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, CommandLineStrings.ArgMustBeNonNegative, "value"), "value");
mColumnSpacing = value;
}
}
/// <summary>
/// Gets or sets the width of the indent to use for any string formatting by this <see cref="UsageInfo"/>.
/// </summary>
/// <value>the width of the indent to use for any string formatting by this <see cref="UsageInfo"/>.</value>
public int IndentWidth
{
get { return mIndentWidth; }
set
{
if (value < 0)
throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, CommandLineStrings.ArgMustBeNonNegative, "value"), "value");
mIndentWidth = value;
}
}
#endregion
#region Public methods
/// <summary>
/// Gets the option with the specified name.
/// </summary>
/// <param name="name">The name of the option to retrieve.</param>
/// <returns>The option in the option manager described by this object with the specified name, or
/// a null reference if no such option exists.</returns>
public OptionInfo GetOption(string name)
{
OptionInfo description;
if (!mOptions.Find(name, out description))
{
// Search through all groups for this option
foreach (OptionGroupInfo gdesc in mGroups.Values)
{
if ((description = gdesc.GetOption(name)) != null)
return description;
}
return null;
}
return description;
}
/// <summary>
/// Gets the option group with the specified id.
/// </summary>
/// <param name="id">The id of the option group to retrieve.</param>
/// <returns>The option group with the specified id of the option manager described
/// by this object, or a null reference if no such option group exists.</returns>
public OptionGroupInfo GetGroup(string id)
{
OptionGroupInfo desc;
if (!mGroups.Find(id, out desc))
return null;
return desc;
}
/// <summary>
/// Gets a string consisting of the program name, version and copyright notice.
/// </summary>
/// <param name="width">The total width in characters in which the string should be fitted</param>
/// <returns>a string consisting of the program name, version and copyright notice.</returns>
/// <remarks>This string is suitable for printing as the first output of a console application.</remarks>
public string GetHeaderAsString(int width)
{
StringBuilder result = new StringBuilder();
result.Append(ApplicationName ?? "Unnamed application");
if (ApplicationVersion != null)
{
result.Append(" ");
result.Append(CommandLineStrings.Version);
result.Append(' ');
result.Append(ApplicationVersion);
}
result.Append(Environment.NewLine);
if (ApplicationCopyright != null)
{
result.Append(ApplicationCopyright);
result.Append(Environment.NewLine);
}
return StringFormatter.WordWrap(result.ToString(), width);
}
/// <summary>
/// Gets a formatted string describing the options and groups available.
/// </summary>
/// <param name="width">The maximum width of each line in the returned string.</param>
/// <returns>A formatted string describing the options available in this parser</returns>
/// <exception cref="ArgumentException">The specified width was too small to generate the requested list.</exception>
public string GetOptionsAsString(int width)
{
// Remove spacing between columns
width -= ColumnSpacing;
if (width < 2)
throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, CommandLineStrings.WidthMustNotBeLessThan0, ColumnSpacing + 2), "width");
// Default minimum width
int maxNameWidth = 5;
// Get the maximum option name length from options not in groups
foreach (OptionInfo option in mOptions.Values)
{
maxNameWidth = Math.Max(option.Name.Length, maxNameWidth);
foreach (string alias in option.Aliases)
{
maxNameWidth = Math.Max(alias.Length, maxNameWidth);
}
}
// Get the maximum option name length from option inside groups
foreach (OptionGroupInfo group in mGroups.Values)
{
foreach (OptionInfo option in group.Options)
{
maxNameWidth = Math.Max(option.Name.Length, maxNameWidth);
foreach (string alias in option.Aliases)
{
maxNameWidth = Math.Max(alias.Length, maxNameWidth);
}
}
}
// Add room for '--' and comma after the option name.
maxNameWidth += 3;
// Make sure the name column isn't more than half the specified width
maxNameWidth = Math.Min(width / 2, maxNameWidth);
return GetOptionsAsString(maxNameWidth, width - maxNameWidth);
}
/// <summary>
/// Gets a string describing all the options of this option manager. Usable for displaying as a help
/// message to the user, provided that descriptions for all options and groups are provided.
/// </summary>
/// <param name="nameColumnWidth">The width in characters of the column holding the names of the options.</param>
/// <param name="descriptionColumnWidth">The width in characters of the column holding the descriptions of the options.</param>
/// <returns>A string describing all the options of this option manager.</returns>
public string GetOptionsAsString(int nameColumnWidth, int descriptionColumnWidth)
{
StringBuilder result = new StringBuilder();
if (!mOptions.IsEmpty)
{
result.Append(StringFormatter.WordWrap(CommandLineStrings.Options, nameColumnWidth + descriptionColumnWidth + ColumnSpacing, WordWrappingMethod.Optimal, Alignment.Left, ' '));
result.Append(Environment.NewLine);
foreach (OptionInfo option in mOptions.Values)
{
result.Append(option.ToString(IndentWidth, nameColumnWidth, descriptionColumnWidth - IndentWidth));
result.Append(Environment.NewLine);
}
result.Append(Environment.NewLine);
}
foreach (OptionGroupInfo group in mGroups.Values)
{
result.Append(group.ToString(0, nameColumnWidth, descriptionColumnWidth));
result.Append(Environment.NewLine);
}
return result.ToString();
}
/// <summary>
/// Gets the list of errors as a formatted string.
/// </summary>
/// <param name="width">The width of the field in which to format the error list.</param>
/// <returns>The list of errors formatted inside a field of the specified <paramref name="width"/></returns>
public string GetErrorsAsString(int width)
{
if (width < IndentWidth + 7)
throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, CommandLineStrings.Arg0MustNotBeLessThan1, "width", IndentWidth + 7), "width");
StringBuilder result = new StringBuilder();
result.Append(StringFormatter.WordWrap("Errors:", width));
result.Append(Environment.NewLine);
StringBuilder errors = new StringBuilder();
foreach (ErrorInfo error in mParser.Errors)
{
errors.Append(error.Message);
if (error.FileName != null)
{
errors.Append(String.Format(CultureInfo.CurrentUICulture, CommandLineStrings.OnLine0InFile1, error.Line, error.FileName));
}
result.Append(StringFormatter.FormatInColumns(IndentWidth, 1, new ColumnInfo(1, "*"), new ColumnInfo(width - 1 - IndentWidth - 1, errors.ToString())));
result.Append('\n');
errors.Length = 0;
}
return result.ToString();
}
/// <summary>
/// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
/// </returns>
/// <remarks>This is equivalent to calling <see cref="ToString(int)">ToString(78)</see></remarks>
public override string ToString()
{
return ToString(78);
}
/// <summary>
/// Converts this <see cref="UsageInfo"/> instance to a string.
/// </summary>
/// <param name="width">The width of the field (in characters) in which to format the usage description.</param>
/// <returns>A string including the header, and a complete list of the options and their descriptions
/// available in this <see cref="UsageInfo"/> object.</returns>
public string ToString(int width)
{
return ToString(width, false);
}
/// <summary>
/// Converts this <see cref="UsageInfo"/> instance to a string.
/// </summary>
/// <param name="width">The width of the field (in characters) in which to format the usage description.</param>
/// <param name="includeErrors">if set to <c>true</c> any errors that occured during parsing the command line will be included
/// in the output.</param>
/// <returns>A string including the header, optionally errors, and a complete list of the options and their descriptions
/// available in this <see cref="UsageInfo"/> object.</returns>
public string ToString(int width, bool includeErrors)
{
StringBuilder result = new StringBuilder();
result.Append(GetHeaderAsString(width));
result.Append(Environment.NewLine);
if (mParser.HasErrors && includeErrors)
{
result.Append(GetErrorsAsString(width));
result.Append(Environment.NewLine);
}
result.Append(GetOptionsAsString(width));
result.Append(Environment.NewLine);
return result.ToString();
}
#endregion
#region Private fields
private CommandLineParser mParser;
private TreeDictionary<string, OptionGroupInfo> mGroups = new TreeDictionary<string, OptionGroupInfo>();
private TreeDictionary<string, OptionInfo> mOptions = new TreeDictionary<string, OptionInfo>();
private int mColumnSpacing = 3;
private int mIndentWidth = 3;
#endregion
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using System.Text;
namespace Org.BouncyCastle.Math.EC.Abc
{
/**
* Class representing a simple version of a big decimal. A
* <code>SimpleBigDecimal</code> is basically a
* {@link java.math.BigInteger BigInteger} with a few digits on the right of
* the decimal point. The number of (binary) digits on the right of the decimal
* point is called the <code>scale</code> of the <code>SimpleBigDecimal</code>.
* Unlike in {@link java.math.BigDecimal BigDecimal}, the scale is not adjusted
* automatically, but must be set manually. All <code>SimpleBigDecimal</code>s
* taking part in the same arithmetic operation must have equal scale. The
* result of a multiplication of two <code>SimpleBigDecimal</code>s returns a
* <code>SimpleBigDecimal</code> with double scale.
*/
internal class SimpleBigDecimal
// : Number
{
// private static final long serialVersionUID = 1L;
private readonly BigInteger bigInt;
private readonly int scale;
/**
* Returns a <code>SimpleBigDecimal</code> representing the same numerical
* value as <code>value</code>.
* @param value The value of the <code>SimpleBigDecimal</code> to be
* created.
* @param scale The scale of the <code>SimpleBigDecimal</code> to be
* created.
* @return The such created <code>SimpleBigDecimal</code>.
*/
public static SimpleBigDecimal GetInstance(BigInteger val, int scale)
{
return new SimpleBigDecimal(val.ShiftLeft(scale), scale);
}
/**
* Constructor for <code>SimpleBigDecimal</code>. The value of the
* constructed <code>SimpleBigDecimal</code> Equals <code>bigInt /
* 2<sup>scale</sup></code>.
* @param bigInt The <code>bigInt</code> value parameter.
* @param scale The scale of the constructed <code>SimpleBigDecimal</code>.
*/
public SimpleBigDecimal(BigInteger bigInt, int scale)
{
if (scale < 0)
throw new ArgumentException("scale may not be negative");
this.bigInt = bigInt;
this.scale = scale;
}
private SimpleBigDecimal(SimpleBigDecimal limBigDec)
{
bigInt = limBigDec.bigInt;
scale = limBigDec.scale;
}
private void CheckScale(SimpleBigDecimal b)
{
if (scale != b.scale)
throw new ArgumentException("Only SimpleBigDecimal of same scale allowed in arithmetic operations");
}
public SimpleBigDecimal AdjustScale(int newScale)
{
if (newScale < 0)
throw new ArgumentException("scale may not be negative");
if (newScale == scale)
return this;
return new SimpleBigDecimal(bigInt.ShiftLeft(newScale - scale), newScale);
}
public SimpleBigDecimal Add(SimpleBigDecimal b)
{
CheckScale(b);
return new SimpleBigDecimal(bigInt.Add(b.bigInt), scale);
}
public SimpleBigDecimal Add(BigInteger b)
{
return new SimpleBigDecimal(bigInt.Add(b.ShiftLeft(scale)), scale);
}
public SimpleBigDecimal Negate()
{
return new SimpleBigDecimal(bigInt.Negate(), scale);
}
public SimpleBigDecimal Subtract(SimpleBigDecimal b)
{
return Add(b.Negate());
}
public SimpleBigDecimal Subtract(BigInteger b)
{
return new SimpleBigDecimal(bigInt.Subtract(b.ShiftLeft(scale)), scale);
}
public SimpleBigDecimal Multiply(SimpleBigDecimal b)
{
CheckScale(b);
return new SimpleBigDecimal(bigInt.Multiply(b.bigInt), scale + scale);
}
public SimpleBigDecimal Multiply(BigInteger b)
{
return new SimpleBigDecimal(bigInt.Multiply(b), scale);
}
public SimpleBigDecimal Divide(SimpleBigDecimal b)
{
CheckScale(b);
BigInteger dividend = bigInt.ShiftLeft(scale);
return new SimpleBigDecimal(dividend.Divide(b.bigInt), scale);
}
public SimpleBigDecimal Divide(BigInteger b)
{
return new SimpleBigDecimal(bigInt.Divide(b), scale);
}
public SimpleBigDecimal ShiftLeft(int n)
{
return new SimpleBigDecimal(bigInt.ShiftLeft(n), scale);
}
public int CompareTo(SimpleBigDecimal val)
{
CheckScale(val);
return bigInt.CompareTo(val.bigInt);
}
public int CompareTo(BigInteger val)
{
return bigInt.CompareTo(val.ShiftLeft(scale));
}
public BigInteger Floor()
{
return bigInt.ShiftRight(scale);
}
public BigInteger Round()
{
SimpleBigDecimal oneHalf = new SimpleBigDecimal(BigInteger.One, 1);
return Add(oneHalf.AdjustScale(scale)).Floor();
}
public int IntValue
{
get { return Floor().IntValue; }
}
public long LongValue
{
get { return Floor().LongValue; }
}
// public double doubleValue()
// {
// return new Double(ToString()).doubleValue();
// }
//
// public float floatValue()
// {
// return new Float(ToString()).floatValue();
// }
public int Scale
{
get { return scale; }
}
public override string ToString()
{
if (scale == 0)
return bigInt.ToString();
BigInteger floorBigInt = Floor();
BigInteger fract = bigInt.Subtract(floorBigInt.ShiftLeft(scale));
if (bigInt.SignValue < 0)
{
fract = BigInteger.One.ShiftLeft(scale).Subtract(fract);
}
if ((floorBigInt.SignValue == -1) && (!(fract.Equals(BigInteger.Zero))))
{
floorBigInt = floorBigInt.Add(BigInteger.One);
}
string leftOfPoint = floorBigInt.ToString();
char[] fractCharArr = new char[scale];
string fractStr = fract.ToString(2);
int fractLen = fractStr.Length;
int zeroes = scale - fractLen;
for (int i = 0; i < zeroes; i++)
{
fractCharArr[i] = '0';
}
for (int j = 0; j < fractLen; j++)
{
fractCharArr[zeroes + j] = fractStr[j];
}
string rightOfPoint = new string(fractCharArr);
StringBuilder sb = new StringBuilder(leftOfPoint);
sb.Append(".");
sb.Append(rightOfPoint);
return sb.ToString();
}
public override bool Equals(
object obj)
{
if (this == obj)
return true;
SimpleBigDecimal other = obj as SimpleBigDecimal;
if (other == null)
return false;
return bigInt.Equals(other.bigInt)
&& scale == other.scale;
}
public override int GetHashCode()
{
return bigInt.GetHashCode() ^ scale;
}
}
}
#endif
| |
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 ConTurnosProgramadosConAsistencium class.
/// </summary>
[Serializable]
public partial class ConTurnosProgramadosConAsistenciumCollection : ReadOnlyList<ConTurnosProgramadosConAsistencium, ConTurnosProgramadosConAsistenciumCollection>
{
public ConTurnosProgramadosConAsistenciumCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the CON_TurnosProgramadosConAsistencia view.
/// </summary>
[Serializable]
public partial class ConTurnosProgramadosConAsistencium : ReadOnlyRecord<ConTurnosProgramadosConAsistencium>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
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("CON_TurnosProgramadosConAsistencia", TableType.View, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.String;
colvarNombre.MaxLength = 100;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarCantidadTurnos = new TableSchema.TableColumn(schema);
colvarCantidadTurnos.ColumnName = "cantidadTurnos";
colvarCantidadTurnos.DataType = DbType.Int32;
colvarCantidadTurnos.MaxLength = 0;
colvarCantidadTurnos.AutoIncrement = false;
colvarCantidadTurnos.IsNullable = true;
colvarCantidadTurnos.IsPrimaryKey = false;
colvarCantidadTurnos.IsForeignKey = false;
colvarCantidadTurnos.IsReadOnly = false;
schema.Columns.Add(colvarCantidadTurnos);
TableSchema.TableColumn colvarIdAgenda = new TableSchema.TableColumn(schema);
colvarIdAgenda.ColumnName = "idAgenda";
colvarIdAgenda.DataType = DbType.Int32;
colvarIdAgenda.MaxLength = 0;
colvarIdAgenda.AutoIncrement = false;
colvarIdAgenda.IsNullable = false;
colvarIdAgenda.IsPrimaryKey = false;
colvarIdAgenda.IsForeignKey = false;
colvarIdAgenda.IsReadOnly = false;
schema.Columns.Add(colvarIdAgenda);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("CON_TurnosProgramadosConAsistencia",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public ConTurnosProgramadosConAsistencium()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public ConTurnosProgramadosConAsistencium(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public ConTurnosProgramadosConAsistencium(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public ConTurnosProgramadosConAsistencium(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get
{
return GetColumnValue<string>("nombre");
}
set
{
SetColumnValue("nombre", value);
}
}
[XmlAttribute("CantidadTurnos")]
[Bindable(true)]
public int? CantidadTurnos
{
get
{
return GetColumnValue<int?>("cantidadTurnos");
}
set
{
SetColumnValue("cantidadTurnos", value);
}
}
[XmlAttribute("IdAgenda")]
[Bindable(true)]
public int IdAgenda
{
get
{
return GetColumnValue<int>("idAgenda");
}
set
{
SetColumnValue("idAgenda", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Nombre = @"nombre";
public static string CantidadTurnos = @"cantidadTurnos";
public static string IdAgenda = @"idAgenda";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
namespace System.Reflection.Emit {
using System;
using System.Threading;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public struct OpCode
{
//
// Use packed bitfield for flags to avoid code bloat
//
internal const int OperandTypeMask = 0x1F; // 000000000000000000000000000XXXXX
internal const int FlowControlShift = 5; // 00000000000000000000000XXXX00000
internal const int FlowControlMask = 0x0F;
internal const int OpCodeTypeShift = 9; // 00000000000000000000XXX000000000
internal const int OpCodeTypeMask = 0x07;
internal const int StackBehaviourPopShift = 12; // 000000000000000XXXXX000000000000
internal const int StackBehaviourPushShift = 17; // 0000000000XXXXX00000000000000000
internal const int StackBehaviourMask = 0x1F;
internal const int SizeShift = 22; // 00000000XX0000000000000000000000
internal const int SizeMask = 0x03;
internal const int EndsUncondJmpBlkFlag = 0x01000000; // 0000000X000000000000000000000000
// unused // 0000XXX0000000000000000000000000
internal const int StackChangeShift = 28; // XXXX0000000000000000000000000000
#if FEATURE_CORECLR
private OpCodeValues m_value;
private int m_flags;
internal OpCode(OpCodeValues value, int flags)
{
m_value = value;
m_flags = flags;
}
internal bool EndsUncondJmpBlk()
{
return (m_flags & EndsUncondJmpBlkFlag) != 0;
}
internal int StackChange()
{
return (m_flags >> StackChangeShift);
}
public OperandType OperandType
{
get
{
return (OperandType)(m_flags & OperandTypeMask);
}
}
public FlowControl FlowControl
{
get
{
return (FlowControl)((m_flags >> FlowControlShift) & FlowControlMask);
}
}
public OpCodeType OpCodeType
{
get
{
return (OpCodeType)((m_flags >> OpCodeTypeShift) & OpCodeTypeMask);
}
}
public StackBehaviour StackBehaviourPop
{
get
{
return (StackBehaviour)((m_flags >> StackBehaviourPopShift) & StackBehaviourMask);
}
}
public StackBehaviour StackBehaviourPush
{
get
{
return (StackBehaviour)((m_flags >> StackBehaviourPushShift) & StackBehaviourMask);
}
}
public int Size
{
get
{
return (m_flags >> SizeShift) & SizeMask;
}
}
public short Value
{
get
{
return (short)m_value;
}
}
#else // FEATURE_CORECLR
//
// The exact layout is part of the legacy COM mscorlib surface, so it is
// pretty much set in stone for desktop CLR. Ideally, we would use the packed
// bit field like for CoreCLR, but that would be a breaking change.
//
// disable csharp compiler warning #0414: field assigned unused value
#pragma warning disable 0414
private String m_stringname; // not used - computed lazily
#pragma warning restore 0414
private StackBehaviour m_pop;
private StackBehaviour m_push;
private OperandType m_operand;
private OpCodeType m_type;
private int m_size;
private byte m_s1;
private byte m_s2;
private FlowControl m_ctrl;
// Specifies whether the current instructions causes the control flow to
// change unconditionally.
private bool m_endsUncondJmpBlk;
// Specifies the stack change that the current instruction causes not
// taking into account the operand dependant stack changes.
private int m_stackChange;
internal OpCode(OpCodeValues value, int flags)
{
m_stringname = null; // computed lazily
m_pop = (StackBehaviour)((flags >> StackBehaviourPopShift) & StackBehaviourMask);
m_push = (StackBehaviour)((flags >> StackBehaviourPushShift) & StackBehaviourMask);
m_operand = (OperandType)(flags & OperandTypeMask);
m_type = (OpCodeType)((flags >> OpCodeTypeShift) & OpCodeTypeMask);
m_size = (flags >> SizeShift) & SizeMask;
m_s1 = (byte)((int)value >> 8);
m_s2 = (byte)(int)value;
m_ctrl = (FlowControl)((flags >> FlowControlShift) & FlowControlMask);
m_endsUncondJmpBlk = (flags & EndsUncondJmpBlkFlag) != 0;
m_stackChange = (flags >> StackChangeShift);
}
internal bool EndsUncondJmpBlk()
{
return m_endsUncondJmpBlk;
}
internal int StackChange()
{
return m_stackChange;
}
public OperandType OperandType
{
get
{
return (m_operand);
}
}
public FlowControl FlowControl
{
get
{
return (m_ctrl);
}
}
public OpCodeType OpCodeType
{
get
{
return (m_type);
}
}
public StackBehaviour StackBehaviourPop
{
get
{
return (m_pop);
}
}
public StackBehaviour StackBehaviourPush
{
get
{
return (m_push);
}
}
public int Size
{
get
{
return (m_size);
}
}
public short Value
{
get
{
if (m_size == 2)
return (short)(m_s1 << 8 | m_s2);
return (short)m_s2;
}
}
#endif // FEATURE_CORECLR
private static volatile string[] g_nameCache;
public String Name
{
get
{
if (Size == 0)
return null;
// Create and cache the opcode names lazily. They should be rarely used (only for logging, etc.)
// Note that we do not any locks here because of we always get the same names. The last one wins.
string[] nameCache = g_nameCache;
if (nameCache == null) {
nameCache = new String[0x11f];
g_nameCache = nameCache;
}
OpCodeValues opCodeValue = (OpCodeValues)(ushort)Value;
int idx = (int)opCodeValue;
if (idx > 0xFF) {
if (idx >= 0xfe00 && idx <= 0xfe1e) {
// Transform two byte opcode value to lower range that's suitable
// for array index
idx = 0x100 + (idx - 0xfe00);
}
else {
// Unknown opcode
return null;
}
}
String name = Volatile.Read(ref nameCache[idx]);
if (name != null)
return name;
// Create ilasm style name from the enum value name.
name = Enum.GetName(typeof(OpCodeValues), opCodeValue).ToLowerInvariant().Replace("_", ".");
Volatile.Write(ref nameCache[idx], name);
return name;
}
}
[Pure]
public override bool Equals(Object obj)
{
if (obj is OpCode)
return Equals((OpCode)obj);
else
return false;
}
[Pure]
public bool Equals(OpCode obj)
{
return obj.Value == Value;
}
[Pure]
public static bool operator ==(OpCode a, OpCode b)
{
return a.Equals(b);
}
[Pure]
public static bool operator !=(OpCode a, OpCode b)
{
return !(a == b);
}
public override int GetHashCode()
{
return Value;
}
public override String ToString()
{
return Name;
}
}
}
| |
#if UNITY_ANDROID && !UNITY_EDITOR
#define USE_ANDROID
#endif
using System;
using System.Collections.Generic;
using UnityEngine;
/**
* @author zeh fernando
*/
class ApplicationChrome {
/**
* Manipulates the system application chrome to change the way the status bar and navigation bar work
*
* References:
* . http://developer.android.com/reference/android/view/View.html#setSystemUiVisibility(int)
* . http://forum.unity3d.com/threads/calling-setsystemuivisibility.139445/#post-952946
* . http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_LAYOUT_IN_SCREEN
**/
// Enums
public enum States {
Unknown,
Visible,
VisibleOverContent,
TranslucentOverContent,
Hidden
}
// Constants
private const uint DEFAULT_BACKGROUND_COLOR = 0xff000000;
#if USE_ANDROID
// Original Android flags
private const int VIEW_SYSTEM_UI_FLAG_VISIBLE = 0; // Added in API 14 (Android 4.0.x): Status bar visible (the default)
private const int VIEW_SYSTEM_UI_FLAG_LOW_PROFILE = 1; // Added in API 14 (Android 4.0.x): Low profile for games, book readers, and video players; the status bar and/or navigation icons are dimmed out (if visible)
private const int VIEW_SYSTEM_UI_FLAG_HIDE_NAVIGATION = 2; // Added in API 14 (Android 4.0.x): Hides all navigation. Cleared when theres any user interaction.
private const int VIEW_SYSTEM_UI_FLAG_FULLSCREEN = 4; // Added in API 16 (Android 4.1.x): Hides status bar. Does nothing in Unity (already hidden if "status bar hidden" is checked)
private const int VIEW_SYSTEM_UI_FLAG_LAYOUT_STABLE = 256; // Added in API 16 (Android 4.1.x): ?
private const int VIEW_SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 512; // Added in API 16 (Android 4.1.x): like HIDE_NAVIGATION, but for layouts? it causes the layout to be drawn like that, even if the whole view isn't (to avoid artifacts in animation)
private const int VIEW_SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 1024; // Added in API 16 (Android 4.1.x): like FULLSCREEN, but for layouts? it causes the layout to be drawn like that, even if the whole view isn't (to avoid artifacts in animation)
private const int VIEW_SYSTEM_UI_FLAG_IMMERSIVE = 2048; // Added in API 19 (Android 4.4): like HIDE_NAVIGATION, but interactive (it's a modifier for HIDE_NAVIGATION, needs to be used with it)
private const int VIEW_SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 4096; // Added in API 19 (Android 4.4): tells that HIDE_NAVIGATION and FULSCREEN are interactive (also just a modifier)
private static int WINDOW_FLAG_FULLSCREEN = 0x00000400;
private static int WINDOW_FLAG_FORCE_NOT_FULLSCREEN = 0x00000800;
private static int WINDOW_FLAG_LAYOUT_IN_SCREEN = 0x00000100;
private static int WINDOW_FLAG_TRANSLUCENT_STATUS = 0x04000000;
private static int WINDOW_FLAG_TRANSLUCENT_NAVIGATION = 0x08000000;
private static int WINDOW_FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS = -2147483648; // 0x80000000; // Added in API 21 (Android 5.0): tells the Window is responsible for drawing the background for the system bars. If set, the system bars are drawn with a transparent background and the corresponding areas in this window are filled with the colors specified in getStatusBarColor() and getNavigationBarColor()
// Current values
private static int systemUiVisibilityValue;
private static int flagsValue;
#endif
// Properties
private static States _statusBarState;
private static States _navigationBarState;
private static uint _statusBarColor = DEFAULT_BACKGROUND_COLOR;
private static uint _navigationBarColor = DEFAULT_BACKGROUND_COLOR;
private static bool _isStatusBarTranslucent; // Just so we know whether its translucent when hidden or not
private static bool _isNavigationBarTranslucent;
private static bool _dimmed;
// ================================================================================================================
// INTERNAL INTERFACE ---------------------------------------------------------------------------------------------
static ApplicationChrome() {
applyUIStates();
applyUIColors();
}
private static void applyUIStates() {
#if USE_ANDROID
applyUIStatesAndroid();
#endif
}
private static void applyUIColors() {
#if USE_ANDROID
applyUIColorsAndroid();
#endif
}
#if USE_ANDROID
private static void applyUIStatesAndroid() {
int newFlagsValue = 0;
int newSystemUiVisibilityValue = 0;
// Apply dim values
if (_dimmed) newSystemUiVisibilityValue |= VIEW_SYSTEM_UI_FLAG_LOW_PROFILE;
// Apply color values
if (_navigationBarColor != DEFAULT_BACKGROUND_COLOR || _statusBarColor != DEFAULT_BACKGROUND_COLOR) newFlagsValue |= WINDOW_FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
// Apply status bar values
switch (_statusBarState) {
case States.Visible:
_isStatusBarTranslucent = false;
newFlagsValue |= WINDOW_FLAG_FORCE_NOT_FULLSCREEN;
break;
case States.VisibleOverContent:
_isStatusBarTranslucent = false;
newFlagsValue |= WINDOW_FLAG_FORCE_NOT_FULLSCREEN | WINDOW_FLAG_LAYOUT_IN_SCREEN;
newSystemUiVisibilityValue |= VIEW_SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
break;
case States.TranslucentOverContent:
_isStatusBarTranslucent = true;
newFlagsValue |= WINDOW_FLAG_FORCE_NOT_FULLSCREEN | WINDOW_FLAG_LAYOUT_IN_SCREEN | WINDOW_FLAG_TRANSLUCENT_STATUS;
newSystemUiVisibilityValue |= VIEW_SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
break;
case States.Hidden:
newFlagsValue |= WINDOW_FLAG_FULLSCREEN | WINDOW_FLAG_LAYOUT_IN_SCREEN;
if (_isStatusBarTranslucent) newFlagsValue |= WINDOW_FLAG_TRANSLUCENT_STATUS;
break;
}
// Applies navigation values
switch (_navigationBarState) {
case States.Visible:
_isNavigationBarTranslucent = false;
newSystemUiVisibilityValue |= VIEW_SYSTEM_UI_FLAG_LAYOUT_STABLE;
break;
case States.VisibleOverContent:
// TODO: Side effect: forces status bar over content if set to VISIBLE
_isNavigationBarTranslucent = false;
newSystemUiVisibilityValue |= VIEW_SYSTEM_UI_FLAG_LAYOUT_STABLE | VIEW_SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
break;
case States.TranslucentOverContent:
// TODO: Side effect: forces status bar over content if set to VISIBLE
_isNavigationBarTranslucent = true;
newFlagsValue |= WINDOW_FLAG_TRANSLUCENT_NAVIGATION;
newSystemUiVisibilityValue |= VIEW_SYSTEM_UI_FLAG_LAYOUT_STABLE | VIEW_SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
break;
case States.Hidden:
newSystemUiVisibilityValue |= VIEW_SYSTEM_UI_FLAG_FULLSCREEN | VIEW_SYSTEM_UI_FLAG_HIDE_NAVIGATION | VIEW_SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
if (_isNavigationBarTranslucent) newFlagsValue |= WINDOW_FLAG_TRANSLUCENT_NAVIGATION;
break;
}
if (Screen.fullScreen) Screen.fullScreen = false;
// Applies everything natively
setFlags(newFlagsValue);
setSystemUiVisibility(newSystemUiVisibilityValue);
}
private static void runOnAndroidUiThread(Action target) {
using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
using (var activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity")) {
activity.Call("runOnUiThread", new AndroidJavaRunnable(target));
}
}
}
private static void setSystemUiVisibility(int value) {
if (systemUiVisibilityValue != value) {
systemUiVisibilityValue = value;
runOnAndroidUiThread(setSystemUiVisibilityInThread);
}
}
private static void setSystemUiVisibilityInThread() {
using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
using (var activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity")) {
using (var window = activity.Call<AndroidJavaObject>("getWindow")) {
using (var view = window.Call<AndroidJavaObject>("getDecorView")) {
// We also remove the existing listener. It seems Unity uses it internally
// to detect changes to the visibility flags, and re-apply its own changes.
// For example, if we hide the navigation bar, it shows up again 1 sec later.
view.Call("setOnSystemUiVisibilityChangeListener", null);
view.Call("setSystemUiVisibility", systemUiVisibilityValue);
}
}
}
}
}
private static void setFlags(int value) {
if (flagsValue != value) {
flagsValue = value;
runOnAndroidUiThread(setFlagsInThread);
}
}
private static void setFlagsInThread() {
using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
using (var activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity")) {
using (var window = activity.Call<AndroidJavaObject>("getWindow")) {
window.Call("setFlags", flagsValue, -1); // (int)0x7FFFFFFF
}
}
}
}
private static void applyUIColorsAndroid() {
runOnAndroidUiThread(applyUIColorsAndroidInThread);
}
private static void applyUIColorsAndroidInThread() {
using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
using (var activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity")) {
using (var window = activity.Call<AndroidJavaObject>("getWindow")) {
//Debug.Log("Colors SET: " + _statusBarColor);
window.Call("setStatusBarColor", unchecked((int)_statusBarColor));
window.Call("setNavigationBarColor", unchecked((int)_navigationBarColor));
}
}
}
}
#endif
// ================================================================================================================
// ACCESSOR INTERFACE ---------------------------------------------------------------------------------------------
public static States navigationBarState {
get { return _navigationBarState; }
set {
if (_navigationBarState != value) {
_navigationBarState = value;
applyUIStates();
}
}
}
public static States statusBarState {
get { return _statusBarState; }
set {
if (_statusBarState != value) {
_statusBarState = value;
applyUIStates();
}
}
}
public static bool dimmed {
get { return _dimmed; }
set {
if (_dimmed != value) {
_dimmed = value;
applyUIStates();
}
}
}
public static uint statusBarColor {
get { return _statusBarColor; }
set {
if (_statusBarColor != value) {
_statusBarColor = value;
applyUIColors();
applyUIStates();
}
}
}
public static uint navigationBarColor {
get { return _navigationBarColor; }
set {
if (_navigationBarColor != value) {
_navigationBarColor = value;
applyUIColors();
applyUIStates();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text.Json;
using Xunit;
namespace Microsoft.JSInterop.Infrastructure
{
public class ByteArrayJsonConverterTest
{
private readonly JSRuntime JSRuntime;
private JsonSerializerOptions JsonSerializerOptions => JSRuntime.JsonSerializerOptions;
public ByteArrayJsonConverterTest()
{
JSRuntime = new TestJSRuntime();
}
[Fact]
public void Read_Throws_IfByteArraysToBeRevivedIsEmpty()
{
// Arrange
var json = "{}";
// Act & Assert
var ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
Assert.Equal("JSON serialization is attempting to deserialize an unexpected byte array.", ex.Message);
}
[Fact]
public void Read_Throws_IfJsonIsMissingByteArraysProperty()
{
// Arrange
JSRuntime.ByteArraysToBeRevived.Append(new byte[] { 1, 2 });
var json = "{}";
// Act & Assert
var ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
Assert.Equal("Unexpected JSON Token EndObject, expected 'PropertyName'.", ex.Message);
}
[Fact]
public void Read_Throws_IfJsonContainsUnknownContent()
{
// Arrange
JSRuntime.ByteArraysToBeRevived.Append(new byte[] { 1, 2 });
var json = "{\"foo\":2}";
// Act & Assert
var ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
Assert.Equal("Unexpected JSON Property foo.", ex.Message);
}
[Fact]
public void Read_Throws_IfJsonIsIncomplete()
{
// Arrange
JSRuntime.ByteArraysToBeRevived.Append(new byte[] { 1, 2 });
var json = $"{{\"__byte[]\":0";
// Act & Assert
var ex = Record.Exception(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
Assert.IsAssignableFrom<JsonException>(ex);
}
[Fact]
public void Read_ReadsBase64EncodedStrings()
{
// Arrange
var expected = new byte[] { 1, 5, 8 };
var json = JsonSerializer.Serialize(expected);
// Act
var deserialized = JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions)!;
// Assert
Assert.Equal(expected, deserialized);
}
[Fact]
public void Read_ThrowsIfTheInputIsNotAValidBase64String()
{
// Arrange
var json = "\"Hello world\"";
// Act
var ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
// Assert
Assert.Equal("JSON serialization is attempting to deserialize an unexpected byte array.", ex.Message);
}
[Fact]
public void Read_ReadsJson()
{
// Arrange
var byteArray = new byte[] { 1, 5, 7 };
JSRuntime.ByteArraysToBeRevived.Append(byteArray);
var json = $"{{\"__byte[]\":0}}";
// Act
var deserialized = JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions)!;
// Assert
Assert.Equal(byteArray, deserialized);
}
[Fact]
public void Read_ByteArraysIdAppearsMultipleTimesThrows()
{
// Arrange
var byteArray = new byte[] { 1, 5, 7 };
JSRuntime.ByteArraysToBeRevived.Append(byteArray);
var json = $"{{\"__byte[]\":9120,\"__byte[]\":0}}";
// Act
var ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
// Assert
Assert.Equal("Unexpected JSON Token PropertyName, expected 'EndObject'.", ex.Message);
}
[Fact]
public void Read_ByteArraysIdValueInvalidStringThrows()
{
// Arrange
var byteArray = new byte[] { 1, 5, 7 };
JSRuntime.ByteArraysToBeRevived.Append(byteArray);
var json = $"{{\"__byte[]\":\"something\"}}";
// Act
var ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
// Assert
Assert.Equal("Unexpected JSON Token String, expected 'Number'.", ex.Message);
}
[Fact]
public void Read_ByteArraysIdValueLargeNumberThrows()
{
// Arrange
var byteArray = new byte[] { 1, 5, 7 };
JSRuntime.ByteArraysToBeRevived.Append(byteArray);
var json = $"{{\"__byte[]\":5000000000}}";
// Act
var ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
// Assert
Assert.Equal("Unexpected number, expected 32-bit integer.", ex.Message);
}
[Fact]
public void Read_ByteArraysIdValueNegativeNumberThrows()
{
// Arrange
var byteArray = new byte[] { 1, 5, 7 };
JSRuntime.ByteArraysToBeRevived.Append(byteArray);
var json = $"{{\"__byte[]\":-5}}";
// Act
var ex = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions));
// Assert
Assert.Equal("Byte array -5 not found.", ex.Message);
}
[Fact]
public void Read_ReadsJson_WithFormatting()
{
// Arrange
var byteArray = new byte[] { 1, 5, 7 };
JSRuntime.ByteArraysToBeRevived.Append(byteArray);
var json =
@$"{{
""__byte[]"": 0
}}";
// Act
var deserialized = JsonSerializer.Deserialize<byte[]>(json, JsonSerializerOptions)!;
// Assert
Assert.Equal(byteArray, deserialized);
}
[Fact]
public void Read_ReturnsTheCorrectInstance()
{
// Arrange
// Track a few arrays and verify that the deserialized value returns the correct value.
var byteArray1 = new byte[] { 1, 5, 7 };
var byteArray2 = new byte[] { 2, 6, 8 };
var byteArray3 = new byte[] { 2, 6, 8 };
JSRuntime.ByteArraysToBeRevived.Append(byteArray1);
JSRuntime.ByteArraysToBeRevived.Append(byteArray2);
JSRuntime.ByteArraysToBeRevived.Append(byteArray3);
var json = $"[{{\"__byte[]\":2}},{{\"__byte[]\":1}}]";
// Act
var deserialized = JsonSerializer.Deserialize<byte[][]>(json, JsonSerializerOptions)!;
// Assert
Assert.Same(byteArray3, deserialized[0]);
Assert.Same(byteArray2, deserialized[1]);
}
[Fact]
public void WriteJsonMultipleTimes_IncrementsByteArrayId()
{
// Arrange
var byteArray = new byte[] { 1, 5, 7 };
// Act & Assert
for (var i = 0; i < 10; i++)
{
var json = JsonSerializer.Serialize(byteArray, JsonSerializerOptions);
Assert.Equal($"{{\"__byte[]\":{i + 1}}}", json);
}
}
}
}
| |
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Worker;
using Moq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Xunit;
using Microsoft.TeamFoundation.DistributedTask.Expressions;
namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker
{
public sealed class StepsRunnerL0
{
private Mock<IExecutionContext> _ec;
private StepsRunner _stepsRunner;
private Variables _variables;
private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
{
var hc = new TestHostContext(this, testName);
var expressionManager = new ExpressionManager();
expressionManager.Initialize(hc);
hc.SetSingleton<IExpressionManager>(expressionManager);
List<string> warnings;
_variables = new Variables(
hostContext: hc,
copy: new Dictionary<string, VariableValue>(),
warnings: out warnings);
_ec = new Mock<IExecutionContext>();
_ec.SetupAllProperties();
_ec.Setup(x => x.Variables).Returns(_variables);
_stepsRunner = new StepsRunner();
_stepsRunner.Initialize(hc);
return hc;
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task RunNormalStepsAllStepPass()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.SucceededOrFailed) },
new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) }
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Select(x => x.Object).ToList());
// Assert.
Assert.Equal(TaskResult.Succeeded, _ec.Object.Result ?? TaskResult.Succeeded);
Assert.Equal(2, variableSet.Length);
variableSet[0].Verify(x => x.RunAsync());
variableSet[1].Verify(x => x.RunAsync());
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task RunNormalStepsContinueOnError()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Succeeded, ExpressionManager.SucceededOrFailed) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Failed, ExpressionManager.SucceededOrFailed, true) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, true), CreateStep(TaskResult.Failed, ExpressionManager.Always, true) }
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Select(x => x.Object).ToList());
// Assert.
Assert.Equal(TaskResult.SucceededWithIssues, _ec.Object.Result);
Assert.Equal(2, variableSet.Length);
variableSet[0].Verify(x => x.RunAsync());
variableSet[1].Verify(x => x.RunAsync());
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task RunsAfterFailureBasedOnCondition()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
Expected = false,
},
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.SucceededOrFailed) },
Expected = true,
},
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Steps.Select(x => x.Object).ToList());
// Assert.
Assert.Equal(TaskResult.Failed, _ec.Object.Result ?? TaskResult.Succeeded);
Assert.Equal(2, variableSet.Steps.Length);
variableSet.Steps[0].Verify(x => x.RunAsync());
variableSet.Steps[1].Verify(x => x.RunAsync(), variableSet.Expected ? Times.Once() : Times.Never());
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task RunsAlwaysSteps()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new
{
Steps = new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
Expected = TaskResult.Succeeded,
},
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
Expected = TaskResult.Failed,
},
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
Expected = TaskResult.Failed,
},
new
{
Steps = new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Failed, ExpressionManager.Always) },
Expected = TaskResult.Failed,
},
new
{
Steps = new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Failed, ExpressionManager.Always, true) },
Expected = TaskResult.SucceededWithIssues,
},
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Steps.Select(x => x.Object).ToList());
// Assert.
Assert.Equal(variableSet.Expected, _ec.Object.Result ?? TaskResult.Succeeded);
Assert.Equal(2, variableSet.Steps.Length);
variableSet.Steps[0].Verify(x => x.RunAsync());
variableSet.Steps[1].Verify(x => x.RunAsync());
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task SetsJobResultCorrectly()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
Expected = TaskResult.Failed
},
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.SucceededOrFailed) },
Expected = TaskResult.Failed
},
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
Expected = TaskResult.Failed
},
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, continueOnError: true), CreateStep(TaskResult.Failed, ExpressionManager.Succeeded) },
Expected = TaskResult.Failed
},
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, continueOnError: true), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
Expected = TaskResult.SucceededWithIssues
},
new
{
Steps = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, continueOnError: true), CreateStep(TaskResult.Failed, ExpressionManager.Succeeded, continueOnError: true) },
Expected = TaskResult.SucceededWithIssues
},
new
{
Steps = new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.SucceededOrFailed) },
Expected = TaskResult.Succeeded
},
new
{
Steps = new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Failed, ExpressionManager.Succeeded) },
Expected = TaskResult.Failed
},
new
{
Steps = new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.SucceededWithIssues, ExpressionManager.Succeeded) },
Expected = TaskResult.SucceededWithIssues
},
new
{
Steps = new[] { CreateStep(TaskResult.SucceededWithIssues, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
Expected = TaskResult.SucceededWithIssues
},
new
{
Steps = new[] { CreateStep(TaskResult.SucceededWithIssues, ExpressionManager.Succeeded), CreateStep(TaskResult.Failed, ExpressionManager.Succeeded) },
Expected = TaskResult.Failed
},
// Abandoned
// Canceled
// Failed
// Skipped
// Succeeded
// SucceededWithIssues
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Steps.Select(x => x.Object).ToList());
// Assert.
Assert.True(
variableSet.Expected == (_ec.Object.Result ?? TaskResult.Succeeded),
$"Expected '{variableSet.Expected}'. Actual '{_ec.Object.Result}'. Steps: {FormatSteps(variableSet.Steps)}");
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task SkipsAfterFailureOnlyBaseOnCondition()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new
{
Step = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
Expected = false
},
new
{
Step = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.SucceededOrFailed) },
Expected = true
},
new
{
Step = new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
Expected = true
}
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Step.Select(x => x.Object).ToList());
// Assert.
Assert.Equal(2, variableSet.Step.Length);
variableSet.Step[0].Verify(x => x.RunAsync());
variableSet.Step[1].Verify(x => x.RunAsync(), variableSet.Expected ? Times.Once() : Times.Never());
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task AlwaysMeansAlways()
{
using (TestHostContext hc = CreateTestContext())
{
// Arrange.
var variableSets = new[]
{
new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
new[] { CreateStep(TaskResult.SucceededWithIssues, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
new[] { CreateStep(TaskResult.Failed, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) },
new[] { CreateStep(TaskResult.Canceled, ExpressionManager.Succeeded), CreateStep(TaskResult.Succeeded, ExpressionManager.Always) }
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Select(x => x.Object).ToList());
// Assert.
Assert.Equal(2, variableSet.Length);
variableSet[0].Verify(x => x.RunAsync());
variableSet[1].Verify(x => x.RunAsync(), Times.Once());
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async Task TreatsConditionErrorAsFailure()
{
using (TestHostContext hc = CreateTestContext())
{
var expressionManager = new Mock<IExpressionManager>();
expressionManager.Object.Initialize(hc);
hc.SetSingleton<IExpressionManager>(expressionManager.Object);
expressionManager.Setup(x => x.Evaluate(It.IsAny<IExecutionContext>(), It.IsAny<IExpressionNode>(), It.IsAny<bool>())).Throws(new Exception());
// Arrange.
var variableSets = new[]
{
new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
new[] { CreateStep(TaskResult.Succeeded, ExpressionManager.Succeeded) },
};
foreach (var variableSet in variableSets)
{
_ec.Object.Result = null;
// Act.
await _stepsRunner.RunAsync(
jobContext: _ec.Object,
steps: variableSet.Select(x => x.Object).ToList());
// Assert.
Assert.Equal(TaskResult.Failed, _ec.Object.Result ?? TaskResult.Succeeded);
}
}
}
private Mock<IStep> CreateStep(TaskResult result, IExpressionNode condition, Boolean continueOnError = false)
{
// Setup the step.
var step = new Mock<IStep>();
step.Setup(x => x.Condition).Returns(condition);
step.Setup(x => x.ContinueOnError).Returns(continueOnError);
step.Setup(x => x.Enabled).Returns(true);
step.Setup(x => x.RunAsync()).Returns(Task.CompletedTask);
// Setup the step execution context.
var stepContext = new Mock<IExecutionContext>();
stepContext.SetupAllProperties();
stepContext.Setup(x => x.Variables).Returns(_variables);
stepContext.Setup(x => x.Complete(It.IsAny<TaskResult?>(), It.IsAny<string>(), It.IsAny<string>()))
.Callback((TaskResult? r, string currentOperation, string resultCode) =>
{
if (r != null)
{
stepContext.Object.Result = r;
}
});
stepContext.Object.Result = result;
step.Setup(x => x.ExecutionContext).Returns(stepContext.Object);
return step;
}
private string FormatSteps(IEnumerable<Mock<IStep>> steps)
{
return String.Join(
" ; ",
steps.Select(x => String.Format(
CultureInfo.InvariantCulture,
"Returns={0},Condition=[{1}],ContinueOnError={2},Enabled={3}",
x.Object.ExecutionContext.Result,
x.Object.Condition,
x.Object.ContinueOnError,
x.Object.Enabled)));
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>CampaignCriterionSimulation</c> resource.</summary>
public sealed partial class CampaignCriterionSimulationName : gax::IResourceName, sys::IEquatable<CampaignCriterionSimulationName>
{
/// <summary>The possible contents of <see cref="CampaignCriterionSimulationName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>
/// customers/{customer_id}/campaignCriterionSimulations/{campaign_id}~{criterion_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// .
/// </summary>
CustomerCampaignCriterionTypeModificationMethodStartDateEndDate = 1,
}
private static gax::PathTemplate s_customerCampaignCriterionTypeModificationMethodStartDateEndDate = new gax::PathTemplate("customers/{customer_id}/campaignCriterionSimulations/{campaign_id_criterion_id_type_modification_method_start_date_end_date}");
/// <summary>
/// Creates a <see cref="CampaignCriterionSimulationName"/> containing an unparsed resource name.
/// </summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="CampaignCriterionSimulationName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CampaignCriterionSimulationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CampaignCriterionSimulationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CampaignCriterionSimulationName"/> with the pattern
/// <c>
/// customers/{customer_id}/campaignCriterionSimulations/{campaign_id}~{criterion_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// .
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="typeId">The <c>Type</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="modificationMethodId">
/// The <c>ModificationMethod</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <param name="startDateId">The <c>StartDate</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="endDateId">The <c>EndDate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="CampaignCriterionSimulationName"/> constructed from the provided ids.
/// </returns>
public static CampaignCriterionSimulationName FromCustomerCampaignCriterionTypeModificationMethodStartDateEndDate(string customerId, string campaignId, string criterionId, string typeId, string modificationMethodId, string startDateId, string endDateId) =>
new CampaignCriterionSimulationName(ResourceNameType.CustomerCampaignCriterionTypeModificationMethodStartDateEndDate, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)), typeId: gax::GaxPreconditions.CheckNotNullOrEmpty(typeId, nameof(typeId)), modificationMethodId: gax::GaxPreconditions.CheckNotNullOrEmpty(modificationMethodId, nameof(modificationMethodId)), startDateId: gax::GaxPreconditions.CheckNotNullOrEmpty(startDateId, nameof(startDateId)), endDateId: gax::GaxPreconditions.CheckNotNullOrEmpty(endDateId, nameof(endDateId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CampaignCriterionSimulationName"/> with
/// pattern
/// <c>
/// customers/{customer_id}/campaignCriterionSimulations/{campaign_id}~{criterion_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// .
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="typeId">The <c>Type</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="modificationMethodId">
/// The <c>ModificationMethod</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <param name="startDateId">The <c>StartDate</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="endDateId">The <c>EndDate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CampaignCriterionSimulationName"/> with pattern
/// <c>
/// customers/{customer_id}/campaignCriterionSimulations/{campaign_id}~{criterion_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// .
/// </returns>
public static string Format(string customerId, string campaignId, string criterionId, string typeId, string modificationMethodId, string startDateId, string endDateId) =>
FormatCustomerCampaignCriterionTypeModificationMethodStartDateEndDate(customerId, campaignId, criterionId, typeId, modificationMethodId, startDateId, endDateId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CampaignCriterionSimulationName"/> with
/// pattern
/// <c>
/// customers/{customer_id}/campaignCriterionSimulations/{campaign_id}~{criterion_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// .
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="typeId">The <c>Type</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="modificationMethodId">
/// The <c>ModificationMethod</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <param name="startDateId">The <c>StartDate</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="endDateId">The <c>EndDate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CampaignCriterionSimulationName"/> with pattern
/// <c>
/// customers/{customer_id}/campaignCriterionSimulations/{campaign_id}~{criterion_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// .
/// </returns>
public static string FormatCustomerCampaignCriterionTypeModificationMethodStartDateEndDate(string customerId, string campaignId, string criterionId, string typeId, string modificationMethodId, string startDateId, string endDateId) =>
s_customerCampaignCriterionTypeModificationMethodStartDateEndDate.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(typeId, nameof(typeId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(modificationMethodId, nameof(modificationMethodId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(startDateId, nameof(startDateId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(endDateId, nameof(endDateId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="CampaignCriterionSimulationName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>
/// customers/{customer_id}/campaignCriterionSimulations/{campaign_id}~{criterion_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="campaignCriterionSimulationName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <returns>The parsed <see cref="CampaignCriterionSimulationName"/> if successful.</returns>
public static CampaignCriterionSimulationName Parse(string campaignCriterionSimulationName) =>
Parse(campaignCriterionSimulationName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CampaignCriterionSimulationName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>
/// customers/{customer_id}/campaignCriterionSimulations/{campaign_id}~{criterion_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="campaignCriterionSimulationName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="CampaignCriterionSimulationName"/> if successful.</returns>
public static CampaignCriterionSimulationName Parse(string campaignCriterionSimulationName, bool allowUnparsed) =>
TryParse(campaignCriterionSimulationName, allowUnparsed, out CampaignCriterionSimulationName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CampaignCriterionSimulationName"/>
/// instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>
/// customers/{customer_id}/campaignCriterionSimulations/{campaign_id}~{criterion_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="campaignCriterionSimulationName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CampaignCriterionSimulationName"/>, or <c>null</c> if
/// parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string campaignCriterionSimulationName, out CampaignCriterionSimulationName result) =>
TryParse(campaignCriterionSimulationName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CampaignCriterionSimulationName"/>
/// instance; optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>
/// customers/{customer_id}/campaignCriterionSimulations/{campaign_id}~{criterion_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="campaignCriterionSimulationName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CampaignCriterionSimulationName"/>, or <c>null</c> if
/// parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string campaignCriterionSimulationName, bool allowUnparsed, out CampaignCriterionSimulationName result)
{
gax::GaxPreconditions.CheckNotNull(campaignCriterionSimulationName, nameof(campaignCriterionSimulationName));
gax::TemplatedResourceName resourceName;
if (s_customerCampaignCriterionTypeModificationMethodStartDateEndDate.TryParseName(campaignCriterionSimulationName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[]
{
'~',
'~',
'~',
'~',
'~',
});
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerCampaignCriterionTypeModificationMethodStartDateEndDate(resourceName[0], split1[0], split1[1], split1[2], split1[3], split1[4], split1[5]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(campaignCriterionSimulationName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private CampaignCriterionSimulationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string campaignId = null, string criterionId = null, string customerId = null, string endDateId = null, string modificationMethodId = null, string startDateId = null, string typeId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CampaignId = campaignId;
CriterionId = criterionId;
CustomerId = customerId;
EndDateId = endDateId;
ModificationMethodId = modificationMethodId;
StartDateId = startDateId;
TypeId = typeId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CampaignCriterionSimulationName"/> class from the component parts
/// of pattern
/// <c>
/// customers/{customer_id}/campaignCriterionSimulations/{campaign_id}~{criterion_id}~{type}~{modification_method}~{start_date}~{end_date}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="typeId">The <c>Type</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="modificationMethodId">
/// The <c>ModificationMethod</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <param name="startDateId">The <c>StartDate</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="endDateId">The <c>EndDate</c> ID. Must not be <c>null</c> or empty.</param>
public CampaignCriterionSimulationName(string customerId, string campaignId, string criterionId, string typeId, string modificationMethodId, string startDateId, string endDateId) : this(ResourceNameType.CustomerCampaignCriterionTypeModificationMethodStartDateEndDate, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)), typeId: gax::GaxPreconditions.CheckNotNullOrEmpty(typeId, nameof(typeId)), modificationMethodId: gax::GaxPreconditions.CheckNotNullOrEmpty(modificationMethodId, nameof(modificationMethodId)), startDateId: gax::GaxPreconditions.CheckNotNullOrEmpty(startDateId, nameof(startDateId)), endDateId: gax::GaxPreconditions.CheckNotNullOrEmpty(endDateId, nameof(endDateId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CampaignId { get; }
/// <summary>
/// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CriterionId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>EndDate</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string EndDateId { get; }
/// <summary>
/// The <c>ModificationMethod</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed
/// resource name.
/// </summary>
public string ModificationMethodId { get; }
/// <summary>
/// The <c>StartDate</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string StartDateId { get; }
/// <summary>
/// The <c>Type</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string TypeId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerCampaignCriterionTypeModificationMethodStartDateEndDate: return s_customerCampaignCriterionTypeModificationMethodStartDateEndDate.Expand(CustomerId, $"{CampaignId}~{CriterionId}~{TypeId}~{ModificationMethodId}~{StartDateId}~{EndDateId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as CampaignCriterionSimulationName);
/// <inheritdoc/>
public bool Equals(CampaignCriterionSimulationName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CampaignCriterionSimulationName a, CampaignCriterionSimulationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CampaignCriterionSimulationName a, CampaignCriterionSimulationName b) => !(a == b);
}
public partial class CampaignCriterionSimulation
{
/// <summary>
/// <see cref="CampaignCriterionSimulationName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal CampaignCriterionSimulationName ResourceNameAsCampaignCriterionSimulationName
{
get => string.IsNullOrEmpty(ResourceName) ? null : CampaignCriterionSimulationName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.RecommendationEngine.V1Beta1.Snippets
{
using Google.Api;
using Google.Api.Gax;
using Google.LongRunning;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedUserEventServiceClientSnippets
{
/// <summary>Snippet for WriteUserEvent</summary>
public void WriteUserEventRequestObject()
{
// Snippet: WriteUserEvent(WriteUserEventRequest, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
WriteUserEventRequest request = new WriteUserEventRequest
{
ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"),
UserEvent = new UserEvent(),
};
// Make the request
UserEvent response = userEventServiceClient.WriteUserEvent(request);
// End snippet
}
/// <summary>Snippet for WriteUserEventAsync</summary>
public async Task WriteUserEventRequestObjectAsync()
{
// Snippet: WriteUserEventAsync(WriteUserEventRequest, CallSettings)
// Additional: WriteUserEventAsync(WriteUserEventRequest, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
WriteUserEventRequest request = new WriteUserEventRequest
{
ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"),
UserEvent = new UserEvent(),
};
// Make the request
UserEvent response = await userEventServiceClient.WriteUserEventAsync(request);
// End snippet
}
/// <summary>Snippet for WriteUserEvent</summary>
public void WriteUserEvent()
{
// Snippet: WriteUserEvent(string, UserEvent, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]";
UserEvent userEvent = new UserEvent();
// Make the request
UserEvent response = userEventServiceClient.WriteUserEvent(parent, userEvent);
// End snippet
}
/// <summary>Snippet for WriteUserEventAsync</summary>
public async Task WriteUserEventAsync()
{
// Snippet: WriteUserEventAsync(string, UserEvent, CallSettings)
// Additional: WriteUserEventAsync(string, UserEvent, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]";
UserEvent userEvent = new UserEvent();
// Make the request
UserEvent response = await userEventServiceClient.WriteUserEventAsync(parent, userEvent);
// End snippet
}
/// <summary>Snippet for WriteUserEvent</summary>
public void WriteUserEventResourceNames()
{
// Snippet: WriteUserEvent(EventStoreName, UserEvent, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
EventStoreName parent = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]");
UserEvent userEvent = new UserEvent();
// Make the request
UserEvent response = userEventServiceClient.WriteUserEvent(parent, userEvent);
// End snippet
}
/// <summary>Snippet for WriteUserEventAsync</summary>
public async Task WriteUserEventResourceNamesAsync()
{
// Snippet: WriteUserEventAsync(EventStoreName, UserEvent, CallSettings)
// Additional: WriteUserEventAsync(EventStoreName, UserEvent, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
EventStoreName parent = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]");
UserEvent userEvent = new UserEvent();
// Make the request
UserEvent response = await userEventServiceClient.WriteUserEventAsync(parent, userEvent);
// End snippet
}
/// <summary>Snippet for CollectUserEvent</summary>
public void CollectUserEventRequestObject()
{
// Snippet: CollectUserEvent(CollectUserEventRequest, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
CollectUserEventRequest request = new CollectUserEventRequest
{
ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"),
UserEvent = "",
Uri = "",
Ets = 0L,
};
// Make the request
HttpBody response = userEventServiceClient.CollectUserEvent(request);
// End snippet
}
/// <summary>Snippet for CollectUserEventAsync</summary>
public async Task CollectUserEventRequestObjectAsync()
{
// Snippet: CollectUserEventAsync(CollectUserEventRequest, CallSettings)
// Additional: CollectUserEventAsync(CollectUserEventRequest, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
CollectUserEventRequest request = new CollectUserEventRequest
{
ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"),
UserEvent = "",
Uri = "",
Ets = 0L,
};
// Make the request
HttpBody response = await userEventServiceClient.CollectUserEventAsync(request);
// End snippet
}
/// <summary>Snippet for CollectUserEvent</summary>
public void CollectUserEvent()
{
// Snippet: CollectUserEvent(string, string, string, long, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]";
string userEvent = "";
string uri = "";
long ets = 0L;
// Make the request
HttpBody response = userEventServiceClient.CollectUserEvent(parent, userEvent, uri, ets);
// End snippet
}
/// <summary>Snippet for CollectUserEventAsync</summary>
public async Task CollectUserEventAsync()
{
// Snippet: CollectUserEventAsync(string, string, string, long, CallSettings)
// Additional: CollectUserEventAsync(string, string, string, long, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]";
string userEvent = "";
string uri = "";
long ets = 0L;
// Make the request
HttpBody response = await userEventServiceClient.CollectUserEventAsync(parent, userEvent, uri, ets);
// End snippet
}
/// <summary>Snippet for CollectUserEvent</summary>
public void CollectUserEventResourceNames()
{
// Snippet: CollectUserEvent(EventStoreName, string, string, long, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
EventStoreName parent = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]");
string userEvent = "";
string uri = "";
long ets = 0L;
// Make the request
HttpBody response = userEventServiceClient.CollectUserEvent(parent, userEvent, uri, ets);
// End snippet
}
/// <summary>Snippet for CollectUserEventAsync</summary>
public async Task CollectUserEventResourceNamesAsync()
{
// Snippet: CollectUserEventAsync(EventStoreName, string, string, long, CallSettings)
// Additional: CollectUserEventAsync(EventStoreName, string, string, long, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
EventStoreName parent = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]");
string userEvent = "";
string uri = "";
long ets = 0L;
// Make the request
HttpBody response = await userEventServiceClient.CollectUserEventAsync(parent, userEvent, uri, ets);
// End snippet
}
/// <summary>Snippet for ListUserEvents</summary>
public void ListUserEventsRequestObject()
{
// Snippet: ListUserEvents(ListUserEventsRequest, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
ListUserEventsRequest request = new ListUserEventsRequest
{
ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"),
Filter = "",
};
// Make the request
PagedEnumerable<ListUserEventsResponse, UserEvent> response = userEventServiceClient.ListUserEvents(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (UserEvent item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListUserEventsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (UserEvent item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<UserEvent> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (UserEvent item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListUserEventsAsync</summary>
public async Task ListUserEventsRequestObjectAsync()
{
// Snippet: ListUserEventsAsync(ListUserEventsRequest, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
ListUserEventsRequest request = new ListUserEventsRequest
{
ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"),
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListUserEventsResponse, UserEvent> response = userEventServiceClient.ListUserEventsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((UserEvent item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListUserEventsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (UserEvent item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<UserEvent> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (UserEvent item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListUserEvents</summary>
public void ListUserEvents()
{
// Snippet: ListUserEvents(string, string, string, int?, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]";
string filter = "";
// Make the request
PagedEnumerable<ListUserEventsResponse, UserEvent> response = userEventServiceClient.ListUserEvents(parent, filter);
// Iterate over all response items, lazily performing RPCs as required
foreach (UserEvent item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListUserEventsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (UserEvent item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<UserEvent> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (UserEvent item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListUserEventsAsync</summary>
public async Task ListUserEventsAsync()
{
// Snippet: ListUserEventsAsync(string, string, string, int?, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]";
string filter = "";
// Make the request
PagedAsyncEnumerable<ListUserEventsResponse, UserEvent> response = userEventServiceClient.ListUserEventsAsync(parent, filter);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((UserEvent item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListUserEventsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (UserEvent item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<UserEvent> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (UserEvent item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListUserEvents</summary>
public void ListUserEventsResourceNames()
{
// Snippet: ListUserEvents(EventStoreName, string, string, int?, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
EventStoreName parent = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]");
string filter = "";
// Make the request
PagedEnumerable<ListUserEventsResponse, UserEvent> response = userEventServiceClient.ListUserEvents(parent, filter);
// Iterate over all response items, lazily performing RPCs as required
foreach (UserEvent item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListUserEventsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (UserEvent item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<UserEvent> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (UserEvent item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListUserEventsAsync</summary>
public async Task ListUserEventsResourceNamesAsync()
{
// Snippet: ListUserEventsAsync(EventStoreName, string, string, int?, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
EventStoreName parent = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]");
string filter = "";
// Make the request
PagedAsyncEnumerable<ListUserEventsResponse, UserEvent> response = userEventServiceClient.ListUserEventsAsync(parent, filter);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((UserEvent item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListUserEventsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (UserEvent item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<UserEvent> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (UserEvent item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for PurgeUserEvents</summary>
public void PurgeUserEventsRequestObject()
{
// Snippet: PurgeUserEvents(PurgeUserEventsRequest, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
PurgeUserEventsRequest request = new PurgeUserEventsRequest
{
ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"),
Filter = "",
Force = false,
};
// Make the request
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> response = userEventServiceClient.PurgeUserEvents(request);
// Poll until the returned long-running operation is complete
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
PurgeUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> retrievedResponse = userEventServiceClient.PollOncePurgeUserEvents(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
PurgeUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PurgeUserEventsAsync</summary>
public async Task PurgeUserEventsRequestObjectAsync()
{
// Snippet: PurgeUserEventsAsync(PurgeUserEventsRequest, CallSettings)
// Additional: PurgeUserEventsAsync(PurgeUserEventsRequest, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
PurgeUserEventsRequest request = new PurgeUserEventsRequest
{
ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"),
Filter = "",
Force = false,
};
// Make the request
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> response = await userEventServiceClient.PurgeUserEventsAsync(request);
// Poll until the returned long-running operation is complete
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
PurgeUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> retrievedResponse = await userEventServiceClient.PollOncePurgeUserEventsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
PurgeUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PurgeUserEvents</summary>
public void PurgeUserEvents()
{
// Snippet: PurgeUserEvents(string, string, bool, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]";
string filter = "";
bool force = false;
// Make the request
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> response = userEventServiceClient.PurgeUserEvents(parent, filter, force);
// Poll until the returned long-running operation is complete
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
PurgeUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> retrievedResponse = userEventServiceClient.PollOncePurgeUserEvents(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
PurgeUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PurgeUserEventsAsync</summary>
public async Task PurgeUserEventsAsync()
{
// Snippet: PurgeUserEventsAsync(string, string, bool, CallSettings)
// Additional: PurgeUserEventsAsync(string, string, bool, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]";
string filter = "";
bool force = false;
// Make the request
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> response = await userEventServiceClient.PurgeUserEventsAsync(parent, filter, force);
// Poll until the returned long-running operation is complete
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
PurgeUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> retrievedResponse = await userEventServiceClient.PollOncePurgeUserEventsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
PurgeUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PurgeUserEvents</summary>
public void PurgeUserEventsResourceNames()
{
// Snippet: PurgeUserEvents(EventStoreName, string, bool, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
EventStoreName parent = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]");
string filter = "";
bool force = false;
// Make the request
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> response = userEventServiceClient.PurgeUserEvents(parent, filter, force);
// Poll until the returned long-running operation is complete
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
PurgeUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> retrievedResponse = userEventServiceClient.PollOncePurgeUserEvents(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
PurgeUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PurgeUserEventsAsync</summary>
public async Task PurgeUserEventsResourceNamesAsync()
{
// Snippet: PurgeUserEventsAsync(EventStoreName, string, bool, CallSettings)
// Additional: PurgeUserEventsAsync(EventStoreName, string, bool, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
EventStoreName parent = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]");
string filter = "";
bool force = false;
// Make the request
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> response = await userEventServiceClient.PurgeUserEventsAsync(parent, filter, force);
// Poll until the returned long-running operation is complete
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
PurgeUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<PurgeUserEventsResponse, PurgeUserEventsMetadata> retrievedResponse = await userEventServiceClient.PollOncePurgeUserEventsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
PurgeUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportUserEvents</summary>
public void ImportUserEventsRequestObject()
{
// Snippet: ImportUserEvents(ImportUserEventsRequest, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
ImportUserEventsRequest request = new ImportUserEventsRequest
{
ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"),
RequestId = "",
InputConfig = new InputConfig(),
ErrorsConfig = new ImportErrorsConfig(),
};
// Make the request
Operation<ImportUserEventsResponse, ImportMetadata> response = userEventServiceClient.ImportUserEvents(request);
// Poll until the returned long-running operation is complete
Operation<ImportUserEventsResponse, ImportMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ImportUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportUserEventsResponse, ImportMetadata> retrievedResponse = userEventServiceClient.PollOnceImportUserEvents(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportUserEventsAsync</summary>
public async Task ImportUserEventsRequestObjectAsync()
{
// Snippet: ImportUserEventsAsync(ImportUserEventsRequest, CallSettings)
// Additional: ImportUserEventsAsync(ImportUserEventsRequest, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
ImportUserEventsRequest request = new ImportUserEventsRequest
{
ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"),
RequestId = "",
InputConfig = new InputConfig(),
ErrorsConfig = new ImportErrorsConfig(),
};
// Make the request
Operation<ImportUserEventsResponse, ImportMetadata> response = await userEventServiceClient.ImportUserEventsAsync(request);
// Poll until the returned long-running operation is complete
Operation<ImportUserEventsResponse, ImportMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ImportUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportUserEventsResponse, ImportMetadata> retrievedResponse = await userEventServiceClient.PollOnceImportUserEventsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportUserEvents</summary>
public void ImportUserEvents()
{
// Snippet: ImportUserEvents(string, string, InputConfig, ImportErrorsConfig, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]";
string requestId = "";
InputConfig inputConfig = new InputConfig();
ImportErrorsConfig errorsConfig = new ImportErrorsConfig();
// Make the request
Operation<ImportUserEventsResponse, ImportMetadata> response = userEventServiceClient.ImportUserEvents(parent, requestId, inputConfig, errorsConfig);
// Poll until the returned long-running operation is complete
Operation<ImportUserEventsResponse, ImportMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ImportUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportUserEventsResponse, ImportMetadata> retrievedResponse = userEventServiceClient.PollOnceImportUserEvents(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportUserEventsAsync</summary>
public async Task ImportUserEventsAsync()
{
// Snippet: ImportUserEventsAsync(string, string, InputConfig, ImportErrorsConfig, CallSettings)
// Additional: ImportUserEventsAsync(string, string, InputConfig, ImportErrorsConfig, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]/catalogs/[CATALOG]/eventStores/[EVENT_STORE]";
string requestId = "";
InputConfig inputConfig = new InputConfig();
ImportErrorsConfig errorsConfig = new ImportErrorsConfig();
// Make the request
Operation<ImportUserEventsResponse, ImportMetadata> response = await userEventServiceClient.ImportUserEventsAsync(parent, requestId, inputConfig, errorsConfig);
// Poll until the returned long-running operation is complete
Operation<ImportUserEventsResponse, ImportMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ImportUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportUserEventsResponse, ImportMetadata> retrievedResponse = await userEventServiceClient.PollOnceImportUserEventsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportUserEvents</summary>
public void ImportUserEventsResourceNames()
{
// Snippet: ImportUserEvents(EventStoreName, string, InputConfig, ImportErrorsConfig, CallSettings)
// Create client
UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
// Initialize request argument(s)
EventStoreName parent = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]");
string requestId = "";
InputConfig inputConfig = new InputConfig();
ImportErrorsConfig errorsConfig = new ImportErrorsConfig();
// Make the request
Operation<ImportUserEventsResponse, ImportMetadata> response = userEventServiceClient.ImportUserEvents(parent, requestId, inputConfig, errorsConfig);
// Poll until the returned long-running operation is complete
Operation<ImportUserEventsResponse, ImportMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ImportUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportUserEventsResponse, ImportMetadata> retrievedResponse = userEventServiceClient.PollOnceImportUserEvents(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportUserEventsAsync</summary>
public async Task ImportUserEventsResourceNamesAsync()
{
// Snippet: ImportUserEventsAsync(EventStoreName, string, InputConfig, ImportErrorsConfig, CallSettings)
// Additional: ImportUserEventsAsync(EventStoreName, string, InputConfig, ImportErrorsConfig, CancellationToken)
// Create client
UserEventServiceClient userEventServiceClient = await UserEventServiceClient.CreateAsync();
// Initialize request argument(s)
EventStoreName parent = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]");
string requestId = "";
InputConfig inputConfig = new InputConfig();
ImportErrorsConfig errorsConfig = new ImportErrorsConfig();
// Make the request
Operation<ImportUserEventsResponse, ImportMetadata> response = await userEventServiceClient.ImportUserEventsAsync(parent, requestId, inputConfig, errorsConfig);
// Poll until the returned long-running operation is complete
Operation<ImportUserEventsResponse, ImportMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ImportUserEventsResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportUserEventsResponse, ImportMetadata> retrievedResponse = await userEventServiceClient.PollOnceImportUserEventsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportUserEventsResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
#if !netstandard11
using System.Numerics;
#endif
namespace System
{
internal static partial class SpanHelpers
{
public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
byte valueHead = value;
ref byte valueTail = ref Unsafe.Add(ref value, 1);
int valueTailLength = valueLength - 1;
int index = 0;
for (;;)
{
Debug.Assert(0 <= index && index <= searchSpaceLength); // Ensures no deceptive underflows in the computation of "remainingSearchSpaceLength".
int remainingSearchSpaceLength = searchSpaceLength - index - valueTailLength;
if (remainingSearchSpaceLength <= 0)
break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there.
// Do a quick search for the first element of "value".
int relativeIndex = IndexOf(ref Unsafe.Add(ref searchSpace, index), valueHead, remainingSearchSpaceLength);
if (relativeIndex == -1)
break;
index += relativeIndex;
// Found the first element of "value". See if the tail matches.
if (SequenceEqual(ref Unsafe.Add(ref searchSpace, index + 1), ref valueTail, valueTailLength))
return index; // The tail matched. Return a successful find.
index++;
}
return -1;
}
public static int IndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
int index = -1;
for (int i = 0; i < valueLength; i++)
{
var tempIndex = IndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength);
if (tempIndex != -1)
{
index = (index == -1 || index > tempIndex) ? tempIndex : index;
}
}
return index;
}
public static unsafe int IndexOf(ref byte searchSpace, byte value, int length)
{
Debug.Assert(length >= 0);
uint uValue = value; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)0; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)(uint)length;
#if !netstandard11
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
unchecked
{
int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)(uint)((Vector<byte>.Count - unaligned) & (Vector<byte>.Count - 1));
}
}
SequentialScan:
#endif
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
if (uValue == Unsafe.Add(ref searchSpace, index))
goto Found;
if (uValue == Unsafe.Add(ref searchSpace, index + 1))
goto Found1;
if (uValue == Unsafe.Add(ref searchSpace, index + 2))
goto Found2;
if (uValue == Unsafe.Add(ref searchSpace, index + 3))
goto Found3;
if (uValue == Unsafe.Add(ref searchSpace, index + 4))
goto Found4;
if (uValue == Unsafe.Add(ref searchSpace, index + 5))
goto Found5;
if (uValue == Unsafe.Add(ref searchSpace, index + 6))
goto Found6;
if (uValue == Unsafe.Add(ref searchSpace, index + 7))
goto Found7;
index += 8;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
if (uValue == Unsafe.Add(ref searchSpace, index))
goto Found;
if (uValue == Unsafe.Add(ref searchSpace, index + 1))
goto Found1;
if (uValue == Unsafe.Add(ref searchSpace, index + 2))
goto Found2;
if (uValue == Unsafe.Add(ref searchSpace, index + 3))
goto Found3;
index += 4;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
if (uValue == Unsafe.Add(ref searchSpace, index))
goto Found;
index += 1;
}
#if !netstandard11
if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length))
{
nLength = (IntPtr)(uint)((length - (uint)index) & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> vComparison = GetVector(value);
while ((byte*)nLength > (byte*)index)
{
var vMatches = Vector.Equals(vComparison, Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index)));
if (Vector<byte>.Zero.Equals(vMatches))
{
index += Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(byte*)index + LocateFirstFoundByte(vMatches);
}
if ((int)(byte*)index < length)
{
unchecked
{
nLength = (IntPtr)(length - (int)(byte*)index);
}
goto SequentialScan;
}
}
#endif
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static unsafe int IndexOfAny(ref byte searchSpace, byte value0, byte value1, int length)
{
Debug.Assert(length >= 0);
uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)0; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)(uint)length;
#if !netstandard11
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
unchecked
{
int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)(uint)((Vector<byte>.Count - unaligned) & (Vector<byte>.Count - 1));
}
}
SequentialScan:
#endif
uint lookUp;
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, index + 4);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found4;
lookUp = Unsafe.Add(ref searchSpace, index + 5);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found5;
lookUp = Unsafe.Add(ref searchSpace, index + 6);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found6;
lookUp = Unsafe.Add(ref searchSpace, index + 7);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found7;
index += 8;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found3;
index += 4;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
index += 1;
}
#if !netstandard11
if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length))
{
nLength = (IntPtr)(uint)((length - (uint)index) & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> values0 = GetVector(value0);
Vector<byte> values1 = GetVector(value1);
while ((byte*)nLength > (byte*)index)
{
var vData = Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index));
var vMatches = Vector.BitwiseOr(
Vector.Equals(vData, values0),
Vector.Equals(vData, values1));
if (Vector<byte>.Zero.Equals(vMatches))
{
index += Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(byte*)index + LocateFirstFoundByte(vMatches);
}
if ((int)(byte*)index < length)
{
unchecked
{
nLength = (IntPtr)(length - (int)(byte*)index);
}
goto SequentialScan;
}
}
#endif
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static unsafe int IndexOfAny(ref byte searchSpace, byte value0, byte value1, byte value2, int length)
{
Debug.Assert(length >= 0);
uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue2 = value2; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)0; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)(uint)length;
#if !netstandard11
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
unchecked
{
int unaligned = (int)(byte*)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
nLength = (IntPtr)(uint)((Vector<byte>.Count - unaligned) & (Vector<byte>.Count - 1));
}
}
SequentialScan:
#endif
uint lookUp;
while ((byte*)nLength >= (byte*)8)
{
nLength -= 8;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found3;
lookUp = Unsafe.Add(ref searchSpace, index + 4);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found4;
lookUp = Unsafe.Add(ref searchSpace, index + 5);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found5;
lookUp = Unsafe.Add(ref searchSpace, index + 6);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found6;
lookUp = Unsafe.Add(ref searchSpace, index + 7);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found7;
index += 8;
}
if ((byte*)nLength >= (byte*)4)
{
nLength -= 4;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
lookUp = Unsafe.Add(ref searchSpace, index + 1);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found1;
lookUp = Unsafe.Add(ref searchSpace, index + 2);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found2;
lookUp = Unsafe.Add(ref searchSpace, index + 3);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found3;
index += 4;
}
while ((byte*)nLength > (byte*)0)
{
nLength -= 1;
lookUp = Unsafe.Add(ref searchSpace, index);
if (uValue0 == lookUp || uValue1 == lookUp || uValue2 == lookUp)
goto Found;
index += 1;
}
#if !netstandard11
if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length))
{
nLength = (IntPtr)(uint)((length - (uint)index) & ~(Vector<byte>.Count - 1));
// Get comparison Vector
Vector<byte> values0 = GetVector(value0);
Vector<byte> values1 = GetVector(value1);
Vector<byte> values2 = GetVector(value2);
while ((byte*)nLength > (byte*)index)
{
var vData = Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, index));
var vMatches = Vector.BitwiseOr(
Vector.BitwiseOr(
Vector.Equals(vData, values0),
Vector.Equals(vData, values1)),
Vector.Equals(vData, values2));
if (Vector<byte>.Zero.Equals(vMatches))
{
index += Vector<byte>.Count;
continue;
}
// Find offset of first match
return (int)(byte*)index + LocateFirstFoundByte(vMatches);
}
if ((int)(byte*)index < length)
{
unchecked
{
nLength = (IntPtr)(length - (int)(byte*)index);
}
goto SequentialScan;
}
}
#endif
return -1;
Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return (int)(byte*)index;
Found1:
return (int)(byte*)(index + 1);
Found2:
return (int)(byte*)(index + 2);
Found3:
return (int)(byte*)(index + 3);
Found4:
return (int)(byte*)(index + 4);
Found5:
return (int)(byte*)(index + 5);
Found6:
return (int)(byte*)(index + 6);
Found7:
return (int)(byte*)(index + 7);
}
public static unsafe bool SequenceEqual(ref byte first, ref byte second, int length)
{
Debug.Assert(length >= 0);
if (Unsafe.AreSame(ref first, ref second))
goto Equal;
IntPtr i = (IntPtr)0; // Use IntPtr and byte* for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr n = (IntPtr)length;
#if !netstandard11
if (Vector.IsHardwareAccelerated && (byte*)n >= (byte*)Vector<byte>.Count)
{
n -= Vector<byte>.Count;
while ((byte*)n > (byte*)i)
{
if (Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref first, i)) !=
Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref second, i)))
{
goto NotEqual;
}
i += Vector<byte>.Count;
}
return Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref first, n)) ==
Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref second, n));
}
#endif
if ((byte*)n >= (byte*)sizeof(UIntPtr))
{
n -= sizeof(UIntPtr);
while ((byte*)n > (byte*)i)
{
if (Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref first, i)) !=
Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref second, i)))
{
goto NotEqual;
}
i += sizeof(UIntPtr);
}
return Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref first, n)) ==
Unsafe.ReadUnaligned<UIntPtr>(ref Unsafe.AddByteOffset(ref second, n));
}
while ((byte*)n > (byte*)i)
{
if (Unsafe.AddByteOffset(ref first, i) != Unsafe.AddByteOffset(ref second, i))
goto NotEqual;
i += 1;
}
Equal:
return true;
NotEqual: // Workaround for https://github.com/dotnet/coreclr/issues/13549
return false;
}
#if !netstandard11
// Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateFirstFoundByte(Vector<byte> match)
{
var vector64 = Vector.AsVectorUInt64(match);
ulong candidate = 0;
int i = 0;
// Pattern unrolled by jit https://github.com/dotnet/coreclr/pull/8001
for (; i < Vector<ulong>.Count; i++)
{
candidate = vector64[i];
if (candidate != 0)
{
break;
}
}
// Single LEA instruction with jitted const (using function result)
return i * 8 + LocateFirstFoundByte(candidate);
}
#endif
#if !netstandard11
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateFirstFoundByte(ulong match)
{
unchecked
{
// Flag least significant power of two bit
var powerOfTwoFlag = match ^ (match - 1);
// Shift all powers of two into the high byte and extract
return (int)((powerOfTwoFlag * XorPowerOfTwoToHighByte) >> 57);
}
}
#endif
#if !netstandard11
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Vector<byte> GetVector(byte vectorByte)
{
#if !netcoreapp
// Vector<byte> .ctor doesn't become an intrinsic due to detection issue
// However this does cause it to become an intrinsic (with additional multiply and reg->reg copy)
// https://github.com/dotnet/coreclr/issues/7459#issuecomment-253965670
return Vector.AsVectorByte(new Vector<uint>(vectorByte * 0x01010101u));
#else
return new Vector<byte>(vectorByte);
#endif
}
#endif
#if !netstandard11
private const ulong XorPowerOfTwoToHighByte = (0x07ul |
0x06ul << 8 |
0x05ul << 16 |
0x04ul << 24 |
0x03ul << 32 |
0x02ul << 40 |
0x01ul << 48) + 1;
#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 System.Collections.Generic;
using System.Text;
using TestLibrary;
public class StringConcat1
{
public static int Main()
{
StringConcat1 sc1 = new StringConcat1();
TestLibrary.TestFramework.BeginTestCase("StringConcat1");
if (sc1.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
retVal = PosTest10() && retVal;
retVal = PosTest11() && retVal;
retVal = PosTest12() && retVal;
retVal = PosTest13() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
string ActualResult;
object ObjA;
TestLibrary.TestFramework.BeginScenario("PostTest1:Concat a random object");
try
{
ObjA = new object();
ActualResult = string.Concat(ObjA);
if (ActualResult != ObjA.ToString())
{
TestLibrary.TestFramework.LogError("001", "Concat a random object ExpectResult is" +ObjA.ToString()+ ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string ActualResult;
object ObjA;
TestLibrary.TestFramework.BeginScenario("PostTest2:Concat an object of null");
try
{
ObjA = null;
ActualResult = string.Concat(ObjA);
if (ActualResult != string.Empty)
{
TestLibrary.TestFramework.LogError("003", "Concat an object of null ExpectResult is" +string.Empty+" ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string ActualResult;
object ObjA;
TestLibrary.TestFramework.BeginScenario("PosTest3:Concat an object of empty");
try
{
ObjA = "";
ActualResult = string.Concat(ObjA);
if (ActualResult != ObjA.ToString())
{
TestLibrary.TestFramework.LogError("005", "Concat an object of empty ExpectResult is equel" +ObjA.ToString()+ ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string ActualResult;
string ObjA;
TestLibrary.TestFramework.BeginScenario("PosTest4: Concat an object of two tab");
try
{
ObjA = new string('\t', 2);
ActualResult = string.Concat(ObjA);
if (ActualResult != ObjA.ToString())
{
TestLibrary.TestFramework.LogError("007", "Concat an object of two tab ExpectResult is" +ObjA.ToString()+" ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
string ActualResult;
object ObjA;
TestLibrary.TestFramework.BeginScenario("PosTest5:Concat an object of int");
try
{
ObjA = new int();
ActualResult = string.Concat(ObjA);
if (ActualResult != ObjA.ToString())
{
TestLibrary.TestFramework.LogError("009", "Concat an object of int ExpectResult is equel" +ObjA.ToString()+" ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
string ActualResult;
object ObjA;
TestLibrary.TestFramework.BeginScenario("PosTest6: Concat an object of datetime");
try
{
ObjA = new DateTime();
ActualResult = string.Concat(ObjA);
if (ActualResult != ObjA.ToString())
{
TestLibrary.TestFramework.LogError("011", " ExpectResult is equel" +ObjA.ToString()+ ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
string ActualResult;
object ObjA;
TestLibrary.TestFramework.BeginScenario("PosTest7: Concat an object of bool");
try
{
ObjA = new bool();
ActualResult = string.Concat(ObjA);
if (ActualResult != ObjA.ToString())
{
TestLibrary.TestFramework.LogError("013", "Concat an object of bool ExpectResult is equel" +ObjA.ToString()+",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
string ActualResult;
object ObjA;
TestLibrary.TestFramework.BeginScenario("PosTest8:Concat an object of random class instance ");
try
{
ObjA = new StringConcat1();
ActualResult = string.Concat(ObjA);
if (ActualResult != ObjA.ToString())
{
TestLibrary.TestFramework.LogError("015", "Concat an object of random class instance ExpectResult is equel" +ObjA.ToString()+" ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest9()
{
bool retVal = true;
string ActualResult;
object ObjA;
TestLibrary.TestFramework.BeginScenario("PosTest9: Concat an object of Guid");
try
{
ObjA = new Guid();
ActualResult = string.Concat(ObjA);
if (ActualResult != ObjA.ToString())
{
TestLibrary.TestFramework.LogError("017", "Concat an object of Guid ExpectResult is equel"+ ObjA.ToString()+",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest10()
{
bool retVal = true;
string ActualResult;
object ObjA;
TestLibrary.TestFramework.BeginScenario("PosTest10:Concat an object of Random ");
try
{
ObjA = new Random(-55);
ActualResult = string.Concat(ObjA);
if (ActualResult != ObjA.ToString())
{
TestLibrary.TestFramework.LogError("019", "Concat an object of Random ExpectResult is equel" + ObjA.ToString() +",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("020", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest11()
{
bool retVal = true;
string ActualResult;
object ObjA;
TestLibrary.TestFramework.BeginScenario("PosTest11: Concat an object of float");
try
{
ObjA = new float();
ActualResult = string.Concat(ObjA);
if (ActualResult != ObjA.ToString())
{
TestLibrary.TestFramework.LogError("021", "Concat an object of float ExpectResult is equel" +ObjA.ToString()+" ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("022", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest12()
{
bool retVal = true;
string ActualResult;
object ObjA;
TestLibrary.TestFramework.BeginScenario("PosTest12:Concat an object of SByte");
try
{
ObjA = new SByte();
ActualResult = string.Concat(ObjA);
if (ActualResult != ObjA.ToString())
{
TestLibrary.TestFramework.LogError("023", "Concat an object of SByte ExpectResult is equel" + ObjA.ToString()+ ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("024", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest13()
{
bool retVal = true;
string ActualResult;
object ObjA;
TestLibrary.TestFramework.BeginScenario("PosTest13:Concat an object of number of less than 0");
try
{
ObjA = -123;
ActualResult = string.Concat(ObjA);
if (ActualResult != ObjA.ToString())
{
TestLibrary.TestFramework.LogError("025", "Concat an object of number of less than 0 ExpectResult is equel" + ObjA.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("026", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
}
| |
/* ====================================================================
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.HSSF.UserModel
{
using System;
using System.Collections;
using System.Collections.Generic;
using NPOI.HSSF.Record;
using NPOI.SS.UserModel;
using NPOI.SS;
/// <summary>
/// High level representation of a row of a spReadsheet.
/// Only rows that have cells should be Added to a Sheet.
/// @author Andrew C. Oliver (acoliver at apache dot org)
/// @author Glen Stampoultzis (glens at apache.org)
/// </summary>
[Serializable]
public class HSSFRow : IComparable,IRow
{
/// <summary>
/// used for collections
/// </summary>
public const int INITIAL_CAPACITY = 5;
private int rowNum;
private SortedDictionary<int, ICell> cells = new SortedDictionary<int, ICell>();
/**
* reference to low level representation
*/
[NonSerialized]
private RowRecord row;
/**
* reference to containing low level Workbook
*/
private HSSFWorkbook book;
/**
* reference to containing Sheet
*/
private HSSFSheet sheet;
// TODO - ditch this constructor
[Obsolete]
public HSSFRow()
{
}
/// <summary>
/// Creates new HSSFRow from scratch. Only HSSFSheet should do this.
/// </summary>
/// <param name="book">low-level Workbook object containing the sheet that Contains this row</param>
/// <param name="sheet">low-level Sheet object that Contains this Row</param>
/// <param name="rowNum">the row number of this row (0 based)</param>
///<see cref="NPOI.HSSF.UserModel.HSSFSheet.CreateRow(int)"/>
public HSSFRow(HSSFWorkbook book, HSSFSheet sheet, int rowNum):this(book, sheet, new RowRecord(rowNum))
{
}
/// <summary>
/// Creates an HSSFRow from a low level RowRecord object. Only HSSFSheet should do
/// this. HSSFSheet uses this when an existing file is Read in.
/// </summary>
/// <param name="book">low-level Workbook object containing the sheet that Contains this row</param>
/// <param name="sheet"> low-level Sheet object that Contains this Row</param>
/// <param name="record">the low level api object this row should represent</param>
///<see cref="NPOI.HSSF.UserModel.HSSFSheet.CreateRow(int)"/>
public HSSFRow(HSSFWorkbook book, HSSFSheet sheet, RowRecord record)
{
this.book = book;
this.sheet = sheet;
row = record;
RowNum=(record.RowNumber);
// Don't trust colIx boundaries as read by other apps
// set the RowRecord empty for the moment
record.SetEmpty();
}
/// <summary>
/// Use this to create new cells within the row and return it.
/// The cell that is returned is a CELL_TYPE_BLANK (<see cref="ICell"/>/<see cref="CellType.Blank"/>).
/// The type can be changed either through calling <c>SetCellValue</c> or <c>SetCellType</c>.
/// </summary>
/// <param name="column">the column number this cell represents</param>
/// <returns>a high level representation of the created cell.</returns>
public ICell CreateCell(int column)
{
return this.CreateCell(column, CellType.Blank);
}
/// <summary>
/// Use this to create new cells within the row and return it.
/// The cell that is returned is a CELL_TYPE_BLANK. The type can be changed
/// either through calling setCellValue or setCellType.
/// </summary>
/// <param name="columnIndex">the column number this cell represents</param>
/// <param name="type">a high level representation of the created cell.</param>
/// <returns></returns>
public ICell CreateCell(int columnIndex, CellType type)
{
short shortCellNum = (short)columnIndex;
if (columnIndex > 0x7FFF)
{
shortCellNum = (short)(0xffff - columnIndex);
}
ICell cell = new HSSFCell(book, sheet, RowNum, (short)columnIndex, type);
AddCell(cell);
sheet.Sheet.AddValueRecord(RowNum, ((HSSFCell)cell).CellValueRecord);
return cell;
}
public IRow CopyRowTo(int targetIndex)
{
return this.sheet.CopyRow(this.RowNum, targetIndex);
}
public ICell CopyCell(int sourceIndex, int targetIndex)
{
return NPOI.SS.Util.CellUtil.CopyCell(this, sourceIndex, targetIndex);
}
/// <summary>
/// Remove the Cell from this row.
/// </summary>
/// <param name="cell">The cell to Remove.</param>
public void RemoveCell(ICell cell)
{
if (cell == null)
{
throw new ArgumentException("cell must not be null");
}
RemoveCell((HSSFCell)cell, true);
}
/// <summary>
/// Removes the cell.
/// </summary>
/// <param name="cell">The cell.</param>
/// <param name="alsoRemoveRecords">if set to <c>true</c> [also remove records].</param>
private void RemoveCell(ICell cell, bool alsoRemoveRecords)
{
int column = cell.ColumnIndex;
if (column < 0)
{
throw new Exception("Negative cell indexes not allowed");
}
//if (column >= cells.Count || cell != cells[column])
if(!cells.ContainsKey(column)|| cell!=cells[column])
{
throw new Exception("Specified cell is not from this row");
}
if (cell.IsPartOfArrayFormulaGroup)
{
((HSSFCell)cell).NotifyArrayFormulaChanging();
}
cells.Remove(column);
if (alsoRemoveRecords)
{
CellValueRecordInterface cval = ((HSSFCell)cell).CellValueRecord;
sheet.Sheet.RemoveValueRecord(RowNum, cval);
}
if (cell.ColumnIndex + 1 == row.LastCol)
{
row.LastCol = CalculateNewLastCellPlusOne(row.LastCol);
}
if (cell.ColumnIndex == row.FirstCol)
{
row.FirstCol = CalculateNewFirstCell(row.FirstCol);
}
}
/**
* used internally to refresh the "last cell plus one" when the last cell is removed.
* @return 0 when row contains no cells
*/
private int CalculateNewLastCellPlusOne(int lastcell)
{
int cellIx = lastcell - 1;
ICell r = RetrieveCell(cellIx);
while (r == null)
{
if (cellIx < 0)
{
return 0;
}
r = RetrieveCell(--cellIx);
}
return cellIx + 1;
}
/**
* used internally to refresh the "first cell" when the first cell is removed.
* @return 0 when row contains no cells (also when first cell is occupied)
*/
private int CalculateNewFirstCell(int firstcell)
{
int cellIx = firstcell + 1;
ICell r = RetrieveCell(cellIx);
if (cells.Count == 0)
return 0;
while (r == null)
{
if (cellIx <= cells.Count)
{
return 0;
}
r = RetrieveCell(++cellIx);
}
return cellIx;
}
/// <summary>
/// Create a high level Cell object from an existing low level record. Should
/// only be called from HSSFSheet or HSSFRow itself.
/// </summary>
/// <param name="cell">The low level cell to Create the high level representation from</param>
/// <returns> the low level record passed in</returns>
public ICell CreateCellFromRecord(CellValueRecordInterface cell)
{
ICell hcell = new HSSFCell(book, sheet, cell);
AddCell(hcell);
int colIx = cell.Column;
if (row.IsEmpty)
{
row.FirstCol=(colIx);
row.LastCol=(colIx + 1);
}
else
{
if (colIx < row.FirstCol)
{
row.FirstCol = (colIx);
}
else if (colIx > row.LastCol)
{
row.LastCol = (colIx + 1);
}
else
{
// added cell is within first and last cells
}
}
// TODO - RowRecord column boundaries need to be updated for cell comments too
return hcell;
}
/// <summary>
/// true, when the row is invisible. This is the case when the height is zero.
/// </summary>
public bool IsHidden
{
get { return this.ZeroHeight; }
set { this.ZeroHeight = value; }
}
/// <summary>
/// Removes all the cells from the row, and their
/// records too.
/// </summary>
public void RemoveAllCells()
{
ICell[] cellsToRemove = new ICell[cells.Values.Count];
cells.Values.CopyTo(cellsToRemove, 0);
foreach (ICell cell in cellsToRemove)
{
RemoveCell(cell, true);
}
}
/// <summary>
/// Get row number this row represents
/// </summary>
/// <value>the row number (0 based)</value>
public int RowNum
{
get
{
return rowNum;
}
set
{
int maxrow = SpreadsheetVersion.EXCEL97.LastRowIndex;
if ((value < 0) || (value > maxrow))
{
throw new ArgumentException("Invalid row number (" + value
+ ") outside allowable range (0.." + maxrow + ")");
}
this.rowNum = value;
if (row != null)
{
row.RowNumber = (value); // used only for KEY comparison (HSSFRow)
}
}
}
/// <summary>
/// Returns the rows outline level. Increased as you
/// put it into more Groups (outlines), reduced as
/// you take it out of them.
/// </summary>
/// <value>The outline level.</value>
public int OutlineLevel
{
get { return row.OutlineLevel; }
}
/// <summary>
/// Moves the supplied cell to a new column, which
/// must not already have a cell there!
/// </summary>
/// <param name="cell">The cell to move</param>
/// <param name="newColumn">The new column number (0 based)</param>
public void MoveCell(ICell cell, int newColumn)
{
// Ensure the destination is free
//if (cells.Count > newColumn && cells[newColumn] != null)
if(cells.ContainsKey(newColumn))
{
throw new ArgumentException("Asked to move cell to column " + newColumn + " but there's already a cell there");
}
// Check it's one of ours
bool existflag = false;
foreach (ICell cellinrow in cells.Values)
{
if (cellinrow.Equals(cell))
{
existflag = true;
break;
}
}
if (!existflag)
{
throw new ArgumentException("Asked to move a cell, but it didn't belong to our row");
}
// Move the cell to the new position
// (Don't Remove the records though)
RemoveCell(cell, false);
((HSSFCell)cell).UpdateCellNum(newColumn);
AddCell(cell);
}
/**
* Returns the HSSFSheet this row belongs to
*
* @return the HSSFSheet that owns this row
*/
public ISheet Sheet
{
get
{
return sheet;
}
}
/// <summary>
/// used internally to Add a cell.
/// </summary>
/// <param name="cell">The cell.</param>
private void AddCell(ICell cell)
{
int column = cell.ColumnIndex;
// re-allocate cells array as required.
//if (column >= cells.Count)
//{
// HSSFCell[] oldCells = cells;
// int newSize = oldCells.Length * 2;
// if (newSize < column + 1)
// {
// newSize = column + 1;
// }
// cells = new HSSFCell[newSize];
// Array.Copy(oldCells, 0, cells, 0, oldCells.Length);
//}
if (cells.ContainsKey(column))
{
cells.Remove(column);
}
cells.Add(column, cell);
// fix up firstCol and lastCol indexes
if (row.IsEmpty|| column < row.FirstCol)
{
row.FirstCol=(column);
}
if (row.IsEmpty || column >= row.LastCol)
{
row.LastCol=((short)(column + 1)); // +1 -> for one past the last index
}
}
/// <summary>
/// Get the hssfcell representing a given column (logical cell)
/// 0-based. If you ask for a cell that is not defined, then
/// you Get a null.
/// This is the basic call, with no policies applied
/// </summary>
/// <param name="cellnum">0 based column number</param>
/// <returns>Cell representing that column or null if Undefined.</returns>
private ICell RetrieveCell(int cellnum)
{
if (!cells.ContainsKey(cellnum))
return null;
//if (cellnum < 0 || cellnum >= cells.Count) return null;
return cells[cellnum];
}
/// <summary>
/// Get the hssfcell representing a given column (logical cell)
/// 0-based. If you ask for a cell that is not defined then
/// you get a null, unless you have set a different
/// MissingCellPolicy on the base workbook.
///
/// Short method signature provided to retain binary
/// compatibility.
/// </summary>
/// <param name="cellnum">0 based column number</param>
/// <returns>Cell representing that column or null if undefined.</returns>
[Obsolete]
public ICell GetCell(short cellnum)
{
int ushortCellNum = cellnum & 0x0000FFFF; // avoid sign extension
return GetCell(ushortCellNum);
}
/// <summary>
/// Get the hssfcell representing a given column (logical cell)
/// 0-based. If you ask for a cell that is not defined then
/// you get a null, unless you have set a different
/// MissingCellPolicy on the base workbook.
/// </summary>
/// <param name="cellnum">0 based column number</param>
/// <returns>Cell representing that column or null if undefined.</returns>
public ICell GetCell(int cellnum)
{
return GetCell(cellnum, book.MissingCellPolicy);
}
/// <summary>
/// Get the hssfcell representing a given column (logical cell)
/// 0-based. If you ask for a cell that is not defined, then
/// your supplied policy says what to do
/// </summary>
/// <param name="cellnum">0 based column number</param>
/// <param name="policy">Policy on blank / missing cells</param>
/// <returns>that column or null if Undefined + policy allows.</returns>
public ICell GetCell(int cellnum, MissingCellPolicy policy)
{
ICell cell = RetrieveCell(cellnum);
if (policy == MissingCellPolicy.RETURN_NULL_AND_BLANK)
{
return cell;
}
if (policy == MissingCellPolicy.RETURN_BLANK_AS_NULL)
{
if (cell == null) return cell;
if (cell.CellType == CellType.Blank)
{
return null;
}
return cell;
}
if (policy == MissingCellPolicy.CREATE_NULL_AS_BLANK)
{
if (cell == null)
{
return CreateCell(cellnum, CellType.Blank);
}
return cell;
}
throw new ArgumentException("Illegal policy " + policy + " (" + policy.id + ")");
}
/// <summary>
/// Get the number of the first cell contained in this row.
/// </summary>
/// <value>the first logical cell in the row, or -1 if the row does not contain any cells.</value>
public short FirstCellNum
{
get
{
if (row.IsEmpty)
return -1;
else
return (short)row.FirstCol;
}
}
/// <summary>
/// Gets the index of the last cell contained in this row PLUS ONE
/// . The result also happens to be the 1-based column number of the last cell. This value can be used as a
/// standard upper bound when iterating over cells:
/// </summary>
/// <value>
/// short representing the last logical cell in the row PLUS ONE, or -1 if the
/// row does not contain any cells.
///</value>
/// <example>
/// short minColIx = row.GetFirstCellNum();
/// short maxColIx = row.GetLastCellNum();
/// for(short colIx=minColIx; colIx<maxColIx; colIx++) {
/// Cell cell = row.GetCell(colIx);
/// if(cell == null) {
/// continue;
/// }
/// //... do something with cell
/// }
/// </example>
public short LastCellNum
{
get
{
if (row.IsEmpty)
{
return -1;
}
return (short)row.LastCol;
}
}
/// <summary>
/// Gets the number of defined cells (NOT number of cells in the actual row!).
/// That is to say if only columns 0,4,5 have values then there would be 3.
/// </summary>
/// <value>the number of defined cells in the row.</value>
public int PhysicalNumberOfCells
{
get
{
return cells.Count;
}
}
/// <summary>
/// Gets or sets whether or not to Display this row with 0 height
/// </summary>
/// <value>height is zero or not.</value>
public bool ZeroHeight
{
get
{
return row.ZeroHeight;
}
set
{
row.ZeroHeight=(value);
}
}
/// <summary>
/// Get or sets the row's height or ff (-1) for undefined/default-height in twips (1/20th of a point)
/// </summary>
/// <value>rowheight or 0xff for Undefined (use sheet default)</value>
public short Height
{
get
{
short height = row.Height;
//The low-order 15 bits contain the row height.
//The 0x8000 bit indicates that the row is standard height (optional)
if ((height & 0x8000) != 0) height = sheet.Sheet.DefaultRowHeight;
else height &= 0x7FFF;
return height;
}
set
{
if (value == -1)
{
row.Height = unchecked((short)(0xFF | 0x8000));
row.BadFontHeight = false;
}
else
{
row.BadFontHeight = true;
row.Height = value;
}
}
}
/// <summary>
/// is this row formatted? Most aren't, but some rows
/// do have whole-row styles. For those that do, you
/// can get the formatting from {@link #getRowStyle()}
/// </summary>
/// <value>
/// <c>true</c> if this instance is formatted; otherwise, <c>false</c>.
/// </value>
public bool IsFormatted
{
get
{
return row.Formatted;
}
}
/// <summary>
/// Returns the whole-row cell styles. Most rows won't
/// have one of these, so will return null. Call IsFormmated to check first
/// </summary>
/// <value>The row style.</value>
public ICellStyle RowStyle
{
get
{
if (!IsFormatted) { return null; }
short styleIndex = row.XFIndex;
ExtendedFormatRecord xf = book.Workbook.GetExFormatAt(styleIndex);
return new HSSFCellStyle(styleIndex, xf, book);
}
set
{
row.Formatted=(true);
row.XFIndex=(value.Index);
}
}
/// <summary>
/// Get the row's height or ff (-1) for Undefined/default-height in points (20*Height)
/// </summary>
/// <value>row height or 0xff for Undefined (use sheet default).</value>
public float HeightInPoints
{
get
{
return (Height / 20f);
}
set
{
if (value == -1)
{
row.Height = unchecked(((short)(0xFF | 0x8000)));
}
else
{
row.BadFontHeight = (true);
row.Height = (short)(value * 20);
}
}
}
/// <summary>
/// Get the lowlevel RowRecord represented by this object - should only be called
/// by other parts of the high level API
/// </summary>
/// <value>RowRecord this row represents</value>
public RowRecord RowRecord
{
get
{
return row;
}
}
/// <summary>
/// used internally to refresh the "first cell" when the first cell is Removed.
/// </summary>
/// <param name="firstcell">The first cell index.</param>
/// <returns></returns>
[Obsolete]
private short FindFirstCell(int firstcell)
{
int cellnum = firstcell + 1;
ICell r = GetCell(cellnum);
while (r == null && cellnum <= LastCellNum)
{
r = GetCell(++cellnum);
}
if (cellnum > LastCellNum)
return -1;
return (short)cellnum;
}
/// <summary>
/// Get cells in the row (existing cells only, no blanks)
/// </summary>
public List<ICell> Cells
{
get {
return new List<ICell>(this.cells.Values);
}
}
/// <summary>
/// Gets the cell enumerator of the physically defined cells.
/// </summary>
/// <remarks>
/// Note that the 4th element might well not be cell 4, as the iterator
/// will not return Un-defined (null) cells.
/// Call CellNum on the returned cells to know which cell they are.
/// </remarks>
public IEnumerator GetEnumerator()
{
//return //new CellEnumerator(this.cells);
return this.cells.Values.GetEnumerator();
}
///// <summary>
///// Alias for {@link CellEnumerator} to allow
///// foreach loops
///// </summary>
///// <returns></returns>
//public IEnumerator GetEnumerator()
//{
// return GetCellEnumerator();
//}
/*
* An iterator over the (physical) cells in the row.
*/
//private class CellEnumerator : IEnumerator
//{
// int thisId = -1;
// int nextId = -1;
// private HSSFCell[] cells;
// public CellEnumerator()
// {
// }
// public CellEnumerator(HSSFCell[] cells)
// {
// this.cells = cells;
// }
// public bool MoveNext()
// {
// FindNext();
// return nextId < cells.Length;
// }
// public Object Current
// {
// get
// {
// thisId = nextId;
// Cell cell = cells[thisId];
// return cell;
// }
// }
// public void Remove()
// {
// if (thisId == -1)
// throw new InvalidOperationException("Remove() called before next()");
// cells[thisId] = null;
// }
// private void FindNext()
// {
// int i = nextId + 1;
// for (; i < cells.Length; i++)
// {
// if (cells[i] != null) break;
// }
// nextId = i;
// }
// public void Reset()
// {
// thisId = -1;
// nextId = -1;
// }
//}
/// <summary>
/// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has these meanings:
/// Value
/// Meaning
/// Less than zero
/// This instance is less than <paramref name="obj"/>.
/// Zero
/// This instance is equal to <paramref name="obj"/>.
/// Greater than zero
/// This instance is greater than <paramref name="obj"/>.
/// </returns>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="obj"/> is not the same type as this instance.
/// </exception>
public int CompareTo(Object obj)
{
HSSFRow loc = (HSSFRow)obj;
if (this.RowNum == loc.RowNum)
{
return 0;
}
if (this.RowNum < loc.RowNum)
{
return -1;
}
if (this.RowNum > loc.RowNum)
{
return 1;
}
return -1;
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
/// <exception cref="T:System.NullReferenceException">
/// The <paramref name="obj"/> parameter is null.
/// </exception>
public override bool Equals(Object obj)
{
if (!(obj is HSSFRow))
{
return false;
}
HSSFRow loc = (HSSFRow)obj;
if (this.RowNum == loc.RowNum)
{
return true;
}
return false;
}
/// <summary>
/// Returns a hash code. In this case it is the number of the row.
/// </summary>
public override int GetHashCode ()
{
return RowNum;
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElastiCache.Model
{
/// <summary>
/// Container for the parameters to the DescribeCacheEngineVersions operation.
/// <para>The <i>DescribeCacheEngineVersions</i> operation returns a list of the available cache engines and their versions.</para>
/// </summary>
/// <seealso cref="Amazon.ElastiCache.AmazonElastiCache.DescribeCacheEngineVersions"/>
public class DescribeCacheEngineVersionsRequest : AmazonWebServiceRequest
{
private string engine;
private string engineVersion;
private string cacheParameterGroupFamily;
private int? maxRecords;
private string marker;
private bool? defaultOnly;
/// <summary>
/// The cache engine to return. Valid values: <c>memcached</c> | <c>redis</c>
///
/// </summary>
public string Engine
{
get { return this.engine; }
set { this.engine = value; }
}
/// <summary>
/// Sets the Engine property
/// </summary>
/// <param name="engine">The value to set for the Engine property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeCacheEngineVersionsRequest WithEngine(string engine)
{
this.engine = engine;
return this;
}
// Check to see if Engine property is set
internal bool IsSetEngine()
{
return this.engine != null;
}
/// <summary>
/// The cache engine version to return. Example: <c>1.4.14</c>
///
/// </summary>
public string EngineVersion
{
get { return this.engineVersion; }
set { this.engineVersion = value; }
}
/// <summary>
/// Sets the EngineVersion property
/// </summary>
/// <param name="engineVersion">The value to set for the EngineVersion property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeCacheEngineVersionsRequest WithEngineVersion(string engineVersion)
{
this.engineVersion = engineVersion;
return this;
}
// Check to see if EngineVersion property is set
internal bool IsSetEngineVersion()
{
return this.engineVersion != null;
}
/// <summary>
/// The name of a specific cache parameter group family to return details for. Constraints: <ul> <li>Must be 1 to 255 alphanumeric
/// characters</li> <li>First character must be a letter</li> <li>Cannot end with a hyphen or contain two consecutive hyphens</li> </ul>
///
/// </summary>
public string CacheParameterGroupFamily
{
get { return this.cacheParameterGroupFamily; }
set { this.cacheParameterGroupFamily = value; }
}
/// <summary>
/// Sets the CacheParameterGroupFamily property
/// </summary>
/// <param name="cacheParameterGroupFamily">The value to set for the CacheParameterGroupFamily property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeCacheEngineVersionsRequest WithCacheParameterGroupFamily(string cacheParameterGroupFamily)
{
this.cacheParameterGroupFamily = cacheParameterGroupFamily;
return this;
}
// Check to see if CacheParameterGroupFamily property is set
internal bool IsSetCacheParameterGroupFamily()
{
return this.cacheParameterGroupFamily != null;
}
/// <summary>
/// The maximum number of records to include in the response. If more records exist than the specified <c>MaxRecords</c> value, a marker is
/// included in the response so that the remaining results can be retrieved. Default: 100Constraints: minimum 20; maximum 100.
///
/// </summary>
public int MaxRecords
{
get { return this.maxRecords ?? default(int); }
set { this.maxRecords = value; }
}
/// <summary>
/// Sets the MaxRecords property
/// </summary>
/// <param name="maxRecords">The value to set for the MaxRecords property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeCacheEngineVersionsRequest WithMaxRecords(int maxRecords)
{
this.maxRecords = maxRecords;
return this;
}
// Check to see if MaxRecords property is set
internal bool IsSetMaxRecords()
{
return this.maxRecords.HasValue;
}
/// <summary>
/// An optional marker returned from a prior request. Use this marker for pagination of results from this operation. If this parameter is
/// specified, the response includes only records beyond the marker, up to the value specified by <i>MaxRecords</i>.
///
/// </summary>
public string Marker
{
get { return this.marker; }
set { this.marker = value; }
}
/// <summary>
/// Sets the Marker property
/// </summary>
/// <param name="marker">The value to set for the Marker property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeCacheEngineVersionsRequest WithMarker(string marker)
{
this.marker = marker;
return this;
}
// Check to see if Marker property is set
internal bool IsSetMarker()
{
return this.marker != null;
}
/// <summary>
/// If <i>true</i>, specifies that only the default version of the specified engine or engine and major version combination is to be returned.
///
/// </summary>
public bool DefaultOnly
{
get { return this.defaultOnly ?? default(bool); }
set { this.defaultOnly = value; }
}
/// <summary>
/// Sets the DefaultOnly property
/// </summary>
/// <param name="defaultOnly">The value to set for the DefaultOnly property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeCacheEngineVersionsRequest WithDefaultOnly(bool defaultOnly)
{
this.defaultOnly = defaultOnly;
return this;
}
// Check to see if DefaultOnly property is set
internal bool IsSetDefaultOnly()
{
return this.defaultOnly.HasValue;
}
}
}
| |
//
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Amazon Software License (the "License").
// You may not use this file except in compliance with the
// License. A copy of the License is located at
//
// http://aws.amazon.com/asl/
//
// or in the "license" file accompanying this file. This file is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, express or implied. See the License
// for the specific language governing permissions and
// limitations under the License.
//
using Amazon.DynamoDBv2.DocumentModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ThirdParty.Json.LitJson;
namespace Amazon.DynamoDBv2.DataModel
{
/// <summary>
/// S3Link is an object that provides a connection to an S3 resource
/// that can be stored in a DynamoDB field through DynamoDBContext
/// </summary>
public partial class S3Link
{
#region Statics
internal static Dictionary<DynamoDBContext, S3ClientCache> Caches = new Dictionary<DynamoDBContext, S3ClientCache>();
private static Object cacheLock = new Object();
///// <summary>
///// Allows the use of a specific config in the creation of the client for a context
///// </summary>
///// <param name="context">The context the client should be used in</param>
///// <param name="config">The config object for the client</param>
//public static void UseConfigForClient(DynamoDBContext context, AmazonS3Config config)
//{
// var castedClient = ((AmazonDynamoDBClient)context.Client);
// var client = new AmazonS3Client(castedClient.GetCredentials(), config);
// S3ClientCache cache;
// if (!S3Link.Caches.TryGetValue(context, out cache))
// {
// cache = new S3ClientCache(castedClient.GetCredentials(),castedClient.CloneConfig<AmazonS3Config>());
// S3Link.Caches.Add(context, cache);
// }
// cache.UseClient(client, config.RegionEndpoint);
//}
/// <summary>
/// Creates an S3Link that can be used to managed an S3 connection
/// </summary>
/// <param name="context">The context that is handling the S3Link</param>
/// <param name="bucket">The bucket the S3Link should manage</param>
/// <param name="key">The key that S3Link should store and download from</param>
/// <param name="region">The region of the S3 resource</param>
/// <returns>A new S3Link object that can upload and download to the target bucket</returns>
public static S3Link Create(DynamoDBContext context, string bucket, string key, Amazon.RegionEndpoint region)
{
S3ClientCache cacheFromKey;
if (S3Link.Caches.TryGetValue(context, out cacheFromKey))
{
return new S3Link(cacheFromKey, bucket, key, region.SystemName);
}
S3ClientCache cache = CreatClientCacheFromContext(context);
return new S3Link(cache, bucket, key, region.SystemName);
}
#endregion
#region Properties
private S3ClientCache s3ClientCache;
private LinkInfo linker;
/// <summary>
/// The Key that S3Link stores and downloads a resource to and from
/// </summary>
public string Key
{
get
{
return this.linker.s3.key;
}
set
{
this.linker.s3.key = value;
}
}
/// <summary>
/// The name of the target Bucket for the managed resource
/// </summary>
public string BucketName
{
get
{
return this.linker.s3.bucket;
}
set
{
this.linker.s3.bucket = value;
}
}
/// <summary>
/// The region the S3 resource is in
/// </summary>
public string Region
{
get
{
if (String.IsNullOrEmpty(this.linker.s3.region))
{
return "us-east-1";
}
return this.linker.s3.region;
}
set
{
if (String.IsNullOrEmpty(value))
{
this.linker.s3.region = "us-east-1";
}
this.linker.s3.region = value;
}
}
/// <summary>
/// Looks up RegionEndpoint based on region as a string
/// </summary>
public RegionEndpoint RegionAsEndpoint
{
get
{
if (linker.s3.region == null)
{
return RegionEndpoint.GetBySystemName("us-east-1");
}
return RegionEndpoint.GetBySystemName(linker.s3.region);
}
}
#endregion
#region Constuctors
internal S3Link(S3ClientCache clientCache, string bucketName, string key)
: this(clientCache, new LinkInfo(bucketName, key)) { }
internal S3Link(S3ClientCache clientCache, string bucketName, string key, string region)
: this(clientCache, new LinkInfo(bucketName, key, region)) { }
private S3Link(S3ClientCache clientCache, LinkInfo linker)
{
if (linker == null) throw new ArgumentNullException("linker");
if (clientCache == null) throw new ArgumentNullException("clientCache");
this.s3ClientCache = clientCache;
this.linker = linker;
}
internal S3Link(S3ClientCache clientCache, string json)
{
if (clientCache == null) throw new ArgumentNullException("clientCache");
if (json == null) throw new ArgumentNullException("json");
this.s3ClientCache = clientCache;
linker = JsonMapper.ToObject<LinkInfo>(json);
}
internal static RegionEndpoint GetRegionFromJSON(string json)
{
var linker = JsonMapper.ToObject<LinkInfo>(json);
if (linker.s3.region == null)
{
return RegionEndpoint.GetBySystemName("us-east-1");
}
return RegionEndpoint.GetBySystemName(linker.s3.region);
}
#endregion
#region Methods
#region Small getters
internal static S3ClientCache CreatClientCacheFromContext(DynamoDBContext context)
{
var client = ((AmazonDynamoDBClient)context.Client);
var cache = new S3ClientCache(client);
lock (S3Link.cacheLock)
{
S3Link.Caches[context] = cache;
}
return cache;
}
#endregion
#region Misc
/// <summary>
/// Provides a URL for accessing the S3 object managed by S3Link
/// </summary>
/// <param name="expiration">The time the link should become invalid</param>
/// <returns>A URL directing to the S3 object</returns>
public string GetPreSignedURL(DateTime expiration)
{
return this.s3ClientCache.GetClient(this.RegionAsEndpoint).GeneratePreSignedURL(this.linker.s3.bucket, this.linker.s3.key, expiration, null);
}
internal string ToJson()
{
return JsonMapper.ToJson(linker);
}
#endregion
#endregion
#region Helper Classes
internal class S3LinkConverter : IPropertyConverter
{
private DynamoDBContext context;
public S3LinkConverter(DynamoDBContext context)
{
this.context = context;
}
public DocumentModel.DynamoDBEntry ToEntry(object value)
{
Primitive S3string = ((S3Link)value).ToJson();
return S3string;
}
public object FromEntry(DocumentModel.DynamoDBEntry entry)
{
S3ClientCache cache;
if (!S3Link.Caches.TryGetValue(context, out cache))
{
cache = S3Link.CreatClientCacheFromContext(context);
}
return new S3Link(cache, entry.AsString());
}
}
private class LinkInfo
{
public S3 s3 { get; set; }
// For JSON mapper
public LinkInfo() { }
public LinkInfo(string bucketName, string key)
: this(bucketName, key, null) { }
public LinkInfo(string bucketName, string key, string region)
{
if (bucketName == null) throw new ArgumentNullException("bucketName");
if (key == null) throw new ArgumentNullException("key");
if (String.IsNullOrEmpty(region))
{
region = null;
}
s3 = new S3(bucketName, key, region);
}
}
private class S3
{
public string bucket { get; set; }
public string key { get; set; }
public string region { get; set; }
// For JSON mapper
public S3() { }
public S3(string bucketName, string key, string region)
{
this.bucket = bucketName;
this.key = key;
if (String.IsNullOrEmpty(region))
{
region = null;
}
this.region = region;
}
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.