context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Collections.Generic;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.Assemblies;
using System.Reflection.Runtime.Dispensers;
using System.Reflection.Runtime.PropertyInfos;
using Internal.Reflection.Core;
using Internal.Reflection.Core.Execution;
//=================================================================================================================
// This file collects the various chokepoints that create the various Runtime*Info objects. This allows
// easy reviewing of the overall caching and unification policy.
//
// The dispenser functions are defined as static members of the associated Info class. This permits us
// to keep the constructors private to ensure that these really are the only ways to obtain these objects.
//=================================================================================================================
namespace System.Reflection.Runtime.Assemblies
{
//-----------------------------------------------------------------------------------------------------------
// Assemblies (maps 1-1 with a MetadataReader/ScopeDefinitionHandle.
//-----------------------------------------------------------------------------------------------------------
internal partial class RuntimeAssembly
{
/// <summary>
/// Returns non-null or throws.
/// </summary>
internal static RuntimeAssembly GetRuntimeAssembly(RuntimeAssemblyName assemblyRefName)
{
RuntimeAssembly result;
Exception assemblyLoadException = TryGetRuntimeAssembly(assemblyRefName, out result);
if (assemblyLoadException != null)
throw assemblyLoadException;
return result;
}
/// <summary>
/// Returns non-null or throws.
/// </summary>
internal static RuntimeAssembly GetRuntimeAssemblyFromByteArray(byte[] rawAssembly, byte[] pdbSymbolStore)
{
AssemblyBinder binder = ReflectionCoreExecution.ExecutionDomain.ReflectionDomainSetup.AssemblyBinder;
AssemblyBindResult bindResult;
Exception exception;
if (!binder.Bind(rawAssembly, pdbSymbolStore, out bindResult, out exception))
{
if (exception != null)
throw exception;
else
throw new BadImageFormatException();
}
RuntimeAssembly result = GetRuntimeAssembly(bindResult);
return result;
}
/// <summary>
/// Returns null if no assembly matches the assemblyRefName. Throws for other error cases.
/// </summary>
internal static RuntimeAssembly GetRuntimeAssemblyIfExists(RuntimeAssemblyName assemblyRefName)
{
object runtimeAssemblyOrException = s_assemblyRefNameToAssemblyDispenser.GetOrAdd(assemblyRefName);
if (runtimeAssemblyOrException is RuntimeAssembly runtimeAssembly)
return runtimeAssembly;
return null;
}
internal static Exception TryGetRuntimeAssembly(RuntimeAssemblyName assemblyRefName, out RuntimeAssembly result)
{
object runtimeAssemblyOrException = s_assemblyRefNameToAssemblyDispenser.GetOrAdd(assemblyRefName);
if (runtimeAssemblyOrException is RuntimeAssembly runtimeAssembly)
{
result = runtimeAssembly;
return null;
}
else
{
result = null;
return (Exception)runtimeAssemblyOrException;
}
}
// The "object" here is either a RuntimeAssembly or an Exception.
private static readonly Dispenser<RuntimeAssemblyName, object> s_assemblyRefNameToAssemblyDispenser =
DispenserFactory.CreateDispenser<RuntimeAssemblyName, object>(
DispenserScenario.AssemblyRefName_Assembly,
delegate (RuntimeAssemblyName assemblyRefName)
{
AssemblyBinder binder = ReflectionCoreExecution.ExecutionDomain.ReflectionDomainSetup.AssemblyBinder;
AssemblyBindResult bindResult;
Exception exception;
if (!binder.Bind(assemblyRefName, cacheMissedLookups: true, out bindResult, out exception))
return exception;
return GetRuntimeAssembly(bindResult);
}
);
private static RuntimeAssembly GetRuntimeAssembly(AssemblyBindResult bindResult)
{
RuntimeAssembly result = null;
GetNativeFormatRuntimeAssembly(bindResult, ref result);
if (result != null)
return result;
GetEcmaRuntimeAssembly(bindResult, ref result);
if (result != null)
return result;
throw new PlatformNotSupportedException();
}
// Use C# partial method feature to avoid complex #if logic, whichever code files are included will drive behavior
static partial void GetNativeFormatRuntimeAssembly(AssemblyBindResult bindResult, ref RuntimeAssembly runtimeAssembly);
static partial void GetEcmaRuntimeAssembly(AssemblyBindResult bindResult, ref RuntimeAssembly runtimeAssembly);
}
}
namespace System.Reflection.Runtime.MethodInfos
{
//-----------------------------------------------------------------------------------------------------------
// ConstructorInfos
//-----------------------------------------------------------------------------------------------------------
internal sealed partial class RuntimePlainConstructorInfo<TRuntimeMethodCommon> : RuntimeConstructorInfo
{
internal static RuntimePlainConstructorInfo<TRuntimeMethodCommon> GetRuntimePlainConstructorInfo(TRuntimeMethodCommon common)
{
return new RuntimePlainConstructorInfo<TRuntimeMethodCommon>(common);
}
}
//-----------------------------------------------------------------------------------------------------------
// Constructors for array types.
//-----------------------------------------------------------------------------------------------------------
internal sealed partial class RuntimeSyntheticConstructorInfo : RuntimeConstructorInfo
{
internal static RuntimeSyntheticConstructorInfo GetRuntimeSyntheticConstructorInfo(SyntheticMethodId syntheticMethodId, RuntimeArrayTypeInfo declaringType, RuntimeTypeInfo[] runtimeParameterTypes, InvokerOptions options, CustomMethodInvokerAction action)
{
return new RuntimeSyntheticConstructorInfo(syntheticMethodId, declaringType, runtimeParameterTypes, options, action);
}
}
//-----------------------------------------------------------------------------------------------------------
// Nullary constructor for types manufactured by Type.GetTypeFromCLSID().
//-----------------------------------------------------------------------------------------------------------
internal sealed partial class RuntimeCLSIDNullaryConstructorInfo : RuntimeConstructorInfo
{
internal static RuntimeCLSIDNullaryConstructorInfo GetRuntimeCLSIDNullaryConstructorInfo(RuntimeCLSIDTypeInfo declaringType)
{
return new RuntimeCLSIDNullaryConstructorInfo(declaringType);
}
}
//-----------------------------------------------------------------------------------------------------------
// MethodInfos for method definitions (i.e. Foo.Moo() or Foo.Moo<>() but not Foo.Moo<int>)
//-----------------------------------------------------------------------------------------------------------
internal sealed partial class RuntimeNamedMethodInfo<TRuntimeMethodCommon>
{
internal static RuntimeNamedMethodInfo<TRuntimeMethodCommon> GetRuntimeNamedMethodInfo(TRuntimeMethodCommon common, RuntimeTypeInfo reflectedType)
{
RuntimeNamedMethodInfo<TRuntimeMethodCommon> method = new RuntimeNamedMethodInfo<TRuntimeMethodCommon>(common, reflectedType);
method.WithDebugName();
return method;
}
}
//-----------------------------------------------------------------------------------------------------------
// MethodInfos for constructed generic methods (Foo.Moo<int> but not Foo.Moo<>)
//-----------------------------------------------------------------------------------------------------------
internal sealed partial class RuntimeConstructedGenericMethodInfo : RuntimeMethodInfo
{
internal static RuntimeMethodInfo GetRuntimeConstructedGenericMethodInfo(RuntimeNamedMethodInfo genericMethodDefinition, RuntimeTypeInfo[] genericTypeArguments)
{
return new RuntimeConstructedGenericMethodInfo(genericMethodDefinition, genericTypeArguments).WithDebugName();
}
}
//-----------------------------------------------------------------------------------------------------------
// MethodInfos for the Get/Set methods on array types.
//-----------------------------------------------------------------------------------------------------------
internal sealed partial class RuntimeSyntheticMethodInfo : RuntimeMethodInfo
{
internal static RuntimeMethodInfo GetRuntimeSyntheticMethodInfo(SyntheticMethodId syntheticMethodId, String name, RuntimeArrayTypeInfo declaringType, RuntimeTypeInfo[] runtimeParameterTypes, RuntimeTypeInfo returnType, InvokerOptions options, CustomMethodInvokerAction action)
{
return new RuntimeSyntheticMethodInfo(syntheticMethodId, name, declaringType, runtimeParameterTypes, returnType, options, action).WithDebugName();
}
}
}
namespace System.Reflection.Runtime.ParameterInfos
{
//-----------------------------------------------------------------------------------------------------------
// ParameterInfos for MethodBase objects with no Parameter metadata.
//-----------------------------------------------------------------------------------------------------------
internal sealed partial class RuntimeThinMethodParameterInfo : RuntimeMethodParameterInfo
{
internal static RuntimeThinMethodParameterInfo GetRuntimeThinMethodParameterInfo(MethodBase member, int position, QSignatureTypeHandle qualifiedParameterType, TypeContext typeContext)
{
return new RuntimeThinMethodParameterInfo(member, position, qualifiedParameterType, typeContext);
}
}
//-----------------------------------------------------------------------------------------------------------
// ParameterInfos returned by PropertyInfo.GetIndexParameters()
//-----------------------------------------------------------------------------------------------------------
internal sealed partial class RuntimePropertyIndexParameterInfo : RuntimeParameterInfo
{
internal static RuntimePropertyIndexParameterInfo GetRuntimePropertyIndexParameterInfo(RuntimePropertyInfo member, RuntimeParameterInfo backingParameter)
{
return new RuntimePropertyIndexParameterInfo(member, backingParameter);
}
}
//-----------------------------------------------------------------------------------------------------------
// ParameterInfos returned by Get/Set methods on array types.
//-----------------------------------------------------------------------------------------------------------
internal sealed partial class RuntimeSyntheticParameterInfo : RuntimeParameterInfo
{
internal static RuntimeSyntheticParameterInfo GetRuntimeSyntheticParameterInfo(MemberInfo member, int position, RuntimeTypeInfo parameterType)
{
return new RuntimeSyntheticParameterInfo(member, position, parameterType);
}
}
}
| |
// 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: A random number generator.
**
**
===========================================================*/
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Diagnostics.Contracts;
namespace System
{
[Serializable]
public class Random
{
//
// Private Constants
//
private const int MBIG = Int32.MaxValue;
private const int MSEED = 161803398;
private const int MZ = 0;
//
// Member Variables
//
private int _inext;
private int _inextp;
private int[] _seedArray = new int[56];
//
// Public Constants
//
//
// Native Declarations
//
//
// Constructors
//
/*=========================================================================================
**Action: Initializes a new instance of the Random class, using a default seed value
===========================================================================================*/
public Random()
: this(GenerateSeed())
{
}
/*=========================================================================================
**Action: Initializes a new instance of the Random class, using a specified seed value
===========================================================================================*/
public Random(int Seed)
{
int ii = 0;
int mj, mk;
//Initialize our Seed array.
int subtraction = (Seed == Int32.MinValue) ? Int32.MaxValue : Math.Abs(Seed);
mj = MSEED - subtraction;
_seedArray[55] = mj;
mk = 1;
for (int i = 1; i < 55; i++)
{ //Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position.
if ((ii += 21) >= 55) ii -= 55;
_seedArray[ii] = mk;
mk = mj - mk;
if (mk < 0) mk += MBIG;
mj = _seedArray[ii];
}
for (int k = 1; k < 5; k++)
{
for (int i = 1; i < 56; i++)
{
int n = i + 30;
if (n >= 55) n -= 55;
_seedArray[i] -= _seedArray[1 + n];
if (_seedArray[i] < 0) _seedArray[i] += MBIG;
}
}
_inext = 0;
_inextp = 21;
Seed = 1;
}
//
// Package Private Methods
//
/*====================================Sample====================================
**Action: Return a new random number [0..1) and reSeed the Seed array.
**Returns: A double [0..1)
**Arguments: None
**Exceptions: None
==============================================================================*/
protected virtual double Sample()
{
//Including this division at the end gives us significantly improved
//random number distribution.
return (InternalSample() * (1.0 / MBIG));
}
private int InternalSample()
{
int retVal;
int locINext = _inext;
int locINextp = _inextp;
if (++locINext >= 56) locINext = 1;
if (++locINextp >= 56) locINextp = 1;
retVal = _seedArray[locINext] - _seedArray[locINextp];
if (retVal == MBIG) retVal--;
if (retVal < 0) retVal += MBIG;
_seedArray[locINext] = retVal;
_inext = locINext;
_inextp = locINextp;
return retVal;
}
[ThreadStatic]
private static Random t_threadRandom;
private static readonly Random s_globalRandom = new Random(GenerateGlobalSeed());
/*=====================================GenerateSeed=====================================
**Returns: An integer that can be used as seed values for consecutively
creating lots of instances on the same thread within a short period of time.
========================================================================================*/
private static int GenerateSeed()
{
Random rnd = t_threadRandom;
if (rnd == null)
{
int seed;
lock (s_globalRandom)
{
seed = s_globalRandom.Next();
}
rnd = new Random(seed);
t_threadRandom = rnd;
}
return rnd.Next();
}
/*==================================GenerateGlobalSeed====================================
**Action: Creates a number to use as global seed.
**Returns: An integer that is safe to use as seed values for thread-local seed generators.
==========================================================================================*/
private static unsafe int GenerateGlobalSeed()
{
int result;
Interop.GetRandomBytes((byte*)&result, sizeof(int));
return result;
}
//
// Public Instance Methods
//
/*=====================================Next=====================================
**Returns: An int [0..Int32.MaxValue)
**Arguments: None
**Exceptions: None.
==============================================================================*/
public virtual int Next()
{
return InternalSample();
}
private double GetSampleForLargeRange()
{
// The distribution of double value returned by Sample
// is not distributed well enough for a large range.
// If we use Sample for a range [Int32.MinValue..Int32.MaxValue)
// We will end up getting even numbers only.
int result = InternalSample();
// Note we can't use addition here. The distribution will be bad if we do that.
bool negative = (InternalSample() % 2 == 0) ? true : false; // decide the sign based on second sample
if (negative)
{
result = -result;
}
double d = result;
d += (Int32.MaxValue - 1); // get a number in range [0 .. 2 * Int32MaxValue - 1)
d /= 2 * (uint)Int32.MaxValue - 1;
return d;
}
/*=====================================Next=====================================
**Returns: An int [minvalue..maxvalue)
**Arguments: minValue -- the least legal value for the Random number.
** maxValue -- One greater than the greatest legal return value.
**Exceptions: None.
==============================================================================*/
public virtual int Next(int minValue, int maxValue)
{
if (minValue > maxValue)
{
throw new ArgumentOutOfRangeException(nameof(minValue), SR.Format(SR.Argument_MinMaxValue, nameof(minValue), nameof(maxValue)));
}
Contract.EndContractBlock();
long range = (long)maxValue - minValue;
if (range <= (long)Int32.MaxValue)
{
return ((int)(Sample() * range) + minValue);
}
else
{
return (int)((long)(GetSampleForLargeRange() * range) + minValue);
}
}
/*=====================================Next=====================================
**Returns: An int [0..maxValue)
**Arguments: maxValue -- One more than the greatest legal return value.
**Exceptions: None.
==============================================================================*/
public virtual int Next(int maxValue)
{
if (maxValue < 0)
{
throw new ArgumentOutOfRangeException(nameof(maxValue), SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(maxValue)));
}
Contract.EndContractBlock();
return (int)(Sample() * maxValue);
}
/*=====================================Next=====================================
**Returns: A double [0..1)
**Arguments: None
**Exceptions: None
==============================================================================*/
public virtual double NextDouble()
{
return Sample();
}
/*==================================NextBytes===================================
**Action: Fills the byte array with random bytes [0..0x7f]. The entire array is filled.
**Returns:Void
**Arguments: buffer -- the array to be filled.
**Exceptions: None
==============================================================================*/
public virtual void NextBytes(byte[] buffer)
{
if (buffer == null) throw new ArgumentNullException(nameof(buffer));
Contract.EndContractBlock();
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = (byte)(InternalSample() % (Byte.MaxValue + 1));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using Xunit;
namespace System.Net.Http.Tests
{
public class HttpHeaderValueCollectionTest
{
// Note: These are not real known headers, so they won't be returned if we call HeaderDescriptor.Get().
private static readonly HeaderDescriptor knownStringHeader = (new KnownHeader("known-string-header", HttpHeaderType.General, new MockHeaderParser(typeof(string)))).Descriptor;
private static readonly HeaderDescriptor knownUriHeader = (new KnownHeader("known-uri-header", HttpHeaderType.General, new MockHeaderParser(typeof(Uri)))).Descriptor;
private static readonly Uri specialValue = new Uri("http://special/");
private static readonly Uri invalidValue = new Uri("http://invalid/");
private static readonly TransferCodingHeaderValue specialChunked = new TransferCodingHeaderValue("chunked");
// Note that this type just forwards calls to HttpHeaders. So this test method focuses on making sure
// the correct calls to HttpHeaders are made. This test suite will not test HttpHeaders functionality.
[Fact]
public void IsReadOnly_CallProperty_AlwaysFalse()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownStringHeader, headers);
Assert.False(collection.IsReadOnly);
}
[Fact]
public void Count_AddSingleValueThenQueryCount_ReturnsValueCountWithSpecialValues()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownStringHeader, headers,
"special");
Assert.Equal(0, collection.Count);
headers.Add(knownStringHeader, "value2");
Assert.Equal(1, collection.Count);
headers.Clear();
headers.Add(knownStringHeader, "special");
Assert.Equal(1, collection.Count);
headers.Add(knownStringHeader, "special");
headers.Add(knownStringHeader, "special");
Assert.Equal(3, collection.Count);
}
[Fact]
public void Count_AddMultipleValuesThenQueryCount_ReturnsValueCountWithSpecialValues()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownStringHeader, headers,
"special");
Assert.Equal(0, collection.Count);
collection.Add("value1");
headers.Add(knownStringHeader, "special");
Assert.Equal(2, collection.Count);
headers.Add(knownStringHeader, "special");
headers.Add(knownStringHeader, "value2");
headers.Add(knownStringHeader, "special");
Assert.Equal(5, collection.Count);
}
[Fact]
public void Add_CallWithNullValue_Throw()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
Assert.Throws<ArgumentNullException>(() => { collection.Add(null); });
}
[Fact]
public void Add_AddValues_AllValuesAdded()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Assert.Equal(3, collection.Count);
}
[Fact]
public void Add_UseSpecialValue_Success()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
Assert.Null(headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.Equal(string.Empty, headers.TransferEncoding.ToString());
headers.TransferEncoding.Add(specialChunked);
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.Equal(specialChunked, headers.TransferEncoding.First());
Assert.Equal(specialChunked.ToString(), headers.TransferEncoding.ToString());
}
[Fact]
public void Add_UseSpecialValueWithSpecialAlreadyPresent_AddsDuplicate()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
headers.TransferEncodingChunked = true;
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.Equal(specialChunked.ToString(), headers.TransferEncoding.ToString());
headers.TransferEncoding.Add(specialChunked);
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(2, headers.TransferEncoding.Count);
Assert.Equal("chunked, chunked", headers.TransferEncoding.ToString());
// removes first instance of
headers.TransferEncodingChunked = false;
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.Equal(specialChunked.ToString(), headers.TransferEncoding.ToString());
// does not add duplicate
headers.TransferEncodingChunked = true;
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.Equal(specialChunked.ToString(), headers.TransferEncoding.ToString());
}
[Fact]
public void ParseAdd_CallWithNullValue_NothingAdded()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.ParseAdd(null);
Assert.False(collection.IsSpecialValueSet);
Assert.Equal(0, collection.Count);
Assert.Equal(string.Empty, collection.ToString());
}
[Fact]
public void ParseAdd_AddValues_AllValuesAdded()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.ParseAdd("http://www.example.org/1/");
collection.ParseAdd("http://www.example.org/2/");
collection.ParseAdd("http://www.example.org/3/");
Assert.Equal(3, collection.Count);
}
[Fact]
public void ParseAdd_UseSpecialValue_Added()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.ParseAdd(specialValue.AbsoluteUri);
Assert.True(collection.IsSpecialValueSet);
Assert.Equal(specialValue.ToString(), collection.ToString());
}
[Fact]
public void ParseAdd_AddBadValue_Throws()
{
HttpResponseHeaders headers = new HttpResponseHeaders();
string input = "Basic, D\rigest qop=\"auth\",algorithm=MD5-sess";
Assert.Throws<FormatException>(() => { headers.WwwAuthenticate.ParseAdd(input); });
}
[Fact]
public void TryParseAdd_CallWithNullValue_NothingAdded()
{
HttpResponseHeaders headers = new HttpResponseHeaders();
Assert.True(headers.WwwAuthenticate.TryParseAdd(null));
Assert.False(headers.WwwAuthenticate.IsSpecialValueSet);
Assert.Equal(0, headers.WwwAuthenticate.Count);
Assert.Equal(string.Empty, headers.WwwAuthenticate.ToString());
}
[Fact]
public void TryParseAdd_AddValues_AllAdded()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
Assert.True(collection.TryParseAdd("http://www.example.org/1/"));
Assert.True(collection.TryParseAdd("http://www.example.org/2/"));
Assert.True(collection.TryParseAdd("http://www.example.org/3/"));
Assert.Equal(3, collection.Count);
}
[Fact]
public void TryParseAdd_UseSpecialValue_Added()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
Assert.True(collection.TryParseAdd(specialValue.AbsoluteUri));
Assert.True(collection.IsSpecialValueSet);
Assert.Equal(specialValue.ToString(), collection.ToString());
}
[Fact]
public void TryParseAdd_AddBadValue_False()
{
HttpResponseHeaders headers = new HttpResponseHeaders();
string input = "Basic, D\rigest qop=\"auth\",algorithm=MD5-sess";
Assert.False(headers.WwwAuthenticate.TryParseAdd(input));
Assert.Equal(string.Empty, headers.WwwAuthenticate.ToString());
Assert.Equal(string.Empty, headers.ToString());
}
[Fact]
public void TryParseAdd_AddBadAfterGoodValue_False()
{
HttpResponseHeaders headers = new HttpResponseHeaders();
headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Negotiate"));
string input = "Basic, D\rigest qop=\"auth\",algorithm=MD5-sess";
Assert.False(headers.WwwAuthenticate.TryParseAdd(input));
Assert.Equal("Negotiate", headers.WwwAuthenticate.ToString());
Assert.Equal("WWW-Authenticate: Negotiate\r\n", headers.ToString());
}
[Fact]
public void Clear_AddValuesThenClear_NoElementsInCollection()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Assert.Equal(3, collection.Count);
collection.Clear();
Assert.Equal(0, collection.Count);
}
[Fact]
public void Clear_AddValuesAndSpecialValueThenClear_EverythingCleared()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.SetSpecialValue();
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Assert.Equal(4, collection.Count);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
collection.Clear();
Assert.Equal(0, collection.Count);
Assert.False(collection.IsSpecialValueSet, "Special value was removed by Clear().");
}
[Fact]
public void Contains_CallWithNullValue_Throw()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
Assert.Throws<ArgumentNullException>(() => { collection.Contains(null); });
}
[Fact]
public void Contains_AddValuesThenCallContains_ReturnsTrueForExistingItemsFalseOtherwise()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Assert.True(collection.Contains(new Uri("http://www.example.org/2/")), "Expected true for existing item.");
Assert.False(collection.Contains(new Uri("http://www.example.org/4/")),
"Expected false for non-existing item.");
}
[Fact]
public void Contains_UseSpecialValueWhenEmpty_False()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
Assert.False(headers.TransferEncoding.Contains(specialChunked));
}
[Fact]
public void Contains_UseSpecialValueWithProperty_True()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
headers.TransferEncodingChunked = true;
Assert.True(headers.TransferEncoding.Contains(specialChunked));
headers.TransferEncodingChunked = false;
Assert.False(headers.TransferEncoding.Contains(specialChunked));
}
[Fact]
public void Contains_UseSpecialValueWhenSpecilValueIsPresent_True()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
headers.TransferEncoding.Add(specialChunked);
Assert.True(headers.TransferEncoding.Contains(specialChunked));
headers.TransferEncoding.Remove(specialChunked);
Assert.False(headers.TransferEncoding.Contains(specialChunked));
}
[Fact]
public void CopyTo_CallWithStartIndexPlusElementCountGreaterArrayLength_Throw()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
Uri[] array = new Uri[2];
// startIndex + Count = 1 + 2 > array.Length
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => { collection.CopyTo(array, 1); });
}
[Fact]
public void CopyTo_EmptyToEmpty_Success()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
Uri[] array = new Uri[0];
collection.CopyTo(array, 0);
}
[Fact]
public void CopyTo_NoValues_DoesNotChangeArray()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
Uri[] array = new Uri[4];
collection.CopyTo(array, 0);
for (int i = 0; i < array.Length; i++)
{
Assert.Null(array[i]);
}
}
[Fact]
public void CopyTo_AddSingleValue_ContainsSingleValue()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/"));
Uri[] array = new Uri[1];
collection.CopyTo(array, 0);
Assert.Equal(new Uri("http://www.example.org/"), array[0]);
// Now only set the special value: nothing should be added to the array.
headers.Clear();
headers.Add(knownUriHeader, specialValue.ToString());
array[0] = null;
collection.CopyTo(array, 0);
Assert.Equal(specialValue, array[0]);
}
[Fact]
public void CopyTo_AddMultipleValues_ContainsAllValuesInTheRightOrder()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Uri[] array = new Uri[5];
collection.CopyTo(array, 1);
Assert.Null(array[0]);
Assert.Equal(new Uri("http://www.example.org/1/"), array[1]);
Assert.Equal(new Uri("http://www.example.org/2/"), array[2]);
Assert.Equal(new Uri("http://www.example.org/3/"), array[3]);
Assert.Null(array[4]);
}
[Fact]
public void CopyTo_AddValuesAndSpecialValue_AllValuesCopied()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.SetSpecialValue();
collection.Add(new Uri("http://www.example.org/3/"));
Uri[] array = new Uri[5];
collection.CopyTo(array, 1);
Assert.Null(array[0]);
Assert.Equal(new Uri("http://www.example.org/1/"), array[1]);
Assert.Equal(new Uri("http://www.example.org/2/"), array[2]);
Assert.Equal(specialValue, array[3]);
Assert.Equal(new Uri("http://www.example.org/3/"), array[4]);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
}
[Fact]
public void CopyTo_OnlySpecialValue_Copied()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.SetSpecialValue();
headers.Add(knownUriHeader, specialValue.ToString());
headers.Add(knownUriHeader, specialValue.ToString());
headers.Add(knownUriHeader, specialValue.ToString());
Uri[] array = new Uri[4];
array[0] = null;
collection.CopyTo(array, 0);
Assert.Equal(specialValue, array[0]);
Assert.Equal(specialValue, array[1]);
Assert.Equal(specialValue, array[2]);
Assert.Equal(specialValue, array[3]);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
}
[Fact]
public void CopyTo_OnlySpecialValueEmptyDestination_Copied()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.SetSpecialValue();
headers.Add(knownUriHeader, specialValue.ToString());
Uri[] array = new Uri[2];
collection.CopyTo(array, 0);
Assert.Equal(specialValue, array[0]);
Assert.Equal(specialValue, array[1]);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
}
[Fact]
public void CopyTo_ArrayTooSmall_Throw()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<string> collection = new HttpHeaderValueCollection<string>(knownStringHeader, headers,
"special");
string[] array = new string[1];
array[0] = null;
collection.CopyTo(array, 0); // no exception
Assert.Null(array[0]);
Assert.Throws<ArgumentNullException>(() => { collection.CopyTo(null, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { collection.CopyTo(array, -1); });
Assert.Throws<ArgumentOutOfRangeException>(() => { collection.CopyTo(array, 2); });
headers.Add(knownStringHeader, "special");
array = new string[0];
AssertExtensions.Throws<ArgumentException>(null, () => { collection.CopyTo(array, 0); });
headers.Add(knownStringHeader, "special");
headers.Add(knownStringHeader, "special");
array = new string[1];
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => { collection.CopyTo(array, 0); });
headers.Add(knownStringHeader, "value1");
array = new string[0];
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => { collection.CopyTo(array, 0); });
headers.Add(knownStringHeader, "value2");
array = new string[1];
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => { collection.CopyTo(array, 0); });
array = new string[2];
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => { collection.CopyTo(array, 1); });
}
[Fact]
public void Remove_CallWithNullValue_Throw()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
Assert.Throws<ArgumentNullException>(() => { collection.Remove(null); });
}
[Fact]
public void Remove_AddValuesThenCallRemove_ReturnsTrueWhenRemovingExistingValuesFalseOtherwise()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
Assert.True(collection.Remove(new Uri("http://www.example.org/2/")), "Expected true for existing item.");
Assert.False(collection.Remove(new Uri("http://www.example.org/4/")),
"Expected false for non-existing item.");
}
[Fact]
public void Remove_UseSpecialValue_FalseWhenEmpty()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
Assert.Null(headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.TransferEncoding.Remove(specialChunked));
Assert.Null(headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
}
[Fact]
public void Remove_UseSpecialValueWhenSetWithProperty_True()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
headers.TransferEncodingChunked = true;
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.True(headers.TransferEncoding.Contains(specialChunked));
Assert.True(headers.TransferEncoding.Remove(specialChunked));
Assert.False((bool)headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.TransferEncoding.Contains(specialChunked));
}
[Fact]
public void Remove_UseSpecialValueWhenAdded_True()
{
HttpRequestHeaders headers = new HttpRequestHeaders();
headers.TransferEncoding.Add(specialChunked);
Assert.True((bool)headers.TransferEncodingChunked);
Assert.Equal(1, headers.TransferEncoding.Count);
Assert.True(headers.TransferEncoding.Contains(specialChunked));
Assert.True(headers.TransferEncoding.Remove(specialChunked));
Assert.Null(headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.TransferEncoding.Contains(specialChunked));
}
[Fact]
public void GetEnumerator_AddSingleValueAndGetEnumerator_AllValuesReturned()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.Add(new Uri("http://www.example.org/"));
bool started = false;
foreach (var item in collection)
{
Assert.False(started, "We have more than one element returned by the enumerator.");
Assert.Equal(new Uri("http://www.example.org/"), item);
}
}
[Fact]
public void GetEnumerator_AddValuesAndGetEnumerator_AllValuesReturned()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
int i = 1;
foreach (var item in collection)
{
Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item);
i++;
}
}
[Fact]
public void GetEnumerator_NoValues_EmptyEnumerator()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
IEnumerator<Uri> enumerator = collection.GetEnumerator();
Assert.False(enumerator.MoveNext(), "No items expected in enumerator.");
}
[Fact]
public void GetEnumerator_AddValuesAndGetEnumeratorFromInterface_AllValuesReturned()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
System.Collections.IEnumerable enumerable = collection;
int i = 1;
foreach (var item in enumerable)
{
Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item);
i++;
}
}
[Fact]
public void GetEnumerator_AddValuesAndSpecialValueAndGetEnumeratorFromInterface_AllValuesReturned()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.Add(new Uri("http://www.example.org/3/"));
collection.SetSpecialValue();
System.Collections.IEnumerable enumerable = collection;
// The "special value" should be ignored and not part of the resulting collection.
int i = 1;
bool specialFound = false;
foreach (var item in enumerable)
{
if (item.Equals(specialValue))
{
specialFound = true;
}
else
{
Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item);
i++;
}
}
Assert.True(specialFound);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
}
[Fact]
public void GetEnumerator_AddValuesAndSpecialValue_AllValuesReturned()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.SetSpecialValue();
collection.Add(new Uri("http://www.example.org/3/"));
System.Collections.IEnumerable enumerable = collection;
// The special value we added above, must be part of the collection returned by GetEnumerator().
int i = 1;
bool specialFound = false;
foreach (var item in enumerable)
{
if (item.Equals(specialValue))
{
specialFound = true;
}
else
{
Assert.Equal(new Uri("http://www.example.org/" + i + "/"), item);
i++;
}
}
Assert.True(specialFound);
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
}
[Fact]
public void IsSpecialValueSet_NoSpecialValueUsed_ReturnsFalse()
{
// Create a new collection _without_ specifying a special value.
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
null, null);
Assert.False(collection.IsSpecialValueSet,
"Special value is set even though collection doesn't define a special value.");
}
[Fact]
public void RemoveSpecialValue_AddRemoveSpecialValue_SpecialValueGetsRemoved()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.SetSpecialValue();
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
Assert.Equal(1, headers.GetValues(knownUriHeader).Count());
collection.RemoveSpecialValue();
Assert.False(collection.IsSpecialValueSet, "Special value is set.");
// Since the only header value was the "special value", removing it will remove the whole header
// from the collection.
Assert.False(headers.Contains(knownUriHeader));
}
[Fact]
public void RemoveSpecialValue_AddValueAndSpecialValueThenRemoveSpecialValue_SpecialValueGetsRemoved()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/"));
collection.SetSpecialValue();
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
Assert.Equal(2, headers.GetValues(knownUriHeader).Count());
collection.RemoveSpecialValue();
Assert.False(collection.IsSpecialValueSet, "Special value is set.");
Assert.Equal(1, headers.GetValues(knownUriHeader).Count());
}
[Fact]
public void RemoveSpecialValue_AddTwoValuesAndSpecialValueThenRemoveSpecialValue_SpecialValueGetsRemoved()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue);
collection.Add(new Uri("http://www.example.org/1/"));
collection.Add(new Uri("http://www.example.org/2/"));
collection.SetSpecialValue();
Assert.True(collection.IsSpecialValueSet, "Special value not set.");
Assert.Equal(3, headers.GetValues(knownUriHeader).Count());
// The difference between this test and the previous one is that HttpHeaders in this case will use
// a List<T> to store the two remaining values, whereas in the previous case it will just store
// the remaining value (no list).
collection.RemoveSpecialValue();
Assert.False(collection.IsSpecialValueSet, "Special value is set.");
Assert.Equal(2, headers.GetValues(knownUriHeader).Count());
}
[Fact]
public void Ctor_ProvideValidator_ValidatorIsUsedWhenAddingValues()
{
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
MockValidator);
// Adding an arbitrary Uri should not throw.
collection.Add(new Uri("http://some/"));
// When we add 'invalidValue' our MockValidator will throw.
Assert.Throws<MockException>(() => { collection.Add(invalidValue); });
}
[Fact]
public void Ctor_ProvideValidator_ValidatorIsUsedWhenRemovingValues()
{
// Use different ctor overload than in previous test to make sure all ctor overloads work correctly.
MockHeaders headers = new MockHeaders();
HttpHeaderValueCollection<Uri> collection = new HttpHeaderValueCollection<Uri>(knownUriHeader, headers,
specialValue, MockValidator);
// When we remove 'invalidValue' our MockValidator will throw.
Assert.Throws<MockException>(() => { collection.Remove(invalidValue); });
}
[Fact]
public void ToString_SpecialValues_Success()
{
HttpRequestMessage request = new HttpRequestMessage();
request.Headers.TransferEncodingChunked = true;
string result = request.Headers.TransferEncoding.ToString();
Assert.Equal("chunked", result);
request.Headers.ExpectContinue = true;
result = request.Headers.Expect.ToString();
Assert.Equal("100-continue", result);
request.Headers.ConnectionClose = true;
result = request.Headers.Connection.ToString();
Assert.Equal("close", result);
}
[Fact]
public void ToString_SpecialValueAndExtra_Success()
{
HttpRequestMessage request = new HttpRequestMessage();
request.Headers.Add(HttpKnownHeaderNames.TransferEncoding, "bla1");
request.Headers.TransferEncodingChunked = true;
request.Headers.Add(HttpKnownHeaderNames.TransferEncoding, "bla2");
string result = request.Headers.TransferEncoding.ToString();
Assert.Equal("bla1, chunked, bla2", result);
}
[Fact]
public void ToString_SingleValue_Success()
{
using (var response = new HttpResponseMessage())
{
string input = "Basic";
response.Headers.Add(HttpKnownHeaderNames.WWWAuthenticate, input);
string result = response.Headers.WwwAuthenticate.ToString();
Assert.Equal(input, result);
}
}
[Fact]
public void ToString_MultipleValue_Success()
{
using (var response = new HttpResponseMessage())
{
string input = "Basic, NTLM, Negotiate, Custom";
response.Headers.Add(HttpKnownHeaderNames.WWWAuthenticate, input);
string result = response.Headers.WwwAuthenticate.ToString();
Assert.Equal(input, result);
}
}
[Fact]
public void ToString_EmptyValue_Success()
{
using (var response = new HttpResponseMessage())
{
string result = response.Headers.WwwAuthenticate.ToString();
Assert.Equal(string.Empty, result);
}
}
#region Helper methods
private static void MockValidator(HttpHeaderValueCollection<Uri> collection, Uri value)
{
if (value == invalidValue)
{
throw new MockException();
}
}
public class MockException : Exception
{
public MockException() { }
public MockException(string message) : base(message) { }
public MockException(string message, Exception inner) : base(message, inner) { }
}
private class MockHeaders : HttpHeaders
{
public MockHeaders()
{
}
}
private class MockHeaderParser : HttpHeaderParser
{
private static MockComparer comparer = new MockComparer();
private Type valueType;
public override IEqualityComparer Comparer
{
get { return comparer; }
}
public MockHeaderParser(Type valueType)
: base(true)
{
Assert.Contains(valueType, new[] { typeof(string), typeof(Uri) });
this.valueType = valueType;
}
public override bool TryParseValue(string value, object storeValue, ref int index, out object parsedValue)
{
parsedValue = null;
if (value == null)
{
return true;
}
index = value.Length;
// Just return the raw string (as string or Uri depending on the value type)
parsedValue = (valueType == typeof(Uri) ? (object)new Uri(value) : value);
return true;
}
}
private class MockComparer : IEqualityComparer
{
public int EqualsCount { get; private set; }
public int GetHashCodeCount { get; private set; }
#region IEqualityComparer Members
public new bool Equals(object x, object y)
{
EqualsCount++;
return x.Equals(y);
}
public int GetHashCode(object obj)
{
GetHashCodeCount++;
return obj.GetHashCode();
}
#endregion
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if !FEATURE_SERIALIZATION_UAPAOT
namespace System.Xml.Serialization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.RegularExpressions;
using System.Xml.Extensions;
internal class XmlSerializationILGen
{
private int _nextMethodNumber = 0;
private readonly Dictionary<TypeMapping, string> _methodNames = new Dictionary<TypeMapping, string>();
// Lookup name->created Method
private Dictionary<string, MethodBuilderInfo> _methodBuilders = new Dictionary<string, MethodBuilderInfo>();
// Lookup name->created Type
internal Dictionary<string, Type> CreatedTypes = new Dictionary<string, Type>();
// Lookup name->class Member
internal Dictionary<string, MemberInfo> memberInfos = new Dictionary<string, MemberInfo>();
private ReflectionAwareILGen _raCodeGen;
private TypeScope[] _scopes;
private TypeDesc _stringTypeDesc = null;
private TypeDesc _qnameTypeDesc = null;
private string _className;
private TypeMapping[] _referencedMethods;
private int _references = 0;
private readonly HashSet<TypeMapping> _generatedMethods = new HashSet<TypeMapping>();
private ModuleBuilder _moduleBuilder;
private TypeAttributes _typeAttributes;
protected TypeBuilder typeBuilder;
protected CodeGenerator ilg;
internal XmlSerializationILGen(TypeScope[] scopes, string access, string className)
{
_scopes = scopes;
if (scopes.Length > 0)
{
_stringTypeDesc = scopes[0].GetTypeDesc(typeof(string));
_qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName));
}
_raCodeGen = new ReflectionAwareILGen();
_className = className;
System.Diagnostics.Debug.Assert(access == "public");
_typeAttributes = TypeAttributes.Public;
}
internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } }
internal ReflectionAwareILGen RaCodeGen { get { return _raCodeGen; } }
internal TypeDesc StringTypeDesc { get { return _stringTypeDesc; } }
internal TypeDesc QnameTypeDesc { get { return _qnameTypeDesc; } }
internal string ClassName { get { return _className; } }
internal TypeScope[] Scopes { get { return _scopes; } }
internal Dictionary<TypeMapping, string> MethodNames { get { return _methodNames; } }
internal HashSet<TypeMapping> GeneratedMethods { get { return _generatedMethods; } }
internal ModuleBuilder ModuleBuilder
{
get { System.Diagnostics.Debug.Assert(_moduleBuilder != null); return _moduleBuilder; }
set { System.Diagnostics.Debug.Assert(_moduleBuilder == null && value != null); _moduleBuilder = value; }
}
internal TypeAttributes TypeAttributes { get { return _typeAttributes; } }
private static Dictionary<string, Regex> s_regexs = new Dictionary<string, Regex>();
internal static Regex NewRegex(string pattern)
{
Regex regex;
lock (s_regexs)
{
if (!s_regexs.TryGetValue(pattern, out regex))
{
regex = new Regex(pattern);
s_regexs.Add(pattern, regex);
}
}
return regex;
}
internal MethodBuilder EnsureMethodBuilder(TypeBuilder typeBuilder, string methodName,
MethodAttributes attributes, Type returnType, Type[] parameterTypes)
{
MethodBuilderInfo methodBuilderInfo;
if (!_methodBuilders.TryGetValue(methodName, out methodBuilderInfo))
{
MethodBuilder methodBuilder = typeBuilder.DefineMethod(
methodName,
attributes,
returnType,
parameterTypes);
methodBuilderInfo = new MethodBuilderInfo(methodBuilder, parameterTypes);
_methodBuilders.Add(methodName, methodBuilderInfo);
}
#if DEBUG
else
{
methodBuilderInfo.Validate(returnType, parameterTypes, attributes);
}
#endif
return methodBuilderInfo.MethodBuilder;
}
internal MethodBuilderInfo GetMethodBuilder(string methodName)
{
System.Diagnostics.Debug.Assert(_methodBuilders.ContainsKey(methodName));
return _methodBuilders[methodName];
}
internal virtual void GenerateMethod(TypeMapping mapping) { }
internal void GenerateReferencedMethods()
{
while (_references > 0)
{
TypeMapping mapping = _referencedMethods[--_references];
GenerateMethod(mapping);
}
}
internal string ReferenceMapping(TypeMapping mapping)
{
if (!_generatedMethods.Contains(mapping))
{
_referencedMethods = EnsureArrayIndex(_referencedMethods, _references);
_referencedMethods[_references++] = mapping;
}
string methodName;
_methodNames.TryGetValue(mapping, out methodName);
return methodName;
}
private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index)
{
if (a == null) return new TypeMapping[32];
if (index < a.Length) return a;
TypeMapping[] b = new TypeMapping[a.Length + 32];
Array.Copy(a, 0, b, 0, index);
return b;
}
internal string GetCSharpString(string value)
{
return ReflectionAwareILGen.GetCSharpString(value);
}
internal FieldBuilder GenerateHashtableGetBegin(string privateName, string publicName, TypeBuilder serializerContractTypeBuilder)
{
FieldBuilder fieldBuilder = serializerContractTypeBuilder.DefineField(
privateName,
typeof(Hashtable),
FieldAttributes.Private
);
ilg = new CodeGenerator(serializerContractTypeBuilder);
PropertyBuilder propertyBuilder = serializerContractTypeBuilder.DefineProperty(
publicName,
PropertyAttributes.None,
CallingConventions.HasThis,
typeof(Hashtable),
null, null, null, null, null);
ilg.BeginMethod(
typeof(Hashtable),
"get_" + publicName,
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName);
propertyBuilder.SetGetMethod(ilg.MethodBuilder);
ilg.Ldarg(0);
ilg.LoadMember(fieldBuilder);
ilg.Load(null);
// this 'if' ends in GenerateHashtableGetEnd
ilg.If(Cmp.EqualTo);
ConstructorInfo Hashtable_ctor = typeof(Hashtable).GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
LocalBuilder _tmpLoc = ilg.DeclareLocal(typeof(Hashtable), "_tmp");
ilg.New(Hashtable_ctor);
ilg.Stloc(_tmpLoc);
return fieldBuilder;
}
internal void GenerateHashtableGetEnd(FieldBuilder fieldBuilder)
{
ilg.Ldarg(0);
ilg.LoadMember(fieldBuilder);
ilg.Load(null);
ilg.If(Cmp.EqualTo);
{
ilg.Ldarg(0);
ilg.Ldloc(typeof(Hashtable), "_tmp");
ilg.StoreMember(fieldBuilder);
}
ilg.EndIf();
// 'endif' from GenerateHashtableGetBegin
ilg.EndIf();
ilg.Ldarg(0);
ilg.LoadMember(fieldBuilder);
ilg.GotoMethodEnd();
ilg.EndMethod();
}
internal FieldBuilder GeneratePublicMethods(string privateName, string publicName, string[] methods, XmlMapping[] xmlMappings, TypeBuilder serializerContractTypeBuilder)
{
FieldBuilder fieldBuilder = GenerateHashtableGetBegin(privateName, publicName, serializerContractTypeBuilder);
if (methods != null && methods.Length != 0 && xmlMappings != null && xmlMappings.Length == methods.Length)
{
MethodInfo Hashtable_set_Item = typeof(Hashtable).GetMethod(
"set_Item",
new Type[] { typeof(Object), typeof(Object) }
);
for (int i = 0; i < methods.Length; i++)
{
if (methods[i] == null)
continue;
ilg.Ldloc(typeof(Hashtable), "_tmp");
ilg.Ldstr(GetCSharpString(xmlMappings[i].Key));
ilg.Ldstr(GetCSharpString(methods[i]));
ilg.Call(Hashtable_set_Item);
}
}
GenerateHashtableGetEnd(fieldBuilder);
return fieldBuilder;
}
internal void GenerateSupportedTypes(Type[] types, TypeBuilder serializerContractTypeBuilder)
{
ilg = new CodeGenerator(serializerContractTypeBuilder);
ilg.BeginMethod(
typeof(bool),
"CanSerialize",
new Type[] { typeof(Type) },
new string[] { "type" },
CodeGenerator.PublicOverrideMethodAttributes);
var uniqueTypes = new HashSet<Type>();
for (int i = 0; i < types.Length; i++)
{
Type type = types[i];
if (type == null)
continue;
if (!type.IsPublic && !type.IsNestedPublic)
continue;
if (!uniqueTypes.Add(type))
continue;
// DDB172141: Wrong generated CS for serializer of List<string> type
if (type.IsGenericType || type.ContainsGenericParameters)
continue;
ilg.Ldarg("type");
ilg.Ldc(type);
ilg.If(Cmp.EqualTo);
{
ilg.Ldc(true);
ilg.GotoMethodEnd();
}
ilg.EndIf();
}
ilg.Ldc(false);
ilg.GotoMethodEnd();
ilg.EndMethod();
}
internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes)
{
baseSerializer = CodeIdentifier.MakeValid(baseSerializer);
baseSerializer = classes.AddUnique(baseSerializer, baseSerializer);
TypeBuilder baseSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder(
_moduleBuilder,
CodeIdentifier.GetCSharpName(baseSerializer),
TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.BeforeFieldInit,
typeof(XmlSerializer),
Array.Empty<Type>());
ConstructorInfo readerCtor = CreatedTypes[readerClass].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg = new CodeGenerator(baseSerializerTypeBuilder);
ilg.BeginMethod(typeof(XmlSerializationReader),
"CreateReader",
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.ProtectedOverrideMethodAttributes);
ilg.New(readerCtor);
ilg.EndMethod();
ConstructorInfo writerCtor = CreatedTypes[writerClass].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.BeginMethod(typeof(XmlSerializationWriter),
"CreateWriter",
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.ProtectedOverrideMethodAttributes);
ilg.New(writerCtor);
ilg.EndMethod();
baseSerializerTypeBuilder.DefineDefaultConstructor(
MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
Type baseSerializerType = baseSerializerTypeBuilder.CreateTypeInfo().AsType();
CreatedTypes.Add(baseSerializerType.Name, baseSerializerType);
return baseSerializer;
}
internal string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass)
{
string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name));
serializerName = classes.AddUnique(serializerName + "Serializer", mapping);
TypeBuilder typedSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder(
_moduleBuilder,
CodeIdentifier.GetCSharpName(serializerName),
TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
CreatedTypes[baseSerializer],
Array.Empty<Type>()
);
ilg = new CodeGenerator(typedSerializerTypeBuilder);
ilg.BeginMethod(
typeof(Boolean),
"CanDeserialize",
new Type[] { typeof(XmlReader) },
new string[] { "xmlReader" },
CodeGenerator.PublicOverrideMethodAttributes
);
if (mapping.Accessor.Any)
{
ilg.Ldc(true);
ilg.Stloc(ilg.ReturnLocal);
ilg.Br(ilg.ReturnLabel);
}
else
{
MethodInfo XmlReader_IsStartElement = typeof(XmlReader).GetMethod(
"IsStartElement",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(String), typeof(String) }
);
ilg.Ldarg(ilg.GetArg("xmlReader"));
ilg.Ldstr(GetCSharpString(mapping.Accessor.Name));
ilg.Ldstr(GetCSharpString(mapping.Accessor.Namespace));
ilg.Call(XmlReader_IsStartElement);
ilg.Stloc(ilg.ReturnLocal);
ilg.Br(ilg.ReturnLabel);
}
ilg.MarkLabel(ilg.ReturnLabel);
ilg.Ldloc(ilg.ReturnLocal);
ilg.EndMethod();
if (writeMethod != null)
{
ilg = new CodeGenerator(typedSerializerTypeBuilder);
ilg.BeginMethod(
typeof(void),
"Serialize",
new Type[] { typeof(object), typeof(XmlSerializationWriter) },
new string[] { "objectToSerialize", "writer" },
CodeGenerator.ProtectedOverrideMethodAttributes);
MethodInfo writerType_writeMethod = CreatedTypes[writerClass].GetMethod(
writeMethod,
CodeGenerator.InstanceBindingFlags,
new Type[] { (mapping is XmlMembersMapping) ? typeof(object[]) : typeof(object) }
);
ilg.Ldarg("writer");
ilg.Castclass(CreatedTypes[writerClass]);
ilg.Ldarg("objectToSerialize");
if (mapping is XmlMembersMapping)
{
ilg.ConvertValue(typeof(object), typeof(object[]));
}
ilg.Call(writerType_writeMethod);
ilg.EndMethod();
}
if (readMethod != null)
{
ilg = new CodeGenerator(typedSerializerTypeBuilder);
ilg.BeginMethod(
typeof(object),
"Deserialize",
new Type[] { typeof(XmlSerializationReader) },
new string[] { "reader" },
CodeGenerator.ProtectedOverrideMethodAttributes);
MethodInfo readerType_readMethod = CreatedTypes[readerClass].GetMethod(
readMethod,
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.Ldarg("reader");
ilg.Castclass(CreatedTypes[readerClass]);
ilg.Call(readerType_readMethod);
ilg.EndMethod();
}
typedSerializerTypeBuilder.DefineDefaultConstructor(CodeGenerator.PublicMethodAttributes);
Type typedSerializerType = typedSerializerTypeBuilder.CreateTypeInfo().AsType();
CreatedTypes.Add(typedSerializerType.Name, typedSerializerType);
return typedSerializerType.Name;
}
private FieldBuilder GenerateTypedSerializers(Dictionary<string, string> serializers, TypeBuilder serializerContractTypeBuilder)
{
string privateName = "typedSerializers";
FieldBuilder fieldBuilder = GenerateHashtableGetBegin(privateName, "TypedSerializers", serializerContractTypeBuilder);
MethodInfo Hashtable_Add = typeof(Hashtable).GetMethod(
"Add",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(Object), typeof(Object) }
);
foreach (string key in serializers.Keys)
{
ConstructorInfo ctor = CreatedTypes[(string)serializers[key]].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.Ldloc(typeof(Hashtable), "_tmp");
ilg.Ldstr(GetCSharpString(key));
ilg.New(ctor);
ilg.Call(Hashtable_Add);
}
GenerateHashtableGetEnd(fieldBuilder);
return fieldBuilder;
}
//GenerateGetSerializer(serializers, xmlMappings);
private void GenerateGetSerializer(Dictionary<string, string> serializers, XmlMapping[] xmlMappings, TypeBuilder serializerContractTypeBuilder)
{
ilg = new CodeGenerator(serializerContractTypeBuilder);
ilg.BeginMethod(
typeof(XmlSerializer),
"GetSerializer",
new Type[] { typeof(Type) },
new string[] { "type" },
CodeGenerator.PublicOverrideMethodAttributes);
for (int i = 0; i < xmlMappings.Length; i++)
{
if (xmlMappings[i] is XmlTypeMapping)
{
Type type = xmlMappings[i].Accessor.Mapping.TypeDesc.Type;
if (type == null)
continue;
if (!type.IsPublic && !type.IsNestedPublic)
continue;
// DDB172141: Wrong generated CS for serializer of List<string> type
if (type.IsGenericType || type.ContainsGenericParameters)
continue;
ilg.Ldarg("type");
ilg.Ldc(type);
ilg.If(Cmp.EqualTo);
{
ConstructorInfo ctor = CreatedTypes[(string)serializers[xmlMappings[i].Key]].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.New(ctor);
ilg.Stloc(ilg.ReturnLocal);
ilg.Br(ilg.ReturnLabel);
}
ilg.EndIf();
}
}
ilg.Load(null);
ilg.Stloc(ilg.ReturnLocal);
ilg.Br(ilg.ReturnLabel);
ilg.MarkLabel(ilg.ReturnLabel);
ilg.Ldloc(ilg.ReturnLocal);
ilg.EndMethod();
}
internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Dictionary<string, string> serializers)
{
TypeBuilder serializerContractTypeBuilder = CodeGenerator.CreateTypeBuilder(
_moduleBuilder,
"XmlSerializerContract",
TypeAttributes.Public | TypeAttributes.BeforeFieldInit,
typeof(XmlSerializerImplementation),
Array.Empty<Type>()
);
ilg = new CodeGenerator(serializerContractTypeBuilder);
PropertyBuilder propertyBuilder = serializerContractTypeBuilder.DefineProperty(
"Reader",
PropertyAttributes.None,
typeof(XmlSerializationReader),
null, null, null, null, null);
ilg.BeginMethod(
typeof(XmlSerializationReader),
"get_Reader",
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName);
propertyBuilder.SetGetMethod(ilg.MethodBuilder);
ConstructorInfo ctor = CreatedTypes[readerType].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.New(ctor);
ilg.EndMethod();
ilg = new CodeGenerator(serializerContractTypeBuilder);
propertyBuilder = serializerContractTypeBuilder.DefineProperty(
"Writer",
PropertyAttributes.None,
typeof(XmlSerializationWriter),
null, null, null, null, null);
ilg.BeginMethod(
typeof(XmlSerializationWriter),
"get_Writer",
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName);
propertyBuilder.SetGetMethod(ilg.MethodBuilder);
ctor = CreatedTypes[writerType].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.New(ctor);
ilg.EndMethod();
FieldBuilder readMethodsField = GeneratePublicMethods(nameof(readMethods), "ReadMethods", readMethods, xmlMappings, serializerContractTypeBuilder);
FieldBuilder writeMethodsField = GeneratePublicMethods("writeMethods", "WriteMethods", writerMethods, xmlMappings, serializerContractTypeBuilder);
FieldBuilder typedSerializersField = GenerateTypedSerializers(serializers, serializerContractTypeBuilder);
GenerateSupportedTypes(types, serializerContractTypeBuilder);
GenerateGetSerializer(serializers, xmlMappings, serializerContractTypeBuilder);
// Default ctor
ConstructorInfo baseCtor = typeof(XmlSerializerImplementation).GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg = new CodeGenerator(serializerContractTypeBuilder);
ilg.BeginMethod(
typeof(void),
".ctor",
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.PublicMethodAttributes | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName
);
ilg.Ldarg(0);
ilg.Load(null);
ilg.StoreMember(readMethodsField);
ilg.Ldarg(0);
ilg.Load(null);
ilg.StoreMember(writeMethodsField);
ilg.Ldarg(0);
ilg.Load(null);
ilg.StoreMember(typedSerializersField);
ilg.Ldarg(0);
ilg.Call(baseCtor);
ilg.EndMethod();
// Instantiate type
Type serializerContractType = serializerContractTypeBuilder.CreateTypeInfo().AsType();
CreatedTypes.Add(serializerContractType.Name, serializerContractType);
}
internal static bool IsWildcard(SpecialMapping mapping)
{
if (mapping is SerializableMapping)
return ((SerializableMapping)mapping).IsAny;
return mapping.TypeDesc.CanBeElementValue;
}
internal void ILGenLoad(string source)
{
ILGenLoad(source, null);
}
internal void ILGenLoad(string source, Type type)
{
if (source.StartsWith("o.@", StringComparison.Ordinal))
{
System.Diagnostics.Debug.Assert(memberInfos.ContainsKey(source.Substring(3)));
MemberInfo memInfo = memberInfos[source.Substring(3)];
ilg.LoadMember(ilg.GetVariable("o"), memInfo);
if (type != null)
{
Type memType = (memInfo is FieldInfo) ? ((FieldInfo)memInfo).FieldType : ((PropertyInfo)memInfo).PropertyType;
ilg.ConvertValue(memType, type);
}
}
else
{
SourceInfo info = new SourceInfo(source, null, null, null, ilg);
info.Load(type);
}
}
}
}
#endif
| |
// Copyright 2017 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.
using System;
using System.Collections.Generic;
using BclType = System.Type;
using Firebase.Firestore.Internal;
namespace Firebase.Firestore {
/// <summary>
/// An immutable snapshot of the data for a document.
/// </summary>
/// <remarks>
/// <para>A <c>DocumentSnapshot</c> contains data read from a document in your Cloud Firestore
/// database. The data can be extracted with the
/// <see cref="DocumentSnapshot.ToDictionary(ServerTimestampBehavior)"/>
/// or <see cref="M:DocumentSnapshot.GetValue`1{T}(string, ServerTimestampBehavior)"/> methods.
/// </para>
///
/// <para>If the <c>DocumentSnapshot</c> points to a non-existing document, <c>ToDictionary</c>
/// will return <c>null</c>. You can always explicitly check for a document's existence by
/// checking <see cref="DocumentSnapshot.Exists"/>.</para>
/// </remarks>
public sealed class DocumentSnapshot {
private readonly DocumentSnapshotProxy _proxy;
private readonly FirebaseFirestore _firestore;
internal DocumentSnapshotProxy Proxy {
get {
return _proxy;
}
}
internal DocumentSnapshot(DocumentSnapshotProxy proxy, FirebaseFirestore firestore) {
_proxy = Util.NotNull(proxy);
_firestore = Util.NotNull(firestore);
}
/// <summary>
/// The full reference to the document.
/// </summary>
public DocumentReference Reference => new DocumentReference(_proxy.reference(), _firestore);
/// <summary>
/// The ID of the document.
/// </summary>
public string Id => _proxy.id();
/// <summary>
/// Whether or not the document exists.
/// </summary>
public bool Exists => _proxy.exists();
/// <summary>
/// The metadata for this <c>DocumentSnapshot</c>.
/// </summary>
public SnapshotMetadata Metadata {
get {
return SnapshotMetadata.ConvertFromProxy(_proxy.metadata());
}
}
/// <summary>
/// Returns the document data as a <see cref="Dictionary{String, Object}"/>.
/// </summary>
/// <param name="serverTimestampBehavior">Configures the behavior for server timestamps that
/// have not yet been set to their final value.</param>
/// <returns>A <see cref="Dictionary{String, Object}"/> containing the document data or
/// <c>null</c> if this is a nonexistent document.</returns>
public Dictionary<string, object> ToDictionary(ServerTimestampBehavior serverTimestampBehavior = ServerTimestampBehavior.None)
=> ConvertTo<Dictionary<string, object>>(serverTimestampBehavior);
/// <summary>
/// Deserializes the document data as the specified type.
/// </summary>
/// <typeparam name="T">The type to deserialize the document data as.</typeparam>
/// <param name="serverTimestampBehavior">Configures the behavior for server timestamps that
/// have not yet been set to their final value.</param>
/// <returns>The deserialized data or <c>default(T)</c> if this is a nonexistent document.
/// </returns>
public T ConvertTo<T>(ServerTimestampBehavior serverTimestampBehavior = ServerTimestampBehavior.None) {
// C++ returns a non-existent document as an empty map, because the map is returned by value.
// For reference types, it makes more sense to return a non-existent document as a null
// value. This matches Android behavior.
var targetType = typeof(T);
if (!Exists) {
BclType underlyingType = Nullable.GetUnderlyingType(targetType);
if (!targetType.IsValueType || underlyingType != null) {
return default(T);
} else {
throw new ArgumentException(String.Format(
"Unable to convert a non-existent document to {0}", targetType.FullName));
}
}
var map = FirestoreCpp.ConvertSnapshotToFieldValue(_proxy, serverTimestampBehavior.ConvertToProxy());
var context = new DeserializationContext(this);
return (T)ValueDeserializer.Deserialize(context, map, targetType);
}
/// <summary>
/// Fetches a field value from the document, throwing an exception if the field does not exist.
/// </summary>
/// <param name="path">The dot-separated field path to fetch. Must not be <c>null</c> or
/// empty.</param>
/// <param name="serverTimestampBehavior">Configures the behavior for server timestamps that
/// have not yet been set to their final value.</param>
/// <exception cref="InvalidOperationException">The field does not exist in the document data.
/// </exception>
/// <returns>The deserialized value.</returns>
public T GetValue<T>(string path, ServerTimestampBehavior serverTimestampBehavior =
ServerTimestampBehavior.None) {
Preconditions.CheckNotNullOrEmpty(path, nameof(path));
return GetValue<T>(FieldPath.FromDotSeparatedString(path), serverTimestampBehavior);
}
/// <summary>
/// Attempts to fetch the given field value from the document, returning whether or not it was
/// found.
/// </summary>
/// <remarks>
/// This method does not throw an exception if the field is not found, but does throw an
/// exception if the field was found but cannot be deserialized.
/// </remarks>
/// <param name="path">The dot-separated field path to fetch. Must not be <c>null</c> or empty.
/// </param>
/// <param name="value">When this method returns, contains the deserialized value if the field
/// was found, or the default value of <typeparamref name="T"/> otherwise.</param>
/// <param name="serverTimestampBehavior">Configures the behavior for server timestamps that
/// have not yet been set to their final value.</param>
/// <returns><c>true</c> if the field was found in the document; <c>false</c> otherwise.
/// </returns>
public bool TryGetValue<T>(
string path, out T value,
ServerTimestampBehavior serverTimestampBehavior = ServerTimestampBehavior.None) {
Preconditions.CheckNotNullOrEmpty(path, nameof(path));
return TryGetValue(FieldPath.FromDotSeparatedString(path), out value,
serverTimestampBehavior);
}
/// <summary>
/// Fetches a field value from the document, throwing an exception if the field does not exist.
/// </summary>
/// <param name="path">The field path to fetch. Must not be <c>null</c> or empty.</param>
/// <param name="serverTimestampBehavior">Configures the behavior for server timestamps that
/// have not yet been set to their final value.</param>
/// <exception cref="InvalidOperationException">The field does not exist in the document data.
/// </exception>
/// <returns>The deserialized value.</returns>
public T GetValue<T>(FieldPath path, ServerTimestampBehavior serverTimestampBehavior = ServerTimestampBehavior.None) {
Preconditions.CheckNotNull(path, nameof(path));
T value;
if (TryGetValue(path, out value, serverTimestampBehavior)) {
return value;
} else {
throw new InvalidOperationException("Field " + path + " not found in document");
}
}
/// <summary>
/// Attempts to fetch the given field value from the document, returning whether or not it was
/// found.
/// </summary>
/// <remarks>
/// This method does not throw an exception if the field is not found, but does throw an
/// exception if the field was found but cannot be deserialized.
/// </remarks>
/// <param name="path">The field path to fetch. Must not be <c>null</c> or empty.</param>
/// <param name="value">When this method returns, contains the deserialized value if the field
/// was found, or the default value of <typeparamref name="T"/> otherwise.</param>
/// <param name="serverTimestampBehavior">Configures the behavior for server timestamps that
/// have not yet been set to their final value.</param>
/// <returns><c>true</c> if the field was found in the document; <c>false</c> otherwise.
/// </returns>
public bool TryGetValue<T>(FieldPath path, out T value, ServerTimestampBehavior serverTimestampBehavior = ServerTimestampBehavior.None) {
Preconditions.CheckNotNull(path, nameof(path));
value = default(T);
if (!Exists) {
return false;
} else {
FieldValueProxy fvi = _proxy.Get(path.ConvertToProxy(), serverTimestampBehavior.ConvertToProxy());
if (!fvi.is_valid()) {
return false;
} else {
var context = new DeserializationContext(this);
value = (T)ValueDeserializer.Deserialize(context, fvi, typeof(T));
return true;
}
}
}
/// <summary>
/// Determines whether or not the given field path is present in the document. If this snapshot
/// represents a missing document, this method will always return <c>false</c>.
/// </summary>
/// <param name="path">The dot-separated field path to check. Must not be <c>null</c> or empty.
/// </param>
/// <returns><c>true</c> if the specified path represents a field in the document; <c>false</c>
/// otherwise.</returns>
public bool ContainsField(string path) {
Preconditions.CheckNotNullOrEmpty(path, nameof(path));
return ContainsField(FieldPath.FromDotSeparatedString(path));
}
/// <summary>
/// Determines whether or not the given field path is present in the document. If this snapshot
/// represents a missing document, this method will always return <c>false</c>.
/// </summary>
/// <param name="path">The field path to check. Must not be <c>null</c>.</param>
/// <returns><c>true</c> if the specified path represents a field in the document; <c>false</c>
/// otherwise. </returns>
public bool ContainsField(FieldPath path) {
Preconditions.CheckNotNull(path, nameof(path));
return Exists && _proxy.Get(path.ConvertToProxy()).is_valid();
}
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as DocumentSnapshot);
/// <inheritdoc />
public bool Equals(DocumentSnapshot other) =>
other != null && FirestoreCpp.DocumentSnapshotEquals(_proxy, other._proxy);
/// <inheritdoc />
public override int GetHashCode() {
return FirestoreCpp.DocumentSnapshotHashCode(_proxy);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace WebAPIApp.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using Scintilla;
using Scintilla.Forms;
using Scintilla.Configuration;
using Scintilla.Configuration.SciTE;
namespace MyGeneration
{
public interface IScintillaNet
{
void AddStyledText(int length, byte[] s);
/*void GetStyledText(ref TextRange tr);
int FindText(int searchFlags, ref TextToFind ttf);
int FormatRange(bool bDraw, ref RangeToFormat oRangeToFormat);
int GetTextRange(ref TextRange tr);*/
char CharAt(int position);
IntPtr DocPointer();
IntPtr CreateDocument();
void AddRefDocument(IntPtr pDoc);
void ReleaseDocument(IntPtr pDoc);
void AssignCmdKey(System.Windows.Forms.Keys keyDefinition, uint sciCommand);
void ClearCmdKey(System.Windows.Forms.Keys keyDefinition);
string GetText();
int CodePage {set; }
void SetFoldMarginColor(bool useSetting, Color back);
void SetFoldMarginHiColor(bool useSetting, Color fore);
void SetSelectionBackground(bool useSetting, Color back);
void StyleSetFore(int style, Color fore);
void StyleSetBack(int style, Color back);
string ConfigurationLanguage { set; get; }
int SafeBraceMatch(int position);
void AddShortcuts(Form parentForm);
void AddShortcuts(Menu.MenuItemCollection m);
void AddShortcuts(ToolStripItemCollection m);
void AddIgnoredKey(System.Windows.Forms.Shortcut shortcutkey);
void AddIgnoredKey(System.Windows.Forms.Keys shortcutkey);
void ClearIgnoredKeys();
bool PreProcessMessage(ref Message m);
string Text { get; set; }
void AddLastLineEnd();
void StripTrailingSpaces();
bool PositionIsOnComment(int position);
bool PositionIsOnComment(int position, int lexer);
void ExpandAllFolds();
void CollapseAllFolds();
string GetWordFromPosition(int position);
int BaseStyleAt(int pos);
bool CanRedo { get; }
bool IsAutoCActive { get; }
bool CanPaste { get; }
bool CanUndo { get; }
bool IsCallTipActive { get; }
int Length { get; }
int CurrentPos { get; set; }
int Anchor_ { get; set; }
bool IsUndoCollection { get; set; }
int EndStyled { get; }
bool IsBufferedDraw { get; set; }
int TabWidth { get; set; }
int SelectionAlpha { get; set; }
bool IsSelEOLFilled { get; set; }
int CaretPeriod { get; set; }
int StyleBits { get; set; }
int MaxLineState { get; }
bool IsCaretLineVisible { get; set; }
int CaretLineBackgroundColor { get; set; }
int AutoCSeparator { get; set; }
bool IsAutoCCancelAtStart { get; set; }
bool IsAutoCChooseSingle { get; set; }
bool IsAutoCIgnoreCase { get; set; }
bool IsAutoCAutoHide { get; set; }
bool IsAutoCDropRestOfWord { get; set; }
int AutoCTypeSeparator { get; set; }
int AutoCMaxWidth { get; set; }
int AutoCMaxHeight { get; set; }
int Indent { get; set; }
bool IsUseTabs { get; set; }
bool IsHScrollBar { get; set; }
Scintilla.Enums.IndentationGuideType IndentationGuide { get; set; }
int HighlightGuide { get; set; }
int CaretFore { get; set; }
bool IsUsePalette { get; set; }
bool IsReadOnly { get; set; }
int SelectionStart { get; set; }
int SelectionEnd { get; set; }
int PrintMagnification { get; set; }
int PrintColorMode { get; set; }
int FirstVisibleLine { get; }
int LineCount { get; }
int MarginLeft { get; set; }
int MarginRight { get; set; }
bool IsModify { get; }
int TextLength { get; }
int DirectFunction { get; }
int DirectPointer { get; }
bool IsOvertype { get; set; }
int CaretWidth { get; set; }
int TargetStart { get; set; }
int TargetEnd { get; set; }
int SearchFlags { get; set; }
bool IsTabIndents { get; set; }
bool BackspaceUnIndents { get; set; }
int MouseDwellTime { get; set; }
int WrapMode { get; set; }
int WrapVisualFlags { get; set; }
int WrapVisualFlagsLocation { get; set; }
int WrapStartIndent { get; set; }
int LayoutCache { get; set; }
int ScrollWidth { get; set; }
bool IsEndAtLastLine { get; set; }
bool IsVScrollBar { get; set; }
bool IsTwoPhaseDraw { get; set; }
bool IsViewEOL { get; set; }
int EdgeColumn { get; set; }
int EdgeMode { get; set; }
int EdgeColor { get; set; }
int LinesOnScreen { get; }
bool IsSelectionIsRectangle { get; }
int Zoom { get; set; }
int ModEventMask { get; set; }
bool IsFocus { get; set; }
int Status { get; set; }
bool IsMouseDownCaptures { get; set; }
int Cursor_ { get; set; }
int ControlCharSymbol { get; set; }
int XOffset { get; set; }
int PrintWrapMode { get; set; }
int HotspotActiveFore { get; set; }
int HotspotActiveBack { get; set; }
bool IsHotspotActiveUnderline { get; set; }
bool IsHotspotSingleLine { get; set; }
int SelectionMode { get; set; }
bool IsCaretSticky { get; set; }
bool IsPasteConvertEndings { get; set; }
int CaretLineBackgroundAlpha { get; set; }
int Lexer { get; set; }
int StyleBitsNeeded { get; }
void AddText(string text);
void InsertText(int pos, string text);
void ClearAll();
void ClearDocumentStyle();
void Redo();
void SelectAll();
void SetSavePoint();
int MarkerLineFromHandle(int handle);
void MarkerDeleteHandle(int handle);
int PositionFromPoint(int x, int y);
int PositionFromPointClose(int x, int y);
void GotoLine(int line);
void GotoPos(int pos);
string GetCurLine();
void StartStyling(int pos, int mask);
void SetStyling(int length, int style);
void MarkerSetForegroundColor(int markerNumber, int fore);
void MarkerSetBackgroundColor(int markerNumber, int back);
int MarkerAdd(int line, int markerNumber);
void MarkerDelete(int line, int markerNumber);
void MarkerDeleteAll(int markerNumber);
int MarkerGet(int line);
int MarkerNext(int lineStart, int markerMask);
int MarkerPrevious(int lineStart, int markerMask);
void MarkerDefinePixmap(int markerNumber, string pixmap);
void MarkerAddSet(int line, int set);
void MarkerSetAlpha(int markerNumber, int alpha);
void StyleResetDefault();
string StyleGetFont(int style);
void SetSelectionForeground(bool useSetting, int fore);
void SetSelectionBackground(bool useSetting, int back);
void ClearAllCmdKeys();
void SetStylingEx(string styles);
void BeginUndoAction();
void EndUndoAction();
void SetWhiteSpaceForeground(bool useSetting, int fore);
void SetWhiteSpaceBackground(bool useSetting, int back);
void AutoCShow(int lenEntered, string itemList);
void AutoCCancel();
int AutoCPosStart();
void AutoCComplete();
void AutoCStops(string characterSet);
void AutoCSelect(string text);
void UserListShow(int listType, string itemList);
void RegisterImage(int type, string xpmData);
void ClearRegisteredImages();
void SetSelection(int start, int end);
string GetSelectedText();
void HideSelection(bool normal);
int PointXFromPosition(int pos);
int PointYFromPosition(int pos);
int LineFromPosition(int pos);
int PositionFromLine(int line);
void LineScroll(int columns, int lines);
void ScrollCaret();
void ReplaceSelection(string text);
void Null();
void EmptyUndoBuffer();
void Undo();
void Cut();
void Copy();
void Paste();
void Clear();
void SetText(string text);
int ReplaceTarget(string text);
int ReplaceTargetRE(string text);
int SearchInTarget(string text);
void CallTipShow(int pos, string definition);
void CallTipCancel();
int CallTipPosStart();
void CallTipSetHlt(int start, int end);
int VisibleFromDocLine(int line);
int DocLineFromVisible(int lineDisplay);
int WrapCount(int line);
void ShowLines(int lineStart, int lineEnd);
void HideLines(int lineStart, int lineEnd);
void ToggleFold(int line);
void EnsureVisible(int line);
void SetFoldFlags(int flags);
void EnsureVisibleEnforcePolicy(int line);
int WordStartPosition(int pos, bool onlyWordCharacters);
int WordEndPosition(int pos, bool onlyWordCharacters);
int TextWidth(int style, string text);
int TextHeight(int line);
void AppendText(string text);
void TargetFromSelection();
void LinesJoin();
void LinesSplit(int pixelWidth);
void SetFoldMarginColor(bool useSetting, int back);
void SetFoldMarginHiColor(bool useSetting, int fore);
void LineDown();
void LineDownExtend();
void LineUp();
void LineUpExtend();
void CharLeft();
void CharLeftExtend();
void CharRight();
void CharRightExtend();
void WordLeft();
void WordLeftExtend();
void WordRight();
void WordRightExtend();
void Home();
void HomeExtend();
void LineEnd();
void LineEndExtend();
void DocumentStart();
void DocumentStartExtend();
void DocumentEnd();
void DocumentEndExtend();
void PageUp();
void PageUpExtend();
void PageDown();
void PageDownExtend();
void EditToggleOvertype();
void Cancel();
void DeleteBack();
void Tab();
void BackTab();
void NewLine();
void FormFeed();
void VCHome();
void VCHomeExtend();
void ZoomIn();
void ZoomOut();
void DelWordLeft();
void DelWordRight();
void LineCut();
void LineDelete();
void LineTranspose();
void LineDuplicate();
void Lowercase();
void Uppercase();
void LineScrollDown();
void LineScrollUp();
void DeleteBackNotLine();
void HomeDisplay();
void HomeDisplayExtend();
void LineEndDisplay();
void LineEndDisplayExtend();
void HomeWrap();
void HomeWrapExtend();
void LineEndWrap();
void LineEndWrapExtend();
void VCHomeWrap();
void VCHomeWrapExtend();
void LineCopy();
void MoveCaretInsideView();
int LineLength(int line);
void BraceHighlight(int pos1, int pos2);
void BraceBadLight(int pos);
int BraceMatch(int pos);
void SearchAnchor();
int SearchNext(int flags, string text);
int SearchPrevious(int flags, string text);
void UsePopup(bool allowPopUp);
void WordPartLeft();
void WordPartLeftExtend();
void WordPartRight();
void WordPartRightExtend();
void SetVisiblePolicy(int visiblePolicy, int visibleSlop);
void DelLineLeft();
void DelLineRight();
void ChooseCaretX();
void GrabFocus();
void SetXCaretPolicy(int caretPolicy, int caretSlop);
void SetYCaretPolicy(int caretPolicy, int caretSlop);
void ParaDown();
void ParaDownExtend();
void ParaUp();
void ParaUpExtend();
int PositionBefore(int pos);
int PositionAfter(int pos);
void CopyRange(int start, int end);
void CopyText(string text);
int GetLineSelectionStartPosition(int line);
int GetLineSelectionEndPosition(int line);
void LineDownRectExtend();
void LineUpRectExtend();
void CharLeftRectExtend();
void CharRightRectExtend();
void HomeRectExtend();
void VCHomeRectExtend();
void LineEndRectExtend();
void PageUpRectExtend();
void PageDownRectExtend();
void StutteredPageUp();
void StutteredPageUpExtend();
void StutteredPageDown();
void StutteredPageDownExtend();
void WordLeftEnd();
void WordLeftEndExtend();
void WordRightEnd();
void WordRightEndExtend();
void SetCharsDefault();
int AutoCGetCurrent();
void Allocate(int bytes);
string TargetAsUTF8();
void SetLengthForEncode(int bytes);
string EncodedFromUTF8(string utf8);
int FindColumn(int line, int column);
void ToggleCaretSticky();
void SelectionDuplicate();
void StartRecord();
void StopRecord();
void Colorize(int start, int end);
void LoadLexerLibrary(string path);
string GetProperty(string key);
string GetPropertyExpanded(string key);
int StyleAt(int pos);
int MarginTypeN(int margin);
int MarginWidthN(int margin);
int MarginMaskN(int margin);
bool MarginSensitiveN(int margin);
int StyleGetFore(int style);
int StyleGetBack(int style);
bool StyleGetBold(int style);
bool StyleGetItalic(int style);
int StyleGetSize(int style);
bool StyleGetEOLFilled(int style);
bool StyleGetUnderline(int style);
int StyleGetCase(int style);
int StyleGetCharacterSet(int style);
bool StyleGetVisible(int style);
bool StyleGetChangeable(int style);
bool StyleGetHotSpot(int style);
int IndicGetFore(int indic);
int LineState(int line);
int LineIndentation(int line);
int LineIndentPosition(int line);
int Column(int pos);
int LineEndPosition(int line);
int FoldLevel(int line);
int LastChild(int line, int level);
int FoldParent(int line);
bool LineVisible(int line);
bool FoldExpanded(int line);
int PropertyInt(string key);
void MarginTypeN(int margin, int marginType);
void MarginWidthN(int margin, int pixelWidth);
void MarginMaskN(int margin, int mask);
void MarginSensitiveN(int margin, bool sensitive);
void StyleClearAll();
void StyleSetFore(int style, int fore);
void StyleSetBack(int style, int back);
void StyleSetBold(int style, bool bold);
void StyleSetItalic(int style, bool italic);
void StyleSetSize(int style, int sizePoints);
void StyleSetFont(int style, string fontName);
void StyleSetEOLFilled(int style, bool filled);
void StyleSetUnderline(int style, bool underline);
void StyleSetHotSpot(int style, bool hotspot);
void StyleSetVisible(int style, bool visible);
void WordChars(string characters);
void LineState(int line, int state);
void StyleSetChangeable(int style, bool changeable);
void AutoCSetFillUps(string characterSet);
void LineIndentation(int line, int indentSize);
void CallTipSetBack(int back);
void CallTipSetFore(int fore);
void CallTipSetForeHlt(int fore);
void CallTipUseStyle(int tabSize);
void FoldLevel(int line, int level);
void FoldExpanded(int line, bool expanded);
void WhitespaceChars(string characters);
void Property(string key, string value);
void KeyWords(int keywordSet, string keyWords);
void LexerLanguage(string language);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ApplicationGatewaysOperations operations.
/// </summary>
internal partial class ApplicationGatewaysOperations : IServiceOperations<NetworkManagementClient>, IApplicationGatewaysOperations
{
/// <summary>
/// Initializes a new instance of the ApplicationGatewaysOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ApplicationGatewaysOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// The delete ApplicationGateway operation deletes the specified application
/// gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(
resourceGroupName, applicationGatewayName, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// The delete ApplicationGateway operation deletes the specified application
/// gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (applicationGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "applicationGatewayName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("applicationGatewayName", applicationGatewayName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{applicationGatewayName}", Uri.EscapeDataString(applicationGatewayName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 204 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The Get ApplicationGateway operation retrieves information about the
/// specified application gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ApplicationGateway>> GetWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (applicationGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "applicationGatewayName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("applicationGatewayName", applicationGatewayName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{applicationGatewayName}", Uri.EscapeDataString(applicationGatewayName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ApplicationGateway>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ApplicationGateway>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The Put ApplicationGateway operation creates/updates a ApplicationGateway
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the ApplicationGateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/delete ApplicationGateway operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ApplicationGateway>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<ApplicationGateway> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(
resourceGroupName, applicationGatewayName, parameters, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// The Put ApplicationGateway operation creates/updates a ApplicationGateway
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the ApplicationGateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/delete ApplicationGateway operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ApplicationGateway>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (applicationGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "applicationGatewayName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("applicationGatewayName", applicationGatewayName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{applicationGatewayName}", Uri.EscapeDataString(applicationGatewayName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ApplicationGateway>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ApplicationGateway>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ApplicationGateway>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The List ApplicationGateway operation retrieves all the application
/// gateways in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ApplicationGateway>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ApplicationGateway>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<ApplicationGateway>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The List ApplicationGateway operation retrieves all the application
/// gateways in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ApplicationGateway>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// 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, "ListAll", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGateways").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ApplicationGateway>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<ApplicationGateway>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The Start ApplicationGateway operation starts application gateway in the
/// specified resource group through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> StartWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginStartWithHttpMessagesAsync(
resourceGroupName, applicationGatewayName, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// The Start ApplicationGateway operation starts application gateway in the
/// specified resource group through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginStartWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (applicationGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "applicationGatewayName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("applicationGatewayName", applicationGatewayName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginStart", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/start").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{applicationGatewayName}", Uri.EscapeDataString(applicationGatewayName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The STOP ApplicationGateway operation stops application gateway in the
/// specified resource group through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> StopWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginStopWithHttpMessagesAsync(
resourceGroupName, applicationGatewayName, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// The STOP ApplicationGateway operation stops application gateway in the
/// specified resource group through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='applicationGatewayName'>
/// The name of the application gateway.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginStopWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (applicationGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "applicationGatewayName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("applicationGatewayName", applicationGatewayName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginStop", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationGateways/{applicationGatewayName}/stop").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{applicationGatewayName}", Uri.EscapeDataString(applicationGatewayName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The List ApplicationGateway operation retrieves all the application
/// gateways in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ApplicationGateway>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ApplicationGateway>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<ApplicationGateway>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The List ApplicationGateway operation retrieves all the application
/// gateways in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ApplicationGateway>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ApplicationGateway>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<ApplicationGateway>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Globalization;
/// <summary>
/// A class to allow the conversion of doubles to string representations of
/// their exact decimal values. The implementation aims for readability over
/// efficiency.
/// </summary>
public class DoubleConverter
{
/// <summary>
/// Converts the given double to a string representation of its
/// exact decimal value.
/// </summary>
/// <param name="d">The double to convert.</param>
/// <returns>A string representation of the double's exact decimal value.</return>
public static string ToExactString (double d)
{
if (double.IsPositiveInfinity(d))
return "+Infinity";
if (double.IsNegativeInfinity(d))
return "-Infinity";
if (double.IsNaN(d))
return "NaN";
// Translate the double into sign, exponent and mantissa.
long bits = BitConverter.DoubleToInt64Bits(d);
// Note that the shift is sign-extended, hence the test against -1 not 1
bool negative = (bits < 0);
int exponent = (int) ((bits >> 52) & 0x7ffL);
long mantissa = bits & 0xfffffffffffffL;
// Subnormal numbers; exponent is effectively one higher,
// but there's no extra normalisation bit in the mantissa
if (exponent==0)
{
exponent++;
}
// Normal numbers; leave exponent as it is but add extra
// bit to the front of the mantissa
else
{
mantissa = mantissa | (1L<<52);
}
// Bias the exponent. It's actually biased by 1023, but we're
// treating the mantissa as m.0 rather than 0.m, so we need
// to subtract another 52 from it.
exponent -= 1075;
if (mantissa == 0)
{
return "0";
}
/* Normalize */
while((mantissa & 1) == 0)
{ /* i.e., Mantissa is even */
mantissa >>= 1;
exponent++;
}
/// Construct a new decimal expansion with the mantissa
ArbitraryDecimal ad = new ArbitraryDecimal (mantissa);
// If the exponent is less than 0, we need to repeatedly
// divide by 2 - which is the equivalent of multiplying
// by 5 and dividing by 10.
if (exponent < 0)
{
for (int i=0; i < -exponent; i++)
ad.MultiplyBy(5);
ad.Shift(-exponent);
}
// Otherwise, we need to repeatedly multiply by 2
else
{
for (int i=0; i < exponent; i++)
ad.MultiplyBy(2);
}
// Finally, return the string with an appropriate sign
if (negative)
return "-"+ad.ToString();
else
return ad.ToString();
}
/// <summary>Private class used for manipulating
class ArbitraryDecimal
{
/// <summary>Digits in the decimal expansion, one byte per digit
byte[] digits;
/// <summary>
/// How many digits are *after* the decimal point
/// </summary>
int decimalPoint=0;
/// <summary>
/// Constructs an arbitrary decimal expansion from the given long.
/// The long must not be negative.
/// </summary>
internal ArbitraryDecimal (long x)
{
string tmp = x.ToString(CultureInfo.InvariantCulture);
digits = new byte[tmp.Length];
for (int i=0; i < tmp.Length; i++)
digits[i] = (byte) (tmp[i]-'0');
Normalize();
}
/// <summary>
/// Multiplies the current expansion by the given amount, which should
/// only be 2 or 5.
/// </summary>
internal void MultiplyBy(int amount)
{
byte[] result = new byte[digits.Length+1];
for (int i=digits.Length-1; i >= 0; i--)
{
int resultDigit = digits[i]*amount+result[i+1];
result[i]=(byte)(resultDigit/10);
result[i+1]=(byte)(resultDigit%10);
}
if (result[0] != 0)
{
digits=result;
}
else
{
Array.Copy (result, 1, digits, 0, digits.Length);
}
Normalize();
}
/// <summary>
/// Shifts the decimal point; a negative value makes
/// the decimal expansion bigger (as fewer digits come after the
/// decimal place) and a positive value makes the decimal
/// expansion smaller.
/// </summary>
internal void Shift (int amount)
{
decimalPoint += amount;
}
/// <summary>
/// Removes leading/trailing zeroes from the expansion.
/// </summary>
internal void Normalize()
{
int first;
for (first=0; first < digits.Length; first++)
if (digits[first]!=0)
break;
int last;
for (last=digits.Length-1; last >= 0; last--)
if (digits[last]!=0)
break;
if (first==0 && last==digits.Length-1)
return;
byte[] tmp = new byte[last-first+1];
for (int i=0; i < tmp.Length; i++)
tmp[i]=digits[i+first];
decimalPoint -= digits.Length-(last+1);
digits=tmp;
}
/// <summary>
/// Converts the value to a proper decimal string representation.
/// </summary>
public override String ToString()
{
char[] digitString = new char[digits.Length];
for (int i=0; i < digits.Length; i++)
digitString[i] = (char)(digits[i]+'0');
// Simplest case - nothing after the decimal point,
// and last real digit is non-zero, eg value=35
if (decimalPoint==0)
{
return new string (digitString);
}
// Fairly simple case - nothing after the decimal
// point, but some 0s to add, eg value=350
if (decimalPoint < 0)
{
return new string (digitString)+
new string ('0', -decimalPoint);
}
// Nothing before the decimal point, eg 0.035
if (decimalPoint >= digitString.Length)
{
return "0."+
new string ('0',(decimalPoint-digitString.Length))+
new string (digitString);
}
// Most complicated case - part of the string comes
// before the decimal point, part comes after it,
// eg 3.5
return new string (digitString, 0,
digitString.Length-decimalPoint)+
"."+
new string (digitString,
digitString.Length-decimalPoint,
decimalPoint);
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// Describes the SDN controller that is to connect with the pool
/// First published in XenServer 7.2.
/// </summary>
public partial class SDN_controller : XenObject<SDN_controller>
{
#region Constructors
public SDN_controller()
{
}
public SDN_controller(string uuid,
sdn_controller_protocol protocol,
string address,
long port)
{
this.uuid = uuid;
this.protocol = protocol;
this.address = address;
this.port = port;
}
/// <summary>
/// Creates a new SDN_controller from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public SDN_controller(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new SDN_controller from a Proxy_SDN_controller.
/// </summary>
/// <param name="proxy"></param>
public SDN_controller(Proxy_SDN_controller proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given SDN_controller.
/// </summary>
public override void UpdateFrom(SDN_controller record)
{
uuid = record.uuid;
protocol = record.protocol;
address = record.address;
port = record.port;
}
internal void UpdateFrom(Proxy_SDN_controller proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
protocol = proxy.protocol == null ? (sdn_controller_protocol) 0 : (sdn_controller_protocol)Helper.EnumParseDefault(typeof(sdn_controller_protocol), (string)proxy.protocol);
address = proxy.address == null ? null : proxy.address;
port = proxy.port == null ? 0 : long.Parse(proxy.port);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this SDN_controller
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("protocol"))
protocol = (sdn_controller_protocol)Helper.EnumParseDefault(typeof(sdn_controller_protocol), Marshalling.ParseString(table, "protocol"));
if (table.ContainsKey("address"))
address = Marshalling.ParseString(table, "address");
if (table.ContainsKey("port"))
port = Marshalling.ParseLong(table, "port");
}
public Proxy_SDN_controller ToProxy()
{
Proxy_SDN_controller result_ = new Proxy_SDN_controller();
result_.uuid = uuid ?? "";
result_.protocol = sdn_controller_protocol_helper.ToString(protocol);
result_.address = address ?? "";
result_.port = port.ToString();
return result_;
}
public bool DeepEquals(SDN_controller other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._protocol, other._protocol) &&
Helper.AreEqual2(this._address, other._address) &&
Helper.AreEqual2(this._port, other._port);
}
public override string SaveChanges(Session session, string opaqueRef, SDN_controller server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given SDN_controller.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static SDN_controller get_record(Session session, string _sdn_controller)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_get_record(session.opaque_ref, _sdn_controller);
else
return new SDN_controller(session.XmlRpcProxy.sdn_controller_get_record(session.opaque_ref, _sdn_controller ?? "").parse());
}
/// <summary>
/// Get a reference to the SDN_controller instance with the specified UUID.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<SDN_controller> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<SDN_controller>.Create(session.XmlRpcProxy.sdn_controller_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given SDN_controller.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static string get_uuid(Session session, string _sdn_controller)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_get_uuid(session.opaque_ref, _sdn_controller);
else
return session.XmlRpcProxy.sdn_controller_get_uuid(session.opaque_ref, _sdn_controller ?? "").parse();
}
/// <summary>
/// Get the protocol field of the given SDN_controller.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static sdn_controller_protocol get_protocol(Session session, string _sdn_controller)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_get_protocol(session.opaque_ref, _sdn_controller);
else
return (sdn_controller_protocol)Helper.EnumParseDefault(typeof(sdn_controller_protocol), (string)session.XmlRpcProxy.sdn_controller_get_protocol(session.opaque_ref, _sdn_controller ?? "").parse());
}
/// <summary>
/// Get the address field of the given SDN_controller.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static string get_address(Session session, string _sdn_controller)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_get_address(session.opaque_ref, _sdn_controller);
else
return session.XmlRpcProxy.sdn_controller_get_address(session.opaque_ref, _sdn_controller ?? "").parse();
}
/// <summary>
/// Get the port field of the given SDN_controller.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static long get_port(Session session, string _sdn_controller)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_get_port(session.opaque_ref, _sdn_controller);
else
return long.Parse(session.XmlRpcProxy.sdn_controller_get_port(session.opaque_ref, _sdn_controller ?? "").parse());
}
/// <summary>
/// Introduce an SDN controller to the pool.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_protocol">Protocol to connect with the controller.</param>
/// <param name="_address">IP address of the controller.</param>
/// <param name="_port">TCP port of the controller.</param>
public static XenRef<SDN_controller> introduce(Session session, sdn_controller_protocol _protocol, string _address, long _port)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_introduce(session.opaque_ref, _protocol, _address, _port);
else
return XenRef<SDN_controller>.Create(session.XmlRpcProxy.sdn_controller_introduce(session.opaque_ref, sdn_controller_protocol_helper.ToString(_protocol), _address ?? "", _port.ToString()).parse());
}
/// <summary>
/// Introduce an SDN controller to the pool.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_protocol">Protocol to connect with the controller.</param>
/// <param name="_address">IP address of the controller.</param>
/// <param name="_port">TCP port of the controller.</param>
public static XenRef<Task> async_introduce(Session session, sdn_controller_protocol _protocol, string _address, long _port)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_sdn_controller_introduce(session.opaque_ref, _protocol, _address, _port);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_sdn_controller_introduce(session.opaque_ref, sdn_controller_protocol_helper.ToString(_protocol), _address ?? "", _port.ToString()).parse());
}
/// <summary>
/// Remove the OVS manager of the pool and destroy the db record.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static void forget(Session session, string _sdn_controller)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.sdn_controller_forget(session.opaque_ref, _sdn_controller);
else
session.XmlRpcProxy.sdn_controller_forget(session.opaque_ref, _sdn_controller ?? "").parse();
}
/// <summary>
/// Remove the OVS manager of the pool and destroy the db record.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static XenRef<Task> async_forget(Session session, string _sdn_controller)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_sdn_controller_forget(session.opaque_ref, _sdn_controller);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_sdn_controller_forget(session.opaque_ref, _sdn_controller ?? "").parse());
}
/// <summary>
/// Return a list of all the SDN_controllers known to the system.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<SDN_controller>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_get_all(session.opaque_ref);
else
return XenRef<SDN_controller>.Create(session.XmlRpcProxy.sdn_controller_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the SDN_controller Records at once, in a single XML RPC call
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<SDN_controller>, SDN_controller> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_get_all_records(session.opaque_ref);
else
return XenRef<SDN_controller>.Create<Proxy_SDN_controller>(session.XmlRpcProxy.sdn_controller_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// Protocol to connect with SDN controller
/// </summary>
[JsonConverter(typeof(sdn_controller_protocolConverter))]
public virtual sdn_controller_protocol protocol
{
get { return _protocol; }
set
{
if (!Helper.AreEqual(value, _protocol))
{
_protocol = value;
NotifyPropertyChanged("protocol");
}
}
}
private sdn_controller_protocol _protocol = sdn_controller_protocol.ssl;
/// <summary>
/// IP address of the controller
/// </summary>
public virtual string address
{
get { return _address; }
set
{
if (!Helper.AreEqual(value, _address))
{
_address = value;
NotifyPropertyChanged("address");
}
}
}
private string _address = "";
/// <summary>
/// TCP port of the controller
/// </summary>
public virtual long port
{
get { return _port; }
set
{
if (!Helper.AreEqual(value, _port))
{
_port = value;
NotifyPropertyChanged("port");
}
}
}
private long _port = 0;
}
}
| |
using System;
using System.Collections.Generic;
using Umbraco.Core.Auditing;
using Umbraco.Core.Events;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Services
{
/// <summary>
/// Represents the File Service, which is an easy access to operations involving <see cref="IFile"/> objects like Scripts, Stylesheets and Templates
/// </summary>
public class FileService : IFileService
{
private readonly RepositoryFactory _repositoryFactory;
private readonly IUnitOfWorkProvider _fileUowProvider;
private readonly IDatabaseUnitOfWorkProvider _dataUowProvider;
public FileService()
: this(new RepositoryFactory())
{}
public FileService(RepositoryFactory repositoryFactory)
: this(new FileUnitOfWorkProvider(), new PetaPocoUnitOfWorkProvider(), repositoryFactory)
{
}
public FileService(IUnitOfWorkProvider fileProvider, IDatabaseUnitOfWorkProvider dataProvider, RepositoryFactory repositoryFactory)
{
_repositoryFactory = repositoryFactory;
_fileUowProvider = fileProvider;
_dataUowProvider = dataProvider;
}
/// <summary>
/// Gets a list of all <see cref="Stylesheet"/> objects
/// </summary>
/// <returns>An enumerable list of <see cref="Stylesheet"/> objects</returns>
public IEnumerable<Stylesheet> GetStylesheets(params string[] names)
{
using (var repository = _repositoryFactory.CreateStylesheetRepository(_fileUowProvider.GetUnitOfWork()))
{
return repository.GetAll(names);
}
}
/// <summary>
/// Gets a <see cref="Stylesheet"/> object by its name
/// </summary>
/// <param name="name">Name of the stylesheet incl. extension</param>
/// <returns>A <see cref="Stylesheet"/> object</returns>
public Stylesheet GetStylesheetByName(string name)
{
using (var repository = _repositoryFactory.CreateStylesheetRepository(_fileUowProvider.GetUnitOfWork()))
{
return repository.Get(name);
}
}
/// <summary>
/// Saves a <see cref="Stylesheet"/>
/// </summary>
/// <param name="stylesheet"><see cref="Stylesheet"/> to save</param>
/// <param name="userId"></param>
public void SaveStylesheet(Stylesheet stylesheet, int userId = 0)
{
if (SavingStylesheet.IsRaisedEventCancelled(new SaveEventArgs<Stylesheet>(stylesheet), this))
return;
var uow = _fileUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateStylesheetRepository(uow))
{
repository.AddOrUpdate(stylesheet);
uow.Commit();
SavedStylesheet.RaiseEvent(new SaveEventArgs<Stylesheet>(stylesheet, false), this);
}
Audit.Add(AuditTypes.Save, string.Format("Save Stylesheet performed by user"), userId, -1);
}
/// <summary>
/// Deletes a stylesheet by its name
/// </summary>
/// <param name="name">Name incl. extension of the Stylesheet to delete</param>
/// <param name="userId"></param>
public void DeleteStylesheet(string name, int userId = 0)
{
var uow = _fileUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateStylesheetRepository(uow))
{
var stylesheet = repository.Get(name);
if (DeletingStylesheet.IsRaisedEventCancelled(new DeleteEventArgs<Stylesheet>(stylesheet), this))
return;
repository.Delete(stylesheet);
uow.Commit();
DeletedStylesheet.RaiseEvent(new DeleteEventArgs<Stylesheet>(stylesheet, false), this);
Audit.Add(AuditTypes.Delete, string.Format("Delete Stylesheet performed by user"), userId, -1);
}
}
/// <summary>
/// Validates a <see cref="Stylesheet"/>
/// </summary>
/// <param name="stylesheet"><see cref="Stylesheet"/> to validate</param>
/// <returns>True if Stylesheet is valid, otherwise false</returns>
public bool ValidateStylesheet(Stylesheet stylesheet)
{
return stylesheet.IsValid() && stylesheet.IsFileValidCss();
}
/// <summary>
/// Gets a list of all <see cref="Script"/> objects
/// </summary>
/// <returns>An enumerable list of <see cref="Script"/> objects</returns>
public IEnumerable<Script> GetScripts(params string[] names)
{
using (var repository = _repositoryFactory.CreateScriptRepository(_fileUowProvider.GetUnitOfWork()))
{
return repository.GetAll(names);
}
}
/// <summary>
/// Gets a <see cref="Script"/> object by its name
/// </summary>
/// <param name="name">Name of the script incl. extension</param>
/// <returns>A <see cref="Script"/> object</returns>
public Script GetScriptByName(string name)
{
using (var repository = _repositoryFactory.CreateScriptRepository(_fileUowProvider.GetUnitOfWork()))
{
return repository.Get(name);
}
}
/// <summary>
/// Saves a <see cref="Script"/>
/// </summary>
/// <param name="script"><see cref="Script"/> to save</param>
/// <param name="userId"></param>
public void SaveScript(Script script, int userId = 0)
{
if (SavingScript.IsRaisedEventCancelled(new SaveEventArgs<Script>(script), this))
return;
var uow = _fileUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateScriptRepository(uow))
{
repository.AddOrUpdate(script);
uow.Commit();
SavedScript.RaiseEvent(new SaveEventArgs<Script>(script, false), this);
}
Audit.Add(AuditTypes.Save, string.Format("Save Script performed by user"), userId, -1);
}
/// <summary>
/// Deletes a script by its name
/// </summary>
/// <param name="name">Name incl. extension of the Script to delete</param>
/// <param name="userId"></param>
public void DeleteScript(string name, int userId = 0)
{
var uow = _fileUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateScriptRepository(uow))
{
var script = repository.Get(name);
if (DeletingScript.IsRaisedEventCancelled(new DeleteEventArgs<Script>(script), this))
return; ;
repository.Delete(script);
uow.Commit();
DeletedScript.RaiseEvent(new DeleteEventArgs<Script>(script, false), this);
Audit.Add(AuditTypes.Delete, string.Format("Delete Script performed by user"), userId, -1);
}
}
/// <summary>
/// Validates a <see cref="Script"/>
/// </summary>
/// <param name="script"><see cref="Script"/> to validate</param>
/// <returns>True if Script is valid, otherwise false</returns>
public bool ValidateScript(Script script)
{
return script.IsValid();
}
/// <summary>
/// Gets a list of all <see cref="ITemplate"/> objects
/// </summary>
/// <returns>An enumerable list of <see cref="ITemplate"/> objects</returns>
public IEnumerable<ITemplate> GetTemplates(params string[] aliases)
{
using (var repository = _repositoryFactory.CreateTemplateRepository(_dataUowProvider.GetUnitOfWork()))
{
return repository.GetAll(aliases);
}
}
/// <summary>
/// Gets a <see cref="ITemplate"/> object by its alias
/// </summary>
/// <param name="alias">Alias of the template</param>
/// <returns>A <see cref="Template"/> object</returns>
public ITemplate GetTemplate(string alias)
{
using (var repository = _repositoryFactory.CreateTemplateRepository(_dataUowProvider.GetUnitOfWork()))
{
return repository.Get(alias);
}
}
/// <summary>
/// Gets a <see cref="ITemplate"/> object by its alias
/// </summary>
/// <param name="id">Id of the template</param>
/// <returns>A <see cref="ITemplate"/> object</returns>
public ITemplate GetTemplate(int id)
{
using (var repository = _repositoryFactory.CreateTemplateRepository(_dataUowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Saves a <see cref="Template"/>
/// </summary>
/// <param name="template"><see cref="Template"/> to save</param>
/// <param name="userId"></param>
public void SaveTemplate(ITemplate template, int userId = 0)
{
if (SavingTemplate.IsRaisedEventCancelled(new SaveEventArgs<ITemplate>(template), this))
return;
var uow = _dataUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateTemplateRepository(uow))
{
repository.AddOrUpdate(template);
uow.Commit();
SavedTemplate.RaiseEvent(new SaveEventArgs<ITemplate>(template, false), this);
}
Audit.Add(AuditTypes.Save, string.Format("Save Template performed by user"), userId, template.Id);
}
/// <summary>
/// Saves a collection of <see cref="Template"/> objects
/// </summary>
/// <param name="templates">List of <see cref="Template"/> to save</param>
/// <param name="userId">Optional id of the user</param>
public void SaveTemplate(IEnumerable<ITemplate> templates, int userId = 0)
{
if (SavingTemplate.IsRaisedEventCancelled(new SaveEventArgs<ITemplate>(templates), this))
return;
var uow = _dataUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateTemplateRepository(uow))
{
foreach (var template in templates)
{
repository.AddOrUpdate(template);
}
uow.Commit();
SavedTemplate.RaiseEvent(new SaveEventArgs<ITemplate>(templates, false), this);
}
Audit.Add(AuditTypes.Save, string.Format("Save Template performed by user"), userId, -1);
}
/// <summary>
/// Deletes a template by its alias
/// </summary>
/// <param name="alias">Alias of the <see cref="ITemplate"/> to delete</param>
/// <param name="userId"></param>
public void DeleteTemplate(string alias, int userId = 0)
{
var uow = _dataUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateTemplateRepository(uow))
{
var template = repository.Get(alias);
if (DeletingTemplate.IsRaisedEventCancelled(new DeleteEventArgs<ITemplate>(template), this))
return;
repository.Delete(template);
uow.Commit();
DeletedTemplate.RaiseEvent(new DeleteEventArgs<ITemplate>(template, false), this);
Audit.Add(AuditTypes.Delete, string.Format("Delete Template performed by user"), userId, template.Id);
}
}
/// <summary>
/// Validates a <see cref="ITemplate"/>
/// </summary>
/// <param name="template"><see cref="ITemplate"/> to validate</param>
/// <returns>True if Script is valid, otherwise false</returns>
public bool ValidateTemplate(ITemplate template)
{
return template.IsValid();
}
//TODO Method to change name and/or alias of view/masterpage template
#region Event Handlers
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IFileService, DeleteEventArgs<ITemplate>> DeletingTemplate;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IFileService, DeleteEventArgs<ITemplate>> DeletedTemplate;
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IFileService, DeleteEventArgs<Script>> DeletingScript;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IFileService, DeleteEventArgs<Script>> DeletedScript;
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IFileService, DeleteEventArgs<Stylesheet>> DeletingStylesheet;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IFileService, DeleteEventArgs<Stylesheet>> DeletedStylesheet;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IFileService, SaveEventArgs<ITemplate>> SavingTemplate;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IFileService, SaveEventArgs<ITemplate>> SavedTemplate;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IFileService, SaveEventArgs<Script>> SavingScript;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IFileService, SaveEventArgs<Script>> SavedScript;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IFileService, SaveEventArgs<Stylesheet>> SavingStylesheet;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IFileService, SaveEventArgs<Stylesheet>> SavedStylesheet;
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Interpreter.Default;
using Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools.Interpreter {
/// <summary>
/// Base class for interpreter factories that have an executable file
/// following CPython command-line conventions, a standard library that is
/// stored on disk as .py files, and using <see cref="PythonTypeDatabase"/>
/// for the completion database.
/// </summary>
public class PythonInterpreterFactoryWithDatabase :
IPythonInterpreterFactoryWithDatabase2,
IDisposable
{
private readonly string _description;
private readonly Guid _id;
private readonly InterpreterConfiguration _config;
private PythonTypeDatabase _typeDb, _typeDbWithoutPackages;
private bool _generating, _isValid, _isCheckingDatabase, _disposed;
private string[] _missingModules;
private string _isCurrentException;
private readonly Timer _refreshIsCurrentTrigger;
private FileSystemWatcher _libWatcher;
private readonly object _libWatcherLock = new object();
private FileSystemWatcher _verWatcher;
private FileSystemWatcher _verDirWatcher;
private readonly object _verWatcherLock = new object();
// Only one thread can be updating our current state
private readonly SemaphoreSlim _isCurrentSemaphore = new SemaphoreSlim(1);
// Only four threads can be updating any state. This is to prevent I/O
// saturation when multiple threads refresh simultaneously.
private static readonly SemaphoreSlim _sharedIsCurrentSemaphore = new SemaphoreSlim(4);
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",
Justification = "breaking change")]
public PythonInterpreterFactoryWithDatabase(
Guid id,
string description,
InterpreterConfiguration config,
bool watchLibraryForChanges
) {
_description = description;
_id = id;
_config = config;
if (_config == null) {
throw new ArgumentNullException("config");
}
// Avoid creating a interpreter with an unsupported version.
// https://github.com/Microsoft/PTVS/issues/706
try {
var langVer = _config.Version.ToLanguageVersion();
} catch (InvalidOperationException ex) {
throw new ArgumentException(ex.Message, ex);
}
if (watchLibraryForChanges && Directory.Exists(_config.LibraryPath)) {
_refreshIsCurrentTrigger = new Timer(RefreshIsCurrentTimer_Elapsed);
_libWatcher = CreateLibraryWatcher();
_isCheckingDatabase = true;
_refreshIsCurrentTrigger.Change(1000, Timeout.Infinite);
_verWatcher = CreateDatabaseVerWatcher();
_verDirWatcher = CreateDatabaseDirectoryWatcher();
}
// Assume the database is valid if the directory exists, then switch
// to invalid after we've checked.
_isValid = Directory.Exists(DatabasePath);
}
public InterpreterConfiguration Configuration {
get {
return _config;
}
}
public virtual string Description {
get { return _description; }
}
public Guid Id {
get { return _id; }
}
/// <summary>
/// Determines whether instances of this factory should assume that
/// libraries are laid out exactly as CPython. If false, the interpreter
/// will be queried for its search paths.
/// </summary>
public virtual bool AssumeSimpleLibraryLayout {
get {
return true;
}
}
/// <summary>
/// Returns a new interpreter created with the specified factory.
/// </summary>
/// <remarks>
/// This is intended for use by derived classes only. To get an
/// interpreter instance, use <see cref="CreateInterpreter"/>.
/// </remarks>
public virtual IPythonInterpreter MakeInterpreter(PythonInterpreterFactoryWithDatabase factory) {
return new CPythonInterpreter(factory);
}
public IPythonInterpreter CreateInterpreter() {
return MakeInterpreter(this);
}
/// <summary>
/// Returns the database for this factory. This database may be shared
/// between callers and should be cloned before making modifications.
///
/// This function never returns null.
/// </summary>
public PythonTypeDatabase GetCurrentDatabase() {
if (_typeDb == null || _typeDb.DatabaseDirectory != DatabasePath) {
_typeDb = MakeTypeDatabase(DatabasePath) ??
PythonTypeDatabase.CreateDefaultTypeDatabase(this);
}
return _typeDb;
}
/// <summary>
/// Returns the database for this factory, optionally excluding package
/// analysis. This database may be shared between callers and should be
/// cloned before making modifications.
///
/// This function never returns null.
/// </summary>
public PythonTypeDatabase GetCurrentDatabase(bool includeSitePackages) {
if (includeSitePackages) {
return GetCurrentDatabase();
}
if (_typeDbWithoutPackages == null || _typeDbWithoutPackages.DatabaseDirectory != DatabasePath) {
_typeDbWithoutPackages = MakeTypeDatabase(DatabasePath, false) ??
PythonTypeDatabase.CreateDefaultTypeDatabase(this);
}
return _typeDbWithoutPackages;
}
/// <summary>
/// Returns a new database loaded from the specified path. If null is
/// returned, <see cref="GetCurrentDatabase"/> will assume the default
/// completion DB is intended.
/// </summary>
/// <remarks>
/// This is intended for overriding in derived classes. To get a
/// queryable database instance, use <see cref="GetCurrentDatabase"/> or
/// <see cref="CreateInterpreter"/>.
/// </remarks>
public virtual PythonTypeDatabase MakeTypeDatabase(string databasePath, bool includeSitePackages = true) {
if (!_generating && PythonTypeDatabase.IsDatabaseVersionCurrent(databasePath)) {
var paths = new List<string>();
paths.Add(databasePath);
if (includeSitePackages) {
paths.AddRange(Directory.EnumerateDirectories(databasePath));
}
try {
return new PythonTypeDatabase(this, paths);
} catch (IOException) {
} catch (UnauthorizedAccessException) {
}
}
return PythonTypeDatabase.CreateDefaultTypeDatabase(this);
}
private bool WatchingLibrary {
get {
if (_libWatcher != null) {
lock (_libWatcherLock) {
return _libWatcher != null && _libWatcher.EnableRaisingEvents;
}
}
return false;
}
set {
if (_libWatcher != null) {
lock (_libWatcherLock) {
if (_libWatcher == null || _libWatcher.EnableRaisingEvents == value) {
return;
}
try {
_libWatcher.EnableRaisingEvents = value;
} catch (IOException) {
// May occur if the library has been deleted while the
// watcher was disabled.
_libWatcher.Dispose();
_libWatcher = null;
} catch (ObjectDisposedException) {
_libWatcher = null;
}
}
}
}
}
public virtual void GenerateDatabase(GenerateDatabaseOptions options, Action<int> onExit = null) {
var req = new PythonTypeDatabaseCreationRequest {
Factory = this,
OutputPath = DatabasePath,
SkipUnchanged = options.HasFlag(GenerateDatabaseOptions.SkipUnchanged),
DetectLibraryPath = !AssumeSimpleLibraryLayout
};
GenerateDatabase(req, onExit);
}
protected virtual void GenerateDatabase(PythonTypeDatabaseCreationRequest request, Action<int> onExit = null) {
WatchingLibrary = false;
_generating = true;
PythonTypeDatabase.GenerateAsync(request).ContinueWith(t => {
int exitCode;
try {
exitCode = t.Result;
} catch (Exception ex) {
Debug.Fail(ex.ToString());
exitCode = PythonTypeDatabase.InvalidOperationExitCode;
}
if (exitCode != PythonTypeDatabase.AlreadyGeneratingExitCode) {
_generating = false;
}
if (onExit != null) {
onExit(exitCode);
}
});
}
/// <summary>
/// Called to inform the interpreter that its database cannot be loaded
/// and may need to be regenerated.
/// </summary>
public void NotifyCorruptDatabase() {
_isValid = false;
OnIsCurrentChanged();
OnNewDatabaseAvailable();
}
public bool IsGenerating {
get {
return _generating;
}
}
private void OnDatabaseVerChanged(object sender, FileSystemEventArgs e) {
if ((!e.Name.Equals("database.ver", StringComparison.OrdinalIgnoreCase) &&
!e.Name.Equals("database.pid", StringComparison.OrdinalIgnoreCase)) ||
!CommonUtils.IsSubpathOf(DatabasePath, e.FullPath)) {
return;
}
RefreshIsCurrent();
if (IsCurrent) {
NotifyNewDatabase();
}
}
private void NotifyNewDatabase() {
_generating = false;
OnIsCurrentChanged();
WatchingLibrary = true;
// This also clears the previous database so that we load the new
// one next time someone requests it.
OnNewDatabaseAvailable();
}
private bool IsValid {
get {
return _isValid && _missingModules == null && _isCurrentException == null;
}
}
public virtual bool IsCurrent {
get {
return !IsGenerating && IsValid;
}
}
public virtual bool IsCheckingDatabase {
get {
return _isCheckingDatabase;
}
}
public virtual string DatabasePath {
get {
return Path.Combine(
PythonTypeDatabase.CompletionDatabasePath,
Id.ToString(),
Configuration.Version.ToString()
);
}
}
public string GetAnalysisLogContent(IFormatProvider culture) {
var analysisLog = Path.Combine(DatabasePath, "AnalysisLog.txt");
if (File.Exists(analysisLog)) {
try {
return File.ReadAllText(analysisLog);
} catch (Exception e) {
return string.Format(culture, "Error reading: {0}", e);
}
}
return null;
}
/// <summary>
/// Called to manually trigger a refresh of <see cref="IsCurrent"/>.
/// After completion, <see cref="IsCurrentChanged"/> will always be
/// raised, regardless of whether the values were changed.
/// </summary>
public virtual void RefreshIsCurrent() {
try {
if (!_isCurrentSemaphore.Wait(0)) {
// Another thread is working on our state, so we will wait for
// them to finish and return, since the value is up to date.
_isCurrentSemaphore.Wait();
_isCurrentSemaphore.Release();
return;
}
} catch (ObjectDisposedException) {
// We've been disposed and the call has come in from
// externally, probably a timer.
return;
}
try {
_isCheckingDatabase = true;
OnIsCurrentChanged();
// Wait for a slot that will allow us to scan the disk. This
// prevents too many threads from updating at once and causing
// I/O saturation.
_sharedIsCurrentSemaphore.Wait();
try {
_generating = PythonTypeDatabase.IsDatabaseRegenerating(DatabasePath);
WatchingLibrary = !_generating;
if (_generating) {
// Skip the rest of the checks, because we know we're
// not current.
} else if (!PythonTypeDatabase.IsDatabaseVersionCurrent(DatabasePath)) {
_isValid = false;
_missingModules = null;
_isCurrentException = null;
} else {
_isValid = true;
HashSet<string> existingDatabase = null;
string[] missingModules = null;
for (int retries = 3; retries > 0; --retries) {
try {
existingDatabase = GetExistingDatabase(DatabasePath);
break;
} catch (UnauthorizedAccessException) {
} catch (IOException) {
}
Thread.Sleep(100);
}
if (existingDatabase == null) {
// This will either succeed or throw again. If it throws
// then the error is reported to the user.
existingDatabase = GetExistingDatabase(DatabasePath);
}
for (int retries = 3; retries > 0; --retries) {
try {
missingModules = GetMissingModules(existingDatabase);
break;
} catch (UnauthorizedAccessException) {
} catch (IOException) {
}
Thread.Sleep(100);
}
if (missingModules == null) {
// This will either succeed or throw again. If it throws
// then the error is reported to the user.
missingModules = GetMissingModules(existingDatabase);
}
if (missingModules.Length > 0) {
var oldModules = _missingModules;
if (oldModules == null ||
oldModules.Length != missingModules.Length ||
!oldModules.SequenceEqual(missingModules)) {
}
_missingModules = missingModules;
} else {
_missingModules = null;
}
}
_isCurrentException = null;
} finally {
_sharedIsCurrentSemaphore.Release();
}
} catch (Exception ex) {
// Report the exception text as the reason.
_isCurrentException = ex.ToString();
_missingModules = null;
} finally {
_isCheckingDatabase = false;
try {
_isCurrentSemaphore.Release();
} catch (ObjectDisposedException) {
// The semaphore is not locked for disposal as it is only
// used to prevent reentrance into this function. As a
// result, it may have been disposed while we were in here.
}
}
OnIsCurrentChanged();
}
private static HashSet<string> GetExistingDatabase(string databasePath) {
return new HashSet<string>(
Directory.EnumerateFiles(databasePath, "*.idb", SearchOption.AllDirectories)
.Select(f => Path.GetFileNameWithoutExtension(f)),
StringComparer.InvariantCultureIgnoreCase
);
}
/// <summary>
/// Returns a sequence of module names that are required for a database.
/// If any of these are missing, the database will be marked as invalid.
/// </summary>
private IEnumerable<string> RequiredBuiltinModules {
get {
if (Configuration.Version.Major == 2) {
yield return "__builtin__";
} else if (Configuration.Version.Major == 3) {
yield return "builtins";
}
}
}
private string[] GetMissingModules(HashSet<string> existingDatabase) {
var searchPaths = PythonTypeDatabase.GetCachedDatabaseSearchPaths(DatabasePath);
if (searchPaths == null) {
// No cached search paths means our database is out of date.
return existingDatabase
.Except(RequiredBuiltinModules)
.OrderBy(name => name, StringComparer.InvariantCultureIgnoreCase)
.ToArray();
}
return PythonTypeDatabase.GetDatabaseExpectedModules(_config.Version, searchPaths)
.SelectMany()
.Select(mp => mp.ModuleName)
.Concat(RequiredBuiltinModules)
.Where(m => !existingDatabase.Contains(m))
.OrderBy(name => name, StringComparer.InvariantCultureIgnoreCase)
.ToArray();
}
private void RefreshIsCurrentTimer_Elapsed(object state) {
if (_disposed) {
return;
}
if (Directory.Exists(Configuration.LibraryPath)) {
RefreshIsCurrent();
} else {
if (_libWatcher != null) {
lock (_libWatcherLock) {
if (_libWatcher != null) {
_libWatcher.Dispose();
_libWatcher = null;
}
}
}
OnIsCurrentChanged();
}
}
private void OnRenamed(object sender, RenamedEventArgs e) {
_refreshIsCurrentTrigger.Change(1000, Timeout.Infinite);
}
private void OnChanged(object sender, FileSystemEventArgs e) {
_refreshIsCurrentTrigger.Change(1000, Timeout.Infinite);
}
public event EventHandler IsCurrentChanged;
public event EventHandler NewDatabaseAvailable;
protected void OnIsCurrentChanged() {
var evt = IsCurrentChanged;
if (evt != null) {
evt(this, EventArgs.Empty);
}
}
/// <summary>
/// Clears any cached type databases and raises the
/// <see cref="NewDatabaseAvailable"/> event.
/// </summary>
protected void OnNewDatabaseAvailable() {
_typeDb = null;
_typeDbWithoutPackages = null;
var evt = NewDatabaseAvailable;
if (evt != null) {
evt(this, EventArgs.Empty);
}
}
static string GetPackageName(string fullName) {
int firstDot = fullName.IndexOf('.');
return (firstDot > 0) ? fullName.Remove(firstDot) : fullName;
}
public virtual string GetFriendlyIsCurrentReason(IFormatProvider culture) {
var missingModules = _missingModules;
if (_isCurrentException != null) {
return "An error occurred. Click Copy to get full details.";
} else if (_generating) {
return "Currently regenerating";
} else if (_libWatcher == null) {
return "Interpreter has no library";
} else if (!Directory.Exists(DatabasePath)) {
return "Database has never been generated";
} else if (!_isValid) {
return "Database is corrupt or an old version";
} else if (missingModules != null) {
if (missingModules.Length < 100) {
return string.Format(culture,
"The following modules have not been analyzed:{0} {1}",
Environment.NewLine,
string.Join(Environment.NewLine + " ", missingModules)
);
} else {
var packages = new List<string>(
from m in missingModules
group m by GetPackageName(m) into groupedByPackage
where groupedByPackage.Count() > 1
orderby groupedByPackage.Key
select groupedByPackage.Key
);
if (packages.Count > 0 && packages.Count < 100) {
return string.Format(culture,
"{0} modules have not been analyzed.{2}Packages include:{2} {1}",
missingModules.Length,
string.Join(Environment.NewLine + " ", packages),
Environment.NewLine
);
} else {
return string.Format(culture,
"{0} modules have not been analyzed.",
missingModules.Length
);
}
}
}
return "Up to date";
}
public virtual string GetIsCurrentReason(IFormatProvider culture) {
var missingModules = _missingModules;
var reason = "Database at " + DatabasePath;
if (_isCurrentException != null) {
return reason + " raised an exception while refreshing:" + Environment.NewLine + _isCurrentException;
} else if (_generating) {
return reason + " is regenerating";
} else if (_libWatcher == null) {
return "Interpreter has no library";
} else if (!Directory.Exists(DatabasePath)) {
return reason + " does not exist";
} else if (!_isValid) {
return reason + " is corrupt or an old version";
} else if (missingModules != null) {
return reason + " does not contain the following modules:" + Environment.NewLine +
string.Join(Environment.NewLine, missingModules);
}
return reason + " is up to date";
}
public IEnumerable<string> GetUpToDateModules() {
if (!Directory.Exists(DatabasePath)) {
return Enumerable.Empty<string>();
}
// Currently we assume that if the file exists, it's up to date.
// PyLibAnalyzer will perform timestamp checks if the user manually
// refreshes.
return Directory.EnumerateFiles(DatabasePath, "*.idb", SearchOption.AllDirectories)
.Select(f => Path.GetFileNameWithoutExtension(f));
}
#region IDisposable Members
protected virtual void Dispose(bool disposing) {
if (!_disposed) {
_disposed = true;
if (_verWatcher != null || _verDirWatcher != null) {
lock (_verWatcherLock) {
if (_verWatcher != null) {
_verWatcher.EnableRaisingEvents = false;
_verWatcher.Dispose();
_verWatcher = null;
}
if (_verDirWatcher != null) {
_verDirWatcher.EnableRaisingEvents = false;
_verDirWatcher.Dispose();
_verDirWatcher = null;
}
}
}
if (_libWatcher != null) {
lock (_libWatcherLock) {
if (_libWatcher != null) {
_libWatcher.EnableRaisingEvents = false;
_libWatcher.Dispose();
_libWatcher = null;
}
}
}
if (_refreshIsCurrentTrigger != null) {
_refreshIsCurrentTrigger.Dispose();
}
_isCurrentSemaphore.Dispose();
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region Directory watchers
private FileSystemWatcher CreateLibraryWatcher() {
FileSystemWatcher watcher = null;
try {
watcher = new FileSystemWatcher {
IncludeSubdirectories = true,
Path = _config.LibraryPath,
NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite
};
watcher.Created += OnChanged;
watcher.Deleted += OnChanged;
watcher.Changed += OnChanged;
watcher.Renamed += OnRenamed;
watcher.EnableRaisingEvents = true;
} catch (IOException) {
// Raced with directory deletion. We normally handle the
// library being deleted by disposing the watcher, but this
// occurs in response to an event from the watcher. Because
// we never got to start watching, we will just dispose
// immediately.
if (watcher != null) {
watcher.Dispose();
}
} catch (ArgumentException ex) {
if (watcher != null) {
watcher.Dispose();
}
Debug.WriteLine("Error starting FileSystemWatcher:\r\n{0}", ex);
}
return watcher;
}
private FileSystemWatcher CreateDatabaseDirectoryWatcher() {
FileSystemWatcher watcher = null;
lock (_verWatcherLock) {
var dirName = CommonUtils.GetFileOrDirectoryName(DatabasePath);
var dir = Path.GetDirectoryName(DatabasePath);
while (CommonUtils.IsValidPath(dir) && !Directory.Exists(dir)) {
dirName = CommonUtils.GetFileOrDirectoryName(dir);
dir = Path.GetDirectoryName(dir);
}
if (Directory.Exists(dir)) {
try {
watcher = new FileSystemWatcher {
IncludeSubdirectories = false,
Path = dir,
Filter = dirName,
NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName
};
} catch (ArgumentException ex) {
Debug.WriteLine("Error starting database directory FileSystemWatcher:\r\n{0}", ex);
return null;
}
watcher.Created += OnDatabaseFolderChanged;
watcher.Renamed += OnDatabaseFolderChanged;
watcher.Deleted += OnDatabaseFolderChanged;
try {
watcher.EnableRaisingEvents = true;
return watcher;
} catch (IOException) {
// Raced with directory deletion
watcher.Dispose();
watcher = null;
}
}
return null;
}
}
private FileSystemWatcher CreateDatabaseVerWatcher() {
FileSystemWatcher watcher = null;
lock (_verWatcherLock) {
var dir = DatabasePath;
if (Directory.Exists(dir)) {
try {
watcher = new FileSystemWatcher {
IncludeSubdirectories = false,
Path = dir,
Filter = "database.*",
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite
};
} catch (ArgumentException ex) {
Debug.WriteLine("Error starting database.ver FileSystemWatcher:\r\n{0}", ex);
return null;
}
watcher.Deleted += OnDatabaseVerChanged;
watcher.Created += OnDatabaseVerChanged;
watcher.Changed += OnDatabaseVerChanged;
try {
watcher.EnableRaisingEvents = true;
return watcher;
} catch (IOException) {
// Raced with directory deletion. Fall through and find
// a parent directory that exists.
watcher.Dispose();
watcher = null;
}
}
return null;
}
}
private void OnDatabaseFolderChanged(object sender, FileSystemEventArgs e) {
lock (_verWatcherLock) {
if (_verWatcher != null) {
_verWatcher.EnableRaisingEvents = false;
_verWatcher.Dispose();
}
if (_verDirWatcher != null) {
_verDirWatcher.EnableRaisingEvents = false;
_verDirWatcher.Dispose();
}
_verDirWatcher = CreateDatabaseDirectoryWatcher();
_verWatcher = CreateDatabaseVerWatcher();
RefreshIsCurrent();
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
public class SelectTest
{
private readonly ITestOutputHelper _log;
public SelectTest(ITestOutputHelper output)
{
_log = output;
}
private const int SmallTimeoutMicroseconds = 10 * 1000;
private const int FailTimeoutMicroseconds = 30 * 1000 * 1000;
[PlatformSpecific(~PlatformID.OSX)] // typical OSX install has very low max open file descriptors value
[Theory]
[InlineData(90, 0)]
[InlineData(0, 90)]
[InlineData(45, 45)]
public void Select_ReadWrite_AllReady_ManySockets(int reads, int writes)
{
Select_ReadWrite_AllReady(reads, writes);
}
[Theory]
[InlineData(1, 0)]
[InlineData(0, 1)]
[InlineData(2, 2)]
public void Select_ReadWrite_AllReady(int reads, int writes)
{
var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToArray();
var writePairs = Enumerable.Range(0, writes).Select(_ => CreateConnectedSockets()).ToArray();
try
{
foreach (var pair in readPairs)
{
pair.Value.Send(new byte[1] { 42 });
}
var readList = new List<Socket>(readPairs.Select(p => p.Key).ToArray());
var writeList = new List<Socket>(writePairs.Select(p => p.Key).ToArray());
Socket.Select(readList, writeList, null, FailTimeoutMicroseconds);
// Since no buffers are full, all writes should be available.
Assert.Equal(writePairs.Length, writeList.Count);
// We could wake up from Select for writes even if reads are about to become available,
// so there's very little we can assert if writes is non-zero.
if (writes == 0 && reads > 0)
{
Assert.InRange(readList.Count, 1, readPairs.Length);
}
// When we do the select again, the lists shouldn't change at all, as they've already
// been filtered to ones that were ready.
int readListCountBefore = readList.Count;
int writeListCountBefore = writeList.Count;
Socket.Select(readList, writeList, null, FailTimeoutMicroseconds);
Assert.Equal(readListCountBefore, readList.Count);
Assert.Equal(writeListCountBefore, writeList.Count);
}
finally
{
DisposeSockets(readPairs);
DisposeSockets(writePairs);
}
}
[PlatformSpecific(~PlatformID.OSX)] // typical OSX install has very low max open file descriptors value
[Fact]
public void Select_ReadError_NoneReady_ManySockets()
{
Select_ReadError_NoneReady(45, 45);
}
[Theory]
[InlineData(1, 0)]
[InlineData(0, 1)]
[InlineData(2, 2)]
public void Select_ReadError_NoneReady(int reads, int errors)
{
var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToArray();
var errorPairs = Enumerable.Range(0, errors).Select(_ => CreateConnectedSockets()).ToArray();
try
{
var readList = new List<Socket>(readPairs.Select(p => p.Key).ToArray());
var errorList = new List<Socket>(errorPairs.Select(p => p.Key).ToArray());
Socket.Select(readList, null, errorList, SmallTimeoutMicroseconds);
Assert.Empty(readList);
Assert.Empty(errorList);
}
finally
{
DisposeSockets(readPairs);
DisposeSockets(errorPairs);
}
}
[PlatformSpecific(~PlatformID.OSX)] // typical OSX install has very low max open file descriptors value
public void Select_Read_OneReadyAtATime_ManySockets(int reads)
{
Select_Read_OneReadyAtATime(90); // value larger than the internal value in SocketPal.Unix that swaps between stack and heap allocation
}
[Theory]
[InlineData(2)]
public void Select_Read_OneReadyAtATime(int reads)
{
var rand = new Random(42);
var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToList();
try
{
while (readPairs.Count > 0)
{
int next = rand.Next(0, readPairs.Count);
readPairs[next].Value.Send(new byte[1] { 42 });
var readList = new List<Socket>(readPairs.Select(p => p.Key).ToArray());
Socket.Select(readList, null, null, FailTimeoutMicroseconds);
Assert.Equal(1, readList.Count);
Assert.Same(readPairs[next].Key, readList[0]);
readPairs.RemoveAt(next);
}
}
finally
{
DisposeSockets(readPairs);
}
}
[PlatformSpecific(~PlatformID.OSX)] // typical OSX install has very low max open file descriptors value
[Fact]
public void Select_Error_OneReadyAtATime()
{
const int Errors = 90; // value larger than the internal value in SocketPal.Unix that swaps between stack and heap allocation
var rand = new Random(42);
var errorPairs = Enumerable.Range(0, Errors).Select(_ => CreateConnectedSockets()).ToList();
try
{
while (errorPairs.Count > 0)
{
int next = rand.Next(0, errorPairs.Count);
errorPairs[next].Value.Send(new byte[1] { 42 }, SocketFlags.OutOfBand);
var errorList = new List<Socket>(errorPairs.Select(p => p.Key).ToArray());
Socket.Select(null, null, errorList, FailTimeoutMicroseconds);
Assert.Equal(1, errorList.Count);
Assert.Same(errorPairs[next].Key, errorList[0]);
errorPairs.RemoveAt(next);
}
}
finally
{
DisposeSockets(errorPairs);
}
}
[Theory]
[InlineData(SelectMode.SelectRead)]
[InlineData(SelectMode.SelectError)]
public void Poll_NotReady(SelectMode mode)
{
KeyValuePair<Socket, Socket> pair = CreateConnectedSockets();
try
{
Assert.False(pair.Key.Poll(SmallTimeoutMicroseconds, mode));
}
finally
{
pair.Key.Dispose();
pair.Value.Dispose();
}
}
[Theory]
[InlineData(-1)]
[InlineData(FailTimeoutMicroseconds)]
public void Poll_ReadReady_LongTimeouts(int microsecondsTimeout)
{
KeyValuePair<Socket, Socket> pair = CreateConnectedSockets();
try
{
Task.Delay(1).ContinueWith(_ => pair.Value.Send(new byte[1] { 42 }),
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
Assert.True(pair.Key.Poll(microsecondsTimeout, SelectMode.SelectRead));
}
finally
{
pair.Key.Dispose();
pair.Value.Dispose();
}
}
private static KeyValuePair<Socket, Socket> CreateConnectedSockets()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.LingerState = new LingerOption(true, 0);
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.LingerState = new LingerOption(true, 0);
Task<Socket> acceptTask = listener.AcceptAsync();
client.Connect(listener.LocalEndPoint);
Socket server = acceptTask.GetAwaiter().GetResult();
return new KeyValuePair<Socket, Socket>(client, server);
}
}
private static void DisposeSockets(IEnumerable<KeyValuePair<Socket, Socket>> sockets)
{
foreach (var pair in sockets)
{
pair.Key.Dispose();
pair.Value.Dispose();
}
}
}
}
| |
using System;
using Content.Shared.Audio;
using Content.Shared.DragDrop;
using Content.Shared.Interaction;
using Content.Shared.Interaction.Events;
using Content.Shared.Inventory.Events;
using Content.Shared.Item;
using Content.Shared.Movement;
using Content.Shared.Movement.Components;
using Content.Shared.Movement.EntitySystems;
using Content.Shared.Speech;
using Content.Shared.Standing;
using Content.Shared.StatusEffect;
using Content.Shared.Throwing;
using JetBrains.Annotations;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.GameStates;
using Robust.Shared.IoC;
using Robust.Shared.Player;
using Robust.Shared.Timing;
namespace Content.Shared.Stunnable
{
[UsedImplicitly]
public abstract class SharedStunSystem : EntitySystem
{
[Dependency] private readonly StandingStateSystem _standingStateSystem = default!;
[Dependency] private readonly StatusEffectsSystem _statusEffectSystem = default!;
[Dependency] private readonly MovementSpeedModifierSystem _movementSpeedModifierSystem = default!;
public override void Initialize()
{
SubscribeLocalEvent<KnockedDownComponent, ComponentInit>(OnKnockInit);
SubscribeLocalEvent<KnockedDownComponent, ComponentRemove>(OnKnockRemove);
SubscribeLocalEvent<SlowedDownComponent, ComponentInit>(OnSlowInit);
SubscribeLocalEvent<SlowedDownComponent, ComponentRemove>(OnSlowRemove);
SubscribeLocalEvent<SlowedDownComponent, ComponentGetState>(OnSlowGetState);
SubscribeLocalEvent<SlowedDownComponent, ComponentHandleState>(OnSlowHandleState);
SubscribeLocalEvent<KnockedDownComponent, ComponentGetState>(OnKnockGetState);
SubscribeLocalEvent<KnockedDownComponent, ComponentHandleState>(OnKnockHandleState);
// helping people up if they're knocked down
SubscribeLocalEvent<KnockedDownComponent, InteractHandEvent>(OnInteractHand);
SubscribeLocalEvent<SlowedDownComponent, RefreshMovementSpeedModifiersEvent>(OnRefreshMovespeed);
// Attempt event subscriptions.
SubscribeLocalEvent<StunnedComponent, MovementAttemptEvent>(OnMoveAttempt);
SubscribeLocalEvent<StunnedComponent, InteractionAttemptEvent>(OnInteractAttempt);
SubscribeLocalEvent<StunnedComponent, UseAttemptEvent>(OnUseAttempt);
SubscribeLocalEvent<StunnedComponent, ThrowAttemptEvent>(OnThrowAttempt);
SubscribeLocalEvent<StunnedComponent, DropAttemptEvent>(OnDropAttempt);
SubscribeLocalEvent<StunnedComponent, PickupAttemptEvent>(OnPickupAttempt);
SubscribeLocalEvent<StunnedComponent, IsEquippingAttemptEvent>(OnEquipAttempt);
SubscribeLocalEvent<StunnedComponent, IsUnequippingAttemptEvent>(OnUnequipAttempt);
}
private void OnSlowGetState(EntityUid uid, SlowedDownComponent component, ref ComponentGetState args)
{
args.State = new SlowedDownComponentState(component.SprintSpeedModifier, component.WalkSpeedModifier);
}
private void OnSlowHandleState(EntityUid uid, SlowedDownComponent component, ref ComponentHandleState args)
{
if (args.Current is SlowedDownComponentState state)
{
component.SprintSpeedModifier = state.SprintSpeedModifier;
component.WalkSpeedModifier = state.WalkSpeedModifier;
}
}
private void OnKnockGetState(EntityUid uid, KnockedDownComponent component, ref ComponentGetState args)
{
args.State = new KnockedDownComponentState(component.HelpInterval, component.HelpTimer);
}
private void OnKnockHandleState(EntityUid uid, KnockedDownComponent component, ref ComponentHandleState args)
{
if (args.Current is KnockedDownComponentState state)
{
component.HelpInterval = state.HelpInterval;
component.HelpTimer = state.HelpTimer;
}
}
private void OnKnockInit(EntityUid uid, KnockedDownComponent component, ComponentInit args)
{
_standingStateSystem.Down(uid);
}
private void OnKnockRemove(EntityUid uid, KnockedDownComponent component, ComponentRemove args)
{
_standingStateSystem.Stand(uid);
}
private void OnSlowInit(EntityUid uid, SlowedDownComponent component, ComponentInit args)
{
_movementSpeedModifierSystem.RefreshMovementSpeedModifiers(uid);
}
private void OnSlowRemove(EntityUid uid, SlowedDownComponent component, ComponentRemove args)
{
_movementSpeedModifierSystem.RefreshMovementSpeedModifiers(uid);
}
private void OnRefreshMovespeed(EntityUid uid, SlowedDownComponent component, RefreshMovementSpeedModifiersEvent args)
{
args.ModifySpeed(component.WalkSpeedModifier, component.SprintSpeedModifier);
}
// TODO STUN: Make events for different things. (Getting modifiers, attempt events, informative events...)
/// <summary>
/// Stuns the entity, disallowing it from doing many interactions temporarily.
/// </summary>
public bool TryStun(EntityUid uid, TimeSpan time, bool refresh,
StatusEffectsComponent? status = null)
{
if (time <= TimeSpan.Zero)
return false;
if (!Resolve(uid, ref status, false))
return false;
return _statusEffectSystem.TryAddStatusEffect<StunnedComponent>(uid, "Stun", time, refresh);
}
/// <summary>
/// Knocks down the entity, making it fall to the ground.
/// </summary>
public bool TryKnockdown(EntityUid uid, TimeSpan time, bool refresh,
StatusEffectsComponent? status = null)
{
if (time <= TimeSpan.Zero)
return false;
if (!Resolve(uid, ref status, false))
return false;
return _statusEffectSystem.TryAddStatusEffect<KnockedDownComponent>(uid, "KnockedDown", time, refresh);
}
/// <summary>
/// Applies knockdown and stun to the entity temporarily.
/// </summary>
public bool TryParalyze(EntityUid uid, TimeSpan time, bool refresh,
StatusEffectsComponent? status = null)
{
if (!Resolve(uid, ref status, false))
return false;
return TryKnockdown(uid, time, refresh, status) && TryStun(uid, time, refresh, status);
}
/// <summary>
/// Slows down the mob's walking/running speed temporarily
/// </summary>
public bool TrySlowdown(EntityUid uid, TimeSpan time, bool refresh,
float walkSpeedMultiplier = 1f, float runSpeedMultiplier = 1f,
StatusEffectsComponent? status = null)
{
if (!Resolve(uid, ref status, false))
return false;
if (time <= TimeSpan.Zero)
return false;
if (_statusEffectSystem.TryAddStatusEffect<SlowedDownComponent>(uid, "SlowedDown", time, refresh, status))
{
var slowed = EntityManager.GetComponent<SlowedDownComponent>(uid);
// Doesn't make much sense to have the "TrySlowdown" method speed up entities now does it?
walkSpeedMultiplier = Math.Clamp(walkSpeedMultiplier, 0f, 1f);
runSpeedMultiplier = Math.Clamp(runSpeedMultiplier, 0f, 1f);
slowed.WalkSpeedModifier *= walkSpeedMultiplier;
slowed.SprintSpeedModifier *= runSpeedMultiplier;
_movementSpeedModifierSystem.RefreshMovementSpeedModifiers(uid);
return true;
}
return false;
}
private void OnInteractHand(EntityUid uid, KnockedDownComponent knocked, InteractHandEvent args)
{
if (args.Handled || knocked.HelpTimer > 0f)
return;
// Set it to half the help interval so helping is actually useful...
knocked.HelpTimer = knocked.HelpInterval/2f;
_statusEffectSystem.TryRemoveTime(uid, "KnockedDown", TimeSpan.FromSeconds(knocked.HelpInterval));
SoundSystem.Play(Filter.Pvs(uid), knocked.StunAttemptSound.GetSound(), uid, AudioHelpers.WithVariation(0.05f));
knocked.Dirty();
args.Handled = true;
}
#region Attempt Event Handling
private void OnMoveAttempt(EntityUid uid, StunnedComponent stunned, MovementAttemptEvent args)
{
args.Cancel();
}
private void OnInteractAttempt(EntityUid uid, StunnedComponent stunned, InteractionAttemptEvent args)
{
args.Cancel();
}
private void OnUseAttempt(EntityUid uid, StunnedComponent stunned, UseAttemptEvent args)
{
args.Cancel();
}
private void OnThrowAttempt(EntityUid uid, StunnedComponent stunned, ThrowAttemptEvent args)
{
args.Cancel();
}
private void OnDropAttempt(EntityUid uid, StunnedComponent stunned, DropAttemptEvent args)
{
args.Cancel();
}
private void OnPickupAttempt(EntityUid uid, StunnedComponent stunned, PickupAttemptEvent args)
{
args.Cancel();
}
private void OnEquipAttempt(EntityUid uid, StunnedComponent stunned, IsEquippingAttemptEvent args)
{
// is this a self-equip, or are they being stripped?
if (args.Equipee == uid)
args.Cancel();
}
private void OnUnequipAttempt(EntityUid uid, StunnedComponent stunned, IsUnequippingAttemptEvent args)
{
// is this a self-equip, or are they being stripped?
if (args.Unequipee == uid)
args.Cancel();
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace System.IO
{
public sealed partial class DriveInfo
{
private string _fileSystemType;
private string _fileSystemName;
private DriveInfo(string mountPath, string fileSystemType, string fileSystemName) : this(mountPath)
{
Debug.Assert(fileSystemType != null);
Debug.Assert(fileSystemName != null);
_fileSystemType = fileSystemType;
_fileSystemName = fileSystemName;
}
private static string NormalizeDriveName(string driveName)
{
if (driveName.Contains("\0"))
{
throw new ArgumentException(SR.Format(SR.Arg_InvalidDriveChars, driveName), "driveName");
}
if (driveName.Length == 0)
{
throw new ArgumentException(SR.Arg_MustBeNonEmptyDriveName);
}
return driveName;
}
public DriveType DriveType
{
[SecuritySafeCritical]
get { return GetDriveType(DriveFormat); }
}
public string DriveFormat
{
[SecuritySafeCritical]
get
{
if (_fileSystemType == null)
{
// If the DriveInfo was created with the public ctor, we need to
// enumerate all of the known drives to find its associated information.
LazyPopulateFileSystemTypeAndName();
}
return _fileSystemType;
}
}
public long AvailableFreeSpace
{
[SecuritySafeCritical]
get
{
Interop.libc.structStatvfs stats = GetStats();
return (long)((ulong)stats.f_bsize * (ulong)stats.f_bavail);
}
}
public long TotalFreeSpace
{
[SecuritySafeCritical]
get
{
Interop.libc.structStatvfs stats = GetStats();
return (long)((ulong)stats.f_bsize * (ulong)stats.f_bfree);
}
}
public long TotalSize
{
[SecuritySafeCritical]
get
{
Interop.libc.structStatvfs stats = GetStats();
return (long)((ulong)stats.f_bsize * (ulong)stats.f_blocks);
}
}
public String VolumeLabel
{
[SecuritySafeCritical]
get { return _fileSystemName; }
[SecuritySafeCritical]
set { throw new PlatformNotSupportedException(); }
}
/// <summary>Loads file system stats for the mounted path.</summary>
/// <returns>The loaded stats.</returns>
private Interop.libc.structStatvfs GetStats()
{
Interop.libc.structStatvfs stats;
if (Interop.libc.statvfs(Name, out stats) != 0)
{
int errno = Marshal.GetLastWin32Error();
if (errno == Interop.Errors.ENOENT)
{
throw new DriveNotFoundException(SR.Format(SR.IO_DriveNotFound_Drive, Name)); // match Win32 exception
}
throw Interop.GetExceptionForIoErrno(errno, Name, isDirectory: true);
}
return stats;
}
/// <summary>Lazily populates _fileSystemType and _fileSystemName if they weren't already filled in.</summary>
private void LazyPopulateFileSystemTypeAndName()
{
Debug.Assert(_fileSystemName == null && _fileSystemType == null);
foreach (DriveInfo drive in GetDrives()) // fill in the info by enumerating drives and copying over the associated data
{
if (drive.Name == this.Name)
{
_fileSystemType = drive._fileSystemType;
_fileSystemName = drive._fileSystemName;
return;
}
}
_fileSystemType = string.Empty;
_fileSystemName = string.Empty;
}
public static unsafe DriveInfo[] GetDrives()
{
const int StringBufferLength = 8192; // there's no defined max size nor an indication through the API when you supply too small a buffer; choosing something that seems reasonable
byte* strBuf = stackalloc byte[StringBufferLength];
// Parse the mounts file
const string MountsPath = "/proc/mounts"; // Linux mounts file
IntPtr fp;
Interop.CheckIoPtr(fp = Interop.libc.setmntent(MountsPath, Interop.libc.MNTOPT_RO), path: MountsPath);
try
{
// Walk the entries in the mounts file, creating a DriveInfo for each that shouldn't be ignored.
List<DriveInfo> drives = new List<DriveInfo>();
Interop.libc.mntent mntent = default(Interop.libc.mntent);
while (Interop.libc.getmntent_r(fp, ref mntent, strBuf, StringBufferLength) != IntPtr.Zero)
{
string type = DecodeString(mntent.mnt_type);
if (!string.IsNullOrWhiteSpace(type) && type != Interop.libc.MNTTYPE_IGNORE)
{
string path = DecodeString(mntent.mnt_dir);
string name = DecodeString(mntent.mnt_fsname);
drives.Add(new DriveInfo(path, type, name));
}
}
return drives.ToArray();
}
finally
{
int result = Interop.libc.endmntent(fp);
Debug.Assert(result == 1); // documented to always return 1
}
}
/// <summary>Gets the string starting at the specifying pointer and going until null termination.</summary>
/// <param name="str">Pointer to the first byte in the string.</param>
/// <returns>The decoded string.</returns>
private static unsafe string DecodeString(byte* str)
{
Debug.Assert(str != null);
if (str == null)
{
return string.Empty;
}
int length = GetNullTerminatedStringLength(str);
return Encoding.UTF8.GetString(str, length); // TODO: determine correct encoding; UTF8 is good enough for now
}
/// <summary>Gets the length of the null-terminated string by searching for its null teminration.</summary>
/// <param name="str">The string.</param>
/// <returns>The string's length, not including the null termination.</returns>
private static unsafe int GetNullTerminatedStringLength(byte* str)
{
int length = 0;
while (*str != '\0')
{
length++;
str++;
}
return length;
}
/// <summary>Categorizes a file system name into a drive type.</summary>
/// <param name="fileSystemName">The name to categorize.</param>
/// <returns>The recognized drive type.</returns>
private static DriveType GetDriveType(string fileSystemName)
{
// This list is based primarily on "man fs", "man mount", "mntent.h", "/proc/filesystems",
// and "wiki.debian.org/FileSystem". It can be extended over time as we
// find additional file systems that should be recognized as a particular drive type.
switch (fileSystemName)
{
case "iso":
case "isofs":
case "iso9660":
case "fuseiso":
case "fuseiso9660":
case "umview-mod-umfuseiso9660":
return DriveType.CDRom;
case "adfs":
case "affs":
case "befs":
case "bfs":
case "btrfs":
case "ecryptfs":
case "efs":
case "ext":
case "ext2":
case "ext3":
case "ext4":
case "ext4dev":
case "fat":
case "fuseblk":
case "fuseext2":
case "fusefat":
case "hfs":
case "hfsplus":
case "hpfs":
case "jbd":
case "jbd2":
case "jfs":
case "jffs":
case "jffs2":
case "minix":
case "msdos":
case "ocfs2":
case "omfs":
case "ntfs":
case "qnx4":
case "reiserfs":
case "squashfs":
case "swap":
case "sysv":
case "ubifs":
case "udf":
case "ufs":
case "umsdos":
case "umview-mod-umfuseext2":
case "xenix":
case "xfs":
case "xiafs":
case "xmount":
case "zfs-fuse":
return DriveType.Fixed;
case "9p":
case "autofs":
case "autofs4":
case "beaglefs":
case "cifs":
case "coda":
case "coherent":
case "curlftpfs":
case "davfs2":
case "dlm":
case "flickrfs":
case "fusedav":
case "fusesmb":
case "gfs2":
case "glusterfs-client":
case "gmailfs":
case "kafs":
case "ltspfs":
case "ncpfs":
case "nfs":
case "nfs4":
case "obexfs":
case "s3ql":
case "smb":
case "smbfs":
case "sshfs":
case "sysfs":
case "wikipediafs":
return DriveType.Network;
case "anon_inodefs":
case "aptfs":
case "avfs":
case "bdev":
case "binfmt_misc":
case "cgroup":
case "configfs":
case "cramfs":
case "cryptkeeper":
case "cpuset":
case "debugfs":
case "devpts":
case "devtmpfs":
case "encfs":
case "fuse":
case "fuse.gvfsd-fuse":
case "fusectl":
case "hugetlbfs":
case "libpam-encfs":
case "ibpam-mount":
case "mtpfs":
case "mythtvfs":
case "mqueue":
case "pipefs":
case "plptools":
case "proc":
case "pstore":
case "pytagsfs":
case "ramfs":
case "rofs":
case "romfs":
case "rootfs":
case "securityfs":
case "sockfs":
case "tmpfs":
return DriveType.Ram;
case "gphotofs":
case "usbfs":
case "vfat":
return DriveType.Removable;
case "aufs": // marking all unions as unknown
case "funionfs":
case "unionfs-fuse":
case "mhddfs":
default:
return DriveType.Unknown;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using EPiServer;
using EPiServer.Configuration;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Filters;
using EPiServer.Logging;
using EPiServer.ServiceLocation;
using EPiServer.Web;
namespace AlloyDemoKit.Business.ContentProviders
{
/// <summary>
/// Used to clone a part of the page tree
/// </summary>
/// <remarks>The current implementation only supports cloning of <see cref="PageData"/> content</remarks>
/// <code>
/// // Example of programmatically registering a cloned content provider
///
/// var rootPageOfContentToClone = new PageReference(10);
///
/// var pageWhereClonedContentShouldAppear = new PageReference(20);
///
/// var provider = new ClonedContentProvider(rootPageOfContentToClone, pageWhereClonedContentShouldAppear);
///
/// var providerManager = ServiceLocator.Current.GetInstance<IContentProviderManager>();
///
/// providerManager.ProviderMap.AddProvider(provider);
/// </code>
public class ClonedContentProvider : ContentProvider, IPageCriteriaQueryService
{
private static readonly ILogger Logger = LogManager.GetLogger();
private readonly NameValueCollection _parameters = new NameValueCollection(1);
public ClonedContentProvider(PageReference cloneRoot, PageReference entryRoot) : this(cloneRoot, entryRoot, null) { }
public ClonedContentProvider(PageReference cloneRoot, PageReference entryRoot, CategoryList categoryFilter)
{
if (cloneRoot.CompareToIgnoreWorkID(entryRoot))
{
throw new NotSupportedException("Entry root and clone root cannot be set to the same content reference");
}
if (ServiceLocator.Current.GetInstance<IContentLoader>().GetChildren<IContent>(entryRoot).Any())
{
throw new NotSupportedException("Unable to create ClonedContentProvider, the EntryRoot property must point to leaf content (without children)");
}
CloneRoot = cloneRoot;
EntryRoot = entryRoot;
Category = categoryFilter;
// Set the entry point parameter
Parameters.Add(ContentProviderElement.EntryPointString, EntryRoot.ID.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// Clones a page to make it appear to come from where the content provider is attached
/// </summary>
private PageData ClonePage(PageData originalPage)
{
if (originalPage == null)
{
throw new ArgumentNullException("originalPage", "No page to clone specified");
}
Logger.Debug("Cloning page {0}...", originalPage.PageLink);
var clone = originalPage.CreateWritableClone();
// If original page was under the clone root, we make it appear to be under the entry root instead
if (originalPage.ParentLink.CompareToIgnoreWorkID(CloneRoot))
{
clone.ParentLink = EntryRoot;
}
// All pages but the entry root should appear to come from this content provider
if (!clone.PageLink.CompareToIgnoreWorkID(EntryRoot))
{
clone.ContentLink.ProviderName = ProviderKey;
}
// Unless the parent is the entry root, it should appear to come from this content provider
if (!clone.ParentLink.CompareToIgnoreWorkID(EntryRoot))
{
var parentLinkClone = clone.ParentLink.CreateWritableClone();
parentLinkClone.ProviderName = ProviderKey;
clone.ParentLink = parentLinkClone;
}
// This is integral to map the cloned page to this content provider
clone.LinkURL = ConstructContentUri(originalPage.PageTypeID, clone.ContentLink, clone.ContentGuid).ToString();
return clone;
}
/// <summary>
/// Filters out content references to content that does not match current category filters, if any
/// </summary>
/// <param name="contentReferences"></param>
/// <returns></returns>
private IList<T> FilterByCategory<T>(IEnumerable<T> contentReferences)
{
if (Category == null || !Category.Any())
{
return contentReferences.ToList();
}
// Filter by category if a category filter has been set
var filteredChildren = new List<T>();
foreach (var contentReference in contentReferences)
{
ICategorizable content = null;
if (contentReference is ContentReference)
{
content = (contentReference as ContentReference).Get<IContent>() as ICategorizable;
} else if (typeof(T) == typeof(GetChildrenReferenceResult))
{
content = (contentReference as GetChildrenReferenceResult).ContentLink.Get<IContent>() as ICategorizable;
}
if (content != null)
{
var atLeastOneMatchingCategory = content.Category.Any(c => Category.Contains(c));
if (atLeastOneMatchingCategory)
{
filteredChildren.Add(contentReference);
}
}
else // Non-categorizable content will also be included
{
filteredChildren.Add(contentReference);
}
}
return filteredChildren;
}
protected override IContent LoadContent(ContentReference contentLink, ILanguageSelector languageSelector)
{
if (ContentReference.IsNullOrEmpty(contentLink) || contentLink.ID == 0)
{
throw new ArgumentNullException("contentLink");
}
if (contentLink.WorkID > 0)
{
return ContentStore.LoadVersion(contentLink, -1);
}
var languageBranchRepository = ServiceLocator.Current.GetInstance<ILanguageBranchRepository>();
LanguageBranch langBr = null;
if (languageSelector.Language != null)
{
langBr = languageBranchRepository.Load(languageSelector.Language);
}
if (contentLink.GetPublishedOrLatest)
{
return ContentStore.LoadVersion(contentLink, langBr != null ? langBr.ID : -1);
}
// Get published version of Content
var originalContent = ContentStore.Load(contentLink, langBr != null ? langBr.ID : -1);
var page = originalContent as PageData;
if (page == null)
{
throw new NotSupportedException("Only cloning of pages is supported");
}
return ClonePage(page);
}
protected override ContentResolveResult ResolveContent(ContentReference contentLink)
{
var contentData = ContentCoreDataLoader.Service.Load(contentLink.ID);
// All pages but the entry root should appear to come from this content provider
if (!contentLink.CompareToIgnoreWorkID(EntryRoot))
{
contentData.ContentReference.ProviderName = ProviderKey;
}
var result = CreateContentResolveResult(contentData);
if (!result.ContentLink.CompareToIgnoreWorkID(EntryRoot))
{
result.ContentLink.ProviderName = ProviderKey;
}
return result;
}
protected override Uri ConstructContentUri(int contentTypeId, ContentReference contentLink, Guid contentGuid)
{
if (!contentLink.CompareToIgnoreWorkID(EntryRoot))
{
contentLink.ProviderName = ProviderKey;
}
return base.ConstructContentUri(contentTypeId, contentLink, contentGuid);
}
protected override IList<GetChildrenReferenceResult> LoadChildrenReferencesAndTypes(ContentReference contentLink, string languageID, out bool languageSpecific)
{
// If retrieving children for the entry point, we retrieve pages from the clone root
contentLink = contentLink.CompareToIgnoreWorkID(EntryRoot) ? CloneRoot : contentLink;
FilterSortOrder sortOrder;
var children = ContentStore.LoadChildrenReferencesAndTypes(contentLink.ID, languageID, out sortOrder);
languageSpecific = sortOrder == FilterSortOrder.Alphabetical;
foreach (var contentReference in children.Where(contentReference => !contentReference.ContentLink.CompareToIgnoreWorkID(EntryRoot)))
{
contentReference.ContentLink.ProviderName = ProviderKey;
}
return FilterByCategory <GetChildrenReferenceResult>(children);
}
protected override IEnumerable<IContent> LoadContents(IList<ContentReference> contentReferences, ILanguageSelector selector)
{
return contentReferences
.Select(contentReference => ClonePage(ContentLoader.Get<PageData>(contentReference.ToReferenceWithoutVersion())))
.Cast<IContent>()
.ToList();
}
protected override void SetCacheSettings(IContent content, CacheSettings cacheSettings)
{
// Make the cache of this content provider depend on the original content
cacheSettings.CacheKeys.Add(DataFactoryCache.PageCommonCacheKey(new ContentReference(content.ContentLink.ID)));
}
protected override void SetCacheSettings(ContentReference contentReference, IEnumerable<GetChildrenReferenceResult> children, CacheSettings cacheSettings)
{
// Make the cache of this content provider depend on the original content
cacheSettings.CacheKeys.Add(DataFactoryCache.PageCommonCacheKey(new ContentReference(contentReference.ID)));
foreach (var child in children)
{
cacheSettings.CacheKeys.Add(DataFactoryCache.PageCommonCacheKey(new ContentReference(child.ContentLink.ID)));
}
}
public override IList<ContentReference> GetDescendentReferences(ContentReference contentLink)
{
// If retrieving children for the entry point, we retrieve pages from the clone root
contentLink = contentLink.CompareToIgnoreWorkID(EntryRoot) ? CloneRoot : contentLink;
var descendents = ContentStore.ListAll(contentLink);
foreach (var contentReference in descendents.Where(contentReference => !contentReference.CompareToIgnoreWorkID(EntryRoot)))
{
contentReference.ProviderName = ProviderKey;
}
return FilterByCategory<ContentReference>(descendents);
}
public PageDataCollection FindAllPagesWithCriteria(PageReference pageLink, PropertyCriteriaCollection criterias, string languageBranch, ILanguageSelector selector)
{
// Any search beneath the entry root should in fact be performed under the clone root as that's where the original content resides
if (pageLink.CompareToIgnoreWorkID(EntryRoot))
{
pageLink = CloneRoot;
}
else if (!string.IsNullOrWhiteSpace(pageLink.ProviderName)) // Any search beneath a cloned page should in fact be performed under the original page, so we use a page link without any provider information
{
pageLink = new PageReference(pageLink.ID);
}
var pages = PageQueryService.FindAllPagesWithCriteria(pageLink, criterias, languageBranch, selector);
// Return cloned search result set
return new PageDataCollection(pages.Select(ClonePage));
}
public PageDataCollection FindPagesWithCriteria(PageReference pageLink, PropertyCriteriaCollection criterias, string languageBranch, ILanguageSelector selector)
{
// Any search beneath the entry root should in fact be performed under the clone root as that's where the original content resides
if (pageLink.CompareToIgnoreWorkID(EntryRoot))
{
pageLink = CloneRoot;
}
else if (!string.IsNullOrWhiteSpace(pageLink.ProviderName)) // Any search beneath a cloned page should in fact be performed under the original page, so we use a page link without any provider information
{
pageLink = new PageReference(pageLink.ID);
}
var pages = PageQueryService.FindPagesWithCriteria(pageLink, criterias, languageBranch, selector);
// Return cloned search result set
return new PageDataCollection(pages.Select(ClonePage));
}
/// <summary>
/// Gets the content store used to get original content
/// </summary>
protected virtual ContentStore ContentStore
{
get { return ServiceLocator.Current.GetInstance<ContentStore>(); }
}
/// <summary>
/// Gets the content loader used to get content
/// </summary>
protected virtual IContentLoader ContentLoader
{
get { return ServiceLocator.Current.GetInstance<IContentLoader>(); }
}
/// <summary>
/// Gets the service used to query for pages using criterias
/// </summary>
protected virtual IPageCriteriaQueryService PageQueryService
{
get { return ServiceLocator.Current.GetInstance<IPageCriteriaQueryService>(); }
}
/// <summary>
/// Content that should be cloned at the entry point
/// </summary>
public PageReference CloneRoot { get; protected set; }
/// <summary>
/// Gets the page where the cloned content will appear
/// </summary>
public PageReference EntryRoot { get; protected set; }
/// <summary>
/// Gets the category filters used for this content provider
/// </summary>
/// <remarks>If set, pages not matching at least one of these categories will be excluded from this content provider</remarks>
public CategoryList Category { get; protected set; }
/// <summary>
/// Gets a unique key for this content provider instance
/// </summary>
public override string ProviderKey
{
get
{
return string.Format("ClonedContent-{0}-{1}", CloneRoot.ID, EntryRoot.ID);
}
}
/// <summary>
/// Gets capabilities indicating no content editing can be performed through this provider
/// </summary>
public override ContentProviderCapabilities ProviderCapabilities { get { return ContentProviderCapabilities.Search; } }
/// <summary>
/// Gets configuration parameters for this content provider instance
/// </summary>
public override NameValueCollection Parameters { get { return _parameters; } }
}
}
| |
// 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
//
// 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.IO.Abstractions.TestingHelpers;
using System.Threading.Tasks;
using DebuggerGrpcClient;
using GgpGrpc.Models;
using Microsoft.VisualStudio.Debugger.Interop;
using Microsoft.VisualStudio.Threading;
using NSubstitute;
using NUnit.Framework;
using YetiCommon;
using YetiVSI.DebugEngine;
using YetiVSI.DebugEngine.CoreDumps;
using YetiVSI.DebugEngine.Variables;
using YetiVSI.DebuggerOptions;
using YetiVSI.GameLaunch;
using YetiVSI.LLDBShell;
using YetiVSI.Metrics;
using YetiVSI.Shared.Metrics;
using YetiVSI.Test.MediumTestsSupport;
using YetiVSI.Test.TestSupport.DebugEngine;
using YetiVSI.Test.TestSupport.Lldb;
using YetiVSITestsCommon;
using static YetiVSI.DebugEngine.DebugEngine;
namespace YetiVSI.Test.DebugEngine
{
/// <summary>
/// These tests were set up as an integration smoke test that exercises the code and makes few
/// asserts. The intention is exercise the previously untestable code and set up a fixture
/// that can act as a launching pad for future integration tests.
/// </summary>
[TestFixture]
class DebugSessionLauncherTests
{
const string _gameBinary = "myGame.exe";
const int _pid = 22;
const string _gameletIpAddress = "136.112.50.119";
const int _gameletPort = 44722;
const string _fastExpressionDisabledErrorMessage =
"Fast expression evaluation setting was disabled.";
const string _binaryNotFound =
"Cannot proceed with the game launch. The game binary was not found.";
IDebugEngine3 _debugEngine;
GrpcConnection _grpcConnection;
YetiVSI.DebuggerOptions.DebuggerOptions _debuggerOptions;
HashSet<string> _libPaths;
Guid _programId;
IVsiGameLaunch _gameLaunch;
IDebugProcess2 _process;
ICancelable _task;
IDebugEventCallback2 _callback;
GrpcDebuggerFactoryFake _debuggerFactory;
GrpcPlatformFactoryFake _platformFactory;
GrpcListenerFactoryFake _listenerFactory;
MockFileSystem _fileSystem;
ActionRecorder _actionRecorder;
[SetUp]
public void SetUp()
{
var taskContext = new JoinableTaskContext();
PipeCallInvokerFactory callInvokerFactory = new PipeCallInvokerFactory();
PipeCallInvoker callInvoker = callInvokerFactory.Create();
_grpcConnection = new GrpcConnection(taskContext.Factory, callInvoker);
_callback = Substitute.For<IDebugEventCallback2>();
_debuggerOptions =
new YetiVSI.DebuggerOptions.DebuggerOptions { [DebuggerOption.CLIENT_LOGGING] =
DebuggerOptionState.DISABLED };
_libPaths = new HashSet<string> { "some/path", "some/other/path", _gameBinary };
_programId = Guid.Empty;
_task = Substitute.For<ICancelable>();
_process = new DebugProcessStub(enum_AD_PROCESS_ID.AD_PROCESS_ID_SYSTEM, _pid);
_fileSystem = new MockFileSystem();
_debugEngine = Substitute.For<IDebugEngine3>();
_gameLaunch = Substitute.For<IVsiGameLaunch>();
_actionRecorder = new ActionRecorder(Substitute.For<IMetrics>());
}
void CheckLldbListenerStops()
{
// Check that the listener's WaitForEvent method is called at most once.
// (We only check 100ms after the launch.)
Assert.That(_listenerFactory.Instances.Count, Is.EqualTo(1));
SbListenerStub listener = _listenerFactory.Instances[0];
long initialCallCount = listener.GetWaitForEventCallCount();
System.Threading.Thread.Sleep(100);
Assert.That(listener.GetWaitForEventCallCount(),
Is.LessThanOrEqualTo(initialCallCount + 1));
}
[Test]
public async Task TestAttachToCoreAsync([Values] bool stadiaPlatformAvailable)
{
var launcherFactory = CreateLauncherFactory(stadiaPlatformAvailable);
var launcher = launcherFactory.Create(_debugEngine, "some/core/path", "", _gameLaunch);
var attachedProgram = await LaunchAsync(launcher, LaunchOption.AttachToCore,
CreateStadiaLldbDebugger("some/core/path",
true));
Assert.That(attachedProgram, Is.Not.Null);
Assert.IsFalse(
_debuggerFactory.Debugger.CommandInterpreter.HandledCommands.Contains(
SbDebuggerExtensions.FastExpressionEvaluationCommand),
_fastExpressionDisabledErrorMessage);
attachedProgram.Stop();
}
[Test]
public async Task TestAttachToGameAsync([Values] bool stadiaPlatformAvailable)
{
var launcherFactory = CreateLauncherFactory(stadiaPlatformAvailable);
var launcher = launcherFactory.Create(_debugEngine, "", _gameBinary, _gameLaunch);
var attachedProgram = await LaunchAsync(launcher, LaunchOption.AttachToGame,
CreateStadiaLldbDebugger(_gameBinary, false));
Assert.That(attachedProgram, Is.Not.Null);
Assert.IsFalse(
_debuggerFactory.Debugger.CommandInterpreter.HandledCommands.Contains(
SbDebuggerExtensions.FastExpressionEvaluationCommand),
_fastExpressionDisabledErrorMessage);
attachedProgram.Stop();
}
[Test]
public void TestAttachToGameFail_AnotherTracer()
{
string parentPid = "1234";
string tracerPid = "9876";
string tracerName = "gdb";
var launcherFactory = CreateLauncherFactory(false);
var launcher = launcherFactory.Create(_debugEngine, "", _gameBinary, _gameLaunch);
_debuggerFactory.SetTargetAttachError("Operation not permitted");
_platformFactory.AddCommandOutput($"cat /proc/{_pid}/status",
"Name:\tgame\n" + $"Pid:\t{_pid}\n" +
$"PPid:\t{parentPid}\n" +
$"TracerPid:\t{tracerPid}\n" + "FDSize:\t256\n");
_platformFactory.AddCommandOutput($"cat /proc/{tracerPid}/comm", tracerName);
AttachException e =
Assert.ThrowsAsync<AttachException>(
async () => await LaunchAsync(launcher, LaunchOption.AttachToGame,
CreateStadiaLldbDebugger(_gameBinary, false)));
Assert.That(e.Message,
Is.EqualTo(
ErrorStrings
.FailedToAttachToProcessOtherTracer(tracerName, tracerPid)));
CheckLldbListenerStops();
}
[Test]
public void TestAttachToGameFail_SelfTrace()
{
string tracerParentPid = "1234";
var launcherFactory = CreateLauncherFactory(false);
var launcher = launcherFactory.Create(_debugEngine, "", _gameBinary, _gameLaunch);
_debuggerFactory.SetTargetAttachError("Operation not permitted");
_platformFactory.AddCommandOutput($"cat /proc/{_pid}/status",
"Name:\tgame\n" + $"Pid:\t{_pid}\n" +
$"PPid:\t{tracerParentPid}\n" +
$"TracerPid:\t{tracerParentPid}\n" +
"FDSize:\t256\n");
AttachException e =
Assert.ThrowsAsync<AttachException>(
async () => await LaunchAsync(launcher, LaunchOption.AttachToGame,
CreateStadiaLldbDebugger(_gameBinary, false)));
Assert.That(e.Message, Is.EqualTo(ErrorStrings.FailedToAttachToProcessSelfTrace));
CheckLldbListenerStops();
}
[Test]
public void TestAttachToGameFail_NoTracer()
{
string parentPid = "1234";
string tracerPid = "0";
var launcherFactory = CreateLauncherFactory(false);
var launcher = launcherFactory.Create(_debugEngine, "", _gameBinary, _gameLaunch);
_debuggerFactory.SetTargetAttachError("Operation not permitted");
_platformFactory.AddCommandOutput($"cat /proc/{_pid}/status",
"Name:\tgame\n" + $"Pid:\t{_pid}\n" +
$"PPid:\t{parentPid}\n" +
$"TracerPid:\t{tracerPid}\n" + "FDSize:\t256\n");
AttachException e =
Assert.ThrowsAsync<AttachException>(
async () => await LaunchAsync(launcher, LaunchOption.AttachToGame,
CreateStadiaLldbDebugger(_gameBinary, false)));
Assert.That(e.Message,
Is.EqualTo(
ErrorStrings.FailedToAttachToProcess("Operation not permitted")));
CheckLldbListenerStops();
}
[Test]
public void TestAttachToGameFail_CannotGetTracer()
{
var launcherFactory = CreateLauncherFactory(false);
var launcher = launcherFactory.Create(_debugEngine, "", _gameBinary, _gameLaunch);
_debuggerFactory.SetTargetAttachError("Operation not permitted");
_platformFactory.AddCommandOutput($"cat /proc/{_pid}/status", null);
AttachException e =
Assert.ThrowsAsync<AttachException>(
async () => await LaunchAsync(launcher, LaunchOption.AttachToGame,
CreateStadiaLldbDebugger(_gameBinary, false)));
Assert.That(e.Message,
Is.EqualTo(
ErrorStrings.FailedToAttachToProcess("Operation not permitted")));
CheckLldbListenerStops();
}
[Test]
public async Task TestLaunchGameAsync([Values] bool stadiaPlatformAvailable)
{
var launcherFactory = CreateLauncherFactory(stadiaPlatformAvailable);
var launcher = launcherFactory.Create(_debugEngine, "", _gameBinary, _gameLaunch);
var attachedProgram = await LaunchAsync(launcher, LaunchOption.LaunchGame,
CreateStadiaLldbDebugger(_gameBinary, false));
Assert.That(attachedProgram, Is.Not.Null);
Assert.IsFalse(
_debuggerFactory.Debugger.CommandInterpreter.HandledCommands.Contains(
SbDebuggerExtensions.FastExpressionEvaluationCommand),
_fastExpressionDisabledErrorMessage);
attachedProgram.Stop();
}
[Test]
public void LaunchGameAbortsWhenLaunchEndedWhileCheckingConnectRemoteStatus()
{
var runningGame = new GgpGrpc.Models.GameLaunch
{
GameLaunchState = GameLaunchState.RunningGame
};
var endedGame = new GgpGrpc.Models.GameLaunch
{
GameLaunchState = GameLaunchState.GameLaunchEnded,
GameLaunchEnded = new GameLaunchEnded(EndReason.GameBinaryNotFound)
};
_gameLaunch.GetLaunchStateAsync(Arg.Any<IAction>())
.Returns(Task.FromResult(runningGame), Task.FromResult(endedGame));
var launcherFactory = CreateLauncherFactory(true);
var launcher = launcherFactory.Create(_debugEngine, "", _gameBinary, _gameLaunch);
_platformFactory.AddConnectRemoteStatuses(false, false);
Assert.ThrowsAsync<GameLaunchAttachException>(
async () => await LaunchAsync(launcher, LaunchOption.LaunchGame,
CreateStadiaLldbDebugger(_gameBinary, false)),
_binaryNotFound);
}
[Test]
public void LaunchGameAbortsWhenLaunchEndedWhilePollingForPid()
{
var runningGame = new GgpGrpc.Models.GameLaunch
{
GameLaunchState = GameLaunchState.RunningGame
};
var endedGame = new GgpGrpc.Models.GameLaunch
{
GameLaunchState = GameLaunchState.GameLaunchEnded,
GameLaunchEnded = new GameLaunchEnded(EndReason.GameBinaryNotFound)
};
_gameLaunch.GetLaunchStateAsync(Arg.Any<IAction>())
.Returns(Task.FromResult(runningGame), Task.FromResult(endedGame));
var launcherFactory = CreateLauncherFactory(true);
var launcher = launcherFactory.Create(_debugEngine, "", _gameBinary, _gameLaunch);
_platformFactory.AddRunStatuses(false, false);
Assert.ThrowsAsync<GameLaunchAttachException>(
async () => await LaunchAsync(launcher, LaunchOption.LaunchGame,
CreateStadiaLldbDebugger(_gameBinary, false)),
_binaryNotFound);
CheckLldbListenerStops();
}
[Test]
public async Task LaunchGamePollsForConnectStatusWhenGameIsRunningAsync()
{
var launch = new GgpGrpc.Models.GameLaunch
{
GameLaunchState = GameLaunchState.RunningGame
};
_gameLaunch.GetLaunchStateAsync(Arg.Any<IAction>()).Returns(Task.FromResult(launch));
var launcherFactory = CreateLauncherFactory(true);
var launcher = launcherFactory.Create(_debugEngine, "", _gameBinary, _gameLaunch);
_platformFactory.AddConnectRemoteStatuses(false, false, true);
var program = await LaunchAsync(launcher, LaunchOption.LaunchGame,
CreateStadiaLldbDebugger(_gameBinary, false));
Assert.That(program, Is.Not.Null);
program.Stop();
}
[Test]
public async Task LaunchGamePollsForPidWhenGameIsRunningAsync()
{
var launch = new GgpGrpc.Models.GameLaunch
{
GameLaunchState = GameLaunchState.RunningGame
};
_gameLaunch.GetLaunchStateAsync(Arg.Any<IAction>()).Returns(Task.FromResult(launch));
var launcherFactory = CreateLauncherFactory(true);
var launcher = launcherFactory.Create(_debugEngine, "", _gameBinary, _gameLaunch);
_platformFactory.AddRunStatuses(false, false, true);
var program = await LaunchAsync(launcher, LaunchOption.LaunchGame,
CreateStadiaLldbDebugger(_gameBinary, false));
Assert.That(program, Is.Not.Null);
program.Stop();
}
[Test]
public async Task LaunchStatusIsIgnoredInLegacyOrAttachFlowAsync()
{
var launcherFactory = CreateLauncherFactory(true);
var launcher = launcherFactory.Create(_debugEngine, "", _gameBinary, null);
_platformFactory.AddConnectRemoteStatuses(false, true);
var program = await LaunchAsync(launcher, LaunchOption.AttachToGame,
CreateStadiaLldbDebugger(_gameBinary, false));
Assert.That(program, Is.Not.Null);
program.Stop();
}
[Test]
public async Task TestInitFilesSourcedAsync([Values] bool stadiaPlatformAvailable)
{
// Add ~/.lldbinit file, LLDB debugger should try loading it.
var lldbinitPath = SbDebuggerExtensions.GetLLDBInitPath();
_fileSystem.AddFile(lldbinitPath, MockFileData.NullObject);
var launcherFactory = CreateLauncherFactory(stadiaPlatformAvailable);
var launcher = launcherFactory.Create(_debugEngine, "some/core/path", "", _gameLaunch);
await LaunchAsync(launcher, LaunchOption.AttachToCore,
CreateStadiaLldbDebugger("some/core/path", true));
Assert.IsTrue(_debuggerFactory.Debugger.IsInitFileSourced);
}
[Test]
public async Task TestInitFilesNotSourcedAsync([Values] bool stadiaPlatformAvailable)
{
// Ensure that local ~/.lldbinit doesn't exist.
var lldbinitPath = SbDebuggerExtensions.GetLLDBInitPath();
Assert.IsFalse(_fileSystem.FileExists(lldbinitPath));
var launcherFactory = CreateLauncherFactory(stadiaPlatformAvailable);
var launcher = launcherFactory.Create(_debugEngine, "some/core/path", "", _gameLaunch);
await LaunchAsync(launcher, LaunchOption.AttachToCore,
CreateStadiaLldbDebugger("some/core/path", true));
Assert.IsFalse(_debuggerFactory.Debugger.IsInitFileSourced);
}
[Test]
public async Task TestConnectRemoteNotCalledWithAttachToCoreAsync(
[Values] bool stadiaPlatformAvailable)
{
var connectRemoteRecorder = new PlatformFactoryFakeConnectRecorder();
var launcherFactory =
CreateLauncherFactory(stadiaPlatformAvailable, connectRemoteRecorder);
var launcher = launcherFactory.Create(_debugEngine, "some/core/path", "", _gameLaunch);
ILldbAttachedProgram program = await LaunchAsync(
launcher, LaunchOption.AttachToCore, CreateStadiaLldbDebugger("some/core/path", true));
Assert.That(connectRemoteRecorder.InvocationCount, Is.EqualTo(0));
Assert.That(program, Is.Not.Null);
program.Stop();
}
[TestCase(LaunchOption.AttachToGame)]
[TestCase(LaunchOption.LaunchGame)]
public async Task TestConnectRemoteCalledForLinuxWithCorrectUrlAsync(
LaunchOption launchOption)
{
var connectRemoteRecorder = new PlatformFactoryFakeConnectRecorder();
var launcherFactory = CreateLauncherFactory(false, connectRemoteRecorder);
var launcher = launcherFactory.Create(_debugEngine, "", _gameBinary, _gameLaunch);
ILldbAttachedProgram program = await LaunchAsync(
launcher, launchOption, CreateStadiaLldbDebugger(_gameBinary, false));
Assert.That(connectRemoteRecorder.InvocationCount, Is.EqualTo(1));
Assert.That(connectRemoteRecorder.InvocationOptions[0].GetUrl(),
Is.EqualTo("connect://localhost:10200"));
Assert.That(program, Is.Not.Null);
program.Stop();
}
[TestCase(LaunchOption.AttachToGame)]
[TestCase(LaunchOption.LaunchGame)]
public async Task TestConnectRemoteCalledForStadiaWithScpCommandAsExtraArgAsync(
LaunchOption launchOption)
{
var connectRemoteRecorder = new PlatformFactoryFakeConnectRecorder();
var launcherFactory = CreateLauncherFactory(true, connectRemoteRecorder);
var launcher = launcherFactory.Create(_debugEngine, "", _gameBinary, _gameLaunch);
ILldbAttachedProgram program = await LaunchAsync(
launcher, launchOption, CreateStadiaLldbDebugger(_gameBinary, false));
Assert.That(connectRemoteRecorder.InvocationCount, Is.EqualTo(1));
Assert.That(connectRemoteRecorder.InvocationOptions.Count, Is.EqualTo(1));
string connectRemoteUrl = connectRemoteRecorder.InvocationOptions[0].GetUrl();
// argument for ConnectRemote should start with a standard value, ending with ';'
// used as a separator between it and scp command.
Assert.That(connectRemoteUrl, Does.StartWith("connect://localhost:10200;"));
// path to the scp.exe should be quoted, to check this we add \" to the assertion.
Assert.That(connectRemoteUrl, Does.Contain("scp.exe\""));
Assert.That(connectRemoteUrl,
Does.Contain("-oStrictHostKeyChecking=yes -oUserKnownHostsFile"));
Assert.That(program, Is.Not.Null);
program.Stop();
}
StadiaLldbDebugger CreateStadiaLldbDebugger(string executableFullPath,
bool attachToCoreDump) =>
new StadiaLldbDebugger.Factory(_debuggerFactory, _platformFactory,
_fileSystem, _actionRecorder, false)
.Create(_grpcConnection, _debuggerOptions, _libPaths, executableFullPath,
attachToCoreDump);
DebugSessionLauncher.Factory CreateLauncherFactory(bool stadiaPlatformAvailable,
PlatformFactoryFakeConnectRecorder
connectRecorder = null)
{
_debuggerFactory =
new GrpcDebuggerFactoryFake(new TimeSpan(0), stadiaPlatformAvailable);
_platformFactory = new GrpcPlatformFactoryFake(connectRecorder);
var taskContext = new JoinableTaskContext();
_listenerFactory = new GrpcListenerFactoryFake();
// If stadiaPlatformAvailable is True the DebugSessionLauncher will connect
// to the platform 'remote-stadia', otherwise it will use 'remote-linux'
var platformName = stadiaPlatformAvailable
? "remote-stadia"
: "remote-linux";
_platformFactory.AddFakeProcess(platformName, _gameBinary, 44);
var exceptionManagerFactory =
new LldbExceptionManager.Factory(new Dictionary<int, Signal>());
var connectOptionsFactory = new GrpcPlatformConnectOptionsFactory();
var platformShellCommandFactory = new GrpcPlatformShellCommandFactory();
var childAdapterFactory = new RemoteValueChildAdapter.Factory();
var varInfoFactory = new LLDBVariableInformationFactory(childAdapterFactory);
var taskExecutor = new TaskExecutor(taskContext.Factory);
var debugCodeContextFactory = new DebugCodeContext.Factory();
var debugDocumentContextFactory = new DebugDocumentContext.Factory();
var threadsEnumFactory = new ThreadEnumFactory();
var moduleEnumFactory = new ModuleEnumFactory();
var frameEnumFactory = new FrameEnumFactory();
var codeContextEnumFactory = new CodeContextEnumFactory();
var moduleFileFinder = Substitute.For<IModuleFileFinder>();
var moduleFileLoadRecorderFactory =
new ModuleFileLoadMetricsRecorder.Factory(moduleFileFinder);
var lldbShell = Substitute.For<ILLDBShell>();
var symbolSettingsProvider = Substitute.For<ISymbolSettingsProvider>();
var attachedProgramFactory = new LldbAttachedProgram.Factory(
taskContext, new DebugEngineHandler.Factory(taskContext), taskExecutor,
new LldbEventManager.Factory(new BoundBreakpointEnumFactory(), taskContext),
new DebugProgram.Factory(taskContext,
new DebugDisassemblyStream.Factory(
debugCodeContextFactory, debugDocumentContextFactory),
debugDocumentContextFactory, debugCodeContextFactory,
threadsEnumFactory, moduleEnumFactory,
codeContextEnumFactory),
new DebugModule.Factory(
FakeCancelableTask.CreateFactory(new JoinableTaskContext(), false),
_actionRecorder, moduleFileLoadRecorderFactory,
symbolSettingsProvider), new DebugAsyncThread.Factory(taskExecutor,
frameEnumFactory),
new DebugAsyncStackFrame.Factory(debugDocumentContextFactory,
new ChildrenProvider.Factory(),
debugCodeContextFactory,
Substitute.For<IDebugExpressionFactory>(),
varInfoFactory,
new VariableInformationEnum.Factory(taskExecutor),
new RegisterSetsBuilder.Factory(varInfoFactory),
taskExecutor), lldbShell,
new LldbBreakpointManager.Factory(taskContext, new DebugPendingBreakpoint.Factory(
taskContext,
new DebugBoundBreakpoint.Factory(
debugDocumentContextFactory,
debugCodeContextFactory,
new DebugBreakpointResolution.Factory()),
new BreakpointErrorEnumFactory(),
new BoundBreakpointEnumFactory()),
new DebugWatchpoint.Factory(
taskContext,
new DebugWatchpointResolution.Factory(),
new BreakpointErrorEnumFactory(),
new BoundBreakpointEnumFactory())),
new SymbolLoader.Factory(Substitute.For<IModuleParser>(), moduleFileFinder),
new BinaryLoader.Factory(moduleFileFinder),
Substitute.For<IModuleFileLoaderFactory>());
var coreAttachWarningDialog = new CoreAttachWarningDialogUtil(
taskContext, Substitute.For<IDialogUtil>());
var compRoot = new MediumTestDebugEngineFactoryCompRoot(new JoinableTaskContext());
var natvisVisualizerScanner = compRoot.GetNatvisVisualizerScanner();
return new DebugSessionLauncher.Factory(
taskContext, _listenerFactory, connectOptionsFactory, platformShellCommandFactory,
attachedProgramFactory, _actionRecorder, moduleFileLoadRecorderFactory,
exceptionManagerFactory, moduleFileFinder, new DumpModulesProvider(_fileSystem),
new ModuleSearchLogHolder(), symbolSettingsProvider, coreAttachWarningDialog,
natvisVisualizerScanner);
}
Task<ILldbAttachedProgram> LaunchAsync(
IDebugSessionLauncher launcher, LaunchOption option, StadiaLldbDebugger lldbDebugger)
{
return launcher.LaunchAsync(_task, _process, _programId, _pid, _grpcConnection, 10200,
_gameletIpAddress, _gameletPort, option, _callback,
lldbDebugger);
}
}
}
| |
/*
* Copyright (C) 2016-2020. Autumn Beauchesne. All rights reserved.
* Author: Autumn Beauchesne
* Date: 8 May 2018
*
* File: Spline.cs
* Purpose: Defines a common interface for splines, along with factory methods.
*/
using System.Collections.Generic;
using UnityEngine;
namespace BeauRoutine.Splines
{
static public partial class Spline
{
#region Simple Spline
/// <summary>
/// Returns a new quadratic bezier spline.
/// </summary>
static public SimpleSpline Simple(Vector3 inStart, Vector3 inEnd, Vector3 inControl)
{
return new SimpleSpline(inStart, inEnd, inControl);
}
/// <summary>
/// Returns a new quadtratic bezier spline,
/// setting the control point as an offset from a point along the line.
/// </summary>
static public SimpleSpline Simple(Vector3 inStart, Vector3 inEnd, float inControlPercent, Vector3 inControlOffset)
{
return new SimpleSpline(inStart, inEnd, inStart + ((inEnd - inStart) * inControlPercent) + inControlOffset);
}
/// <summary>
/// Returns a new quadratic bezier spline.
/// </summary>
static public SimpleSpline Simple(Vector2 inStart, Vector2 inEnd, Vector2 inControl)
{
return new SimpleSpline(inStart, inEnd, inControl);
}
/// <summary>
/// Returns a new quadratic bezier spline.
/// </summary>
static public SimpleSpline Simple(Vector2 inStart, Vector2 inEnd, float inControlPercent, Vector2 inControlOffset)
{
return new SimpleSpline(inStart, inEnd, inStart + ((inEnd - inStart) * inControlPercent) + inControlOffset);
}
#endregion // Simple
#region Vertex Spline
/// <summary>
/// Creates a new vertex spline.
/// </summary>
static public LinearSpline Linear(bool inbLooped, params CSplineVertex[] inVertices)
{
LinearSpline spline = new LinearSpline(inVertices.Length);
spline.SetLooped(inbLooped);
spline.SetVertices(inVertices);
return spline;
}
/// <summary>
/// Creates a new vertex spline.
/// </summary>
static public LinearSpline Linear(bool inbLooped, List<CSplineVertex> inVertices)
{
LinearSpline spline = new LinearSpline(inVertices.Count);
spline.SetLooped(inbLooped);
spline.SetVertices(inVertices);
return spline;
}
/// <summary>
/// Creates a new vertex spline.
/// </summary>
static public LinearSpline Linear(bool inbLooped, params Vector3[] inVertices)
{
LinearSpline spline = new LinearSpline(inVertices.Length);
spline.SetLooped(inbLooped);
spline.SetVertices(inVertices);
return spline;
}
/// <summary>
/// Creates a new vertex spline.
/// </summary>
static public LinearSpline Linear(bool inbLooped, List<Vector3> inVertices)
{
LinearSpline spline = new LinearSpline(inVertices.Count);
spline.SetLooped(inbLooped);
spline.SetVertices(inVertices);
return spline;
}
/// <summary>
/// Creates a new vertex spline.
/// </summary>
static public LinearSpline Linear(bool inbLooped, params Vector2[] inVertices)
{
LinearSpline spline = new LinearSpline(inVertices.Length);
spline.SetLooped(inbLooped);
spline.SetVertices(inVertices);
return spline;
}
/// <summary>
/// Creates a new vertex spline.
/// </summary>
static public LinearSpline Linear(bool inbLooped, List<Vector2> inVertices)
{
LinearSpline spline = new LinearSpline(inVertices.Count);
spline.SetLooped(inbLooped);
spline.SetVertices(inVertices);
return spline;
}
/// <summary>
/// Creates a new vertex spline from the given transforms.
/// </summary>
static public LinearSpline Linear(bool inbLooped, Space inSpace, params Transform[] inVertices)
{
LinearSpline spline = new LinearSpline(inVertices.Length);
spline.SetLooped(inbLooped);
spline.SetVertices(inVertices, inSpace);
return spline;
}
/// <summary>
/// Creates a new vertex spline from the given transforms.
/// </summary>
static public LinearSpline Linear(bool inbLooped, Space inSpace, List<Transform> inVertices)
{
LinearSpline spline = new LinearSpline(inVertices.Count);
spline.SetLooped(inbLooped);
spline.SetVertices(inVertices, inSpace);
return spline;
}
#endregion // Vertex
#region CSpline
/// <summary>
/// Creates a new CSpline.
/// </summary>
static public CSpline CSpline(bool inbLooped, params CSplineVertex[] inVertices)
{
CSpline spline = new CSpline(inVertices.Length);
spline.SetAsCSpline();
spline.SetLooped(inbLooped);
spline.SetVertices(inVertices);
return spline;
}
/// <summary>
/// Creates a new CSpline.
/// </summary>
static public CSpline CSpline(bool inbLooped, List<CSplineVertex> inVertices)
{
CSpline spline = new CSpline(inVertices.Count);
spline.SetAsCSpline();
spline.SetLooped(inbLooped);
spline.SetVertices(inVertices);
return spline;
}
#endregion // CSpline
#region Cardinal
/// <summary>
/// Creates a new CSpline using the Catmull-Rom algorithm.
/// </summary>
static public CSpline CatmullRom(bool inbLooped, params Vector3[] inPoints)
{
CSpline spline = new CSpline(inPoints.Length);
spline.SetAsCatmullRom();
spline.SetLooped(inbLooped);
spline.SetVertices(inPoints);
if (!inbLooped)
spline.ResetControlPoints();
return spline;
}
/// <summary>
/// Creates a new CSpline using the Catmull-Rom algorithm.
/// </summary>
static public CSpline CatmullRom(bool inbLooped, List<Vector3> inPoints)
{
CSpline spline = new CSpline(inPoints.Count);
spline.SetAsCatmullRom();
spline.SetLooped(inbLooped);
spline.SetVertices(inPoints);
if (!inbLooped)
spline.ResetControlPoints();
return spline;
}
/// <summary>
/// Creates a new CSpline using the Cardinal algorithm.
/// </summary>
static public CSpline Cardinal(bool inbLooped, float inTension, params Vector3[] inPoints)
{
CSpline spline = new CSpline(inPoints.Length);
spline.SetAsCardinal(inTension);
spline.SetLooped(inbLooped);
spline.SetVertices(inPoints);
if (!inbLooped)
spline.ResetControlPoints();
return spline;
}
/// <summary>
/// Creates a new CSpline using the Cardinal algorithm.
/// </summary>
static public CSpline Cardinal(bool inbLooped, float inTension, List<Vector3> inPoints)
{
CSpline spline = new CSpline(inPoints.Count);
spline.SetAsCardinal(inTension);
spline.SetLooped(inbLooped);
spline.SetVertices(inPoints);
if (!inbLooped)
spline.ResetControlPoints();
return spline;
}
/// <summary>
/// Creates a new CSpline using the Catmull-Rom algorithm.
/// </summary>
static public CSpline CatmullRom(bool inbLooped, params Vector2[] inPoints)
{
CSpline spline = new CSpline(inPoints.Length);
spline.SetAsCatmullRom();
spline.SetLooped(inbLooped);
spline.SetVertices(inPoints);
if (!inbLooped)
spline.ResetControlPoints();
return spline;
}
/// <summary>
/// Creates a new CSpline using the Catmull-Rom algorithm.
/// </summary>
static public CSpline CatmullRom(bool inbLooped, List<Vector2> inPoints)
{
CSpline spline = new CSpline(inPoints.Count);
spline.SetAsCatmullRom();
spline.SetLooped(inbLooped);
spline.SetVertices(inPoints);
if (!inbLooped)
spline.ResetControlPoints();
return spline;
}
/// <summary>
/// Creates a new CSpline using the Cardinal algorithm.
/// </summary>
static public CSpline Cardinal(bool inbLooped, float inTension, params Vector2[] inPoints)
{
CSpline spline = new CSpline(inPoints.Length);
spline.SetAsCardinal(inTension);
spline.SetLooped(inbLooped);
spline.SetVertices(inPoints);
if (!inbLooped)
spline.ResetControlPoints();
return spline;
}
/// <summary>
/// Creates a new CSpline using the Cardinal algorithm.
/// </summary>
static public CSpline Cardinal(bool inbLooped, float inTension, List<Vector2> inPoints)
{
CSpline spline = new CSpline(inPoints.Count);
spline.SetAsCardinal(inTension);
spline.SetLooped(inbLooped);
spline.SetVertices(inPoints);
if (!inbLooped)
spline.ResetControlPoints();
return spline;
}
/// <summary>
/// Creates a new CSpline from the given transforms using the Catmull-Rom algorithm.
/// </summary>
static public CSpline CatmullRom(bool inbLooped, Space inSpace, params Transform[] inPoints)
{
CSpline spline = new CSpline(inPoints.Length);
spline.SetAsCatmullRom();
spline.SetLooped(inbLooped);
spline.SetVertices(inPoints, inSpace);
if (!inbLooped)
spline.ResetControlPoints();
return spline;
}
/// <summary>
/// Creates a new CSpline from the given transforms using the Catmull-Rom algorithm.
/// </summary>
static public CSpline CatmullRom(bool inbLooped, Space inSpace, List<Transform> inPoints)
{
CSpline spline = new CSpline(inPoints.Count);
spline.SetAsCatmullRom();
spline.SetLooped(inbLooped);
spline.SetVertices(inPoints, inSpace);
if (!inbLooped)
spline.ResetControlPoints();
return spline;
}
/// <summary>
/// Creates a new CSpline from the given transforms using the Cardinal algorithm.
/// </summary>
static public CSpline Cardinal(bool inbLooped, float inTension, Space inSpace, params Transform[] inPoints)
{
CSpline spline = new CSpline(inPoints.Length);
spline.SetAsCardinal(inTension);
spline.SetLooped(inbLooped);
spline.SetVertices(inPoints, inSpace);
if (!inbLooped)
spline.ResetControlPoints();
return spline;
}
/// <summary>
/// Creates a new CSpline from the given transforms using the Cardinal algorithm.
/// </summary>
static public CSpline Cardinal(bool inbLooped, float inTension, Space inSpace, List<Transform> inPoints)
{
CSpline spline = new CSpline(inPoints.Count);
spline.SetAsCardinal(inTension);
spline.SetLooped(inbLooped);
spline.SetVertices(inPoints, inSpace);
if (!inbLooped)
spline.ResetControlPoints();
return spline;
}
#endregion // Cardinal
#region Extension Methods
/// <summary>
/// Samples the spline for the given range and outputs to an array.
/// </summary>
static public int Sample(this ISpline inSpline, Vector3[] outPoints, float inStart, float inEnd, int inStartIdx, int inNumSamples, SplineLerp inLerp = SplineLerp.Vertex)
{
inNumSamples = Mathf.Min(outPoints.Length - inStartIdx, inNumSamples);
float delta = inEnd - inStart;
for (int i = 0; i < inNumSamples; ++i)
{
float t = (float) i / (inNumSamples - 1);
outPoints[inStartIdx + i] = inSpline.GetPoint(inSpline.TransformPercent(inStart + t * delta, inLerp));
}
return inNumSamples;
}
/// <summary>
/// Samples the spline for the given range and outputs to an array.
/// </summary>
static public int Sample(this ISpline inSpline, Vector2[] outPoints, float inStart, float inEnd, int inStartIdx, int inNumSamples, SplineLerp inLerp = SplineLerp.Vertex)
{
inNumSamples = Mathf.Min(outPoints.Length - inStartIdx, inNumSamples);
float delta = inEnd - inStart;
for (int i = 0; i < inNumSamples; ++i)
{
float t = (float) i / (inNumSamples - 1);
outPoints[inStartIdx + i] = inSpline.GetPoint(inSpline.TransformPercent(inStart + t * delta, inLerp));
}
return inNumSamples;
}
/// <summary>
/// Samples the spline for the given range and outputs to a list.
/// </summary>
static public void Sample(this ISpline inSpline, List<Vector3> outPoints, float inStart, float inEnd, int inNumSamples, SplineLerp inLerp = SplineLerp.Vertex)
{
float delta = inEnd - inStart;
for (int i = 0; i < inNumSamples; ++i)
{
float t = (float) i / (inNumSamples - 1);
outPoints.Add(inSpline.GetPoint(inSpline.TransformPercent(inStart + t * delta, inLerp)));
}
}
/// <summary>
/// Samples the spline for the given range and outputs to a list.
/// </summary>
static public void Sample(this ISpline inSpline, List<Vector2> outPoints, float inStart, float inEnd, int inNumSamples, SplineLerp inLerp = SplineLerp.Vertex)
{
float delta = inEnd - inStart;
for (int i = 0; i < inNumSamples; ++i)
{
float t = (float) i / (inNumSamples - 1);
outPoints.Add(inSpline.GetPoint(inSpline.TransformPercent(inStart + t * delta, inLerp)));
}
}
/// <summary>
/// Samples the spline for the given range and outputs to an array.
/// </summary>
static public int Sample(this ISpline inSpline, Vector3[] outPoints, float inStart, float inEnd, int inStartIdx, SplineLerp inLerp = SplineLerp.Vertex)
{
return Sample(inSpline, outPoints, inStart, inEnd, inStartIdx, outPoints.Length - inStartIdx, inLerp);
}
/// <summary>
/// Samples the spline for the given range and outputs to an array.
/// </summary>
static public int Sample(this ISpline inSpline, Vector2[] outPoints, float inStart, float inEnd, int inStartIdx, SplineLerp inLerp = SplineLerp.Vertex)
{
return Sample(inSpline, outPoints, inStart, inEnd, inStartIdx, outPoints.Length - inStartIdx, inLerp);
}
/// <summary>
/// Samples the spline for the given range and outputs to an array.
/// </summary>
static public int Sample(this ISpline inSpline, Vector3[] outPoints, float inStart, float inEnd, SplineLerp inLerp = SplineLerp.Vertex)
{
return Sample(inSpline, outPoints, inStart, inEnd, 0, outPoints.Length, inLerp);
}
/// <summary>
/// Samples the spline for the given range and outputs to an array.
/// </summary>
static public int Sample(this ISpline inSpline, Vector2[] outPoints, float inStart, float inEnd, SplineLerp inLerp = SplineLerp.Vertex)
{
return Sample(inSpline, outPoints, inStart, inEnd, 0, outPoints.Length, inLerp);
}
/// <summary>
/// Returns the userdata for the given vertex, casted as a Transform.
/// </summary>
static public Transform GetVertexTransform(this ISpline inSpline, int inIndex)
{
return inSpline.GetVertexUserData(inIndex) as Transform;
}
/// <summary>
/// Returns info about a segment on the spline.
/// </summary>
static public SplineSegment GetSegment(this ISpline inSpline, float inPercent)
{
SplineSegment seg;
inSpline.GetSegment(inPercent, out seg);
return seg;
}
/// <summary>
/// Generates info about an interpolation along the given spline.
/// </summary>
static public void GetUpdateInfo(this ISpline inSpline, float inPercent, SplineTweenSettings inTweenSettings, out SplineUpdateInfo outInfo)
{
GetUpdateInfo(inSpline, inPercent, inTweenSettings.LerpMethod, inTweenSettings.SegmentEase, out outInfo);
}
/// <summary>
/// Generates info about an interpolation along the given spline.
/// </summary>
static public void GetUpdateInfo(this ISpline inSpline, float inPercent, SplineLerp inLerp, out SplineUpdateInfo outInfo)
{
GetUpdateInfo(inSpline, inPercent, inLerp, Curve.Linear, out outInfo);
}
/// <summary>
/// Generates info about an interpolation along the given spline.
/// </summary>
static public void GetUpdateInfo(this ISpline inSpline, float inPercent, out SplineUpdateInfo outInfo)
{
GetUpdateInfo(inSpline, inPercent, SplineLerp.Vertex, Curve.Linear, out outInfo);
}
/// <summary>
/// Generates info about an interpolation along the given spline.
/// </summary>
static public void GetUpdateInfo(this ISpline inSpline, float inPercent, SplineLerp inLerpMethod, Curve inSegmentEase, out SplineUpdateInfo outInfo)
{
outInfo.Spline = inSpline;
outInfo.Percent = inSpline.TransformPercent(inPercent, inLerpMethod);
outInfo.Point = inSpline.GetPoint(outInfo.Percent, inSegmentEase);
outInfo.Direction = inSpline.GetDirection(outInfo.Percent, inSegmentEase);
}
#endregion // Extension Methods
#region Alignment
/// <summary>
/// Aligns a Transform to a point along the spline, using either localPosition or position.
/// </summary>
static public void Align(ISpline inSpline, Transform inTransform, float inPercent, Axis inAxis, Space inSpace, SplineLerp inLerpMethod, Curve inSegmentEase, SplineOrientationSettings inOrientation)
{
SplineUpdateInfo info;
GetUpdateInfo(inSpline, inPercent, inLerpMethod, inSegmentEase, out info);
inTransform.SetPosition(info.Point, inAxis, inSpace);
if (inOrientation != null)
{
inOrientation.Apply(ref info, inTransform, inSpace);
}
}
/// <summary>
/// Aligns a RectTransform to a point along the spline, using anchoredPosition.
/// </summary>
static public void AlignAnchorPos(ISpline inSpline, RectTransform inTransform, float inPercent, Axis inAxis, SplineLerp inLerpMethod, Curve inSegmentEase, SplineOrientationSettings inOrientation)
{
SplineUpdateInfo info;
GetUpdateInfo(inSpline, inPercent, inLerpMethod, inSegmentEase, out info);
inTransform.SetAnchorPos(info.Point, inAxis);
if (inOrientation != null)
{
inOrientation.Apply(ref info, inTransform, Space.Self);
}
}
#endregion // Alignment
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Differencing;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus
{
/// <summary>
/// An IVisualStudioDocument which represents the secondary buffer to the workspace API.
/// </summary>
internal sealed class ContainedDocument : ForegroundThreadAffinitizedObject, IVisualStudioHostDocument
{
private const string ReturnReplacementString = @"{|r|}";
private const string NewLineReplacementString = @"{|n|}";
private const string HTML = nameof(HTML);
private const string HTMLX = nameof(HTMLX);
private const string Razor = nameof(Razor);
private const string XOML = nameof(XOML);
private const char RazorExplicit = '@';
private const string CSharpRazorBlock = "{";
private const string VBRazorBlock = "code";
private const string HelperRazor = "helper";
private const string FunctionsRazor = "functions";
private static readonly EditOptions s_venusEditOptions = new EditOptions(new StringDifferenceOptions
{
DifferenceType = StringDifferenceTypes.Character,
IgnoreTrimWhiteSpace = false
});
private readonly AbstractContainedLanguage _containedLanguage;
private readonly SourceCodeKind _sourceCodeKind;
private readonly IComponentModel _componentModel;
private readonly Workspace _workspace;
private readonly ITextDifferencingSelectorService _differenceSelectorService;
private readonly HostType _hostType;
private readonly ReiteratedVersionSnapshotTracker _snapshotTracker;
private readonly IFormattingRule _vbHelperFormattingRule;
private readonly string _itemMoniker;
public AbstractProject Project { get { return _containedLanguage.Project; } }
public bool SupportsRename { get { return _hostType == HostType.Razor; } }
public DocumentId Id { get; }
public IReadOnlyList<string> Folders { get; }
public TextLoader Loader { get; }
public DocumentKey Key { get; }
public ContainedDocument(
AbstractContainedLanguage containedLanguage,
SourceCodeKind sourceCodeKind,
Workspace workspace,
IVsHierarchy hierarchy,
uint itemId,
IComponentModel componentModel,
IFormattingRule vbHelperFormattingRule)
{
Contract.ThrowIfNull(containedLanguage);
_containedLanguage = containedLanguage;
_sourceCodeKind = sourceCodeKind;
_componentModel = componentModel;
_workspace = workspace;
_hostType = GetHostType();
string filePath;
if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemId, out filePath)))
{
// we couldn't look up the document moniker from an hierarchy for an itemid.
// Since we only use this moniker as a key, we could fall back to something else, like the document name.
Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy.");
if (!hierarchy.TryGetItemName(itemId, out filePath))
{
Environment.FailFast("Failed to get document moniker for a contained document");
}
}
if (Project.Hierarchy != null)
{
string moniker;
Project.Hierarchy.GetCanonicalName(itemId, out moniker);
_itemMoniker = moniker;
}
this.Key = new DocumentKey(Project, filePath);
this.Id = DocumentId.CreateNewId(Project.Id, filePath);
this.Folders = containedLanguage.Project.GetFolderNamesFromHierarchy(itemId);
this.Loader = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath);
_differenceSelectorService = componentModel.GetService<ITextDifferencingSelectorService>();
_snapshotTracker = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer);
_vbHelperFormattingRule = vbHelperFormattingRule;
}
private HostType GetHostType()
{
var projectionBuffer = _containedLanguage.DataBuffer as IProjectionBuffer;
if (projectionBuffer != null)
{
// For TypeScript hosted in HTML the source buffers will have type names
// HTMLX and TypeScript. RazorCSharp has an HTMLX base type but should
// not be associated with the HTML host type. Use ContentType.TypeName
// instead of ContentType.IsOfType for HTMLX to ensure the Razor host
// type is identified correctly.
if (projectionBuffer.SourceBuffers.Any(b => b.ContentType.IsOfType(HTML) ||
string.Compare(HTMLX, b.ContentType.TypeName, StringComparison.OrdinalIgnoreCase) == 0))
{
return HostType.HTML;
}
if (projectionBuffer.SourceBuffers.Any(b => b.ContentType.IsOfType(Razor)))
{
return HostType.Razor;
}
}
else
{
// XOML is set up differently. For XOML, the secondary buffer (i.e. SubjectBuffer)
// is a projection buffer, while the primary buffer (i.e. DataBuffer) is not. Instead,
// the primary buffer is a regular unprojected ITextBuffer with the HTML content type.
if (_containedLanguage.DataBuffer.CurrentSnapshot.ContentType.IsOfType(HTML))
{
return HostType.XOML;
}
}
throw ExceptionUtilities.Unreachable;
}
public DocumentInfo GetInitialState()
{
return DocumentInfo.Create(
this.Id,
this.Name,
folders: this.Folders,
sourceCodeKind: _sourceCodeKind,
loader: this.Loader,
filePath: this.Key.Moniker);
}
public bool IsOpen
{
get
{
return true;
}
}
#pragma warning disable 67
public event EventHandler UpdatedOnDisk;
public event EventHandler<bool> Opened;
public event EventHandler<bool> Closing;
#pragma warning restore 67
IVisualStudioHostProject IVisualStudioHostDocument.Project { get { return this.Project; } }
public ITextBuffer GetOpenTextBuffer()
{
return _containedLanguage.SubjectBuffer;
}
public SourceTextContainer GetOpenTextContainer()
{
return this.GetOpenTextBuffer().AsTextContainer();
}
public IContentType ContentType
{
get
{
return _containedLanguage.SubjectBuffer.ContentType;
}
}
public string Name
{
get
{
try
{
return Path.GetFileName(this.FilePath);
}
catch (ArgumentException)
{
return this.FilePath;
}
}
}
public SourceCodeKind SourceCodeKind
{
get
{
return _sourceCodeKind;
}
}
public string FilePath
{
get
{
return Key.Moniker;
}
}
public AbstractContainedLanguage ContainedLanguage
{
get
{
return _containedLanguage;
}
}
public void Dispose()
{
_snapshotTracker.StopTracking(_containedLanguage.SubjectBuffer);
this.ContainedLanguage.Dispose();
}
public DocumentId FindProjectDocumentIdWithItemId(uint itemidInsertionPoint)
{
return Project.GetCurrentDocuments().SingleOrDefault(d => d.GetItemId() == itemidInsertionPoint).Id;
}
public uint FindItemIdOfDocument(Document document)
{
return Project.GetDocumentOrAdditionalDocument(document.Id).GetItemId();
}
public void UpdateText(SourceText newText)
{
var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer();
var originalSnapshot = subjectBuffer.CurrentSnapshot;
var originalText = originalSnapshot.AsText();
var changes = newText.GetTextChanges(originalText);
IEnumerable<int> affectedVisibleSpanIndices = null;
var editorVisibleSpansInOriginal = SharedPools.Default<List<TextSpan>>().AllocateAndClear();
try
{
var originalDocument = _workspace.CurrentSolution.GetDocument(this.Id);
editorVisibleSpansInOriginal.AddRange(GetEditorVisibleSpans());
var newChanges = FilterTextChanges(originalText, editorVisibleSpansInOriginal, changes).ToList();
if (newChanges.Count == 0)
{
// no change to apply
return;
}
ApplyChanges(subjectBuffer, newChanges, editorVisibleSpansInOriginal, out affectedVisibleSpanIndices);
AdjustIndentation(subjectBuffer, affectedVisibleSpanIndices);
}
finally
{
SharedPools.Default<HashSet<int>>().ClearAndFree((HashSet<int>)affectedVisibleSpanIndices);
SharedPools.Default<List<TextSpan>>().ClearAndFree(editorVisibleSpansInOriginal);
}
}
private IEnumerable<TextChange> FilterTextChanges(SourceText originalText, List<TextSpan> editorVisibleSpansInOriginal, IReadOnlyList<TextChange> changes)
{
// no visible spans or changes
if (editorVisibleSpansInOriginal.Count == 0 || changes.Count == 0)
{
// return empty one
yield break;
}
using (var pooledObject = SharedPools.Default<List<TextChange>>().GetPooledObject())
{
var changeQueue = pooledObject.Object;
changeQueue.AddRange(changes);
var spanIndex = 0;
var changeIndex = 0;
for (; spanIndex < editorVisibleSpansInOriginal.Count; spanIndex++)
{
var visibleSpan = editorVisibleSpansInOriginal[spanIndex];
var visibleTextSpan = GetVisibleTextSpan(originalText, visibleSpan, uptoFirstAndLastLine: true);
for (; changeIndex < changeQueue.Count; changeIndex++)
{
var change = changeQueue[changeIndex];
// easy case first
if (change.Span.End < visibleSpan.Start)
{
// move to next change
continue;
}
if (visibleSpan.End < change.Span.Start)
{
// move to next visible span
break;
}
// make sure we are not replacing whitespace around start and at the end of visible span
if (WhitespaceOnEdges(originalText, visibleTextSpan, change))
{
continue;
}
if (visibleSpan.Contains(change.Span))
{
yield return change;
continue;
}
// now it is complex case where things are intersecting each other
var subChanges = GetSubTextChanges(originalText, change, visibleSpan).ToList();
if (subChanges.Count > 0)
{
if (subChanges.Count == 1 && subChanges[0] == change)
{
// we can't break it. not much we can do here. just don't touch and ignore this change
continue;
}
changeQueue.InsertRange(changeIndex + 1, subChanges);
continue;
}
}
}
}
}
private bool WhitespaceOnEdges(SourceText text, TextSpan visibleTextSpan, TextChange change)
{
if (!string.IsNullOrWhiteSpace(change.NewText))
{
return false;
}
if (change.Span.End <= visibleTextSpan.Start)
{
return true;
}
if (visibleTextSpan.End <= change.Span.Start)
{
return true;
}
return false;
}
private IEnumerable<TextChange> GetSubTextChanges(SourceText originalText, TextChange changeInOriginalText, TextSpan visibleSpanInOriginalText)
{
using (var changes = SharedPools.Default<List<TextChange>>().GetPooledObject())
{
var leftText = originalText.ToString(changeInOriginalText.Span);
var rightText = changeInOriginalText.NewText;
var offsetInOriginalText = changeInOriginalText.Span.Start;
if (TryGetSubTextChanges(originalText, visibleSpanInOriginalText, leftText, rightText, offsetInOriginalText, changes.Object))
{
return changes.Object.ToList();
}
return GetSubTextChanges(originalText, visibleSpanInOriginalText, leftText, rightText, offsetInOriginalText);
}
}
private bool TryGetSubTextChanges(
SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText, List<TextChange> changes)
{
// these are expensive. but hopefully we don't hit this as much except the boundary cases.
using (var leftPool = SharedPools.Default<List<TextSpan>>().GetPooledObject())
using (var rightPool = SharedPools.Default<List<TextSpan>>().GetPooledObject())
{
var spansInLeftText = leftPool.Object;
var spansInRightText = rightPool.Object;
if (TryGetWhitespaceOnlyChanges(leftText, rightText, spansInLeftText, spansInRightText))
{
for (var i = 0; i < spansInLeftText.Count; i++)
{
var spanInLeftText = spansInLeftText[i];
var spanInRightText = spansInRightText[i];
if (spanInLeftText.IsEmpty && spanInRightText.IsEmpty)
{
continue;
}
var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length);
TextChange textChange;
if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText, out textChange))
{
changes.Add(textChange);
}
}
return true;
}
return false;
}
}
private IEnumerable<TextChange> GetSubTextChanges(
SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText)
{
// these are expensive. but hopefully we don't hit this as much except the boundary cases.
using (var leftPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject())
using (var rightPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject())
{
var leftReplacementMap = leftPool.Object;
var rightReplacementMap = rightPool.Object;
string leftTextWithReplacement, rightTextWithReplacement;
GetTextWithReplacements(leftText, rightText, leftReplacementMap, rightReplacementMap, out leftTextWithReplacement, out rightTextWithReplacement);
var diffResult = DiffStrings(leftTextWithReplacement, rightTextWithReplacement);
foreach (var difference in diffResult)
{
var spanInLeftText = AdjustSpan(diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left), leftReplacementMap);
var spanInRightText = AdjustSpan(diffResult.RightDecomposition.GetSpanInOriginal(difference.Right), rightReplacementMap);
var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length);
TextChange textChange;
if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText.ToTextSpan(), out textChange))
{
yield return textChange;
}
}
}
}
private bool TryGetWhitespaceOnlyChanges(string leftText, string rightText, List<TextSpan> spansInLeftText, List<TextSpan> spansInRightText)
{
return TryGetWhitespaceGroup(leftText, spansInLeftText) && TryGetWhitespaceGroup(rightText, spansInRightText) && spansInLeftText.Count == spansInRightText.Count;
}
private bool TryGetWhitespaceGroup(string text, List<TextSpan> groups)
{
if (text.Length == 0)
{
groups.Add(new TextSpan(0, 0));
return true;
}
var start = 0;
for (var i = 0; i < text.Length; i++)
{
var ch = text[i];
switch (ch)
{
case ' ':
if (!TextAt(text, i - 1, ' '))
{
start = i;
}
break;
case '\r':
case '\n':
if (i == 0)
{
groups.Add(TextSpan.FromBounds(0, 0));
}
else if (TextAt(text, i - 1, ' '))
{
groups.Add(TextSpan.FromBounds(start, i));
}
else if (TextAt(text, i - 1, '\n'))
{
groups.Add(TextSpan.FromBounds(start, i));
}
start = i + 1;
break;
default:
return false;
}
}
if (start <= text.Length)
{
groups.Add(TextSpan.FromBounds(start, text.Length));
}
return true;
}
private bool TextAt(string text, int index, char ch)
{
if (index < 0 || text.Length <= index)
{
return false;
}
return text[index] == ch;
}
private bool TryGetSubTextChange(
SourceText originalText, TextSpan visibleSpanInOriginalText,
string rightText, TextSpan spanInOriginalText, TextSpan spanInRightText, out TextChange textChange)
{
textChange = default(TextChange);
var visibleFirstLineInOriginalText = originalText.Lines.GetLineFromPosition(visibleSpanInOriginalText.Start);
var visibleLastLineInOriginalText = originalText.Lines.GetLineFromPosition(visibleSpanInOriginalText.End);
// skip easy case
// 1. things are out of visible span
if (!visibleSpanInOriginalText.IntersectsWith(spanInOriginalText))
{
return false;
}
// 2. there are no intersects
var snippetInRightText = rightText.Substring(spanInRightText.Start, spanInRightText.Length);
if (visibleSpanInOriginalText.Contains(spanInOriginalText) && visibleSpanInOriginalText.End != spanInOriginalText.End)
{
textChange = new TextChange(spanInOriginalText, snippetInRightText);
return true;
}
// okay, more complex case. things are intersecting boundaries.
var firstLineOfRightTextSnippet = snippetInRightText.GetFirstLineText();
var lastLineOfRightTextSnippet = snippetInRightText.GetLastLineText();
// there are 4 complex cases - these are all heuristic. not sure what better way I have. and the heuristic is heavily based on
// text differ's behavior.
// 1. it is a single line
if (visibleFirstLineInOriginalText.LineNumber == visibleLastLineInOriginalText.LineNumber)
{
// don't do anything
return false;
}
// 2. replacement contains visible spans
if (spanInOriginalText.Contains(visibleSpanInOriginalText))
{
// header
// don't do anything
// body
textChange = new TextChange(
TextSpan.FromBounds(visibleFirstLineInOriginalText.EndIncludingLineBreak, visibleLastLineInOriginalText.Start),
snippetInRightText.Substring(firstLineOfRightTextSnippet.Length, snippetInRightText.Length - firstLineOfRightTextSnippet.Length - lastLineOfRightTextSnippet.Length));
// footer
// don't do anything
return true;
}
// 3. replacement intersects with start
if (spanInOriginalText.Start < visibleSpanInOriginalText.Start &&
visibleSpanInOriginalText.Start <= spanInOriginalText.End &&
spanInOriginalText.End < visibleSpanInOriginalText.End)
{
// header
// don't do anything
// body
if (visibleFirstLineInOriginalText.EndIncludingLineBreak <= spanInOriginalText.End)
{
textChange = new TextChange(
TextSpan.FromBounds(visibleFirstLineInOriginalText.EndIncludingLineBreak, spanInOriginalText.End),
snippetInRightText.Substring(firstLineOfRightTextSnippet.Length));
return true;
}
return false;
}
// 4. replacement intersects with end
if (visibleSpanInOriginalText.Start < spanInOriginalText.Start &&
spanInOriginalText.Start <= visibleSpanInOriginalText.End &&
visibleSpanInOriginalText.End <= spanInOriginalText.End)
{
// body
if (spanInOriginalText.Start <= visibleLastLineInOriginalText.Start)
{
textChange = new TextChange(
TextSpan.FromBounds(spanInOriginalText.Start, visibleLastLineInOriginalText.Start),
snippetInRightText.Substring(0, snippetInRightText.Length - lastLineOfRightTextSnippet.Length));
return true;
}
// footer
// don't do anything
return false;
}
// if it got hit, then it means there is a missing case
throw ExceptionUtilities.Unreachable;
}
private IHierarchicalDifferenceCollection DiffStrings(string leftTextWithReplacement, string rightTextWithReplacement)
{
var diffService = _differenceSelectorService.GetTextDifferencingService(
_workspace.Services.GetLanguageServices(this.Project.Language).GetService<IContentTypeLanguageService>().GetDefaultContentType());
diffService = diffService ?? _differenceSelectorService.DefaultTextDifferencingService;
return diffService.DiffStrings(leftTextWithReplacement, rightTextWithReplacement, s_venusEditOptions.DifferenceOptions);
}
private void GetTextWithReplacements(
string leftText, string rightText,
List<ValueTuple<int, int>> leftReplacementMap, List<ValueTuple<int, int>> rightReplacementMap,
out string leftTextWithReplacement, out string rightTextWithReplacement)
{
// to make diff works better, we choose replacement strings that don't appear in both texts.
var returnReplacement = GetReplacementStrings(leftText, rightText, ReturnReplacementString);
var newLineReplacement = GetReplacementStrings(leftText, rightText, NewLineReplacementString);
leftTextWithReplacement = GetTextWithReplacementMap(leftText, returnReplacement, newLineReplacement, leftReplacementMap);
rightTextWithReplacement = GetTextWithReplacementMap(rightText, returnReplacement, newLineReplacement, rightReplacementMap);
}
private static string GetReplacementStrings(string leftText, string rightText, string initialReplacement)
{
if (leftText.IndexOf(initialReplacement, StringComparison.Ordinal) < 0 && rightText.IndexOf(initialReplacement, StringComparison.Ordinal) < 0)
{
return initialReplacement;
}
// okay, there is already one in the given text.
const string format = "{{|{0}|{1}|{0}|}}";
for (var i = 0; true; i++)
{
var replacement = string.Format(format, i.ToString(), initialReplacement);
if (leftText.IndexOf(replacement, StringComparison.Ordinal) < 0 && rightText.IndexOf(replacement, StringComparison.Ordinal) < 0)
{
return replacement;
}
}
}
private string GetTextWithReplacementMap(string text, string returnReplacement, string newLineReplacement, List<ValueTuple<int, int>> replacementMap)
{
var delta = 0;
var returnLength = returnReplacement.Length;
var newLineLength = newLineReplacement.Length;
var sb = StringBuilderPool.Allocate();
for (var i = 0; i < text.Length; i++)
{
var ch = text[i];
if (ch == '\r')
{
sb.Append(returnReplacement);
delta += returnLength - 1;
replacementMap.Add(ValueTuple.Create(i + delta, delta));
continue;
}
else if (ch == '\n')
{
sb.Append(newLineReplacement);
delta += newLineLength - 1;
replacementMap.Add(ValueTuple.Create(i + delta, delta));
continue;
}
sb.Append(ch);
}
return StringBuilderPool.ReturnAndFree(sb);
}
private Span AdjustSpan(Span span, List<ValueTuple<int, int>> replacementMap)
{
var start = span.Start;
var end = span.End;
for (var i = 0; i < replacementMap.Count; i++)
{
var positionAndDelta = replacementMap[i];
if (positionAndDelta.Item1 <= span.Start)
{
start = span.Start - positionAndDelta.Item2;
}
if (positionAndDelta.Item1 <= span.End)
{
end = span.End - positionAndDelta.Item2;
}
if (positionAndDelta.Item1 > span.End)
{
break;
}
}
return Span.FromBounds(start, end);
}
public IEnumerable<TextSpan> GetEditorVisibleSpans()
{
var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer();
var projectionDataBuffer = _containedLanguage.DataBuffer as IProjectionBuffer;
if (projectionDataBuffer != null)
{
return projectionDataBuffer.CurrentSnapshot
.GetSourceSpans()
.Where(ss => ss.Snapshot.TextBuffer == subjectBuffer)
.Select(s => s.Span.ToTextSpan())
.OrderBy(s => s.Start);
}
else
{
return SpecializedCollections.EmptyEnumerable<TextSpan>();
}
}
private static void ApplyChanges(
IProjectionBuffer subjectBuffer,
IEnumerable<TextChange> changes,
IList<TextSpan> visibleSpansInOriginal,
out IEnumerable<int> affectedVisibleSpansInNew)
{
using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null))
{
var affectedSpans = SharedPools.Default<HashSet<int>>().AllocateAndClear();
affectedVisibleSpansInNew = affectedSpans;
var currentVisibleSpanIndex = 0;
foreach (var change in changes)
{
// Find the next visible span that either overlaps or intersects with
while (currentVisibleSpanIndex < visibleSpansInOriginal.Count &&
visibleSpansInOriginal[currentVisibleSpanIndex].End < change.Span.Start)
{
currentVisibleSpanIndex++;
}
// no more place to apply text changes
if (currentVisibleSpanIndex >= visibleSpansInOriginal.Count)
{
break;
}
var newText = change.NewText;
var span = change.Span.ToSpan();
edit.Replace(span, newText);
affectedSpans.Add(currentVisibleSpanIndex);
}
edit.Apply();
}
}
private void AdjustIndentation(IProjectionBuffer subjectBuffer, IEnumerable<int> visibleSpanIndex)
{
if (!visibleSpanIndex.Any())
{
return;
}
var snapshot = subjectBuffer.CurrentSnapshot;
var document = _workspace.CurrentSolution.GetDocument(this.Id);
if (!document.SupportsSyntaxTree)
{
return;
}
var originalText = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
Contract.Requires(object.ReferenceEquals(originalText, snapshot.AsText()));
var root = document.GetSyntaxRootSynchronously(CancellationToken.None);
var editorOptionsFactory = _componentModel.GetService<IEditorOptionsFactoryService>();
var editorOptions = editorOptionsFactory.GetOptions(_containedLanguage.DataBuffer);
var options = _workspace.Options
.WithChangedOption(FormattingOptions.UseTabs, root.Language, !editorOptions.IsConvertTabsToSpacesEnabled())
.WithChangedOption(FormattingOptions.TabSize, root.Language, editorOptions.GetTabSize())
.WithChangedOption(FormattingOptions.IndentationSize, root.Language, editorOptions.GetIndentSize());
using (var pooledObject = SharedPools.Default<List<TextSpan>>().GetPooledObject())
{
var spans = pooledObject.Object;
spans.AddRange(this.GetEditorVisibleSpans());
using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null))
{
foreach (var spanIndex in visibleSpanIndex)
{
var rule = GetBaseIndentationRule(root, originalText, spans, spanIndex);
var visibleSpan = spans[spanIndex];
AdjustIndentationForSpan(document, edit, visibleSpan, rule, options);
}
edit.Apply();
}
}
}
private void AdjustIndentationForSpan(
Document document, ITextEdit edit, TextSpan visibleSpan, IFormattingRule baseIndentationRule, OptionSet options)
{
var root = document.GetSyntaxRootSynchronously(CancellationToken.None);
using (var rulePool = SharedPools.Default<List<IFormattingRule>>().GetPooledObject())
using (var spanPool = SharedPools.Default<List<TextSpan>>().GetPooledObject())
{
var venusFormattingRules = rulePool.Object;
var visibleSpans = spanPool.Object;
venusFormattingRules.Add(baseIndentationRule);
venusFormattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance);
var formattingRules = venusFormattingRules.Concat(Formatter.GetDefaultFormattingRules(document));
var workspace = document.Project.Solution.Workspace;
var changes = Formatter.GetFormattedTextChanges(
root, new TextSpan[] { CommonFormattingHelpers.GetFormattingSpan(root, visibleSpan) },
workspace, options, formattingRules, CancellationToken.None);
visibleSpans.Add(visibleSpan);
var newChanges = FilterTextChanges(document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None), visibleSpans, changes.ToReadOnlyCollection()).Where(t => visibleSpan.Contains(t.Span));
foreach (var change in newChanges)
{
edit.Replace(change.Span.ToSpan(), change.NewText);
}
}
}
public BaseIndentationFormattingRule GetBaseIndentationRule(SyntaxNode root, SourceText text, List<TextSpan> spans, int spanIndex)
{
if (_hostType == HostType.Razor)
{
var currentSpanIndex = spanIndex;
TextSpan visibleSpan;
TextSpan visibleTextSpan;
GetVisibleAndTextSpan(text, spans, currentSpanIndex, out visibleSpan, out visibleTextSpan);
var end = visibleSpan.End;
var current = root.FindToken(visibleTextSpan.Start).Parent;
while (current != null)
{
if (current.Span.Start == visibleTextSpan.Start)
{
var blockType = GetRazorCodeBlockType(visibleSpan.Start);
if (blockType == RazorCodeBlockType.Explicit)
{
var baseIndentation = GetBaseIndentation(root, text, visibleSpan);
return new BaseIndentationFormattingRule(root, TextSpan.FromBounds(visibleSpan.Start, end), baseIndentation, _vbHelperFormattingRule);
}
}
if (current.Span.Start < visibleSpan.Start)
{
var blockType = GetRazorCodeBlockType(visibleSpan.Start);
if (blockType == RazorCodeBlockType.Block || blockType == RazorCodeBlockType.Helper)
{
var baseIndentation = GetBaseIndentation(root, text, visibleSpan);
return new BaseIndentationFormattingRule(root, TextSpan.FromBounds(visibleSpan.Start, end), baseIndentation, _vbHelperFormattingRule);
}
if (currentSpanIndex == 0)
{
break;
}
GetVisibleAndTextSpan(text, spans, --currentSpanIndex, out visibleSpan, out visibleTextSpan);
continue;
}
current = current.Parent;
}
}
var span = spans[spanIndex];
var indentation = GetBaseIndentation(root, text, span);
return new BaseIndentationFormattingRule(root, span, indentation, _vbHelperFormattingRule);
}
private void GetVisibleAndTextSpan(SourceText text, List<TextSpan> spans, int spanIndex, out TextSpan visibleSpan, out TextSpan visibleTextSpan)
{
visibleSpan = spans[spanIndex];
visibleTextSpan = GetVisibleTextSpan(text, visibleSpan);
if (visibleTextSpan.IsEmpty)
{
// span has no text in them
visibleTextSpan = visibleSpan;
}
}
private int GetBaseIndentation(SyntaxNode root, SourceText text, TextSpan span)
{
// Is this right? We should probably get this from the IVsContainedLanguageHost instead.
var editorOptionsFactory = _componentModel.GetService<IEditorOptionsFactoryService>();
var editorOptions = editorOptionsFactory.GetOptions(_containedLanguage.DataBuffer);
var additionalIndentation = GetAdditionalIndentation(root, text, span);
string baseIndentationString;
int parent, indentSize, useTabs = 0, tabSize = 0;
// Skip over the first line, since it's in "Venus space" anyway.
var startingLine = text.Lines.GetLineFromPosition(span.Start);
for (var line = startingLine; line.Start < span.End; line = text.Lines[line.LineNumber + 1])
{
Marshal.ThrowExceptionForHR(
this.ContainedLanguage.ContainedLanguageHost.GetLineIndent(
line.LineNumber,
out baseIndentationString,
out parent,
out indentSize,
out useTabs,
out tabSize));
if (!string.IsNullOrEmpty(baseIndentationString))
{
return baseIndentationString.GetColumnFromLineOffset(baseIndentationString.Length, editorOptions.GetTabSize()) + additionalIndentation;
}
}
return additionalIndentation;
}
private TextSpan GetVisibleTextSpan(SourceText text, TextSpan visibleSpan, bool uptoFirstAndLastLine = false)
{
var start = visibleSpan.Start;
for (; start < visibleSpan.End; start++)
{
if (!char.IsWhiteSpace(text[start]))
{
break;
}
}
var end = visibleSpan.End - 1;
if (start <= end)
{
for (; start <= end; end--)
{
if (!char.IsWhiteSpace(text[end]))
{
break;
}
}
}
if (uptoFirstAndLastLine)
{
var firstLine = text.Lines.GetLineFromPosition(visibleSpan.Start);
var lastLine = text.Lines.GetLineFromPosition(visibleSpan.End);
if (firstLine.LineNumber < lastLine.LineNumber)
{
start = (start < firstLine.End) ? start : firstLine.End;
end = (lastLine.Start < end + 1) ? end : lastLine.Start - 1;
}
}
return (start <= end) ? TextSpan.FromBounds(start, end + 1) : default(TextSpan);
}
private int GetAdditionalIndentation(SyntaxNode root, SourceText text, TextSpan span)
{
if (_hostType == HostType.HTML)
{
return _workspace.Options.GetOption(FormattingOptions.IndentationSize, this.Project.Language);
}
if (_hostType == HostType.Razor)
{
var type = GetRazorCodeBlockType(span.Start);
// razor block
if (type == RazorCodeBlockType.Block)
{
// more workaround for csharp razor case. when } for csharp razor code block is just typed, "}" exist
// in both subject and surface buffer and there is no easy way to figure out who owns } just typed.
// in this case, we let razor owns it. later razor will remove } from subject buffer if it is something
// razor owns.
if (this.Project.Language == LanguageNames.CSharp)
{
var textSpan = GetVisibleTextSpan(text, span);
var end = textSpan.End - 1;
if (end >= 0 && text[end] == '}')
{
var token = root.FindToken(end);
var syntaxFact = _workspace.Services.GetLanguageServices(Project.Language).GetService<ISyntaxFactsService>();
if (token.Span.Start == end && syntaxFact != null)
{
SyntaxToken openBrace;
if (syntaxFact.TryGetCorrespondingOpenBrace(token, out openBrace) && !textSpan.Contains(openBrace.Span))
{
return 0;
}
}
}
}
// same as C#, but different text is in the buffer
if (this.Project.Language == LanguageNames.VisualBasic)
{
var textSpan = GetVisibleTextSpan(text, span);
var subjectSnapshot = _containedLanguage.SubjectBuffer.CurrentSnapshot;
var end = textSpan.End - 1;
if (end >= 0)
{
var ch = subjectSnapshot[end];
if (CheckCode(subjectSnapshot, textSpan.End, ch, VBRazorBlock, checkAt: false) ||
CheckCode(subjectSnapshot, textSpan.End, ch, FunctionsRazor, checkAt: false))
{
var token = root.FindToken(end, findInsideTrivia: true);
var syntaxFact = _workspace.Services.GetLanguageServices(Project.Language).GetService<ISyntaxFactsService>();
if (token.Span.End == textSpan.End && syntaxFact != null)
{
if (syntaxFact.IsSkippedTokensTrivia(token.Parent))
{
return 0;
}
}
}
}
}
return _workspace.Options.GetOption(FormattingOptions.IndentationSize, this.Project.Language);
}
}
return 0;
}
private RazorCodeBlockType GetRazorCodeBlockType(int position)
{
Debug.Assert(_hostType == HostType.Razor);
var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer();
var subjectSnapshot = subjectBuffer.CurrentSnapshot;
var surfaceSnapshot = ((IProjectionBuffer)_containedLanguage.DataBuffer).CurrentSnapshot;
var surfacePoint = surfaceSnapshot.MapFromSourceSnapshot(new SnapshotPoint(subjectSnapshot, position), PositionAffinity.Predecessor);
if (!surfacePoint.HasValue)
{
// how this can happen?
return RazorCodeBlockType.Implicit;
}
var ch = char.ToLower(surfaceSnapshot[Math.Max(surfacePoint.Value - 1, 0)]);
// razor block
if (IsCodeBlock(surfaceSnapshot, surfacePoint.Value, ch))
{
return RazorCodeBlockType.Block;
}
if (ch == RazorExplicit)
{
return RazorCodeBlockType.Explicit;
}
if (CheckCode(surfaceSnapshot, surfacePoint.Value, HelperRazor))
{
return RazorCodeBlockType.Helper;
}
return RazorCodeBlockType.Implicit;
}
private bool IsCodeBlock(ITextSnapshot surfaceSnapshot, int position, char ch)
{
if (this.Project.Language == LanguageNames.CSharp)
{
return CheckCode(surfaceSnapshot, position, ch, CSharpRazorBlock) ||
CheckCode(surfaceSnapshot, position, ch, FunctionsRazor, CSharpRazorBlock);
}
if (this.Project.Language == LanguageNames.VisualBasic)
{
return CheckCode(surfaceSnapshot, position, ch, VBRazorBlock) ||
CheckCode(surfaceSnapshot, position, ch, FunctionsRazor);
}
return false;
}
private bool CheckCode(ITextSnapshot snapshot, int position, char ch, string tag, bool checkAt = true)
{
if (ch != tag[tag.Length - 1] || position < tag.Length)
{
return false;
}
var start = position - tag.Length;
var razorTag = snapshot.GetText(start, tag.Length);
return string.Equals(razorTag, tag, StringComparison.OrdinalIgnoreCase) && (!checkAt || snapshot[start - 1] == RazorExplicit);
}
private bool CheckCode(ITextSnapshot snapshot, int position, string tag)
{
int i = position - 1;
if (i < 0)
{
return false;
}
for (; i >= 0; i--)
{
if (!char.IsWhiteSpace(snapshot[i]))
{
break;
}
}
var ch = snapshot[i];
position = i + 1;
return CheckCode(snapshot, position, ch, tag);
}
private bool CheckCode(ITextSnapshot snapshot, int position, char ch, string tag1, string tag2)
{
if (!CheckCode(snapshot, position, ch, tag2, checkAt: false))
{
return false;
}
return CheckCode(snapshot, position - tag2.Length, tag1);
}
public ITextUndoHistory GetTextUndoHistory()
{
// In Venus scenarios, the undo history is associated with the data buffer
return _componentModel.GetService<ITextUndoHistoryRegistry>().GetHistory(_containedLanguage.DataBuffer);
}
public uint GetItemId()
{
AssertIsForeground();
if (_itemMoniker == null)
{
return (uint)VSConstants.VSITEMID.Nil;
}
uint itemId;
return Project.Hierarchy.ParseCanonicalName(_itemMoniker, out itemId) == VSConstants.S_OK
? itemId
: (uint)VSConstants.VSITEMID.Nil;
}
private enum RazorCodeBlockType
{
Block,
Explicit,
Implicit,
Helper
}
private enum HostType
{
HTML,
Razor,
XOML
}
}
}
| |
/*
* 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 Apache.Ignite.Core.Tests.Services
{
using System;
using System.Collections;
using System.Collections.Generic;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Platform.Model;
/// <summary>
/// Explicit service proxy over dynamic variable.
/// </summary>
public class JavaServiceDynamicProxy : IJavaService
{
/** */
private readonly dynamic _svc;
/** */
public JavaServiceDynamicProxy(dynamic svc)
{
_svc = svc;
}
/** <inheritDoc /> */
public bool isCancelled()
{
return _svc.isCancelled();
}
/** <inheritDoc /> */
public bool isInitialized()
{
return _svc.isInitialized();
}
/** <inheritDoc /> */
public bool isExecuted()
{
return _svc.isExecuted();
}
/** <inheritDoc /> */
public byte test(byte x)
{
return _svc.test(x);
}
/** <inheritDoc /> */
public short test(short x)
{
return _svc.test(x);
}
/** <inheritDoc /> */
public int test(int x)
{
return _svc.test(x);
}
/** <inheritDoc /> */
public long test(long x)
{
return _svc.test(x);
}
/** <inheritDoc /> */
public float test(float x)
{
return _svc.test(x);
}
/** <inheritDoc /> */
public double test(double x)
{
return _svc.test(x);
}
/** <inheritDoc /> */
public char test(char x)
{
return _svc.test(x);
}
/** <inheritDoc /> */
public string test(string x)
{
return _svc.test(x);
}
/** <inheritDoc /> */
public bool test(bool x)
{
return _svc.test(x);
}
/** <inheritDoc /> */
public DateTime test(DateTime x)
{
return _svc.test(x);
}
/** <inheritDoc /> */
public Guid test(Guid x)
{
return _svc.test(x);
}
/** <inheritDoc /> */
public byte? testWrapper(byte? x)
{
return _svc.testWrapper(x);
}
/** <inheritDoc /> */
public short? testWrapper(short? x)
{
return _svc.testWrapper(x);
}
/** <inheritDoc /> */
public int? testWrapper(int? x)
{
return _svc.testWrapper(x);
}
/** <inheritDoc /> */
public long? testWrapper(long? x)
{
return _svc.testWrapper(x);
}
/** <inheritDoc /> */
public float? testWrapper(float? x)
{
return _svc.testWrapper(x);
}
/** <inheritDoc /> */
public double? testWrapper(double? x)
{
return _svc.testWrapper(x);
}
/** <inheritDoc /> */
public char? testWrapper(char? x)
{
return _svc.testWrapper(x);
}
/** <inheritDoc /> */
public bool? testWrapper(bool? x)
{
return _svc.testWrapper(x);
}
/** <inheritDoc /> */
public byte[] testArray(byte[] x)
{
return _svc.testArray(x);
}
/** <inheritDoc /> */
public short[] testArray(short[] x)
{
return _svc.testArray(x);
}
/** <inheritDoc /> */
public int[] testArray(int[] x)
{
return _svc.testArray(x);
}
/** <inheritDoc /> */
public long[] testArray(long[] x)
{
return _svc.testArray(x);
}
/** <inheritDoc /> */
public float[] testArray(float[] x)
{
return _svc.testArray(x);
}
/** <inheritDoc /> */
public double[] testArray(double[] x)
{
return _svc.testArray(x);
}
/** <inheritDoc /> */
public char[] testArray(char[] x)
{
return _svc.testArray(x);
}
/** <inheritDoc /> */
public string[] testArray(string[] x)
{
return _svc.testArray(x);
}
/** <inheritDoc /> */
public bool[] testArray(bool[] x)
{
return _svc.testArray(x);
}
/** <inheritDoc /> */
public DateTime?[] testArray(DateTime?[] x)
{
return _svc.testArray(x);
}
/** <inheritDoc /> */
public Guid?[] testArray(Guid?[] x)
{
return _svc.testArray(x);
}
/** <inheritDoc /> */
public int test(int x, string y)
{
return _svc.test(x, y);
}
/** <inheritDoc /> */
public int test(string x, int y)
{
return _svc.test(x, y);
}
/** <inheritDoc /> */
public int? testNull(int? x)
{
return _svc.testNull(x);
}
/** <inheritDoc /> */
public DateTime? testNullTimestamp(DateTime? x)
{
return _svc.testNullTimestamp(x);
}
/** <inheritDoc /> */
public Guid? testNullUUID(Guid? x)
{
return _svc.testNullUUID(x);
}
/** <inheritDoc /> */
public int testParams(params object[] args)
{
return _svc.testParams(args);
}
/** <inheritDoc /> */
public PlatformComputeBinarizable testBinarizable(PlatformComputeBinarizable x)
{
return _svc.testBinarizable(x);
}
/** <inheritDoc /> */
public object[] testBinarizableArrayOfObjects(object[] x)
{
return _svc.testBinarizableArrayOfObjects(x);
}
/** <inheritDoc /> */
public IBinaryObject[] testBinaryObjectArray(IBinaryObject[] x)
{
return _svc.testBinaryObjectArray(x);
}
/** <inheritDoc /> */
public PlatformComputeBinarizable[] testBinarizableArray(PlatformComputeBinarizable[] x)
{
return _svc.testBinarizableArray(x);
}
/** <inheritDoc /> */
public ICollection testBinarizableCollection(ICollection x)
{
return _svc.testBinarizableCollection(x);
}
/** <inheritDoc /> */
public IBinaryObject testBinaryObject(IBinaryObject x)
{
return _svc.testBinaryObject(x);
}
/** <inheritDoc /> */
public Address testAddress(Address addr)
{
return _svc.testAddress(addr);
}
/** <inheritDoc /> */
public int testOverload(int count, Employee[] emps)
{
return _svc.testOverload(count, emps);
}
/** <inheritDoc /> */
public int testOverload(int first, int second)
{
return _svc.testOverload(first, second);
}
/** <inheritDoc /> */
public int testOverload(int count, Parameter[] param)
{
return _svc.testOverload(count, param);
}
/** <inheritDoc /> */
public Employee[] testEmployees(Employee[] emps)
{
return _svc.testEmployees(emps);
}
public Account[] testAccounts()
{
return _svc.testAccounts();
}
public User[] testUsers()
{
return _svc.testUsers();
}
/** <inheritDoc /> */
public ICollection testDepartments(ICollection deps)
{
return _svc.testDepartments(deps);
}
/** <inheritDoc /> */
public IDictionary testMap(IDictionary<Key, Value> dict)
{
return _svc.testMap(dict);
}
/** <inheritDoc /> */
public void testDateArray(DateTime?[] dates)
{
_svc.testDateArray(dates);
}
/** <inheritDoc /> */
public DateTime testDate(DateTime date)
{
return _svc.testDate(date);
}
/** <inheritDoc /> */
public void testUTCDateFromCache()
{
_svc.testUTCDateFromCache();
}
/** <inheritDoc /> */
public void testLocalDateFromCache()
{
_svc.testLocalDateFromCache();
}
/** <inheritDoc /> */
public void testException(string exceptionClass)
{
_svc.testException(exceptionClass);
}
/** <inheritDoc /> */
public void sleep(long delayMs)
{
_svc.sleep(delayMs);
}
/** <inheritDoc /> */
public object testRoundtrip(object x)
{
return x;
}
/** <inheritDoc /> */
public object contextAttribute(string name)
{
return _svc.contextAttribute(name);
}
}
}
| |
// 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.Drawing {
using System.Runtime.Serialization.Formatters;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Win32;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Reflection;
/// <include file='doc\RectangleConverter.uex' path='docs/doc[@for="RectangleConverter"]/*' />
/// <devdoc>
/// RectangleConverter is a class that can be used to convert
/// rectangles from one data type to another. Access this
/// class through the TypeDescriptor.
/// </devdoc>
public class RectangleConverter : TypeConverter {
/// <include file='doc\RectangleConverter.uex' path='docs/doc[@for="RectangleConverter.CanConvertFrom"]/*' />
/// <devdoc>
/// Determines if this converter can convert an object in the given source
/// type to the native type of the converter.
/// </devdoc>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
if (sourceType == typeof(string)) {
return true;
}
return base.CanConvertFrom(context, sourceType);
}
/// <include file='doc\RectangleConverter.uex' path='docs/doc[@for="RectangleConverter.CanConvertTo"]/*' />
/// <devdoc>
/// <para>Gets a value indicating whether this converter can
/// convert an object to the given destination type using the context.</para>
/// </devdoc>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
if (destinationType == typeof(InstanceDescriptor)) {
return true;
}
return base.CanConvertTo(context, destinationType);
}
/// <include file='doc\RectangleConverter.uex' path='docs/doc[@for="RectangleConverter.ConvertFrom"]/*' />
/// <devdoc>
/// Converts the given object to the converter's native type.
/// </devdoc>
[SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")]
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
string strValue = value as string;
if (strValue != null) {
string text = strValue.Trim();
if (text.Length == 0) {
return null;
}
else {
// Parse 4 integer values.
//
if (culture == null) {
culture = CultureInfo.CurrentCulture;
}
char sep = culture.TextInfo.ListSeparator[0];
string[] tokens = text.Split(new char[] {sep});
int[] values = new int[tokens.Length];
TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
for (int i = 0; i < values.Length; i++) {
// Note: ConvertFromString will raise exception if value cannot be converted.
values[i] = (int)intConverter.ConvertFromString(context, culture, tokens[i]);
}
if (values.Length == 4) {
return new Rectangle(values[0], values[1], values[2], values[3]);
}
else {
throw new ArgumentException(SR.Format(SR.TextParseFailedFormat,
"text",
text,
"x, y, width, height"));
}
}
}
return base.ConvertFrom(context, culture, value);
}
/// <include file='doc\RectangleConverter.uex' path='docs/doc[@for="RectangleConverter.ConvertTo"]/*' />
/// <devdoc>
/// Converts the given object to another type. The most common types to convert
/// are to and from a string object. The default implementation will make a call
/// to ToString on the object if the object is valid and if the destination
/// type is string. If this cannot convert to the desitnation type, this will
/// throw a NotSupportedException.
/// </devdoc>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
if (destinationType == null) {
throw new ArgumentNullException(nameof(destinationType));
}
if( value is Rectangle ){
if (destinationType == typeof(string)) {
Rectangle rect = (Rectangle)value;
if (culture == null) {
culture = CultureInfo.CurrentCulture;
}
string sep = culture.TextInfo.ListSeparator + " ";
TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
string[] args = new string[4];
int nArg = 0;
// Note: ConvertToString will raise exception if value cannot be converted.
args[nArg++] = intConverter.ConvertToString(context, culture, rect.X);
args[nArg++] = intConverter.ConvertToString(context, culture, rect.Y);
args[nArg++] = intConverter.ConvertToString(context, culture, rect.Width);
args[nArg++] = intConverter.ConvertToString(context, culture, rect.Height);
return string.Join(sep, args);
}
if (destinationType == typeof(InstanceDescriptor)) {
Rectangle rect = (Rectangle)value;
ConstructorInfo ctor = typeof(Rectangle).GetConstructor(new Type[] {
typeof(int), typeof(int), typeof(int), typeof(int)});
if (ctor != null) {
return new InstanceDescriptor(ctor, new object[] {
rect.X, rect.Y, rect.Width, rect.Height});
}
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
/// <include file='doc\RectangleConverter.uex' path='docs/doc[@for="RectangleConverter.CreateInstance"]/*' />
/// <devdoc>
/// Creates an instance of this type given a set of property values
/// for the object. This is useful for objects that are immutable, but still
/// want to provide changable properties.
/// </devdoc>
[SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")]
[SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")]
public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) {
if( propertyValues == null ){
throw new ArgumentNullException( nameof(propertyValues) );
}
object x = propertyValues["X"];
object y = propertyValues["Y"];
object width = propertyValues["Width"];
object height = propertyValues["Height"];
if(x == null || y == null || width == null || height == null ||
!(x is int) || !(y is int) || !(width is int) || !(height is int) ) {
throw new ArgumentException(SR.PropertyValueInvalidEntry);
}
return new Rectangle((int)x,
(int)y,
(int)width,
(int)height);
}
/// <include file='doc\RectangleConverter.uex' path='docs/doc[@for="RectangleConverter.GetCreateInstanceSupported"]/*' />
/// <devdoc>
/// Determines if changing a value on this object should require a call to
/// CreateInstance to create a new value.
/// </devdoc>
public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) {
return true;
}
/// <include file='doc\RectangleConverter.uex' path='docs/doc[@for="RectangleConverter.GetProperties"]/*' />
/// <devdoc>
/// Retrieves the set of properties for this type. By default, a type has
/// does not return any properties. An easy implementation of this method
/// can just call TypeDescriptor.GetProperties for the correct data type.
/// </devdoc>
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) {
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(Rectangle), attributes);
return props.Sort(new string[] {"X", "Y", "Width", "Height"});
}
/// <include file='doc\RectangleConverter.uex' path='docs/doc[@for="RectangleConverter.GetPropertiesSupported"]/*' />
/// <devdoc>
/// Determines if this object supports properties. By default, this
/// is false.
/// </devdoc>
public override bool GetPropertiesSupported(ITypeDescriptorContext context) {
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace MvcMusicStore.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/********************************************************
* ADO.NET 2.0 Data Provider for SQLite Version 3.X
* Written by Robert Simpson (robert@blackcastlesoft.com)
*
* Released to the public domain, use at your own risk!
********************************************************/
namespace Mono.Data.Sqlite
{
using System;
using System.Data;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Text;
#if !PLATFORM_COMPACTFRAMEWORK
using System.ComponentModel.Design;
#endif
/// <summary>
/// This base class provides datatype conversion services for the SQLite provider.
/// </summary>
public abstract class SqliteConvert
{
/// <summary>
/// The value for the Unix epoch (e.g. January 1, 1970 at midnight, in UTC).
/// </summary>
protected static readonly DateTime UnixEpoch =
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// An array of ISO8601 datetime formats we support conversion from
/// </summary>
private static string[] _datetimeFormats = new string[] {
"THHmmssK",
"THHmmK",
"HH:mm:ss.FFFFFFFK",
"HH:mm:ssK",
"HH:mmK",
"yyyy-MM-dd HH:mm:ss.FFFFFFFK", /* NOTE: UTC default (5). */
"yyyy-MM-dd HH:mm:ssK",
"yyyy-MM-dd HH:mmK",
"yyyy-MM-ddTHH:mm:ss.FFFFFFFK",
"yyyy-MM-ddTHH:mmK",
"yyyy-MM-ddTHH:mm:ssK",
"yyyyMMddHHmmssK",
"yyyyMMddHHmmK",
"yyyyMMddTHHmmssFFFFFFFK",
"THHmmss",
"THHmm",
"HH:mm:ss.FFFFFFF",
"HH:mm:ss",
"HH:mm",
"yyyy-MM-dd HH:mm:ss.FFFFFFF", /* NOTE: Non-UTC default (19). */
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd HH:mm",
"yyyy-MM-ddTHH:mm:ss.FFFFFFF",
"yyyy-MM-ddTHH:mm",
"yyyy-MM-ddTHH:mm:ss",
"yyyyMMddHHmmss",
"yyyyMMddHHmm",
"yyyyMMddTHHmmssFFFFFFF",
"yyyy-MM-dd",
"yyyyMMdd",
"yy-MM-dd"
};
/// <summary>
/// An UTF-8 Encoding instance, so we can convert strings to and from UTF-8
/// </summary>
private static Encoding _utf8 = new UTF8Encoding();
/// <summary>
/// The default DateTime format for this instance
/// </summary>
internal SQLiteDateFormats _datetimeFormat;
/// <summary>
/// Initializes the conversion class
/// </summary>
/// <param name="fmt">The default date/time format to use for this instance</param>
internal SqliteConvert(SQLiteDateFormats fmt)
{
_datetimeFormat = fmt;
}
#region UTF-8 Conversion Functions
/// <summary>
/// Converts a string to a UTF-8 encoded byte array sized to include a null-terminating character.
/// </summary>
/// <param name="sourceText">The string to convert to UTF-8</param>
/// <returns>A byte array containing the converted string plus an extra 0 terminating byte at the end of the array.</returns>
public static byte[] ToUTF8(string sourceText)
{
Byte[] byteArray;
int nlen = _utf8.GetByteCount(sourceText) + 1;
byteArray = new byte[nlen];
nlen = _utf8.GetBytes(sourceText, 0, sourceText.Length, byteArray, 0);
byteArray[nlen] = 0;
return byteArray;
}
/// <summary>
/// Convert a DateTime to a UTF-8 encoded, zero-terminated byte array.
/// </summary>
/// <remarks>
/// This function is a convenience function, which first calls ToString() on the DateTime, and then calls ToUTF8() with the
/// string result.
/// </remarks>
/// <param name="dateTimeValue">The DateTime to convert.</param>
/// <returns>The UTF-8 encoded string, including a 0 terminating byte at the end of the array.</returns>
public byte[] ToUTF8(DateTime dateTimeValue)
{
return ToUTF8(ToString(dateTimeValue));
}
/// <summary>
/// Converts a UTF-8 encoded IntPtr of the specified length into a .NET string
/// </summary>
/// <param name="nativestring">The pointer to the memory where the UTF-8 string is encoded</param>
/// <param name="nativestringlen">The number of bytes to decode</param>
/// <returns>A string containing the translated character(s)</returns>
public virtual string ToString(IntPtr nativestring, int nativestringlen)
{
return UTF8ToString(nativestring, nativestringlen);
}
/// <summary>
/// Converts a UTF-8 encoded IntPtr of the specified length into a .NET string
/// </summary>
/// <param name="nativestring">The pointer to the memory where the UTF-8 string is encoded</param>
/// <param name="nativestringlen">The number of bytes to decode</param>
/// <returns>A string containing the translated character(s)</returns>
public static string UTF8ToString(IntPtr nativestring, int nativestringlen)
{
if (nativestringlen == 0 || nativestring == IntPtr.Zero) return "";
if (nativestringlen == -1)
{
do
{
nativestringlen++;
} while (Marshal.ReadByte(nativestring, nativestringlen) != 0);
}
byte[] byteArray = new byte[nativestringlen];
Marshal.Copy(nativestring, byteArray, 0, nativestringlen);
return _utf8.GetString(byteArray, 0, nativestringlen);
}
#endregion
#region DateTime Conversion Functions
/// <summary>
/// Converts a string into a DateTime, using the current DateTimeFormat specified for the connection when it was opened.
/// </summary>
/// <remarks>
/// Acceptable ISO8601 DateTime formats are:
/// yyyy-MM-dd HH:mm:ss
/// yyyyMMddHHmmss
/// yyyyMMddTHHmmssfffffff
/// yyyy-MM-dd
/// yy-MM-dd
/// yyyyMMdd
/// HH:mm:ss
/// THHmmss
/// </remarks>
/// <param name="dateText">The string containing either a Tick value, a JulianDay double, or an ISO8601-format string</param>
/// <returns>A DateTime value</returns>
public DateTime ToDateTime(string dateText)
{
switch (_datetimeFormat)
{
case SQLiteDateFormats.Ticks:
return new DateTime(Convert.ToInt64(dateText, CultureInfo.InvariantCulture));
case SQLiteDateFormats.JulianDay:
return ToDateTime(Convert.ToDouble(dateText, CultureInfo.InvariantCulture));
case SQLiteDateFormats.UnixEpoch:
return UnixEpoch.AddSeconds(Convert.ToInt32(dateText, CultureInfo.InvariantCulture));
default:
return DateTime.ParseExact(dateText, _datetimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None);
}
}
/// <summary>
/// Converts a julianday value into a DateTime
/// </summary>
/// <param name="julianDay">The value to convert</param>
/// <returns>A .NET DateTime</returns>
public DateTime ToDateTime(double julianDay)
{
return DateTime.FromOADate(julianDay - 2415018.5);
}
/// <summary>
/// Converts a DateTime struct to a JulianDay double
/// </summary>
/// <param name="value">The DateTime to convert</param>
/// <returns>The JulianDay value the Datetime represents</returns>
public double ToJulianDay(DateTime value)
{
return value.ToOADate() + 2415018.5;
}
/// <summary>
/// Converts a DateTime to a string value, using the current DateTimeFormat specified for the connection when it was opened.
/// </summary>
/// <param name="dateValue">The DateTime value to convert</param>
/// <returns>Either a string consisting of the tick count for DateTimeFormat.Ticks, a JulianDay double, or a date/time in ISO8601 format.</returns>
public string ToString(DateTime dateValue)
{
switch (_datetimeFormat)
{
case SQLiteDateFormats.Ticks:
return dateValue.Ticks.ToString(CultureInfo.InvariantCulture);
case SQLiteDateFormats.JulianDay:
return ToJulianDay(dateValue).ToString(CultureInfo.InvariantCulture);
case SQLiteDateFormats.UnixEpoch:
return ((long)(dateValue.Subtract(UnixEpoch).Ticks / TimeSpan.TicksPerSecond)).ToString();
default:
return dateValue.ToString(_datetimeFormats[5], CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Internal function to convert a UTF-8 encoded IntPtr of the specified length to a DateTime.
/// </summary>
/// <remarks>
/// This is a convenience function, which first calls ToString() on the IntPtr to convert it to a string, then calls
/// ToDateTime() on the string to return a DateTime.
/// </remarks>
/// <param name="ptr">A pointer to the UTF-8 encoded string</param>
/// <param name="len">The length in bytes of the string</param>
/// <returns>The parsed DateTime value</returns>
internal DateTime ToDateTime(IntPtr ptr, int len)
{
return ToDateTime(ToString(ptr, len));
}
#endregion
/// <summary>
/// Smart method of splitting a string. Skips quoted elements, removes the quotes.
/// </summary>
/// <remarks>
/// This split function works somewhat like the String.Split() function in that it breaks apart a string into
/// pieces and returns the pieces as an array. The primary differences are:
/// <list type="bullet">
/// <item><description>Only one character can be provided as a separator character</description></item>
/// <item><description>Quoted text inside the string is skipped over when searching for the separator, and the quotes are removed.</description></item>
/// </list>
/// Thus, if splitting the following string looking for a comma:<br/>
/// One,Two, "Three, Four", Five<br/>
/// <br/>
/// The resulting array would contain<br/>
/// [0] One<br/>
/// [1] Two<br/>
/// [2] Three, Four<br/>
/// [3] Five<br/>
/// <br/>
/// Note that the leading and trailing spaces were removed from each item during the split.
/// </remarks>
/// <param name="source">Source string to split apart</param>
/// <param name="separator">Separator character</param>
/// <returns>A string array of the split up elements</returns>
public static string[] Split(string source, char separator)
{
char[] toks = new char[2] { '\"', separator };
char[] quot = new char[1] { '\"' };
int n = 0;
List<string> ls = new List<string>();
string s;
while (source.Length > 0)
{
n = source.IndexOfAny(toks, n);
if (n == -1) break;
if (source[n] == toks[0])
{
//source = source.Remove(n, 1);
n = source.IndexOfAny(quot, n + 1);
if (n == -1)
{
//source = "\"" + source;
break;
}
n++;
//source = source.Remove(n, 1);
}
else
{
s = source.Substring(0, n).Trim();
if (s.Length > 1 && s[0] == quot[0] && s[s.Length - 1] == s[0])
s = s.Substring(1, s.Length - 2);
source = source.Substring(n + 1).Trim();
if (s.Length > 0) ls.Add(s);
n = 0;
}
}
if (source.Length > 0)
{
s = source.Trim();
if (s.Length > 1 && s[0] == quot[0] && s[s.Length - 1] == s[0])
s = s.Substring(1, s.Length - 2);
ls.Add(s);
}
string[] ar = new string[ls.Count];
ls.CopyTo(ar, 0);
return ar;
}
/// <summary>
/// Convert a value to true or false.
/// </summary>
/// <param name="source">A string or number representing true or false</param>
/// <returns></returns>
public static bool ToBoolean(object source)
{
if (source is bool) return (bool)source;
return ToBoolean(source.ToString());
}
/// <summary>
/// Convert a string to true or false.
/// </summary>
/// <param name="source">A string representing true or false</param>
/// <returns></returns>
/// <remarks>
/// "yes", "no", "y", "n", "0", "1", "on", "off" as well as Boolean.FalseString and Boolean.TrueString will all be
/// converted to a proper boolean value.
/// </remarks>
public static bool ToBoolean(string source)
{
if (String.Compare(source, bool.TrueString, StringComparison.OrdinalIgnoreCase) == 0) return true;
else if (String.Compare(source, bool.FalseString, StringComparison.OrdinalIgnoreCase) == 0) return false;
switch(source.ToLower())
{
case "yes":
case "y":
case "1":
case "on":
return true;
case "no":
case "n":
case "0":
case "off":
return false;
default:
throw new ArgumentException("source");
}
}
#region Type Conversions
/// <summary>
/// Determines the data type of a column in a statement
/// </summary>
/// <param name="stmt">The statement to retrieve information for</param>
/// <param name="i">The column to retrieve type information on</param>
/// <param name="typ">The SQLiteType to receive the affinity for the given column</param>
internal static void ColumnToType(SqliteStatement stmt, int i, SQLiteType typ)
{
typ.Type = TypeNameToDbType(stmt._sql.ColumnType(stmt, i, out typ.Affinity));
}
/// <summary>
/// Converts a SQLiteType to a .NET Type object
/// </summary>
/// <param name="t">The SQLiteType to convert</param>
/// <returns>Returns a .NET Type object</returns>
internal static Type SQLiteTypeToType(SQLiteType t)
{
if (t.Type == DbType.Object)
return _affinitytotype[(int)t.Affinity];
else
return SqliteConvert.DbTypeToType(t.Type);
}
private static Type[] _affinitytotype = {
typeof(object),
typeof(Int64),
typeof(Double),
typeof(string),
typeof(byte[]),
typeof(object),
typeof(DateTime),
typeof(object)
};
/// <summary>
/// For a given intrinsic type, return a DbType
/// </summary>
/// <param name="typ">The native type to convert</param>
/// <returns>The corresponding (closest match) DbType</returns>
internal static DbType TypeToDbType(Type typ)
{
TypeCode tc = Type.GetTypeCode(typ);
if (tc == TypeCode.Object)
{
if (typ == typeof(byte[])) return DbType.Binary;
if (typ == typeof(Guid)) return DbType.Guid;
return DbType.String;
}
return _typetodbtype[(int)tc];
}
private static DbType[] _typetodbtype = {
DbType.Object,
DbType.Binary,
DbType.Object,
DbType.Boolean,
DbType.SByte,
DbType.SByte,
DbType.Byte,
DbType.Int16, // 7
DbType.UInt16,
DbType.Int32,
DbType.UInt32,
DbType.Int64, // 11
DbType.UInt64,
DbType.Single,
DbType.Double,
DbType.Decimal,
DbType.DateTime,
DbType.Object,
DbType.String,
};
/// <summary>
/// Returns the ColumnSize for the given DbType
/// </summary>
/// <param name="typ">The DbType to get the size of</param>
/// <returns></returns>
internal static int DbTypeToColumnSize(DbType typ)
{
return _dbtypetocolumnsize[(int)typ];
}
private static int[] _dbtypetocolumnsize = {
2147483647, // 0
2147483647, // 1
1, // 2
1, // 3
8, // 4
8, // 5
8, // 6
8, // 7
8, // 8
16, // 9
2,
4,
8,
2147483647,
1,
4,
2147483647,
8,
2,
4,
8,
8,
2147483647,
2147483647,
2147483647,
2147483647, // 25 (Xml)
};
internal static object DbTypeToNumericPrecision(DbType typ)
{
return _dbtypetonumericprecision[(int)typ];
}
private static object[] _dbtypetonumericprecision = {
DBNull.Value, // 0
DBNull.Value, // 1
3,
DBNull.Value,
19,
DBNull.Value, // 5
DBNull.Value, // 6
53,
53,
DBNull.Value,
5,
10,
19,
DBNull.Value,
3,
24,
DBNull.Value,
DBNull.Value,
5,
10,
19,
53,
DBNull.Value,
DBNull.Value,
DBNull.Value
};
internal static object DbTypeToNumericScale(DbType typ)
{
return _dbtypetonumericscale[(int)typ];
}
private static object[] _dbtypetonumericscale = {
DBNull.Value, // 0
DBNull.Value, // 1
0,
DBNull.Value,
4,
DBNull.Value, // 5
DBNull.Value, // 6
DBNull.Value,
DBNull.Value,
DBNull.Value,
0,
0,
0,
DBNull.Value,
0,
DBNull.Value,
DBNull.Value,
DBNull.Value,
0,
0,
0,
0,
DBNull.Value,
DBNull.Value,
DBNull.Value
};
internal static string DbTypeToTypeName(DbType typ)
{
for (int n = 0; n < _dbtypeNames.Length; n++)
{
if (_dbtypeNames[n].dataType == typ)
return _dbtypeNames[n].typeName;
}
return String.Empty;
}
private static SQLiteTypeNames[] _dbtypeNames = {
new SQLiteTypeNames("INTEGER", DbType.Int64),
new SQLiteTypeNames("TINYINT", DbType.Byte),
new SQLiteTypeNames("INT", DbType.Int32),
new SQLiteTypeNames("VARCHAR", DbType.AnsiString),
new SQLiteTypeNames("NVARCHAR", DbType.String),
new SQLiteTypeNames("CHAR", DbType.AnsiStringFixedLength),
new SQLiteTypeNames("NCHAR", DbType.StringFixedLength),
new SQLiteTypeNames("FLOAT", DbType.Double),
new SQLiteTypeNames("REAL", DbType.Single),
new SQLiteTypeNames("BIT", DbType.Boolean),
new SQLiteTypeNames("DECIMAL", DbType.Decimal),
new SQLiteTypeNames("DATETIME", DbType.DateTime),
new SQLiteTypeNames("BLOB", DbType.Binary),
new SQLiteTypeNames("UNIQUEIDENTIFIER", DbType.Guid),
new SQLiteTypeNames("SMALLINT", DbType.Int16),
};
/// <summary>
/// Convert a DbType to a Type
/// </summary>
/// <param name="typ">The DbType to convert from</param>
/// <returns>The closest-match .NET type</returns>
internal static Type DbTypeToType(DbType typ)
{
return _dbtypeToType[(int)typ];
}
private static Type[] _dbtypeToType = {
typeof(string), // 0
typeof(byte[]), // 1
typeof(byte), // 2
typeof(bool), // 3
typeof(decimal), // 4
typeof(DateTime), // 5
typeof(DateTime), // 6
typeof(decimal), // 7
typeof(double), // 8
typeof(Guid), // 9
typeof(Int16),
typeof(Int32),
typeof(Int64),
typeof(object),
typeof(sbyte),
typeof(float),
typeof(string),
typeof(DateTime),
typeof(UInt16),
typeof(UInt32),
typeof(UInt64),
typeof(double),
typeof(string),
typeof(string),
typeof(string),
typeof(string), // 25 (Xml)
};
/// <summary>
/// For a given type, return the closest-match SQLite TypeAffinity, which only understands a very limited subset of types.
/// </summary>
/// <param name="typ">The type to evaluate</param>
/// <returns>The SQLite type affinity for that type.</returns>
internal static TypeAffinity TypeToAffinity(Type typ)
{
TypeCode tc = Type.GetTypeCode(typ);
if (tc == TypeCode.Object)
{
if (typ == typeof(byte[]) || typ == typeof(Guid))
return TypeAffinity.Blob;
else
return TypeAffinity.Text;
}
return _typecodeAffinities[(int)tc];
}
private static TypeAffinity[] _typecodeAffinities = {
TypeAffinity.Null,
TypeAffinity.Blob,
TypeAffinity.Null,
TypeAffinity.Int64,
TypeAffinity.Int64,
TypeAffinity.Int64,
TypeAffinity.Int64,
TypeAffinity.Int64, // 7
TypeAffinity.Int64,
TypeAffinity.Int64,
TypeAffinity.Int64,
TypeAffinity.Int64, // 11
TypeAffinity.Int64,
TypeAffinity.Double,
TypeAffinity.Double,
TypeAffinity.Double,
TypeAffinity.DateTime,
TypeAffinity.Null,
TypeAffinity.Text,
};
/// <summary>
/// For a given type name, return a closest-match .NET type
/// </summary>
/// <param name="Name">The name of the type to match</param>
/// <returns>The .NET DBType the text evaluates to.</returns>
internal static DbType TypeNameToDbType(string Name)
{
if (String.IsNullOrEmpty(Name)) return DbType.Object;
string nameToCompare = Name;
int parenthesis = nameToCompare.IndexOf ('(');
if (parenthesis > 0)
nameToCompare = nameToCompare.Substring (0, parenthesis);
for (int n = 0; n < _typeNames.Length; n++)
{
if (string.Compare(nameToCompare, _typeNames[n].typeName, true, CultureInfo.InvariantCulture) == 0)
return _typeNames[n].dataType;
}
/* http://www.sqlite.org/datatype3.html
* 2.1 Determination Of Column Affinity
* The affinity of a column is determined by the declared type of the column, according to the following rules in the order shown:
* 1. If the declared type contains the string "INT" then it is assigned INTEGER affinity.
* 2. If the declared type of the column contains any of the strings "CHAR", "CLOB", or "TEXT" then that column has TEXT affinity. Notice that the type VARCHAR contains the string "CHAR" and is thus assigned TEXT affinity.
* 3. If the declared type for a column contains the string "BLOB" or if no type is specified then the column has affinity NONE.
* 4. If the declared type for a column contains any of the strings "REAL", "FLOA", or "DOUB" then the column has REAL affinity.
* 5. Otherwise, the affinity is NUMERIC.
*/
if (Name.IndexOf ("INT", StringComparison.OrdinalIgnoreCase) >= 0) {
return DbType.Int64;
} else if (Name.IndexOf ("CHAR", StringComparison.OrdinalIgnoreCase) >= 0
|| Name.IndexOf ("CLOB", StringComparison.OrdinalIgnoreCase) >= 0
|| Name.IndexOf ("TEXT", StringComparison.OrdinalIgnoreCase) >= 0) {
return DbType.String;
} else if (Name.IndexOf ("BLOB", StringComparison.OrdinalIgnoreCase) >= 0 /* || Name == string.Empty // handled at the top of this functin */) {
return DbType.Object;
} else if (Name.IndexOf ("REAL", StringComparison.OrdinalIgnoreCase) >= 0
|| Name.IndexOf ("FLOA", StringComparison.OrdinalIgnoreCase) >= 0
|| Name.IndexOf ("DOUB", StringComparison.OrdinalIgnoreCase) >= 0) {
return DbType.Double;
} else {
return DbType.Object; // This can be anything, so use Object instead of Decimal (which we use otherwise where the type affinity is NUMERIC)
}
}
#endregion
private static SQLiteTypeNames[] _typeNames = {
new SQLiteTypeNames("COUNTER", DbType.Int64),
new SQLiteTypeNames("AUTOINCREMENT", DbType.Int64),
new SQLiteTypeNames("IDENTITY", DbType.Int64),
new SQLiteTypeNames("LONGTEXT", DbType.String),
new SQLiteTypeNames("LONGCHAR", DbType.String),
new SQLiteTypeNames("LONGVARCHAR", DbType.String),
new SQLiteTypeNames("LONG", DbType.Int64),
new SQLiteTypeNames("TINYINT", DbType.Byte),
new SQLiteTypeNames("INTEGER", DbType.Int64),
new SQLiteTypeNames("INT", DbType.Int32),
new SQLiteTypeNames("VARCHAR", DbType.String),
new SQLiteTypeNames("NVARCHAR", DbType.String),
new SQLiteTypeNames("CHAR", DbType.String),
new SQLiteTypeNames("NCHAR", DbType.String),
new SQLiteTypeNames("TEXT", DbType.String),
new SQLiteTypeNames("NTEXT", DbType.String),
new SQLiteTypeNames("STRING", DbType.String),
new SQLiteTypeNames("DOUBLE", DbType.Double),
new SQLiteTypeNames("FLOAT", DbType.Double),
new SQLiteTypeNames("REAL", DbType.Single),
new SQLiteTypeNames("BIT", DbType.Boolean),
new SQLiteTypeNames("YESNO", DbType.Boolean),
new SQLiteTypeNames("LOGICAL", DbType.Boolean),
new SQLiteTypeNames("BOOL", DbType.Boolean),
new SQLiteTypeNames("BOOLEAN", DbType.Boolean),
new SQLiteTypeNames("NUMERIC", DbType.Decimal),
new SQLiteTypeNames("DECIMAL", DbType.Decimal),
new SQLiteTypeNames("MONEY", DbType.Decimal),
new SQLiteTypeNames("CURRENCY", DbType.Decimal),
new SQLiteTypeNames("TIME", DbType.DateTime),
new SQLiteTypeNames("DATE", DbType.DateTime),
new SQLiteTypeNames("SMALLDATE", DbType.DateTime),
new SQLiteTypeNames("BLOB", DbType.Binary),
new SQLiteTypeNames("BINARY", DbType.Binary),
new SQLiteTypeNames("VARBINARY", DbType.Binary),
new SQLiteTypeNames("IMAGE", DbType.Binary),
new SQLiteTypeNames("GENERAL", DbType.Binary),
new SQLiteTypeNames("OLEOBJECT", DbType.Binary),
new SQLiteTypeNames("GUID", DbType.Guid),
new SQLiteTypeNames("GUIDBLOB", DbType.Guid),
new SQLiteTypeNames("UNIQUEIDENTIFIER", DbType.Guid),
new SQLiteTypeNames("MEMO", DbType.String),
new SQLiteTypeNames("NOTE", DbType.String),
new SQLiteTypeNames("SMALLINT", DbType.Int16),
new SQLiteTypeNames("BIGINT", DbType.Int64),
new SQLiteTypeNames("TIMESTAMP", DbType.DateTime),
new SQLiteTypeNames("DATETIME", DbType.DateTime),
};
}
/// <summary>
/// SQLite has very limited types, and is inherently text-based. The first 5 types below represent the sum of all types SQLite
/// understands. The DateTime extension to the spec is for internal use only.
/// </summary>
public enum TypeAffinity
{
/// <summary>
/// Not used
/// </summary>
Uninitialized = 0,
/// <summary>
/// All integers in SQLite default to Int64
/// </summary>
Int64 = 1,
/// <summary>
/// All floating point numbers in SQLite default to double
/// </summary>
Double = 2,
/// <summary>
/// The default data type of SQLite is text
/// </summary>
Text = 3,
/// <summary>
/// Typically blob types are only seen when returned from a function
/// </summary>
Blob = 4,
/// <summary>
/// Null types can be returned from functions
/// </summary>
Null = 5,
/// <summary>
/// Used internally by this provider
/// </summary>
DateTime = 10,
/// <summary>
/// Used internally
/// </summary>
None = 11,
}
/// <summary>
/// This implementation of SQLite for ADO.NET can process date/time fields in databases in only one of three formats. Ticks, ISO8601
/// and JulianDay.
/// </summary>
/// <remarks>
/// ISO8601 is more compatible, readable, fully-processable, but less accurate as it doesn't provide time down to fractions of a second.
/// JulianDay is the numeric format the SQLite uses internally and is arguably the most compatible with 3rd party tools. It is
/// not readable as text without post-processing.
/// Ticks less compatible with 3rd party tools that query the database, and renders the DateTime field unreadable as text without post-processing.
///
/// The preferred order of choosing a datetime format is JulianDay, ISO8601, and then Ticks. Ticks is mainly present for legacy
/// code support.
/// </remarks>
public enum SQLiteDateFormats
{
/// <summary>
/// Using ticks is not recommended and is not well supported with LINQ.
/// </summary>
Ticks = 0,
/// <summary>
/// The default format for this provider.
/// </summary>
ISO8601 = 1,
/// <summary>
/// JulianDay format, which is what SQLite uses internally
/// </summary>
JulianDay = 2,
/// <summary>
/// The whole number of seconds since the Unix epoch (January 1, 1970).
/// </summary>
UnixEpoch = 3,
}
/// <summary>
/// This enum determines how SQLite treats its journal file.
/// </summary>
/// <remarks>
/// By default SQLite will create and delete the journal file when needed during a transaction.
/// However, for some computers running certain filesystem monitoring tools, the rapid
/// creation and deletion of the journal file can cause those programs to fail, or to interfere with SQLite.
///
/// If a program or virus scanner is interfering with SQLite's journal file, you may receive errors like "unable to open database file"
/// when starting a transaction. If this is happening, you may want to change the default journal mode to Persist.
/// </remarks>
public enum SQLiteJournalModeEnum
{
/// <summary>
/// The default mode, this causes SQLite to create and destroy the journal file as-needed.
/// </summary>
Delete = 0,
/// <summary>
/// When this is set, SQLite will keep the journal file even after a transaction has completed. It's contents will be erased,
/// and the journal re-used as often as needed. If it is deleted, it will be recreated the next time it is needed.
/// </summary>
Persist = 1,
/// <summary>
/// This option disables the rollback journal entirely. Interrupted transactions or a program crash can cause database
/// corruption in this mode!
/// </summary>
Off = 2
}
/// <summary>
/// Struct used internally to determine the datatype of a column in a resultset
/// </summary>
internal class SQLiteType
{
/// <summary>
/// The DbType of the column, or DbType.Object if it cannot be determined
/// </summary>
internal DbType Type;
/// <summary>
/// The affinity of a column, used for expressions or when Type is DbType.Object
/// </summary>
internal TypeAffinity Affinity;
}
internal struct SQLiteTypeNames
{
internal SQLiteTypeNames(string newtypeName, DbType newdataType)
{
typeName = newtypeName;
dataType = newdataType;
}
internal string typeName;
internal DbType dataType;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using Vexe.Runtime.Extensions;
using Vexe.Runtime.Helpers;
using Vexe.Runtime.Types;
using UnityObject = UnityEngine.Object;
namespace Vexe.Editor.Types
{
public class EditorMember
{
public object RawTarget;
public UnityObject UnityTarget;
public string DisplayText;
public Action Write = () => { };
// These are set when the member is an element of a collection (list, array, dictionary)
// So you can use these to query whether or not an element is a collection element (Elemnts != null or ElementIndex != -1)
public IList Elements;
public int ElementIndex = -1;
// Set when the member is a collection (list, array, dictionary)
// Use this to query whether an element is a collection (CollectionCoun != -1)
public int CollectionCount = -1;
public readonly int Id;
public readonly string Name;
public readonly string NiceName;
public readonly string TypeNiceName;
public readonly Type Type;
public readonly MemberInfo Info;
public readonly Attribute[] Attributes;
public static readonly Dictionary<string, Func<EditorMember, string>> Formatters = new Dictionary<string, Func<EditorMember, string>>()
{
{ @"\$type" , x => x.Type.Name },
{ @"\$nicetype", x => x.TypeNiceName },
{ @"\$name" , x => x.Name },
{ @"\$nicename", x =>
{
string name = x.Name;
string result = null;
if (name.IsPrefix("m_"))
result = name.Remove(0, 1);
else result = name;
result = result.ToTitleCase();
if (!VFWSettings.UseHungarianNotation)
return result.SplitPascalCase();;
if (name.Length > 1 && char.IsLower(result[0]) && char.IsUpper(result[1]))
{
var lowerResultInitial = char.ToLower(result[0]);
var nicetype = x.TypeNiceName;
// check for n as well, eg nSize
if ((nicetype == "int" && lowerResultInitial == 'i' || lowerResultInitial == 'n')
|| char.ToLower(nicetype[0]) == lowerResultInitial)
return result.Remove(0, 1).SplitPascalCase();
}
return result.SplitPascalCase();
}
},
};
public object Value
{
get { return Get(); }
set { Set(value); }
}
public bool IsCollection
{
get { return ElementIndex != -1; }
}
private Action<object> _set;
private Func<object> _get;
private MemberSetter<object, object> _memberSetter;
private MemberGetter<object, object> _memberGetter;
private static BetterUndo _undo = new BetterUndo();
private double _undoTimer, _undoLastTime;
private const double kUndoTick = .5;
private SetVarOp<object> _setVar;
private static Attribute[] Empty = new Attribute[0];
public readonly HashSet<Attribute> InitializedComposites = new HashSet<Attribute>();
private EditorMember(MemberInfo memberInfo, Type memberType, string memberName,
object rawTarget, UnityObject unityTarget, int targetId, Attribute[] attributes)
{
if (attributes == null)
attributes = Empty;
else ResolveUsing(ref attributes);
Info = memberInfo;
Type = memberType;
RawTarget = rawTarget;
TypeNiceName = memberType.GetNiceName();
Name = memberName;
NiceName = Formatters[@"\$nicename"].Invoke(this);
UnityTarget = unityTarget;
Attributes = attributes;
string displayFormat = null;
var displayAttr = attributes.GetAttribute<DisplayAttribute>();
if (displayAttr != null && MemberDrawersHandler.IsApplicableAttribute(memberType, displayAttr, attributes))
displayFormat = displayAttr.FormatLabel;
if (displayFormat == null)
{
if (Type.IsImplementerOfRawGeneric(typeof(IDictionary<,>)))
displayFormat = VFWSettings.DefaultDictionaryFormat;
else if (Type.IsImplementerOfRawGeneric(typeof(IList<>)))
displayFormat = VFWSettings.DefaultSequenceFormat;
else displayFormat = VFWSettings.DefaultMemberFormat;
}
var iter = Formatters.GetEnumerator();
while(iter.MoveNext())
{
var pair = iter.Current;
var pattern = pair.Key;
var result = pair.Value(this);
displayFormat = Regex.Replace(displayFormat, pattern, result, RegexOptions.IgnoreCase);
}
DisplayText = displayFormat;
Id = RuntimeHelper.CombineHashCodes(targetId, TypeNiceName, DisplayText);
}
private void ResolveUsing(ref Attribute[] attributes)
{
var idx = attributes.IndexOf(x => x.GetType() == typeof(UsingAttribute));
if (idx == -1)
return;
var usingAttr = attributes[idx] as UsingAttribute;
FieldInfo field;
var path = usingAttr.Path;
var period = path.IndexOf('.');
if (period == -1) // find field in [AttributeContainer] classes
{
field = ReflectionHelper.GetAllTypes()
.Where(t => t.IsDefined<AttributeContainer>())
.SelectMany(t => t.GetFields(Flags.StaticAnyVisibility))
.FirstOrDefault(f => f.Name == path);
if (field == null)
{
Debug.Log("Couldn't find field: " + path + " in any [AttributeContainer] marked class");
return;
}
}
else
{
var typeName = path.Substring(0, period);
var container = ReflectionHelper.GetAllTypes().FirstOrDefault(x => x.Name == typeName);
if (container == null)
{
Debug.Log("Couldn't find type: " + typeName);
return;
}
var fieldName = path.Substring(period + 1);
field = container.GetField(fieldName, Flags.StaticAnyVisibility);
if (field == null)
{
Debug.Log("Couldn't find static field: " + fieldName + " inside: " + typeName);
return;
}
}
if (field.FieldType != typeof(Attribute[]))
{
Debug.Log("Field must be of type Attribute[] " + field.Name);
return;
}
var imported = field.GetValue(null) as Attribute[];
var display1 = attributes.GetAttribute<DisplayAttribute>();
if (display1 != null)
{
var display2 = imported.GetAttribute<DisplayAttribute>();
if (display2 != null)
CombineDisplays(src: display1, dest: display2);
}
var tmp = attributes.ToList();
tmp.AddRange(imported);
tmp.RemoveAt(idx);
if (display1 != null)
tmp.Remove(display1);
attributes = tmp.ToArray();
}
public static void CombineDisplays(DisplayAttribute src, DisplayAttribute dest)
{
// combine seq/dict options
dest.DictOpt |= src.DictOpt;
dest.SeqOpt |= src.SeqOpt;
// display1 overrides display2 if any formatting/order values are specified
if (src.DisplayOrder.HasValue)
dest.Order = src.Order;
if (!string.IsNullOrEmpty(src.FormatMethod))
dest.FormatMethod = src.FormatMethod;
if (!string.IsNullOrEmpty(src.FormatKVPair))
dest.FormatKVPair = src.FormatKVPair;
}
public static DisplayAttribute CombineDisplays(DisplayAttribute[] attributes)
{
var result = new DisplayAttribute();
for (int i = 0; i < attributes.Length; i++)
{
var display = attributes[i];
CombineDisplays(src: display, dest: result);
}
return result;
}
public object Get()
{
return _get();
}
public void Set(object value)
{
bool sameValue = value.GenericEquals(Get());
if (sameValue)
return;
HandleUndoAndSet(value);
if (UnityTarget != null)
EditorUtility.SetDirty(UnityTarget);
}
public T As<T>() where T : class
{
return Get() as T;
}
private void HandleUndoAndSet(object value)
{
if (UnityTarget != null)
Undo.RecordObject(UnityTarget, "Editor Member Modification");
_undoTimer = EditorApplication.timeSinceStartup - _undoLastTime;
if (_undoTimer > kUndoTick)
{
_undoTimer = 0f;
_undoLastTime = EditorApplication.timeSinceStartup;
BetterUndo.MakeCurrent(ref _undo);
_setVar.ToValue = value;
_undo.RegisterThenPerform(_setVar);
}
else _set(value);
}
public override string ToString()
{
return TypeNiceName + " " + Name;
}
public override int GetHashCode()
{
return Id;
}
public override bool Equals(object obj)
{
var member = obj as EditorMember;
return member != null && this.Id == member.Id;
}
public static EditorMember WrapMember(string memberName, Type targetType, object rawTarget, UnityObject unityTarget, int id, Attribute[] attributes)
{
var member = GetMember(memberName, targetType);
return WrapMember(member, rawTarget, unityTarget, id, attributes);
}
public static EditorMember WrapMember(string memberName, Type targetType, object rawTarget, UnityObject unityTarget, int id)
{
var member = GetMember(memberName, targetType);
return WrapMember(member, rawTarget, unityTarget, id, member.GetAttributes());
}
private static MemberInfo GetMember(string memberName, Type targetType)
{
var members = targetType.GetMember(memberName, MemberTypes.Field | MemberTypes.Property, Flags.StaticInstanceAnyVisibility);
if (members.IsNullOrEmpty())
ErrorHelper.MemberNotFound(targetType, memberName);
return members[0];
}
public static EditorMember WrapMember(MemberInfo memberInfo, object rawTarget, UnityObject unityTarget, int id)
{
return WrapMember(memberInfo, rawTarget, unityTarget, id, memberInfo.GetAttributes());
}
public static EditorMember WrapMember(MemberInfo memberInfo, object rawTarget, UnityObject unityTarget, int id, Attribute[] attributes)
{
var field = memberInfo as FieldInfo;
if (field != null)
{
if (field.IsLiteral)
throw new InvalidOperationException("Field is const, this is not supported: " + field);
var result = new EditorMember(field, field.FieldType, field.Name, rawTarget, unityTarget, id, attributes);
result.InitGetSet(result.GetWrappedMemberValue, result.SetWrappedMemberValue);
result._memberGetter = field.DelegateForGet();
result._memberSetter = field.DelegateForSet();
return result;
}
else
{
var property = memberInfo as PropertyInfo;
if (property == null)
throw new InvalidOperationException("Member " + memberInfo + " is not a field nor property.");
if (!property.CanRead)
throw new InvalidOperationException("Property doesn't have a getter method: " + property);
if(property.IsIndexer())
throw new InvalidOperationException("Property is an indexer, this is not supported: " + property);
var result = new EditorMember(property, property.PropertyType, property.Name, rawTarget, unityTarget, id, attributes);
result.InitGetSet(result.GetWrappedMemberValue, result.SetWrappedMemberValue);
result._memberGetter = property.DelegateForGet();
if (property.CanWrite)
result._memberSetter = property.DelegateForSet();
else
result._memberSetter = delegate(ref object obj, object value) { };
return result;
}
}
public static EditorMember WrapGetSet(Func<object> get, Action<object> set, object rawTarget, UnityObject unityTarget, Type dataType, string name, int id, Attribute[] attributes)
{
var result = new EditorMember(null, dataType, name, rawTarget, unityTarget, id, attributes);
result.InitGetSet(get, set);
return result;
}
public static EditorMember WrapIListElement(string elementName, Type elementType, int elementId, Attribute[] attributes)
{
var result = new EditorMember(null, elementType, elementName, null, null, elementId, attributes);
result.InitGetSet(result.GetListElement, result.SetListElement);
return result;
}
public void InitializeIList<T>(IList<T> list, int index, object rawTarget, UnityObject unityTarget)
{
Elements = list as IList;
ElementIndex = index;
RawTarget = rawTarget;
UnityTarget = unityTarget;
}
private void InitGetSet(Func<object> get, Action<object> set)
{
_get = get;
_set = set;
_setVar = new SetVarOp<object>();
_setVar.GetCurrent = get;
_setVar.SetValue = set;
}
private object GetListElement()
{
if (ElementIndex < 0 || ElementIndex >= Elements.Count)
return null;
return Elements[ElementIndex];
}
private void SetListElement(object value)
{
Elements[ElementIndex] = value;
}
private object GetWrappedMemberValue()
{
return _memberGetter(RawTarget);
}
private void SetWrappedMemberValue(object value)
{
try
{
_memberSetter(ref RawTarget, value);
}
catch(InvalidCastException)
{
ErrorHelper.InvalidCast(value, TypeNiceName);
}
}
}
public static class EditorMemberExtensions
{
public static bool IsNull(this EditorMember member)
{
object value;
return (member == null || member.Equals(null)) || ((value = member.Value) == null || value.Equals(null));
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007-2016 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if PARALLEL
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Globalization;
using System.Runtime.Serialization;
using System.Threading;
#if NET20 || NET35
using ManualResetEventSlim = System.Threading.ManualResetEvent;
#endif
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal.Execution
{
#region Individual Event Classes
/// <summary>
/// NUnit.Core.Event is the abstract base for all stored events.
/// An Event is the stored representation of a call to the
/// ITestListener interface and is used to record such calls
/// or to queue them for forwarding on another thread or at
/// a later time.
/// </summary>
public abstract class Event
{
/// <summary>
/// The Send method is implemented by derived classes to send the event to the specified listener.
/// </summary>
/// <param name="listener">The listener.</param>
public abstract void Send(ITestListener listener);
}
/// <summary>
/// TestStartedEvent holds information needed to call the TestStarted method.
/// </summary>
public class TestStartedEvent : Event
{
private readonly ITest _test;
/// <summary>
/// Initializes a new instance of the <see cref="TestStartedEvent"/> class.
/// </summary>
/// <param name="test">The test.</param>
public TestStartedEvent(ITest test)
{
_test = test;
}
/// <summary>
/// Calls TestStarted on the specified listener.
/// </summary>
/// <param name="listener">The listener.</param>
public override void Send(ITestListener listener)
{
listener.TestStarted(_test);
}
}
/// <summary>
/// TestFinishedEvent holds information needed to call the TestFinished method.
/// </summary>
public class TestFinishedEvent : Event
{
private readonly ITestResult _result;
/// <summary>
/// Initializes a new instance of the <see cref="TestFinishedEvent"/> class.
/// </summary>
/// <param name="result">The result.</param>
public TestFinishedEvent(ITestResult result)
{
_result = result;
}
/// <summary>
/// Calls TestFinished on the specified listener.
/// </summary>
/// <param name="listener">The listener.</param>
public override void Send(ITestListener listener)
{
listener.TestFinished(_result);
}
}
/// <summary>
/// TestOutputEvent holds information needed to call the TestOutput method.
/// </summary>
public class TestOutputEvent : Event
{
private readonly TestOutput _output;
/// <summary>
/// Initializes a new instance of the <see cref="TestOutputEvent"/> class.
/// </summary>
/// <param name="output">The output object.</param>
public TestOutputEvent(TestOutput output)
{
_output = output;
}
/// <summary>
/// Calls TestOutput on the specified listener.
/// </summary>
/// <param name="listener">The listener.</param>
public override void Send(ITestListener listener)
{
listener.TestOutput(_output);
}
}
#endregion
/// <summary>
/// Implements a queue of work items each of which
/// is queued as a WaitCallback.
/// </summary>
public class EventQueue
{
private const int spinCount = 5;
// static readonly Logger log = InternalTrace.GetLogger("EventQueue");
private readonly ConcurrentQueue<Event> _queue = new ConcurrentQueue<Event>();
/* This event is used solely for the purpose of having an optimized sleep cycle when
* we have to wait on an external event (Add or Remove for instance)
*/
private readonly ManualResetEventSlim _mreAdd = new ManualResetEventSlim(false);
/* The whole idea is to use these two values in a transactional
* way to track and manage the actual data inside the underlying lock-free collection
* instead of directly working with it or using external locking.
*
* They are manipulated with CAS and are guaranteed to increase over time and use
* of the instance thus preventing ABA problems.
*/
private int _addId = int.MinValue;
private int _removeId = int.MinValue;
private int _stopped;
/// <summary>
/// Gets the count of items in the queue.
/// </summary>
public int Count
{
get
{
return _queue.Count;
}
}
/// <summary>
/// Enqueues the specified event
/// </summary>
/// <param name="e">The event to enqueue.</param>
public void Enqueue(Event e)
{
do
{
int cachedAddId = _addId;
// Validate that we have are the current enqueuer
if (Interlocked.CompareExchange(ref _addId, cachedAddId + 1, cachedAddId) != cachedAddId)
continue;
// Add to the collection
_queue.Enqueue(e);
// Wake up threads that may have been sleeping
_mreAdd.Set();
break;
} while (true);
// Setting this to anything other than 0 causes NUnit to be sensitive
// to the windows timer resolution - see issue #2217
Thread.Sleep(0); // give EventPump thread a chance to process the event
}
/// <summary>
/// Removes the first element from the queue and returns it (or <c>null</c>).
/// </summary>
/// <param name="blockWhenEmpty">
/// If <c>true</c> and the queue is empty, the calling thread is blocked until
/// either an element is enqueued, or <see cref="Stop"/> is called.
/// </param>
/// <returns>
/// <list type="bullet">
/// <item>
/// <term>If the queue not empty</term>
/// <description>the first element.</description>
/// </item>
/// <item>
/// <term>otherwise, if <paramref name="blockWhenEmpty"/>==<c>false</c>
/// or <see cref="Stop"/> has been called</term>
/// <description><c>null</c>.</description>
/// </item>
/// </list>
/// </returns>
public Event Dequeue(bool blockWhenEmpty)
{
SpinWait sw = new SpinWait();
do
{
int cachedRemoveId = _removeId;
int cachedAddId = _addId;
// Empty case
if (cachedRemoveId == cachedAddId)
{
if (!blockWhenEmpty || _stopped != 0)
return null;
// Spin a few times to see if something changes
if (sw.Count <= spinCount)
{
sw.SpinOnce();
}
else
{
// Reset to wait for an enqueue
_mreAdd.Reset();
// Recheck for an enqueue to avoid a Wait
if (cachedRemoveId != _removeId || cachedAddId != _addId)
{
// Queue is not empty, set the event
_mreAdd.Set();
continue;
}
// Wait for something to happen
_mreAdd.Wait(500);
}
continue;
}
// Validate that we are the current dequeuer
if (Interlocked.CompareExchange(ref _removeId, cachedRemoveId + 1, cachedRemoveId) != cachedRemoveId)
continue;
// Dequeue our work item
Event e;
while (!_queue.TryDequeue (out e))
{
if (!blockWhenEmpty || _stopped != 0)
return null;
}
return e;
} while (true);
}
/// <summary>
/// Stop processing of the queue
/// </summary>
public void Stop()
{
if (Interlocked.CompareExchange(ref _stopped, 1, 0) == 0)
_mreAdd.Set();
}
}
}
#endif
| |
/*===============================================================================
Copyright (c) 2015-2016 PTC Inc. All Rights Reserved.
Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved.
Vuforia is a trademark of PTC Inc., registered in the United States and other
countries.
==============================================================================*/
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System.IO;
using System;
/// <summary>
/// This is a utility class to actually play back videos on a texture or in full screen.
/// </summary>
public class VideoPlayerHelper
{
#region NESTED
/// <summary>
/// Various states a video can be in
/// </summary>
public enum MediaState
{
REACHED_END,
PAUSED,
STOPPED,
PLAYING,
READY,
NOT_READY,
ERROR,
PLAYING_FULLSCREEN // iOS-only
}
/// <summary>
/// If the video can be played back on texture, in full screen on both.
/// </summary>
public enum MediaType
{
ON_TEXTURE,
FULLSCREEN,
ON_TEXTURE_FULLSCREEN
}
#endregion // NESTED
#region PRIVATE_MEMBER_VARIABLES
private string mFilename = null;
private string mFullScreenFilename = null;
#endregion // PRIVATE_MEMBER_VARIABLES
#region PUBLIC_METHODS
/// <summary>
/// Get the native plugin render event function
/// </summary>
public static IntPtr GetNativeRenderEventFunc()
{
#if UNITY_WSA_10_0 && !UNITY_EDITOR
return GetRenderEventFunc();
#else
return IntPtr.Zero;
#endif
}
/// <summary>
/// Set the video filename
/// </summary>
public void SetFilename(string filename)
{
#if UNITY_ANDROID
mFilename = filename;
videoPlayerSetActivity();
if (videoPlayerIsFileInAssetsFolder(filename) || filename.Contains("://"))
{
mFullScreenFilename = filename;
}
else
{
mFullScreenFilename = "file://" + filename;
}
#elif (UNITY_IPHONE || UNITY_IOS)
mFilename = filename;
if (!filename.Contains("://"))
{
// Not a remote file, assume this file is located in the StreamingAssets folder
mFilename = "Data/Raw/" + filename;
}
mFullScreenFilename = filename;
#elif UNITY_WSA_10_0
mFilename = filename;
if (!filename.Contains("://"))
{
// Not a remote file, assume this file is located in the StreamingAssets folder
mFilename = "ms-appx:///Data/StreamingAssets/" + filename;
}
mFullScreenFilename = mFilename;
#endif
}
/// <summary>
/// Initializes the VideoPlayerHelper object
/// </summary>
public bool Init(bool isMetalRendering)
{
return videoPlayerInit(isMetalRendering);
}
/// <summary>
/// Deinitializes the VideoPlayerHelper object
/// </summary>
/// <returns></returns>
public bool Deinit()
{
return videoPlayerDeinit();
}
/// <summary>
/// Loads a local or remote movie file
/// </summary>
public bool Load(string filename, MediaType requestedType, bool playOnTextureImmediately, float seekPosition)
{
SetFilename(filename);
return videoPlayerLoad(mFilename, (int) requestedType, playOnTextureImmediately, seekPosition);
}
/// <summary>
/// Unloads the currently loaded movie
/// After this is called a new load() has to be invoked
/// </summary>
public bool Unload()
{
return videoPlayerUnload();
}
/// <summary>
/// Indicates whether the movie can be played on a texture
/// </summary>
public bool IsPlayableOnTexture()
{
return videoPlayerIsPlayableOnTexture();
}
/// <summary>
/// Indicates whether the movie can be played fullscreen
/// </summary>
public bool IsPlayableFullscreen()
{
return videoPlayerIsPlayableFullscreen();
}
/// <summary>
/// Set the native texture object that the video frames will be copied to
/// </summary>
public bool SetVideoTexturePtr(IntPtr texturePtr)
{
return videoPlayerSetVideoTexturePtr(texturePtr);
}
/// <summary>
/// Return the current status of the movie such as Playing, Paused or Not Ready
/// </summary>
public MediaState GetStatus()
{
return (MediaState) videoPlayerGetStatus();
}
/// <summary>
/// Returns the width of the video frame
/// </summary>
public int GetVideoWidth()
{
return videoPlayerGetVideoWidth();
}
/// <summary>
/// Returns the height of the video frame
/// </summary>
public int GetVideoHeight()
{
return videoPlayerGetVideoHeight();
}
/// <summary>
/// Returns the length of the current movie
/// </summary>
public float GetLength()
{
return videoPlayerGetLength();
}
/// <summary>
/// Request a movie to be played either full screen or on texture and at a given position
/// </summary>
public bool Play(bool fullScreen, float seekPosition)
{
// We use Unity's built-in full screen movie player
if (fullScreen)
{
if (mFilename == null)
{
return false;
}
Handheld.PlayFullScreenMovie(mFullScreenFilename, Color.black, FullScreenMovieControlMode.Full, FullScreenMovieScalingMode.AspectFit);
return true;
}
else
{
return videoPlayerPlay(fullScreen, seekPosition);
}
}
/// <summary>
/// Pauses the current movie being played
/// </summary>
public bool Pause()
{
return videoPlayerPause();
}
/// <summary>
/// Stops the current movie being played
/// </summary>
public bool Stop()
{
return videoPlayerStop();
}
/// <summary>
/// Tells the VideoPlayerHelper to update the data from the video feed
/// </summary>
public MediaState UpdateVideoData()
{
return (MediaState)videoPlayerUpdateVideoData();
}
/// <summary>
/// Moves the movie to the requested seek position
/// </summary>
public bool SeekTo(float position)
{
return videoPlayerSeekTo(position);
}
/// <summary>
/// Gets the current seek position
/// </summary>
public float GetCurrentPosition()
{
return videoPlayerGetCurrentPosition();
}
/// <summary>
/// Sets the volume of the movie to the desired value
/// </summary>
public bool SetVolume(float value)
{
return videoPlayerSetVolume(value);
}
/// <summary>
/// Gets the buffering percentage in case the movie is loaded from network
/// Note this is not supported on iOS
/// </summary>
public int GetCurrentBufferingPercentage()
{
return videoPlayerGetCurrentBufferingPercentage();
}
/// <summary>
/// Allows native player to do appropriate on pause cleanup
/// </summary>
public void OnPause()
{
videoPlayerOnPause();
}
#endregion // PUBLIC_METHODS
#region NATIVE_FUNCTIONS
#if !UNITY_EDITOR
#if UNITY_ANDROID
private AndroidJavaObject javaObj = null;
private AndroidJavaObject GetJavaObject()
{
if (javaObj == null)
{
javaObj = new AndroidJavaObject("com.vuforia.VuforiaMedia.VideoPlayerHelper");
}
return javaObj;
}
private void videoPlayerSetActivity()
{
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
GetJavaObject().Call("setActivity", jo);
}
private bool videoPlayerIsFileInAssetsFolder(string filename)
{
return GetJavaObject().Call<bool>("isFileInAssetsFolder", filename);
}
private bool videoPlayerInit(bool unused_isMetalRendering)
{
return GetJavaObject().Call<bool>("init");
}
private bool videoPlayerDeinit()
{
return GetJavaObject().Call<bool>("deinit");
}
private bool videoPlayerLoad(string filename, int requestType, bool playOnTextureImmediately, float seekPosition)
{
return GetJavaObject().Call<bool>("load", filename, requestType, playOnTextureImmediately, seekPosition);
}
private bool videoPlayerUnload()
{
return GetJavaObject().Call<bool>("unload");
}
private bool videoPlayerIsPlayableOnTexture()
{
return GetJavaObject().Call<bool>("isPlayableOnTexture");
}
private bool videoPlayerIsPlayableFullscreen()
{
return GetJavaObject().Call<bool>("isPlayableFullscreen");
}
private bool videoPlayerSetVideoTexturePtr(IntPtr texturePtr)
{
// Android OpenGL ES: cast texturePtr to OpenGL texture ID (32bit integer), as documented here:
// http://docs.unity3d.com/ScriptReference/Texture.GetNativeTexturePtr.html
return GetJavaObject().Call<bool>("setVideoTextureID", texturePtr.ToInt32() );
}
private int videoPlayerGetStatus()
{
return GetJavaObject().Call<int>("getStatus");
}
private int videoPlayerGetVideoWidth()
{
return GetJavaObject().Call<int>("getVideoWidth");
}
private int videoPlayerGetVideoHeight()
{
return GetJavaObject().Call<int>("getVideoHeight");
}
private float videoPlayerGetLength()
{
return GetJavaObject().Call<float>("getLength");
}
private bool videoPlayerPlay(bool fullScreen, float seekPosition)
{
return GetJavaObject().Call<bool>("play", fullScreen, seekPosition);
}
private bool videoPlayerPause()
{
return GetJavaObject().Call<bool>("pause");
}
private bool videoPlayerStop()
{
return GetJavaObject().Call<bool>("stop");
}
private int videoPlayerUpdateVideoData()
{
return GetJavaObject().Call<int>("updateVideoData");
}
private bool videoPlayerSeekTo(float position)
{
return GetJavaObject().Call<bool>("seekTo", position);
}
private float videoPlayerGetCurrentPosition()
{
return GetJavaObject().Call<float>("getCurrentPosition");
}
private bool videoPlayerSetVolume(float value)
{
return GetJavaObject().Call<bool>("setVolume", value);
}
private int videoPlayerGetCurrentBufferingPercentage()
{
return GetJavaObject().Call<int>("getCurrentBufferingPercentage");
}
private void videoPlayerOnPause()
{
// nothing to do for Android
}
#elif (UNITY_IPHONE || UNITY_IOS)
private IntPtr mVideoPlayerPtr = IntPtr.Zero;
[DllImport("__Internal")]
private static extern IntPtr videoPlayerInitIOS(bool isMetalRendering);
[DllImport("__Internal")]
private static extern bool videoPlayerDeinitIOS(IntPtr videoPlayerPtr);
[DllImport("__Internal")]
private static extern bool videoPlayerLoadIOS(IntPtr videoPlayerPtr, string filename, int requestType, bool playOnTextureImmediately, float seekPosition);
[DllImport("__Internal")]
private static extern bool videoPlayerUnloadIOS(IntPtr videoPlayerPtr);
[DllImport("__Internal")]
private static extern bool videoPlayerIsPlayableOnTextureIOS(IntPtr videoPlayerPtr);
[DllImport("__Internal")]
private static extern bool videoPlayerIsPlayableFullscreenIOS(IntPtr videoPlayerPtr);
[DllImport("__Internal")]
private static extern bool videoPlayerSetVideoTexturePtrIOS(IntPtr videoPlayerPtr, IntPtr texturePtr);
[DllImport("__Internal")]
private static extern int videoPlayerGetStatusIOS(IntPtr videoPlayerPtr);
[DllImport("__Internal")]
private static extern int videoPlayerGetVideoWidthIOS(IntPtr videoPlayerPtr);
[DllImport("__Internal")]
private static extern int videoPlayerGetVideoHeightIOS(IntPtr videoPlayerPtr);
[DllImport("__Internal")]
private static extern float videoPlayerGetLengthIOS(IntPtr videoPlayerPtr);
[DllImport("__Internal")]
private static extern bool videoPlayerPlayIOS(IntPtr videoPlayerPtr, bool fullScreen, float seekPosition);
[DllImport("__Internal")]
private static extern bool videoPlayerPauseIOS(IntPtr videoPlayerPtr);
[DllImport("__Internal")]
private static extern bool videoPlayerStopIOS(IntPtr videoPlayerPtr);
[DllImport("__Internal")]
private static extern int videoPlayerUpdateVideoDataIOS(IntPtr videoPlayerPtr);
[DllImport("__Internal")]
private static extern bool videoPlayerSeekToIOS(IntPtr videoPlayerPtr, float position);
[DllImport("__Internal")]
private static extern float videoPlayerGetCurrentPositionIOS(IntPtr videoPlayerPtr);
[DllImport("__Internal")]
private static extern bool videoPlayerSetVolumeIOS(IntPtr videoPlayerPtr, float value);
[DllImport("__Internal")]
private static extern int videoPlayerGetCurrentBufferingPercentageIOS(IntPtr videoPlayerPtr);
[DllImport("__Internal")]
private static extern void videoPlayerOnPauseIOS(IntPtr videoPlayerPtr);
private bool videoPlayerInit(bool isMetalRendering)
{
mVideoPlayerPtr = videoPlayerInitIOS(isMetalRendering);
return mVideoPlayerPtr != IntPtr.Zero;
}
private bool videoPlayerDeinit()
{
bool result = videoPlayerDeinitIOS(mVideoPlayerPtr);
mVideoPlayerPtr = IntPtr.Zero;
return result;
}
private bool videoPlayerLoad(string filename, int requestType, bool playOnTextureImmediately, float seekPosition)
{
return videoPlayerLoadIOS(mVideoPlayerPtr, filename, requestType, playOnTextureImmediately, seekPosition);
}
private bool videoPlayerUnload()
{
return videoPlayerUnloadIOS(mVideoPlayerPtr);
}
private bool videoPlayerIsPlayableOnTexture()
{
return videoPlayerIsPlayableOnTextureIOS(mVideoPlayerPtr);
}
private bool videoPlayerIsPlayableFullscreen()
{
return videoPlayerIsPlayableFullscreenIOS(mVideoPlayerPtr);
}
private bool videoPlayerSetVideoTexturePtr(IntPtr texturePtr)
{
return videoPlayerSetVideoTexturePtrIOS(mVideoPlayerPtr, texturePtr);
}
private int videoPlayerGetStatus()
{
return videoPlayerGetStatusIOS(mVideoPlayerPtr);
}
private int videoPlayerGetVideoWidth()
{
return videoPlayerGetVideoWidthIOS(mVideoPlayerPtr);
}
private int videoPlayerGetVideoHeight()
{
return videoPlayerGetVideoHeightIOS(mVideoPlayerPtr);
}
private float videoPlayerGetLength()
{
return videoPlayerGetLengthIOS(mVideoPlayerPtr);
}
private bool videoPlayerPlay(bool fullScreen, float seekPosition)
{
return videoPlayerPlayIOS(mVideoPlayerPtr, fullScreen, seekPosition);
}
private bool videoPlayerPause()
{
return videoPlayerPauseIOS(mVideoPlayerPtr);
}
private bool videoPlayerStop()
{
return videoPlayerStopIOS(mVideoPlayerPtr);
}
private int videoPlayerUpdateVideoData()
{
return videoPlayerUpdateVideoDataIOS(mVideoPlayerPtr);
}
private bool videoPlayerSeekTo(float position)
{
return videoPlayerSeekToIOS(mVideoPlayerPtr, position);
}
private float videoPlayerGetCurrentPosition()
{
return videoPlayerGetCurrentPositionIOS(mVideoPlayerPtr);
}
private bool videoPlayerSetVolume(float value)
{
return videoPlayerSetVolumeIOS(mVideoPlayerPtr, value);
}
private int videoPlayerGetCurrentBufferingPercentage()
{
return videoPlayerGetCurrentBufferingPercentageIOS(mVideoPlayerPtr);
}
private void videoPlayerOnPause()
{
videoPlayerOnPauseIOS(mVideoPlayerPtr);
}
#elif (UNITY_WSA_10_0)
[DllImport("VuforiaMedia")]
private static extern IntPtr GetRenderEventFunc();
private IntPtr mVideoPlayerPtr = IntPtr.Zero;
[DllImport("VuforiaMedia")]
private static extern IntPtr VideoPlayerInitWSA();
[DllImport("VuforiaMedia")]
private static extern bool VideoPlayerDeinitWSA(IntPtr videoPlayerPtr);
[DllImport("VuforiaMedia")]
private static extern bool VideoPlayerLoadWSA(IntPtr videoPlayerPtr, [MarshalAs(UnmanagedType.LPStr)] string filename, int requestType, bool playOnTextureImmediately, float seekPosition);
[DllImport("VuforiaMedia")]
private static extern bool VideoPlayerUnloadWSA(IntPtr videoPlayerPtr);
[DllImport("VuforiaMedia")]
private static extern bool VideoPlayerIsPlayableOnTextureWSA(IntPtr videoPlayerPtr);
[DllImport("VuforiaMedia")]
private static extern bool VideoPlayerIsPlayableFullscreenWSA(IntPtr videoPlayerPtr);
[DllImport("VuforiaMedia")]
private static extern bool VideoPlayerSetVideoTexturePtrWSA(IntPtr videoPlayerPtr, IntPtr texturePtr);
[DllImport("VuforiaMedia")]
private static extern int VideoPlayerGetStatusWSA(IntPtr videoPlayerPtr);
[DllImport("VuforiaMedia")]
private static extern int VideoPlayerGetVideoWidthWSA(IntPtr videoPlayerPtr);
[DllImport("VuforiaMedia")]
private static extern int VideoPlayerGetVideoHeightWSA(IntPtr videoPlayerPtr);
[DllImport("VuforiaMedia")]
private static extern float VideoPlayerGetLengthWSA(IntPtr videoPlayerPtr);
[DllImport("VuforiaMedia")]
private static extern bool VideoPlayerPlayWSA(IntPtr videoPlayerPtr, bool fullScreen, float seekPosition);
[DllImport("VuforiaMedia")]
private static extern bool VideoPlayerPauseWSA(IntPtr videoPlayerPtr);
[DllImport("VuforiaMedia")]
private static extern bool VideoPlayerStopWSA(IntPtr videoPlayerPtr);
[DllImport("VuforiaMedia")]
private static extern int VideoPlayerUpdateVideoDataWSA(IntPtr videoPlayerPtr);
[DllImport("VuforiaMedia")]
private static extern bool VideoPlayerSeekToWSA(IntPtr videoPlayerPtr, float position);
[DllImport("VuforiaMedia")]
private static extern float VideoPlayerGetCurrentPositionWSA(IntPtr videoPlayerPtr);
[DllImport("VuforiaMedia")]
private static extern bool VideoPlayerSetVolumeWSA(IntPtr videoPlayerPtr, float value);
[DllImport("VuforiaMedia")]
private static extern int VideoPlayerGetCurrentBufferingPercentageWSA(IntPtr videoPlayerPtr);
[DllImport("VuforiaMedia")]
private static extern void VideoPlayerOnPauseWSA(IntPtr videoPlayerPtr);
private bool videoPlayerInit(bool unused_isMetalRendering)
{
mVideoPlayerPtr = VideoPlayerInitWSA();
return mVideoPlayerPtr != IntPtr.Zero;
}
private bool videoPlayerDeinit()
{
bool result = VideoPlayerDeinitWSA(mVideoPlayerPtr);
mVideoPlayerPtr = IntPtr.Zero;
return result;
}
private bool videoPlayerLoad(string filename, int requestType, bool playOnTextureImmediately, float seekPosition)
{
return VideoPlayerLoadWSA(mVideoPlayerPtr, filename, requestType, playOnTextureImmediately, seekPosition);
}
private bool videoPlayerUnload()
{
return VideoPlayerUnloadWSA(mVideoPlayerPtr);
}
private bool videoPlayerIsPlayableOnTexture()
{
return VideoPlayerIsPlayableOnTextureWSA(mVideoPlayerPtr);
}
private bool videoPlayerIsPlayableFullscreen()
{
return VideoPlayerIsPlayableFullscreenWSA(mVideoPlayerPtr);
}
private bool videoPlayerSetVideoTexturePtr(IntPtr texturePtr)
{
return VideoPlayerSetVideoTexturePtrWSA(mVideoPlayerPtr, texturePtr);
}
private int videoPlayerGetStatus()
{
return VideoPlayerGetStatusWSA(mVideoPlayerPtr);
}
private int videoPlayerGetVideoWidth()
{
return VideoPlayerGetVideoWidthWSA(mVideoPlayerPtr);
}
private int videoPlayerGetVideoHeight()
{
return VideoPlayerGetVideoHeightWSA(mVideoPlayerPtr);
}
private float videoPlayerGetLength()
{
return VideoPlayerGetLengthWSA(mVideoPlayerPtr);
}
private bool videoPlayerPlay(bool fullScreen, float seekPosition)
{
return VideoPlayerPlayWSA(mVideoPlayerPtr, fullScreen, seekPosition);
}
private bool videoPlayerPause()
{
return VideoPlayerPauseWSA(mVideoPlayerPtr);
}
private bool videoPlayerStop()
{
return VideoPlayerStopWSA(mVideoPlayerPtr);
}
private int videoPlayerUpdateVideoData()
{
return VideoPlayerUpdateVideoDataWSA(mVideoPlayerPtr);
}
private bool videoPlayerSeekTo(float position)
{
return VideoPlayerSeekToWSA(mVideoPlayerPtr, position);
}
private float videoPlayerGetCurrentPosition()
{
return VideoPlayerGetCurrentPositionWSA(mVideoPlayerPtr);
}
private bool videoPlayerSetVolume(float value)
{
return VideoPlayerSetVolumeWSA(mVideoPlayerPtr, value);
}
private int videoPlayerGetCurrentBufferingPercentage()
{
return VideoPlayerGetCurrentBufferingPercentageWSA(mVideoPlayerPtr);
}
private void videoPlayerOnPause()
{
VideoPlayerOnPauseWSA(mVideoPlayerPtr);
}
#endif
#else // !UNITY_EDITOR
void videoPlayerSetActivity() { }
bool videoPlayerIsFileInAssetsFolder(string filename) { return false; }
bool videoPlayerInit(bool isMetalRendering) { return false; }
bool videoPlayerDeinit() { return false; }
bool videoPlayerLoad(string filename, int requestType, bool playOnTextureImmediately, float seekPosition) { return false; }
bool videoPlayerUnload() { return false; }
bool videoPlayerIsPlayableOnTexture() { return false; }
bool videoPlayerIsPlayableFullscreen() { return false; }
bool videoPlayerSetVideoTexturePtr(IntPtr texturePtr) { return false; }
int videoPlayerGetStatus() { return 0; }
int videoPlayerGetVideoWidth() { return 0; }
int videoPlayerGetVideoHeight() { return 0; }
float videoPlayerGetLength() { return 0; }
bool videoPlayerPlay(bool fullScreen, float seekPosition) { return false; }
bool videoPlayerPause() { return false; }
bool videoPlayerStop() { return false; }
int videoPlayerUpdateVideoData() { return 0; }
bool videoPlayerSeekTo(float position) { return false; }
float videoPlayerGetCurrentPosition() { return 0; }
bool videoPlayerSetVolume(float value) { return false; }
int videoPlayerGetCurrentBufferingPercentage() { return 0; }
void videoPlayerOnPause() { }
#endif // !UNITY_EDITOR
#endregion // NATIVE_FUNCTIONS
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using HtmlGenerationWebSite.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace HtmlGenerationWebSite.Controllers
{
public class HtmlGeneration_HomeController : Controller
{
private readonly List<Product> _products = new List<Product>
{
new Product
{
ProductName = "Product_0",
Number = 0,
HomePage = new Uri("http://www.contoso.com")
},
new Product
{
ProductName = "Product_1",
Number = 1,
},
new Product
{
ProductName = "Product_2",
Number = 2,
Description = "Product_2 description"
},
};
private readonly IEnumerable<SelectListItem> _productsList;
private readonly IEnumerable<SelectListItem> _productsListWithSelection;
private readonly Order _order = new Order
{
Shipping = "UPSP",
Customer = new Customer
{
Key = "KeyA",
Number = 1,
Gender = Gender.Female,
Name = "NameStringValue",
},
NeedSpecialHandle = true,
PaymentMethod = new List<string> { "Check" },
Products = new List<int> { 0, 1 },
};
public HtmlGeneration_HomeController()
{
_productsList = new SelectList(_products, "Number", "ProductName");
_productsListWithSelection = new SelectList(_products, "Number", "ProductName", 2);
foreach (var i in _order.Products)
{
_order.ProductDetails.Add(_products[i]);
}
}
public IActionResult Enum()
{
return View(new AClass { DayOfWeek = Models.DayOfWeek.Friday, Month = Month.FirstOne });
}
public IActionResult Order()
{
ViewData["Items"] = _productsListWithSelection;
return View(_order);
}
public IActionResult OrderUsingHtmlHelpers()
{
ViewData["Items"] = _productsListWithSelection;
return View(_order);
}
public IActionResult Product()
{
var product = new Product
{
HomePage = new System.Uri("http://www.contoso.com"),
Description = "Type the product description"
};
return View(product);
}
public IActionResult ProductSubmit(Product product)
{
throw new NotImplementedException();
}
public IActionResult Customer()
{
return View();
}
public IActionResult Index()
{
return View();
}
public IActionResult ProductList()
{
return View(_products);
}
public IActionResult ProductListUsingTagHelpers() => View(_products);
public IActionResult ProductListUsingTagHelpersWithNullModel()
{
var model = new List<Product>
{
null,
};
return View(nameof(ProductListUsingTagHelpers), model);
}
public IActionResult EmployeeList()
{
var employees = new List<Employee>
{
new Employee
{
Name = "EmployeeName_0",
Number = 0,
Address = "Employee_0 address"
},
new Employee
{
Name = "EmployeeName_1",
Number = 1,
OfficeNumber = "1002",
Gender = Gender.Female
},
new Employee
{
Name = "EmployeeName_2",
Number = 2,
Remote = true
},
};
// Extra data that should be ignored / not used within a template.
ViewData[nameof(Employee.Gender)] = "Gender value that will not match.";
ViewData[nameof(Employee.Name)] = "Name value that should not be seen.";
return View(employees);
}
public IActionResult CreateWarehouse()
{
ViewData["Items"] = _productsList;
return View();
}
public IActionResult EditWarehouse()
{
var warehouse = new Warehouse
{
City = "City_1",
Employee = new Employee
{
Name = "EmployeeName_1",
Number = 1,
Address = "Address_1",
PhoneNumber = "PhoneNumber_1",
Gender = Gender.Female
}
};
return View(warehouse);
}
public IActionResult Warehouse()
{
var warehouse = new Warehouse
{
City = "City_1",
Employee = new Employee
{
Name = "EmployeeName_1",
OfficeNumber = "Number_1",
Address = "Address_1",
}
};
return View(warehouse);
}
public IActionResult Environment()
{
return View();
}
public IActionResult Link()
{
return View();
}
public IActionResult Image()
{
return View();
}
public IActionResult Script()
{
return View();
}
public IActionResult Form()
{
return View();
}
public IActionResult Input()
{
return View();
}
public IActionResult ItemUsingSharedEditorTemplate()
{
return View();
}
public IActionResult ItemUsingModelSpecificEditorTemplate()
{
return View();
}
public IActionResult AttributesWithBooleanValues()
{
return View();
}
public IActionResult ValidationProviderAttribute() => View();
[HttpPost]
public IActionResult ValidationProviderAttribute(ValidationProviderAttributeModel model) => View(model);
public IActionResult PartialTagHelperWithoutModel() => View();
public IActionResult StatusMessage() => View(new StatusMessageModel { Message = "Some status message"});
public IActionResult NullStatusMessage() => View("StatusMessage", new StatusMessageModel());
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithLowerAndUpperSByte()
{
var test = new VectorGetAndWithLowerAndUpper__GetAndWithLowerAndUpperSByte();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithLowerAndUpper__GetAndWithLowerAndUpperSByte
{
private static readonly int LargestVectorSize = 16;
private static readonly int ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
SByte[] values = new SByte[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSByte();
}
Vector128<SByte> value = Vector128.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15]);
Vector64<SByte> lowerResult = value.GetLower();
Vector64<SByte> upperResult = value.GetUpper();
ValidateGetResult(lowerResult, upperResult, values);
Vector128<SByte> result = value.WithLower(upperResult);
result = result.WithUpper(lowerResult);
ValidateWithResult(result, values);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
SByte[] values = new SByte[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSByte();
}
Vector128<SByte> value = Vector128.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15]);
object lowerResult = typeof(Vector128)
.GetMethod(nameof(Vector128.GetLower))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value });
object upperResult = typeof(Vector128)
.GetMethod(nameof(Vector128.GetUpper))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value });
ValidateGetResult((Vector64<SByte>)(lowerResult), (Vector64<SByte>)(upperResult), values);
object result = typeof(Vector128)
.GetMethod(nameof(Vector128.WithLower))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value, upperResult });
result = typeof(Vector128)
.GetMethod(nameof(Vector128.WithUpper))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { result, lowerResult });
ValidateWithResult((Vector128<SByte>)(result), values);
}
private void ValidateGetResult(Vector64<SByte> lowerResult, Vector64<SByte> upperResult, SByte[] values, [CallerMemberName] string method = "")
{
SByte[] lowerElements = new SByte[ElementCount / 2];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref lowerElements[0]), lowerResult);
SByte[] upperElements = new SByte[ElementCount / 2];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref upperElements[0]), upperResult);
ValidateGetResult(lowerElements, upperElements, values, method);
}
private void ValidateGetResult(SByte[] lowerResult, SByte[] upperResult, SByte[] values, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount / 2; i++)
{
if (lowerResult[i] != values[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<SByte>.GetLower(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", lowerResult)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = true;
for (int i = ElementCount / 2; i < ElementCount; i++)
{
if (upperResult[i - (ElementCount / 2)] != values[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<SByte>.GetUpper(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", upperResult)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
private void ValidateWithResult(Vector128<SByte> result, SByte[] values, [CallerMemberName] string method = "")
{
SByte[] resultElements = new SByte[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, method);
}
private void ValidateWithResult(SByte[] result, SByte[] values, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount / 2; i++)
{
if (result[i] != values[i + (ElementCount / 2)])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<SByte.WithLower(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = true;
for (int i = ElementCount / 2; i < ElementCount; i++)
{
if (result[i] != values[i - (ElementCount / 2)])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<SByte.WithUpper(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
using OpenHome.Net.Core;
namespace OpenHome.Net.Device.Providers
{
public interface IDvProviderUpnpOrgConnectionManager2 : IDisposable
{
/// <summary>
/// Set the value of the SourceProtocolInfo property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertySourceProtocolInfo(string aValue);
/// <summary>
/// Get a copy of the value of the SourceProtocolInfo property
/// </summary>
/// <returns>Value of the SourceProtocolInfo property.</param>
string PropertySourceProtocolInfo();
/// <summary>
/// Set the value of the SinkProtocolInfo property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertySinkProtocolInfo(string aValue);
/// <summary>
/// Get a copy of the value of the SinkProtocolInfo property
/// </summary>
/// <returns>Value of the SinkProtocolInfo property.</param>
string PropertySinkProtocolInfo();
/// <summary>
/// Set the value of the CurrentConnectionIDs property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertyCurrentConnectionIDs(string aValue);
/// <summary>
/// Get a copy of the value of the CurrentConnectionIDs property
/// </summary>
/// <returns>Value of the CurrentConnectionIDs property.</param>
string PropertyCurrentConnectionIDs();
}
/// <summary>
/// Provider for the upnp.org:ConnectionManager:2 UPnP service
/// </summary>
public class DvProviderUpnpOrgConnectionManager2 : DvProvider, IDisposable, IDvProviderUpnpOrgConnectionManager2
{
private GCHandle iGch;
private ActionDelegate iDelegateGetProtocolInfo;
private ActionDelegate iDelegatePrepareForConnection;
private ActionDelegate iDelegateConnectionComplete;
private ActionDelegate iDelegateGetCurrentConnectionIDs;
private ActionDelegate iDelegateGetCurrentConnectionInfo;
private PropertyString iPropertySourceProtocolInfo;
private PropertyString iPropertySinkProtocolInfo;
private PropertyString iPropertyCurrentConnectionIDs;
/// <summary>
/// Constructor
/// </summary>
/// <param name="aDevice">Device which owns this provider</param>
protected DvProviderUpnpOrgConnectionManager2(DvDevice aDevice)
: base(aDevice, "upnp.org", "ConnectionManager", 2)
{
iGch = GCHandle.Alloc(this);
}
/// <summary>
/// Enable the SourceProtocolInfo property.
/// </summary>
public void EnablePropertySourceProtocolInfo()
{
List<String> allowedValues = new List<String>();
iPropertySourceProtocolInfo = new PropertyString(new ParameterString("SourceProtocolInfo", allowedValues));
AddProperty(iPropertySourceProtocolInfo);
}
/// <summary>
/// Enable the SinkProtocolInfo property.
/// </summary>
public void EnablePropertySinkProtocolInfo()
{
List<String> allowedValues = new List<String>();
iPropertySinkProtocolInfo = new PropertyString(new ParameterString("SinkProtocolInfo", allowedValues));
AddProperty(iPropertySinkProtocolInfo);
}
/// <summary>
/// Enable the CurrentConnectionIDs property.
/// </summary>
public void EnablePropertyCurrentConnectionIDs()
{
List<String> allowedValues = new List<String>();
iPropertyCurrentConnectionIDs = new PropertyString(new ParameterString("CurrentConnectionIDs", allowedValues));
AddProperty(iPropertyCurrentConnectionIDs);
}
/// <summary>
/// Set the value of the SourceProtocolInfo property
/// </summary>
/// <remarks>Can only be called if EnablePropertySourceProtocolInfo has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertySourceProtocolInfo(string aValue)
{
if (iPropertySourceProtocolInfo == null)
throw new PropertyDisabledError();
return SetPropertyString(iPropertySourceProtocolInfo, aValue);
}
/// <summary>
/// Get a copy of the value of the SourceProtocolInfo property
/// </summary>
/// <remarks>Can only be called if EnablePropertySourceProtocolInfo has previously been called.</remarks>
/// <returns>Value of the SourceProtocolInfo property.</returns>
public string PropertySourceProtocolInfo()
{
if (iPropertySourceProtocolInfo == null)
throw new PropertyDisabledError();
return iPropertySourceProtocolInfo.Value();
}
/// <summary>
/// Set the value of the SinkProtocolInfo property
/// </summary>
/// <remarks>Can only be called if EnablePropertySinkProtocolInfo has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertySinkProtocolInfo(string aValue)
{
if (iPropertySinkProtocolInfo == null)
throw new PropertyDisabledError();
return SetPropertyString(iPropertySinkProtocolInfo, aValue);
}
/// <summary>
/// Get a copy of the value of the SinkProtocolInfo property
/// </summary>
/// <remarks>Can only be called if EnablePropertySinkProtocolInfo has previously been called.</remarks>
/// <returns>Value of the SinkProtocolInfo property.</returns>
public string PropertySinkProtocolInfo()
{
if (iPropertySinkProtocolInfo == null)
throw new PropertyDisabledError();
return iPropertySinkProtocolInfo.Value();
}
/// <summary>
/// Set the value of the CurrentConnectionIDs property
/// </summary>
/// <remarks>Can only be called if EnablePropertyCurrentConnectionIDs has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertyCurrentConnectionIDs(string aValue)
{
if (iPropertyCurrentConnectionIDs == null)
throw new PropertyDisabledError();
return SetPropertyString(iPropertyCurrentConnectionIDs, aValue);
}
/// <summary>
/// Get a copy of the value of the CurrentConnectionIDs property
/// </summary>
/// <remarks>Can only be called if EnablePropertyCurrentConnectionIDs has previously been called.</remarks>
/// <returns>Value of the CurrentConnectionIDs property.</returns>
public string PropertyCurrentConnectionIDs()
{
if (iPropertyCurrentConnectionIDs == null)
throw new PropertyDisabledError();
return iPropertyCurrentConnectionIDs.Value();
}
/// <summary>
/// Signal that the action GetProtocolInfo is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetProtocolInfo must be overridden if this is called.</remarks>
protected void EnableActionGetProtocolInfo()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetProtocolInfo");
action.AddOutputParameter(new ParameterRelated("Source", iPropertySourceProtocolInfo));
action.AddOutputParameter(new ParameterRelated("Sink", iPropertySinkProtocolInfo));
iDelegateGetProtocolInfo = new ActionDelegate(DoGetProtocolInfo);
EnableAction(action, iDelegateGetProtocolInfo, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action PrepareForConnection is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// PrepareForConnection must be overridden if this is called.</remarks>
protected void EnableActionPrepareForConnection()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("PrepareForConnection");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("RemoteProtocolInfo", allowedValues));
action.AddInputParameter(new ParameterString("PeerConnectionManager", allowedValues));
action.AddInputParameter(new ParameterInt("PeerConnectionID"));
allowedValues.Add("Input");
allowedValues.Add("Output");
action.AddInputParameter(new ParameterString("Direction", allowedValues));
allowedValues.Clear();
action.AddOutputParameter(new ParameterInt("ConnectionID"));
action.AddOutputParameter(new ParameterInt("AVTransportID"));
action.AddOutputParameter(new ParameterInt("RcsID"));
iDelegatePrepareForConnection = new ActionDelegate(DoPrepareForConnection);
EnableAction(action, iDelegatePrepareForConnection, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action ConnectionComplete is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// ConnectionComplete must be overridden if this is called.</remarks>
protected void EnableActionConnectionComplete()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("ConnectionComplete");
action.AddInputParameter(new ParameterInt("ConnectionID"));
iDelegateConnectionComplete = new ActionDelegate(DoConnectionComplete);
EnableAction(action, iDelegateConnectionComplete, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetCurrentConnectionIDs is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetCurrentConnectionIDs must be overridden if this is called.</remarks>
protected void EnableActionGetCurrentConnectionIDs()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetCurrentConnectionIDs");
action.AddOutputParameter(new ParameterRelated("ConnectionIDs", iPropertyCurrentConnectionIDs));
iDelegateGetCurrentConnectionIDs = new ActionDelegate(DoGetCurrentConnectionIDs);
EnableAction(action, iDelegateGetCurrentConnectionIDs, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetCurrentConnectionInfo is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetCurrentConnectionInfo must be overridden if this is called.</remarks>
protected void EnableActionGetCurrentConnectionInfo()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetCurrentConnectionInfo");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterInt("ConnectionID"));
action.AddOutputParameter(new ParameterInt("RcsID"));
action.AddOutputParameter(new ParameterInt("AVTransportID"));
action.AddOutputParameter(new ParameterString("ProtocolInfo", allowedValues));
action.AddOutputParameter(new ParameterString("PeerConnectionManager", allowedValues));
action.AddOutputParameter(new ParameterInt("PeerConnectionID"));
allowedValues.Add("Input");
allowedValues.Add("Output");
action.AddOutputParameter(new ParameterString("Direction", allowedValues));
allowedValues.Clear();
allowedValues.Add("OK");
allowedValues.Add("ContentFormatMismatch");
allowedValues.Add("InsufficientBandwidth");
allowedValues.Add("UnreliableChannel");
allowedValues.Add("Unknown");
action.AddOutputParameter(new ParameterString("Status", allowedValues));
allowedValues.Clear();
iDelegateGetCurrentConnectionInfo = new ActionDelegate(DoGetCurrentConnectionInfo);
EnableAction(action, iDelegateGetCurrentConnectionInfo, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// GetProtocolInfo action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetProtocolInfo action for the owning device.
///
/// Must be implemented iff EnableActionGetProtocolInfo was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aSource"></param>
/// <param name="aSink"></param>
protected virtual void GetProtocolInfo(IDvInvocation aInvocation, out string aSource, out string aSink)
{
throw (new ActionDisabledError());
}
/// <summary>
/// PrepareForConnection action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// PrepareForConnection action for the owning device.
///
/// Must be implemented iff EnableActionPrepareForConnection was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aRemoteProtocolInfo"></param>
/// <param name="aPeerConnectionManager"></param>
/// <param name="aPeerConnectionID"></param>
/// <param name="aDirection"></param>
/// <param name="aConnectionID"></param>
/// <param name="aAVTransportID"></param>
/// <param name="aRcsID"></param>
protected virtual void PrepareForConnection(IDvInvocation aInvocation, string aRemoteProtocolInfo, string aPeerConnectionManager, int aPeerConnectionID, string aDirection, out int aConnectionID, out int aAVTransportID, out int aRcsID)
{
throw (new ActionDisabledError());
}
/// <summary>
/// ConnectionComplete action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// ConnectionComplete action for the owning device.
///
/// Must be implemented iff EnableActionConnectionComplete was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aConnectionID"></param>
protected virtual void ConnectionComplete(IDvInvocation aInvocation, int aConnectionID)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetCurrentConnectionIDs action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetCurrentConnectionIDs action for the owning device.
///
/// Must be implemented iff EnableActionGetCurrentConnectionIDs was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aConnectionIDs"></param>
protected virtual void GetCurrentConnectionIDs(IDvInvocation aInvocation, out string aConnectionIDs)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetCurrentConnectionInfo action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetCurrentConnectionInfo action for the owning device.
///
/// Must be implemented iff EnableActionGetCurrentConnectionInfo was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aConnectionID"></param>
/// <param name="aRcsID"></param>
/// <param name="aAVTransportID"></param>
/// <param name="aProtocolInfo"></param>
/// <param name="aPeerConnectionManager"></param>
/// <param name="aPeerConnectionID"></param>
/// <param name="aDirection"></param>
/// <param name="aStatus"></param>
protected virtual void GetCurrentConnectionInfo(IDvInvocation aInvocation, int aConnectionID, out int aRcsID, out int aAVTransportID, out string aProtocolInfo, out string aPeerConnectionManager, out int aPeerConnectionID, out string aDirection, out string aStatus)
{
throw (new ActionDisabledError());
}
private static int DoGetProtocolInfo(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgConnectionManager2 self = (DvProviderUpnpOrgConnectionManager2)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string source;
string sink;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.GetProtocolInfo(invocation, out source, out sink);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetProtocolInfo");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetProtocolInfo"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetProtocolInfo", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("Source", source);
invocation.WriteString("Sink", sink);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetProtocolInfo", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoPrepareForConnection(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgConnectionManager2 self = (DvProviderUpnpOrgConnectionManager2)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string remoteProtocolInfo;
string peerConnectionManager;
int peerConnectionID;
string direction;
int connectionID;
int aVTransportID;
int rcsID;
try
{
invocation.ReadStart();
remoteProtocolInfo = invocation.ReadString("RemoteProtocolInfo");
peerConnectionManager = invocation.ReadString("PeerConnectionManager");
peerConnectionID = invocation.ReadInt("PeerConnectionID");
direction = invocation.ReadString("Direction");
invocation.ReadEnd();
self.PrepareForConnection(invocation, remoteProtocolInfo, peerConnectionManager, peerConnectionID, direction, out connectionID, out aVTransportID, out rcsID);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "PrepareForConnection");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "PrepareForConnection"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "PrepareForConnection", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteInt("ConnectionID", connectionID);
invocation.WriteInt("AVTransportID", aVTransportID);
invocation.WriteInt("RcsID", rcsID);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "PrepareForConnection", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoConnectionComplete(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgConnectionManager2 self = (DvProviderUpnpOrgConnectionManager2)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
int connectionID;
try
{
invocation.ReadStart();
connectionID = invocation.ReadInt("ConnectionID");
invocation.ReadEnd();
self.ConnectionComplete(invocation, connectionID);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "ConnectionComplete");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "ConnectionComplete"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "ConnectionComplete", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "ConnectionComplete", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetCurrentConnectionIDs(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgConnectionManager2 self = (DvProviderUpnpOrgConnectionManager2)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string connectionIDs;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.GetCurrentConnectionIDs(invocation, out connectionIDs);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetCurrentConnectionIDs");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetCurrentConnectionIDs"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetCurrentConnectionIDs", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("ConnectionIDs", connectionIDs);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetCurrentConnectionIDs", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetCurrentConnectionInfo(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderUpnpOrgConnectionManager2 self = (DvProviderUpnpOrgConnectionManager2)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
int connectionID;
int rcsID;
int aVTransportID;
string protocolInfo;
string peerConnectionManager;
int peerConnectionID;
string direction;
string status;
try
{
invocation.ReadStart();
connectionID = invocation.ReadInt("ConnectionID");
invocation.ReadEnd();
self.GetCurrentConnectionInfo(invocation, connectionID, out rcsID, out aVTransportID, out protocolInfo, out peerConnectionManager, out peerConnectionID, out direction, out status);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetCurrentConnectionInfo");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", "GetCurrentConnectionInfo"));
return -1;
}
catch (Exception e)
{
Console.WriteLine("WARNING: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetCurrentConnectionInfo", e.TargetSite.Name);
Console.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteInt("RcsID", rcsID);
invocation.WriteInt("AVTransportID", aVTransportID);
invocation.WriteString("ProtocolInfo", protocolInfo);
invocation.WriteString("PeerConnectionManager", peerConnectionManager);
invocation.WriteInt("PeerConnectionID", peerConnectionID);
invocation.WriteString("Direction", direction);
invocation.WriteString("Status", status);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
Console.WriteLine("ERROR: unexpected exception {0}(\"{1}\") thrown by {2} in {3}", e.GetType(), e.Message, "GetCurrentConnectionInfo", e.TargetSite.Name);
Console.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
/// <summary>
/// Must be called for each class instance. Must be called before Core.Library.Close().
/// </summary>
public virtual void Dispose()
{
if (DisposeProvider())
iGch.Free();
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: SortedList
**
** Purpose: A sorted dictionary.
**
**
===========================================================*/
namespace System.Collections
{
using System;
////using System.Security.Permissions;
using System.Diagnostics;
using System.Globalization;
// The SortedList class implements a sorted list of keys and values. Entries in
// a sorted list are sorted by their keys and are accessible both by key and by
// index. The keys of a sorted list can be ordered either according to a
// specific IComparer implementation given when the sorted list is
// instantiated, or according to the IComparable implementation provided
// by the keys themselves. In either case, a sorted list does not allow entries
// with duplicate keys.
//
// A sorted list internally maintains two arrays that store the keys and
// values of the entries. The capacity of a sorted list is the allocated
// length of these internal arrays. As elements are added to a sorted list, the
// capacity of the sorted list is automatically increased as required by
// reallocating the internal arrays. The capacity is never automatically
// decreased, but users can call either TrimToSize or
// Capacity explicitly.
//
// The GetKeyList and GetValueList methods of a sorted list
// provides access to the keys and values of the sorted list in the form of
// List implementations. The List objects returned by these
// methods are aliases for the underlying sorted list, so modifications
// made to those lists are directly reflected in the sorted list, and vice
// versa.
//
// The SortedList class provides a convenient way to create a sorted
// copy of another dictionary, such as a Hashtable. For example:
//
// Hashtable h = new Hashtable();
// h.Add(...);
// h.Add(...);
// ...
// SortedList s = new SortedList(h);
//
// The last line above creates a sorted list that contains a copy of the keys
// and values stored in the hashtable. In this particular example, the keys
// will be ordered according to the IComparable interface, which they
// all must implement. To impose a different ordering, SortedList also
// has a constructor that allows a specific IComparer implementation to
// be specified.
//
////[DebuggerTypeProxy( typeof( System.Collections.SortedList.SortedListDebugView ) )]
////[DebuggerDisplay( "Count = {Count}" )]
[Serializable]
public class SortedList : IDictionary, ICloneable
{
private const int cDefaultCapacity = 16;
private static Object[] emptyArray = new Object[0];
private Object[] m_keys;
private Object[] m_values;
private int m_size;
private int m_version;
private IComparer m_comparer;
private KeyList m_keyList;
private ValueList m_valueList;
[NonSerialized]
private Object m_syncRoot;
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to 16, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
public SortedList()
{
m_keys = emptyArray;
m_values = emptyArray;
m_size = 0;
m_comparer = new Comparer( CultureInfo.CurrentCulture );
}
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to 16, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
//
public SortedList( int initialCapacity )
{
if(initialCapacity < 0)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException( "initialCapacity", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) );
#else
throw new ArgumentOutOfRangeException();
#endif
}
m_keys = new Object[initialCapacity];
m_values = new Object[initialCapacity];
m_comparer = new Comparer( CultureInfo.CurrentCulture );
}
// Constructs a new sorted list with a given IComparer
// implementation. The sorted list is initially empty and has a capacity of
// zero. Upon adding the first element to the sorted list the capacity is
// increased to 16, and then increased in multiples of two as required. The
// elements of the sorted list are ordered according to the given
// IComparer implementation. If comparer is null, the
// elements are compared to each other using the IComparable
// interface, which in that case must be implemented by the keys of all
// entries added to the sorted list.
//
public SortedList( IComparer comparer ) : this()
{
if(comparer != null)
{
m_comparer = comparer;
}
}
// Constructs a new sorted list with a given IComparer
// implementation and a given initial capacity. The sorted list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required. The elements of the sorted list
// are ordered according to the given IComparer implementation. If
// comparer is null, the elements are compared to each other using
// the IComparable interface, which in that case must be implemented
// by the keys of all entries added to the sorted list.
//
public SortedList( IComparer comparer, int capacity ) : this( comparer )
{
this.Capacity = capacity;
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the IComparable interface, which must be implemented by the
// keys of all entries in the the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList( IDictionary d ) : this( d, null )
{
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the given IComparer implementation. If comparer is
// null, the elements are compared to each other using the
// IComparable interface, which in that case must be implemented
// by the keys of all entries in the the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList( IDictionary d, IComparer comparer ) : this( comparer, (d != null ? d.Count : 0) )
{
if(d == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException( "d", Environment.GetResourceString( "ArgumentNull_Dictionary" ) );
#else
throw new ArgumentNullException();
#endif
}
d.Keys .CopyTo( m_keys , 0 );
d.Values.CopyTo( m_values, 0 );
Array.Sort( m_keys, m_values, comparer );
m_size = d.Count;
}
// Adds an entry with the given key and value to this sorted list. An
// ArgumentException is thrown if the key is already present in the sorted list.
//
public virtual void Add( Object key, Object value )
{
if(key == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException( "key", Environment.GetResourceString( "ArgumentNull_Key" ) );
#else
throw new ArgumentNullException();
#endif
}
int i = Array.BinarySearch( m_keys, 0, m_size, key, m_comparer );
if(i >= 0)
{
#if EXCEPTION_STRINGS
throw new ArgumentException( Environment.GetResourceString( "Argument_AddingDuplicate__", GetKey( i ), key ) );
#else
throw new ArgumentException();
#endif
}
Insert( ~i, key, value );
}
// Returns the capacity of this sorted list. The capacity of a sorted list
// represents the allocated length of the internal arrays used to store the
// keys and values of the list, and thus also indicates the maximum number
// of entries the list can contain before a reallocation of the internal
// arrays is required.
//
public virtual int Capacity
{
get
{
return m_keys.Length;
}
set
{
if(value != m_keys.Length)
{
if(value < m_size)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString( "ArgumentOutOfRange_SmallCapacity" ) );
#else
throw new ArgumentOutOfRangeException();
#endif
}
if(value > 0)
{
Object[] newKeys = new Object[value];
Object[] newValues = new Object[value];
if(m_size > 0)
{
Array.Copy( m_keys , 0, newKeys , 0, m_size );
Array.Copy( m_values, 0, newValues, 0, m_size );
}
m_keys = newKeys;
m_values = newValues;
}
else
{
// size can only be zero here.
BCLDebug.Assert( m_size == 0, "Size is not zero" );
m_keys = emptyArray;
m_values = emptyArray;
}
}
}
}
// Returns the number of entries in this sorted list.
//
public virtual int Count
{
get
{
return m_size;
}
}
// Returns a collection representing the keys of this sorted list. This
// method returns the same object as GetKeyList, but typed as an
// ICollection instead of an IList.
//
public virtual ICollection Keys
{
get
{
return GetKeyList();
}
}
// Returns a collection representing the values of this sorted list. This
// method returns the same object as GetValueList, but typed as an
// ICollection instead of an IList.
//
public virtual ICollection Values
{
get
{
return GetValueList();
}
}
// Is this SortedList read-only?
public virtual bool IsReadOnly
{
get
{
return false;
}
}
public virtual bool IsFixedSize
{
get
{
return false;
}
}
// Is this SortedList synchronized (thread-safe)?
public virtual bool IsSynchronized
{
get
{
return false;
}
}
// Synchronization root for this object.
public virtual Object SyncRoot
{
get
{
if(m_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange( ref m_syncRoot, new Object(), null );
}
return m_syncRoot;
}
}
// Removes all entries from this sorted list.
public virtual void Clear()
{
// clear does not change the capacity
m_version++;
Array.Clear( m_keys , 0, m_size ); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
Array.Clear( m_values, 0, m_size ); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
m_size = 0;
}
// Makes a virtually identical copy of this SortedList. This is a shallow
// copy. IE, the Objects in the SortedList are not cloned - we copy the
// references to those objects.
public virtual Object Clone()
{
SortedList sl = new SortedList( m_size );
Array.Copy( m_keys , 0, sl.m_keys , 0, m_size );
Array.Copy( m_values, 0, sl.m_values, 0, m_size );
sl.m_size = m_size;
sl.m_version = m_version;
sl.m_comparer = m_comparer;
// Don't copy keyList nor valueList.
return sl;
}
// Checks if this sorted list contains an entry with the given key.
//
public virtual bool Contains( Object key )
{
return IndexOfKey( key ) >= 0;
}
// Checks if this sorted list contains an entry with the given key.
//
public virtual bool ContainsKey( Object key )
{
// Yes, this is a SPEC'ed duplicate of Contains().
return IndexOfKey( key ) >= 0;
}
// Checks if this sorted list contains an entry with the given value. The
// values of the entries of the sorted list are compared to the given value
// using the Object.Equals method. This method performs a linear
// search and is substantially slower than the Contains
// method.
//
public virtual bool ContainsValue( Object value )
{
return IndexOfValue( value ) >= 0;
}
// Copies the values in this SortedList to an array.
public virtual void CopyTo( Array array, int arrayIndex )
{
if(array == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException( "array", Environment.GetResourceString( "ArgumentNull_Array" ) );
#else
throw new ArgumentNullException();
#endif
}
if(array.Rank != 1)
{
#if EXCEPTION_STRINGS
throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) );
#else
throw new ArgumentException();
#endif
}
if(arrayIndex < 0)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException( "arrayIndex", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) );
#else
throw new ArgumentOutOfRangeException();
#endif
}
if(array.Length - arrayIndex < Count)
{
#if EXCEPTION_STRINGS
throw new ArgumentException( Environment.GetResourceString( "Arg_ArrayPlusOffTooSmall" ) );
#else
throw new ArgumentException();
#endif
}
for(int i = 0; i < Count; i++)
{
DictionaryEntry entry = new DictionaryEntry( m_keys[i], m_values[i] );
array.SetValue( entry, i + arrayIndex );
}
}
// Copies the values in this SortedList to an KeyValuePairs array.
// KeyValuePairs is different from Dictionary Entry in that it has special
// debugger attributes on its fields.
internal virtual KeyValuePairs[] ToKeyValuePairsArray()
{
KeyValuePairs[] array = new KeyValuePairs[Count];
for(int i = 0; i < Count; i++)
{
array[i] = new KeyValuePairs( m_keys[i], m_values[i] );
}
return array;
}
// Ensures that the capacity of this sorted list is at least the given
// minimum value. If the currect capacity of the list is less than
// min, the capacity is increased to twice the current capacity or
// to min, whichever is larger.
private void EnsureCapacity( int min )
{
int newCapacity = m_keys.Length == 0 ? cDefaultCapacity : m_keys.Length * 2;
if(newCapacity < min)
{
newCapacity = min;
}
this.Capacity = newCapacity;
}
// Returns the value of the entry at the given index.
//
public virtual Object GetByIndex( int index )
{
if(index < 0 || index >= m_size)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) );
#else
throw new ArgumentOutOfRangeException();
#endif
}
return m_values[index];
}
// Returns an IEnumerator for this sorted list. If modifications
// made to the sorted list while an enumeration is in progress,
// the MoveNext and Remove methods
// of the enumerator will throw an exception.
//
IEnumerator IEnumerable.GetEnumerator()
{
return new SortedListEnumerator( this, 0, m_size, SortedListEnumerator.DictEntry );
}
// Returns an IDictionaryEnumerator for this sorted list. If modifications
// made to the sorted list while an enumeration is in progress,
// the MoveNext and Remove methods
// of the enumerator will throw an exception.
//
public virtual IDictionaryEnumerator GetEnumerator()
{
return new SortedListEnumerator( this, 0, m_size, SortedListEnumerator.DictEntry );
}
// Returns the key of the entry at the given index.
//
public virtual Object GetKey( int index )
{
if(index < 0 || index >= m_size)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) );
#else
throw new ArgumentOutOfRangeException();
#endif
}
return m_keys[index];
}
// Returns an IList representing the keys of this sorted list. The
// returned list is an alias for the keys of this sorted list, so
// modifications made to the returned list are directly reflected in the
// underlying sorted list, and vice versa. The elements of the returned
// list are ordered in the same way as the elements of the sorted list. The
// returned list does not support adding, inserting, or modifying elements
// (the Add, AddRange, Insert, InsertRange,
// Reverse, Set, SetRange, and Sort methods
// throw exceptions), but it does allow removal of elements (through the
// Remove and RemoveRange methods or through an enumerator).
// Null is an invalid key value.
//
public virtual IList GetKeyList()
{
if(m_keyList == null)
{
m_keyList = new KeyList( this );
}
return m_keyList;
}
// Returns an IList representing the values of this sorted list. The
// returned list is an alias for the values of this sorted list, so
// modifications made to the returned list are directly reflected in the
// underlying sorted list, and vice versa. The elements of the returned
// list are ordered in the same way as the elements of the sorted list. The
// returned list does not support adding or inserting elements (the
// Add, AddRange, Insert and InsertRange
// methods throw exceptions), but it does allow modification and removal of
// elements (through the Remove, RemoveRange, Set and
// SetRange methods or through an enumerator).
//
public virtual IList GetValueList()
{
if(m_valueList == null)
{
m_valueList = new ValueList( this );
}
return m_valueList;
}
// Returns the value associated with the given key. If an entry with the
// given key is not found, the returned value is null.
//
public virtual Object this[Object key]
{
get
{
int i = IndexOfKey( key );
if(i >= 0)
{
return m_values[i];
}
return null;
}
set
{
if(key == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException( "key", Environment.GetResourceString( "ArgumentNull_Key" ) );
#else
throw new ArgumentNullException();
#endif
}
int i = Array.BinarySearch( m_keys, 0, m_size, key, m_comparer );
if(i >= 0)
{
m_values[i] = value;
m_version++;
return;
}
Insert( ~i, key, value );
}
}
// Returns the index of the entry with a given key in this sorted list. The
// key is located through a binary search, and thus the average execution
// time of this method is proportional to Log2(size), where
// size is the size of this sorted list. The returned value is -1 if
// the given key does not occur in this sorted list. Null is an invalid
// key value.
//
public virtual int IndexOfKey( Object key )
{
if(key == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException( "key", Environment.GetResourceString( "ArgumentNull_Key" ) );
#else
throw new ArgumentNullException();
#endif
}
int ret = Array.BinarySearch( m_keys, 0, m_size, key, m_comparer );
return ret >= 0 ? ret : -1;
}
// Returns the index of the first occurrence of an entry with a given value
// in this sorted list. The entry is located through a linear search, and
// thus the average execution time of this method is proportional to the
// size of this sorted list. The elements of the list are compared to the
// given value using the Object.Equals method.
//
public virtual int IndexOfValue( Object value )
{
return Array.IndexOf( m_values, value, 0, m_size );
}
// Inserts an entry with a given key and value at a given index.
private void Insert( int index, Object key, Object value )
{
if(m_size == m_keys.Length)
{
EnsureCapacity( m_size + 1 );
}
if(index < m_size)
{
Array.Copy( m_keys , index, m_keys , index + 1, m_size - index );
Array.Copy( m_values, index, m_values, index + 1, m_size - index );
}
m_keys [index] = key;
m_values[index] = value;
m_size++;
m_version++;
}
// Removes the entry at the given index. The size of the sorted list is
// decreased by one.
//
public virtual void RemoveAt( int index )
{
if(index < 0 || index >= m_size)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) );
#else
throw new ArgumentOutOfRangeException();
#endif
}
m_size--;
if(index < m_size)
{
Array.Copy( m_keys , index + 1, m_keys , index, m_size - index );
Array.Copy( m_values, index + 1, m_values, index, m_size - index );
}
m_keys [m_size] = null;
m_values[m_size] = null;
m_version++;
}
// Removes an entry from this sorted list. If an entry with the specified
// key exists in the sorted list, it is removed. An ArgumentException is
// thrown if the key is null.
//
public virtual void Remove( Object key )
{
int i = IndexOfKey( key );
if(i >= 0)
{
RemoveAt( i );
}
}
// Sets the value at an index to a given value. The previous value of
// the given entry is overwritten.
//
public virtual void SetByIndex( int index, Object value )
{
if(index < 0 || index >= m_size)
{
#if EXCEPTION_STRINGS
throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) );
#else
throw new ArgumentOutOfRangeException();
#endif
}
m_values[index] = value;
m_version++;
}
//// // Returns a thread-safe SortedList.
//// //
//// [HostProtection( Synchronization = true )]
//// public static SortedList Synchronized( SortedList list )
//// {
//// if(list == null)
//// {
//// throw new ArgumentNullException( "list" );
//// }
////
//// return new SyncSortedList( list );
//// }
// Sets the capacity of this sorted list to the size of the sorted list.
// This method can be used to minimize a sorted list's memory overhead once
// it is known that no new elements will be added to the sorted list. To
// completely clear a sorted list and release all memory referenced by the
// sorted list, execute the following statements:
//
// sortedList.Clear();
// sortedList.TrimToSize();
//
public virtual void TrimToSize()
{
Capacity = m_size;
}
//// [Serializable]
//// private class SyncSortedList : SortedList
//// {
//// private SortedList m_list;
//// private Object m_root;
////
//// internal SyncSortedList( SortedList list )
//// {
//// m_list = list;
//// m_root = list.SyncRoot;
//// }
////
//// public override int Count
//// {
//// get
//// {
//// lock(m_root)
//// {
//// return m_list.Count;
//// }
//// }
//// }
////
//// public override Object SyncRoot
//// {
//// get
//// {
//// return m_root;
//// }
//// }
////
//// public override bool IsReadOnly
//// {
//// get
//// {
//// return m_list.IsReadOnly;
//// }
//// }
////
//// public override bool IsFixedSize
//// {
//// get
//// {
//// return m_list.IsFixedSize;
//// }
//// }
////
////
//// public override bool IsSynchronized
//// {
//// get
//// {
//// return true;
//// }
//// }
////
//// public override Object this[Object key]
//// {
//// get
//// {
//// lock(m_root)
//// {
//// return m_list[key];
//// }
//// }
////
//// set
//// {
//// lock(m_root)
//// {
//// m_list[key] = value;
//// }
//// }
//// }
////
//// public override void Add( Object key, Object value )
//// {
//// lock(m_root)
//// {
//// m_list.Add( key, value );
//// }
//// }
////
//// public override int Capacity
//// {
//// get
//// {
//// lock(m_root)
//// {
//// return m_list.Capacity;
//// }
//// }
//// }
////
//// public override void Clear()
//// {
//// lock(m_root)
//// {
//// m_list.Clear();
//// }
//// }
////
//// public override Object Clone()
//// {
//// lock(m_root)
//// {
//// return m_list.Clone();
//// }
//// }
////
//// public override bool Contains( Object key )
//// {
//// lock(m_root)
//// {
//// return m_list.Contains( key );
//// }
//// }
////
//// public override bool ContainsKey( Object key )
//// {
//// lock(m_root)
//// {
//// return m_list.ContainsKey( key );
//// }
//// }
////
//// public override bool ContainsValue( Object key )
//// {
//// lock(m_root)
//// {
//// return m_list.ContainsValue( key );
//// }
//// }
////
//// public override void CopyTo( Array array, int index )
//// {
//// lock(m_root)
//// {
//// m_list.CopyTo( array, index );
//// }
//// }
////
//// public override Object GetByIndex( int index )
//// {
//// lock(m_root)
//// {
//// return m_list.GetByIndex( index );
//// }
//// }
////
//// public override IDictionaryEnumerator GetEnumerator()
//// {
//// lock(m_root)
//// {
//// return m_list.GetEnumerator();
//// }
//// }
////
//// public override Object GetKey( int index )
//// {
//// lock(m_root)
//// {
//// return m_list.GetKey( index );
//// }
//// }
////
//// public override IList GetKeyList()
//// {
//// lock(m_root)
//// {
//// return m_list.GetKeyList();
//// }
//// }
////
//// public override IList GetValueList()
//// {
//// lock(m_root)
//// {
//// return m_list.GetValueList();
//// }
//// }
////
//// public override int IndexOfKey( Object key )
//// {
//// lock(m_root)
//// {
//// return m_list.IndexOfKey( key );
//// }
//// }
////
//// public override int IndexOfValue( Object value )
//// {
//// lock(m_root)
//// {
//// return m_list.IndexOfValue( value );
//// }
//// }
////
//// public override void RemoveAt( int index )
//// {
//// lock(m_root)
//// {
//// m_list.RemoveAt( index );
//// }
//// }
////
//// public override void Remove( Object key )
//// {
//// lock(m_root)
//// {
//// m_list.Remove( key );
//// }
//// }
////
//// public override void SetByIndex( int index, Object value )
//// {
//// lock(m_root)
//// {
//// m_list.SetByIndex( index, value );
//// }
//// }
////
//// internal override KeyValuePairs[] ToKeyValuePairsArray()
//// {
//// return m_list.ToKeyValuePairsArray();
//// }
////
//// public override void TrimToSize()
//// {
//// lock(m_root)
//// {
//// m_list.TrimToSize();
//// }
//// }
//// }
[Serializable]
private class SortedListEnumerator : IDictionaryEnumerator, ICloneable
{
internal const int Keys = 1;
internal const int Values = 2;
internal const int DictEntry = 3;
private SortedList m_sortedList;
private Object m_key;
private Object m_value;
private int m_index;
private int m_startIndex; // Store for Reset.
private int m_endIndex;
private int m_version;
private bool m_current; // Is the current element valid?
private int m_getObjectRetType; // What should GetObject return?
internal SortedListEnumerator( SortedList sortedList, int index, int count, int getObjRetType )
{
m_sortedList = sortedList;
m_index = index;
m_startIndex = index;
m_endIndex = index + count;
m_version = sortedList.m_version;
m_current = false;
m_getObjectRetType = getObjRetType;
}
public Object Clone()
{
return MemberwiseClone();
}
public virtual Object Key
{
get
{
if(m_version != m_sortedList.m_version)
{
#if EXCEPTION_STRINGS
throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) );
#else
throw new InvalidOperationException();
#endif
}
if(m_current == false)
{
#if EXCEPTION_STRINGS
throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumOpCantHappen" ) );
#else
throw new InvalidOperationException();
#endif
}
return m_key;
}
}
public virtual bool MoveNext()
{
if(m_version != m_sortedList.m_version)
{
#if EXCEPTION_STRINGS
throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) );
#else
throw new InvalidOperationException();
#endif
}
if(m_index < m_endIndex)
{
m_key = m_sortedList.m_keys [m_index];
m_value = m_sortedList.m_values[m_index];
m_index++;
m_current = true;
return true;
}
m_key = null;
m_value = null;
m_current = false;
return false;
}
public virtual DictionaryEntry Entry
{
get
{
if(m_version != m_sortedList.m_version)
{
#if EXCEPTION_STRINGS
throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) );
#else
throw new InvalidOperationException();
#endif
}
if(m_current == false)
{
#if EXCEPTION_STRINGS
throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumOpCantHappen" ) );
#else
throw new InvalidOperationException();
#endif
}
return new DictionaryEntry( m_key, m_value );
}
}
public virtual Object Current
{
get
{
if(m_current == false)
{
#if EXCEPTION_STRINGS
throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumOpCantHappen" ) );
#else
throw new InvalidOperationException();
#endif
}
if(m_getObjectRetType == Keys)
{
return m_key;
}
else if(m_getObjectRetType == Values)
{
return m_value;
}
else
{
return new DictionaryEntry( m_key, m_value );
}
}
}
public virtual Object Value
{
get
{
if(m_version != m_sortedList.m_version)
{
#if EXCEPTION_STRINGS
throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) );
#else
throw new InvalidOperationException();
#endif
}
if(m_current == false)
{
#if EXCEPTION_STRINGS
throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumOpCantHappen" ) );
#else
throw new InvalidOperationException();
#endif
}
return m_value;
}
}
public virtual void Reset()
{
if(m_version != m_sortedList.m_version)
{
#if EXCEPTION_STRINGS
throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_EnumFailedVersion" ) );
#else
throw new InvalidOperationException();
#endif
}
m_index = m_startIndex;
m_current = false;
m_key = null;
m_value = null;
}
}
[Serializable]
private class KeyList : IList
{
private SortedList m_sortedList;
internal KeyList( SortedList sortedList )
{
this.m_sortedList = sortedList;
}
public virtual int Count
{
get
{
return m_sortedList.m_size;
}
}
public virtual bool IsReadOnly
{
get
{
return true;
}
}
public virtual bool IsFixedSize
{
get
{
return true;
}
}
public virtual bool IsSynchronized
{
get
{
return m_sortedList.IsSynchronized;
}
}
public virtual Object SyncRoot
{
get
{
return m_sortedList.SyncRoot;
}
}
public virtual int Add( Object key )
{
#if EXCEPTION_STRINGS
throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) );
#else
throw new NotSupportedException();
#endif
}
public virtual void Clear()
{
#if EXCEPTION_STRINGS
throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) );
#else
throw new NotSupportedException();
#endif
}
public virtual bool Contains( Object key )
{
return m_sortedList.Contains( key );
}
public virtual void CopyTo( Array array, int arrayIndex )
{
if(array != null && array.Rank != 1)
{
#if EXCEPTION_STRINGS
throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) );
#else
throw new ArgumentException();
#endif
}
// defer error checking to Array.Copy
Array.Copy( m_sortedList.m_keys, 0, array, arrayIndex, m_sortedList.Count );
}
public virtual void Insert( int index, Object value )
{
#if EXCEPTION_STRINGS
throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) );
#else
throw new NotSupportedException();
#endif
}
public virtual Object this[int index]
{
get
{
return m_sortedList.GetKey( index );
}
set
{
#if EXCEPTION_STRINGS
throw new NotSupportedException( Environment.GetResourceString( "NotSupported_KeyCollectionSet" ) );
#else
throw new NotSupportedException();
#endif
}
}
public virtual IEnumerator GetEnumerator()
{
return new SortedListEnumerator( m_sortedList, 0, m_sortedList.Count, SortedListEnumerator.Keys );
}
public virtual int IndexOf( Object key )
{
if(key == null)
{
#if EXCEPTION_STRINGS
throw new ArgumentNullException( "key", Environment.GetResourceString( "ArgumentNull_Key" ) );
#else
throw new ArgumentNullException();
#endif
}
int i = Array.BinarySearch( m_sortedList.m_keys, 0, m_sortedList.Count, key, m_sortedList.m_comparer );
if(i >= 0) return i;
return -1;
}
public virtual void Remove( Object key )
{
#if EXCEPTION_STRINGS
throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) );
#else
throw new NotSupportedException();
#endif
}
public virtual void RemoveAt( int index )
{
#if EXCEPTION_STRINGS
throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) );
#else
throw new NotSupportedException();
#endif
}
}
[Serializable]
private class ValueList : IList
{
private SortedList m_sortedList;
internal ValueList( SortedList sortedList )
{
m_sortedList = sortedList;
}
public virtual int Count
{
get
{
return m_sortedList.m_size;
}
}
public virtual bool IsReadOnly
{
get
{
return true;
}
}
public virtual bool IsFixedSize
{
get
{
return true;
}
}
public virtual bool IsSynchronized
{
get
{
return m_sortedList.IsSynchronized;
}
}
public virtual Object SyncRoot
{
get
{
return m_sortedList.SyncRoot;
}
}
public virtual int Add( Object key )
{
#if EXCEPTION_STRINGS
throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) );
#else
throw new NotSupportedException();
#endif
}
public virtual void Clear()
{
#if EXCEPTION_STRINGS
throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) );
#else
throw new NotSupportedException();
#endif
}
public virtual bool Contains( Object value )
{
return m_sortedList.ContainsValue( value );
}
public virtual void CopyTo( Array array, int arrayIndex )
{
if(array != null && array.Rank != 1)
{
#if EXCEPTION_STRINGS
throw new ArgumentException( Environment.GetResourceString( "Arg_RankMultiDimNotSupported" ) );
#else
throw new ArgumentException();
#endif
}
// defer error checking to Array.Copy
Array.Copy( m_sortedList.m_values, 0, array, arrayIndex, m_sortedList.Count );
}
public virtual void Insert( int index, Object value )
{
#if EXCEPTION_STRINGS
throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) );
#else
throw new NotSupportedException();
#endif
}
public virtual Object this[int index]
{
get
{
return m_sortedList.GetByIndex( index );
}
set
{
#if EXCEPTION_STRINGS
throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) );
#else
throw new NotSupportedException();
#endif
}
}
public virtual IEnumerator GetEnumerator()
{
return new SortedListEnumerator( m_sortedList, 0, m_sortedList.Count, SortedListEnumerator.Values );
}
public virtual int IndexOf( Object value )
{
return Array.IndexOf( m_sortedList.m_values, value, 0, m_sortedList.Count );
}
public virtual void Remove( Object value )
{
#if EXCEPTION_STRINGS
throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) );
#else
throw new NotSupportedException();
#endif
}
public virtual void RemoveAt( int index )
{
#if EXCEPTION_STRINGS
throw new NotSupportedException( Environment.GetResourceString( "NotSupported_SortedListNestedWrite" ) );
#else
throw new NotSupportedException();
#endif
}
}
//// // internal debug view class for sorted list
//// internal class SortedListDebugView
//// {
//// private SortedList sortedList;
////
//// public SortedListDebugView( SortedList sortedList )
//// {
//// if(sortedList == null)
//// {
//// throw new ArgumentNullException( "sortedList" );
//// }
////
//// this.sortedList = sortedList;
//// }
////
//// [DebuggerBrowsable( DebuggerBrowsableState.RootHidden )]
//// public KeyValuePairs[] Items
//// {
//// get
//// {
//// return sortedList.ToKeyValuePairsArray();
//// }
//// }
//// }
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
namespace OpenSim.Data
{
/// <summary>
///
/// The Migration theory is based on the ruby on rails concept.
/// Each database driver is going to be allowed to have files in
/// Resources that specify the database migrations. They will be
/// of the form:
///
/// 001_Users.sql
/// 002_Users.sql
/// 003_Users.sql
/// 001_Prims.sql
/// 002_Prims.sql
/// ...etc...
///
/// When a database driver starts up, it specifies a resource that
/// needs to be brought up to the current revision. For instance:
///
/// Migration um = new Migration(DbConnection, Assembly, "Users");
/// um.Update();
///
/// This works out which version Users is at, and applies all the
/// revisions past it to it. If there is no users table, all
/// revisions are applied in order. Consider each future
/// migration to be an incremental roll forward of the tables in
/// question.
///
/// Assembly must be specifically passed in because otherwise you
/// get the assembly that Migration.cs is part of, and what you
/// really want is the assembly of your database class.
///
/// </summary>
public class Migration
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected string _type;
protected DbConnection _conn;
protected Assembly _assem;
private Regex _match_old;
private Regex _match_new;
/// <summary>Have the parameterless constructor just so we can specify it as a generic parameter with the new() constraint.
/// Currently this is only used in the tests. A Migration instance created this way must be then
/// initialized with Initialize(). Regular creation should be through the parameterized constructors.
/// </summary>
public Migration()
{
}
public Migration(DbConnection conn, Assembly assem, string subtype, string type)
{
Initialize(conn, assem, type, subtype);
}
public Migration(DbConnection conn, Assembly assem, string type)
{
Initialize(conn, assem, type, "");
}
/// <summary>Must be called after creating with the parameterless constructor.
/// NOTE that the Migration class now doesn't access database in any way during initialization.
/// Specifically, it won't check if the [migrations] table exists. Such checks are done later:
/// automatically on Update(), or you can explicitly call InitMigrationsTable().
/// </summary>
/// <param name="conn"></param>
/// <param name="assem"></param>
/// <param name="subtype"></param>
/// <param name="type"></param>
public void Initialize (DbConnection conn, Assembly assem, string type, string subtype)
{
_type = type;
_conn = conn;
_assem = assem;
_match_old = new Regex(subtype + @"\.(\d\d\d)_" + _type + @"\.sql");
string s = String.IsNullOrEmpty(subtype) ? _type : _type + @"\." + subtype;
_match_new = new Regex(@"\." + s + @"\.migrations(?:\.(?<ver>\d+)$|.*)");
}
public void InitMigrationsTable()
{
// NOTE: normally when the [migrations] table is created, the version record for 'migrations' is
// added immediately. However, if for some reason the table is there but empty, we want to handle that as well.
int ver = FindVersion(_conn, "migrations");
if (ver <= 0) // -1 = no table, 0 = no version record
{
if (ver < 0)
ExecuteScript("create table migrations(name varchar(100), version int)");
InsertVersion("migrations", 1);
}
}
/// <summary>Executes a script, possibly in a database-specific way.
/// It can be redefined for a specific DBMS, if necessary. Specifically,
/// to avoid problems with proc definitions in MySQL, we must use
/// MySqlScript class instead of just DbCommand. We don't want to bring
/// MySQL references here, so instead define a MySQLMigration class
/// in OpenSim.Data.MySQL
/// </summary>
/// <param name="conn"></param>
/// <param name="script">Array of strings, one-per-batch (often just one)</param>
protected virtual void ExecuteScript(DbConnection conn, string[] script)
{
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandTimeout = 0;
foreach (string sql in script)
{
cmd.CommandText = sql;
try
{
cmd.ExecuteNonQuery();
}
catch(Exception e)
{
throw new Exception(e.Message + " in SQL: " + sql);
}
}
}
}
protected void ExecuteScript(DbConnection conn, string sql)
{
ExecuteScript(conn, new string[]{sql});
}
protected void ExecuteScript(string sql)
{
ExecuteScript(_conn, sql);
}
protected void ExecuteScript(string[] script)
{
ExecuteScript(_conn, script);
}
public void Update()
{
InitMigrationsTable();
int version = FindVersion(_conn, _type);
SortedList<int, string[]> migrations = GetMigrationsAfter(version);
if (migrations.Count < 1)
return;
// to prevent people from killing long migrations.
m_log.InfoFormat("[MIGRATIONS]: Upgrading {0} to latest revision {1}.", _type, migrations.Keys[migrations.Count - 1]);
m_log.Info("[MIGRATIONS]: NOTE - this may take a while, don't interrupt this process!");
foreach (KeyValuePair<int, string[]> kvp in migrations)
{
int newversion = kvp.Key;
// we need to up the command timeout to infinite as we might be doing long migrations.
/* [AlexRa 01-May-10]: We can't always just run any SQL in a single batch (= ExecuteNonQuery()). Things like
* stored proc definitions might have to be sent to the server each in a separate batch.
* This is certainly so for MS SQL; not sure how the MySQL connector sorts out the mess
* with 'delimiter @@'/'delimiter ;' around procs. So each "script" this code executes now is not
* a single string, but an array of strings, executed separately.
*/
try
{
ExecuteScript(kvp.Value);
}
catch (Exception e)
{
m_log.DebugFormat("[MIGRATIONS]: Cmd was {0}", e.Message.Replace("\n", " "));
m_log.Debug("[MIGRATIONS]: An error has occurred in the migration. If you're running OpenSim for the first time then you can probably safely ignore this, since certain migration commands attempt to fetch data out of old tables. However, if you're using an existing database and you see database related errors while running OpenSim then you will need to fix these problems manually. Continuing.");
ExecuteScript("ROLLBACK;");
}
if (version == 0)
{
InsertVersion(_type, newversion);
}
else
{
UpdateVersion(_type, newversion);
}
version = newversion;
}
}
public int Version
{
get { return FindVersion(_conn, _type); }
set {
if (Version < 1)
{
InsertVersion(_type, value);
}
else
{
UpdateVersion(_type, value);
}
}
}
protected virtual int FindVersion(DbConnection conn, string type)
{
int version = 0;
using (DbCommand cmd = conn.CreateCommand())
{
try
{
cmd.CommandText = "select version from migrations where name='" + type + "' order by version desc";
using (DbDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
version = Convert.ToInt32(reader["version"]);
}
reader.Close();
}
}
catch
{
// Something went wrong (probably no table), so we're at version -1
version = -1;
}
}
return version;
}
private void InsertVersion(string type, int version)
{
m_log.InfoFormat("[MIGRATIONS]: Creating {0} at version {1}", type, version);
ExecuteScript("insert into migrations(name, version) values('" + type + "', " + version + ")");
}
private void UpdateVersion(string type, int version)
{
m_log.InfoFormat("[MIGRATIONS]: Updating {0} to version {1}", type, version);
ExecuteScript("update migrations set version=" + version + " where name='" + type + "'");
}
private delegate void FlushProc();
/// <summary>Scans for migration resources in either old-style "scattered" (one file per version)
/// or new-style "integrated" format (single file with ":VERSION nnn" sections).
/// In the new-style migrations it also recognizes ':GO' separators for parts of the SQL script
/// that must be sent to the server separately. The old-style migrations are loaded each in one piece
/// and don't support the ':GO' feature.
/// </summary>
/// <param name="after">The version we are currently at. Scan for any higher versions</param>
/// <returns>A list of string arrays, representing the scripts.</returns>
private SortedList<int, string[]> GetMigrationsAfter(int after)
{
SortedList<int, string[]> migrations = new SortedList<int, string[]>();
string[] names = _assem.GetManifestResourceNames();
if (names.Length == 0) // should never happen
return migrations;
Array.Sort(names); // we want all the migrations ordered
int nLastVerFound = 0;
Match m = null;
string sFile = Array.FindLast(names, nm => { m = _match_new.Match(nm); return m.Success; }); // ; nm.StartsWith(sPrefix, StringComparison.InvariantCultureIgnoreCase
if ((m != null) && !String.IsNullOrEmpty(sFile))
{
/* The filename should be '<StoreName>.migrations[.NNN]' where NNN
* is the last version number defined in the file. If the '.NNN' part is recognized, the code can skip
* the file without looking inside if we have a higher version already. Without the suffix we read
* the file anyway and use the version numbers inside. Any unrecognized suffix (such as '.sql')
* is valid but ignored.
*
* NOTE that we expect only one 'merged' migration file. If there are several, we take the last one.
* If you are numbering them, leave only the latest one in the project or at least make sure they numbered
* to come up in the correct order (e.g. 'SomeStore.migrations.001' rather than 'SomeStore.migrations.1')
*/
if (m.Groups.Count > 1 && int.TryParse(m.Groups[1].Value, out nLastVerFound))
{
if (nLastVerFound <= after)
goto scan_old_style;
}
System.Text.StringBuilder sb = new System.Text.StringBuilder(4096);
int nVersion = -1;
List<string> script = new List<string>();
FlushProc flush = delegate()
{
if (sb.Length > 0) // last SQL stmt to script list
{
script.Add(sb.ToString());
sb.Length = 0;
}
if ((nVersion > 0) && (nVersion > after) && (script.Count > 0) && !migrations.ContainsKey(nVersion)) // script to the versioned script list
{
migrations[nVersion] = script.ToArray();
}
script.Clear();
};
using (Stream resource = _assem.GetManifestResourceStream(sFile))
using (StreamReader resourceReader = new StreamReader(resource))
{
int nLineNo = 0;
while (!resourceReader.EndOfStream)
{
string sLine = resourceReader.ReadLine();
nLineNo++;
if (String.IsNullOrEmpty(sLine) || sLine.StartsWith("#")) // ignore a comment or empty line
continue;
if (sLine.Trim().Equals(":GO", StringComparison.InvariantCultureIgnoreCase))
{
if (sb.Length == 0) continue;
if (nVersion > after)
script.Add(sb.ToString());
sb.Length = 0;
continue;
}
if (sLine.StartsWith(":VERSION ", StringComparison.InvariantCultureIgnoreCase)) // ":VERSION nnn"
{
flush();
int n = sLine.IndexOf('#'); // Comment is allowed in version sections, ignored
if (n >= 0)
sLine = sLine.Substring(0, n);
if (!int.TryParse(sLine.Substring(9).Trim(), out nVersion))
{
m_log.ErrorFormat("[MIGRATIONS]: invalid version marker at {0}: line {1}. Migration failed!", sFile, nLineNo);
break;
}
}
else
{
sb.AppendLine(sLine);
}
}
flush();
// If there are scattered migration files as well, only look for those with higher version numbers.
if (after < nVersion)
after = nVersion;
}
}
scan_old_style:
// scan "old style" migration pieces anyway, ignore any versions already filled from the single file
foreach (string s in names)
{
m = _match_old.Match(s);
if (m.Success)
{
int version = int.Parse(m.Groups[1].ToString());
if ((version > after) && !migrations.ContainsKey(version))
{
using (Stream resource = _assem.GetManifestResourceStream(s))
{
using (StreamReader resourceReader = new StreamReader(resource))
{
string sql = resourceReader.ReadToEnd();
migrations.Add(version, new string[]{sql});
}
}
}
}
}
if (migrations.Count < 1)
m_log.DebugFormat("[MIGRATIONS]: {0} data tables already up to date at revision {1}", _type, after);
return migrations;
}
}
}
| |
using System.Configuration;
using System.Data.Entity;
using AngularBreezeWebAPI.Model;
using AngularBreezeWebAPI.Model.Views;
using CompanyContact = AngularBreezeWebAPI.Model.Views.CompanyContact;
namespace AngularBreezeWebAPI.DataAccess
{
public class ProspectDbContext : BaseDbContext
{
static ProspectDbContext()
{
//This way EntityFramework will not try to make any changes to the DB. Very important in a production environment.
Database.SetInitializer<ProspectDbContext>(null);
}
public ProspectDbContext()
: base(ConfigurationManager.ConnectionStrings["ProspectDataContext"].ConnectionString)
{
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
}
public virtual DbSet<Company> Companies { get; set; }
public virtual DbSet<ContactNoteDetail> ContactNoteDetails { get; set; }
public virtual DbSet<SalesPerson> DMSalesPersons { get; set; }
public virtual DbSet<Activity> Activities { get; set; }
public virtual DbSet<Contact> Contacts { get; set; }
public virtual DbSet<ContactCorrespondence> ContactCorrespondence { get; set; }
public virtual DbSet<CompanyContact> CompanyContactsView { get; set; }
public virtual DbSet<ContactNameListForCompany> ContactNameListForCompaniesView { get; set; }
public virtual DbSet<ClientContact> ClientContactsView { get; set; }
public virtual DbSet<ToDoList> ToDoListsView { get; set; }
/// <summary>
/// This method is called when the model for a derived context has been initialized, but
/// before the model has been locked down and used to initialize the context. The default
/// implementation of this method does nothing, but it can be overridden in a derived class
/// such that the model can be further configured before it is locked down.
/// </summary>
/// <remarks>
/// Typically, this method is called only once when the first instance of a derived context
/// is created. The model for that context is then cached and is for all further instances of
/// the context in the app domain. This caching can be disabled by setting the ModelCaching
/// property on the given ModelBuidler, but note that this can seriously degrade performance.
/// More control over caching is provided through use of the DbModelBuilder and DbContextFactory
/// classes directly.
/// </remarks>
/// <param name="modelBuilder">The builder that defines the model for the context being created. </param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
BuildCompanyModel(modelBuilder);
BuildContactMethodModel(modelBuilder);
BuildContactNoteDetailModel(modelBuilder);
BuildSalesPersonModel(modelBuilder);
BuildActivityModel(modelBuilder);
BuildContactModel(modelBuilder);
BuildStatusActionModel(modelBuilder);
BuildCompanyContactModel(modelBuilder);
BuildCompanyContactViewModel(modelBuilder);
BuildContactNameListForCompanyModel(modelBuilder);
BuildClientContactModel(modelBuilder);
BuldMainSearchDataModel(modelBuilder);
}
private static void BuildClientContactModel(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ClientContact>()
.Property(e => e.CompanyName)
.IsUnicode(false);
modelBuilder.Entity<ClientContact>()
.Property(e => e.FirstName)
.IsUnicode(false);
modelBuilder.Entity<ClientContact>()
.Property(e => e.LastName)
.IsUnicode(false);
modelBuilder.Entity<ClientContact>()
.Property(e => e.ContactTitle)
.IsUnicode(false);
modelBuilder.Entity<ClientContact>()
.Property(e => e.EmailAddress)
.IsUnicode(false);
}
private static void BuildStatusActionModel(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<StatusAction>()
.Property(e => e.Description)
.IsUnicode(false);
modelBuilder.Entity<StatusAction>()
.Property(e => e.AdditionalInfoCaption)
.IsUnicode(false);
modelBuilder.Entity<StatusAction>()
.HasMany(e => e.Activities)
.WithRequired(e => e.StatusAction)
.HasForeignKey(e => e.ActionID)
.WillCascadeOnDelete(false);
}
private static void BuildActivityModel(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Activity>()
.Property(e => e.timestamp)
.IsFixedLength();
}
private static void BuildContactNoteDetailModel(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ContactNoteDetail>()
.Property(e => e.Note)
.IsUnicode(false);
modelBuilder.Entity<ContactNoteDetail>()
.Property(e => e.CompanyNote)
.IsUnicode(false);
modelBuilder.Entity<ContactNoteDetail>()
.Property(e => e.timestamp)
.IsFixedLength();
}
private static void BuldMainSearchDataModel(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MainSearchData>()
.Property(e => e.SalesPerson)
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.CompanyName)
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.StreetAddress_P)
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.City_P)
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.State_P)
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.ZipCode_P)
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.StreetAddress_M)
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.City_M)
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.State_M)
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.ZipCode_M)
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.ServiceBureau)
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.Acct)
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.bank)
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.Attorney)
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.CompanyTotal)
.HasPrecision(38, 2);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.Freq)
.IsFixedLength()
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.OfficePhone)
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.PriorServiceBureau)
.IsUnicode(false);
modelBuilder.Entity<MainSearchData>()
.Property(e => e.LastMailingTemplate)
.IsUnicode(false);
}
private static void BuildContactNameListForCompanyModel(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ContactNameListForCompany>()
.Property(e => e.JobTitle)
.IsUnicode(false);
modelBuilder.Entity<ContactNameListForCompany>()
.Property(e => e.Prefix)
.IsUnicode(false);
modelBuilder.Entity<ContactNameListForCompany>()
.Property(e => e.LastName)
.IsUnicode(false);
modelBuilder.Entity<ContactNameListForCompany>()
.Property(e => e.MiddleName)
.IsUnicode(false);
modelBuilder.Entity<ContactNameListForCompany>()
.Property(e => e.FirstName)
.IsUnicode(false);
modelBuilder.Entity<ContactNameListForCompany>()
.Property(e => e.Suffix)
.IsUnicode(false);
modelBuilder.Entity<ContactNameListForCompany>()
.Property(e => e.PhoneType)
.IsUnicode(false);
modelBuilder.Entity<ContactNameListForCompany>()
.Property(e => e.Phone)
.IsUnicode(false);
modelBuilder.Entity<ContactNameListForCompany>()
.Property(e => e.Extension)
.IsUnicode(false);
modelBuilder.Entity<ContactNameListForCompany>()
.Property(e => e.EmailType)
.IsUnicode(false);
modelBuilder.Entity<ContactNameListForCompany>()
.Property(e => e.Email)
.IsUnicode(false);
}
private static void BuildCompanyContactModel(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Model.CompanyContact>()
.Property(e => e.timestamp)
.IsFixedLength();
modelBuilder.Entity<Model.CompanyContact>()
.Property(e => e.CreateUser)
.IsUnicode(false);
modelBuilder.Entity<Model.CompanyContact>()
.Property(e => e.ModifyUser)
.IsUnicode(false);
modelBuilder.Entity<Model.CompanyContact>()
.HasMany(e => e.ContactNoteDetails)
.WithOptional(e => e.CompanyContact)
.HasForeignKey(e => new { e.ContactID, e.CompanyID })
.WillCascadeOnDelete();
}
private static void BuildCompanyContactViewModel(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<CompanyContact>()
.Property(e => e.ContactName)
.IsUnicode(false);
modelBuilder.Entity<CompanyContact>()
.Property(e => e.PhoneNumber)
.IsUnicode(false);
modelBuilder.Entity<CompanyContact>()
.Property(e => e.EmailAddress)
.IsUnicode(false);
modelBuilder.Entity<CompanyContact>()
.Property(e => e.Description)
.IsUnicode(false);
modelBuilder.Entity<CompanyContact>()
.Property(e => e.LastContactBy)
.IsUnicode(false);
modelBuilder.Entity<CompanyContact>()
.Property(e => e.LastContactMethod)
.IsUnicode(false);
}
private static void BuildContactModel(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Contact>()
.Property(e => e.timestamp)
.IsFixedLength();
modelBuilder.Entity<Contact>()
.Property(e => e.LastName)
.IsUnicode(false);
modelBuilder.Entity<Contact>()
.Property(e => e.FirstName)
.IsUnicode(false);
modelBuilder.Entity<Contact>()
.Property(e => e.MiddleName)
.IsUnicode(false);
modelBuilder.Entity<Contact>()
.Property(e => e.Prefix)
.IsUnicode(false);
modelBuilder.Entity<Contact>()
.Property(e => e.Suffix)
.IsUnicode(false);
modelBuilder.Entity<Contact>()
.Property(e => e.PersonalNote)
.IsUnicode(false);
modelBuilder.Entity<Contact>()
.Property(e => e.CreateUser)
.IsUnicode(false);
modelBuilder.Entity<Contact>()
.Property(e => e.ModifyUser)
.IsUnicode(false);
modelBuilder.Entity<Contact>()
.HasMany(e => e.Activities)
.WithOptional(e => e.Contact)
.WillCascadeOnDelete();
modelBuilder.Entity<Contact>()
.HasOptional(e => e.ContactCorrespondence)
.WithRequired(e => e.Contact)
.WillCascadeOnDelete();
modelBuilder.Entity<Contact>()
.HasMany(e => e.CompanyContact)
.WithRequired(e => e.Contact)
.WillCascadeOnDelete(false);
}
private static void BuildSalesPersonModel(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SalesPerson>()
.Property(e => e.LastName)
.IsUnicode(false);
modelBuilder.Entity<SalesPerson>()
.Property(e => e.FirstName)
.IsUnicode(false);
modelBuilder.Entity<SalesPerson>()
.Property(e => e.MidName)
.IsUnicode(false);
modelBuilder.Entity<SalesPerson>()
.Property(e => e.LogName)
.IsUnicode(false);
modelBuilder.Entity<SalesPerson>()
.Property(e => e.timestamp)
.IsFixedLength();
modelBuilder.Entity<SalesPerson>()
.HasMany(e => e.Activities)
.WithRequired(e => e.SalesPerson)
.WillCascadeOnDelete(false);
}
private static void BuildContactMethodModel(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ContactMethod>()
.Property(e => e.Description)
.IsUnicode(false);
modelBuilder.Entity<ContactMethod>()
.Property(e => e.timestamp)
.IsFixedLength();
modelBuilder.Entity<ContactMethod>()
.HasMany(e => e.ContactNoteDetails)
.WithRequired(e => e.ContactMethod)
.WillCascadeOnDelete(false);
}
private static void BuildCompanyModel(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Company>()
.Property(e => e.CompanyName)
.IsUnicode(false);
modelBuilder.Entity<Company>()
.Property(e => e.CreateUser)
.IsUnicode(false);
modelBuilder.Entity<Company>()
.Property(e => e.ModifyUser)
.IsUnicode(false);
modelBuilder.Entity<Company>()
.HasMany(e => e.ContactNoteDetails)
.WithRequired(e => e.Company)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Company>()
.HasMany(e => e.tdmActivities)
.WithRequired(e => e.Company)
.WillCascadeOnDelete(false);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Remoting.Lifetime;
using System.Threading;
using log4net;
using OpenMetaverse;
using Nini.Config;
using OpenSim;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api.Plugins;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces;
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
namespace OpenSim.Region.ScriptEngine.Shared.Api
{
[Serializable]
public class MOD_Api : MarshalByRefObject, IMOD_Api, IScriptApi
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
internal IScriptEngine m_ScriptEngine;
internal SceneObjectPart m_host;
internal TaskInventoryItem m_item;
internal bool m_MODFunctionsEnabled = false;
internal IScriptModuleComms m_comms = null;
internal IConfig m_osslconfig;
public void Initialize(
IScriptEngine scriptEngine, SceneObjectPart host, TaskInventoryItem item)
{
m_ScriptEngine = scriptEngine;
m_host = host;
m_item = item;
m_osslconfig = m_ScriptEngine.ConfigSource.Configs["OSSL"];
if(m_osslconfig == null)
m_osslconfig = m_ScriptEngine.Config;
if (m_osslconfig.GetBoolean("AllowMODFunctions", false))
m_MODFunctionsEnabled = true;
m_comms = m_ScriptEngine.World.RequestModuleInterface<IScriptModuleComms>();
if (m_comms == null)
m_MODFunctionsEnabled = false;
}
public override Object InitializeLifetimeService()
{
ILease lease = (ILease)base.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
// lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0);
// lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0);
}
return lease;
}
public Scene World
{
get { return m_ScriptEngine.World; }
}
internal void MODError(string msg)
{
throw new ScriptException("MOD Runtime Error: " + msg);
}
/// <summary>
/// Dumps an error message on the debug console.
/// </summary>
/// <param name='message'></param>
internal void MODShoutError(string message)
{
if (message.Length > 1023)
message = message.Substring(0, 1023);
World.SimChat(
Utils.StringToBytes(message),
ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL,
m_host.ParentGroup.RootPart.AbsolutePosition, m_host.Name, m_host.UUID, false);
IWorldComm wComm = m_ScriptEngine.World.RequestModuleInterface<IWorldComm>();
wComm.DeliverMessage(ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL, m_host.Name, m_host.UUID, message);
}
/// <summary>
///
/// </summary>
/// <param name="fname">The name of the function to invoke</param>
/// <param name="parms">List of parameters</param>
/// <returns>string result of the invocation</returns>
public void modInvokeN(string fname, params object[] parms)
{
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type returntype = m_comms.LookupReturnType(fname);
if (returntype != typeof(void))
MODError(String.Format("return type mismatch for {0}",fname));
modInvoke(fname,parms);
}
public LSL_String modInvokeS(string fname, params object[] parms)
{
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type returntype = m_comms.LookupReturnType(fname);
if (returntype != typeof(string))
MODError(String.Format("return type mismatch for {0}",fname));
string result = (string)modInvoke(fname,parms);
return new LSL_String(result);
}
public LSL_Integer modInvokeI(string fname, params object[] parms)
{
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type returntype = m_comms.LookupReturnType(fname);
if (returntype != typeof(int))
MODError(String.Format("return type mismatch for {0}",fname));
int result = (int)modInvoke(fname,parms);
return new LSL_Integer(result);
}
public LSL_Float modInvokeF(string fname, params object[] parms)
{
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type returntype = m_comms.LookupReturnType(fname);
if (returntype != typeof(float))
MODError(String.Format("return type mismatch for {0}",fname));
float result = (float)modInvoke(fname,parms);
return new LSL_Float(result);
}
public LSL_Key modInvokeK(string fname, params object[] parms)
{
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type returntype = m_comms.LookupReturnType(fname);
if (returntype != typeof(UUID))
MODError(String.Format("return type mismatch for {0}",fname));
UUID result = (UUID)modInvoke(fname,parms);
return new LSL_Key(result.ToString());
}
public LSL_Vector modInvokeV(string fname, params object[] parms)
{
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type returntype = m_comms.LookupReturnType(fname);
if (returntype != typeof(OpenMetaverse.Vector3))
MODError(String.Format("return type mismatch for {0}",fname));
OpenMetaverse.Vector3 result = (OpenMetaverse.Vector3)modInvoke(fname,parms);
return new LSL_Vector(result.X,result.Y,result.Z);
}
public LSL_Rotation modInvokeR(string fname, params object[] parms)
{
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type returntype = m_comms.LookupReturnType(fname);
if (returntype != typeof(OpenMetaverse.Quaternion))
MODError(String.Format("return type mismatch for {0}",fname));
OpenMetaverse.Quaternion result = (OpenMetaverse.Quaternion)modInvoke(fname,parms);
return new LSL_Rotation(result.X,result.Y,result.Z,result.W);
}
public LSL_List modInvokeL(string fname, params object[] parms)
{
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type returntype = m_comms.LookupReturnType(fname);
if (returntype != typeof(object[]))
MODError(String.Format("return type mismatch for {0}",fname));
object[] result = (object[])modInvoke(fname,parms);
object[] llist = new object[result.Length];
for (int i = 0; i < result.Length; i++)
{
if (result[i] is string)
{
llist[i] = new LSL_String((string)result[i]);
}
else if (result[i] is int)
{
llist[i] = new LSL_Integer((int)result[i]);
}
else if (result[i] is float)
{
llist[i] = new LSL_Float((float)result[i]);
}
else if (result[i] is double)
{
llist[i] = new LSL_Float((double)result[i]);
}
else if (result[i] is UUID)
{
llist[i] = new LSL_Key(result[i].ToString());
}
else if (result[i] is OpenMetaverse.Vector3)
{
OpenMetaverse.Vector3 vresult = (OpenMetaverse.Vector3)result[i];
llist[i] = new LSL_Vector(vresult.X, vresult.Y, vresult.Z);
}
else if (result[i] is OpenMetaverse.Quaternion)
{
OpenMetaverse.Quaternion qresult = (OpenMetaverse.Quaternion)result[i];
llist[i] = new LSL_Rotation(qresult.X, qresult.Y, qresult.Z, qresult.W);
}
else
{
MODError(String.Format("unknown list element {1} returned by {0}", fname, result[i].GetType().Name));
}
}
return new LSL_List(llist);
}
/// <summary>
/// Invokes a preregistered function through the ScriptModuleComms class
/// </summary>
/// <param name="fname">The name of the function to invoke</param>
/// <param name="fname">List of parameters</param>
/// <returns>string result of the invocation</returns>
protected object modInvoke(string fname, params object[] parms)
{
if (!m_MODFunctionsEnabled)
{
MODShoutError("Module command functions not enabled");
return "";
}
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type[] signature = m_comms.LookupTypeSignature(fname);
if (signature.Length != parms.Length)
MODError(String.Format("wrong number of parameters to function {0}",fname));
object[] convertedParms = new object[parms.Length];
for (int i = 0; i < parms.Length; i++)
convertedParms[i] = ConvertFromLSL(parms[i], signature[i], fname);
// now call the function, the contract with the function is that it will always return
// non-null but don't trust it completely
try
{
object result = m_comms.InvokeOperation(m_host.UUID, m_item.ItemID, fname, convertedParms);
if (result != null)
return result;
Type returntype = m_comms.LookupReturnType(fname);
if (returntype == typeof(void))
return null;
MODError(String.Format("Invocation of {0} failed; null return value",fname));
}
catch (Exception e)
{
MODError(String.Format("Invocation of {0} failed; {1}",fname,e.Message));
}
return null;
}
/// <summary>
/// Send a command to functions registered on an event
/// </summary>
public string modSendCommand(string module, string command, string k)
{
if (!m_MODFunctionsEnabled)
{
MODShoutError("Module command functions not enabled");
return UUID.Zero.ToString();;
}
UUID req = UUID.Random();
m_comms.RaiseEvent(m_item.ItemID, req.ToString(), module, command, k);
return req.ToString();
}
/// <summary>
/// </summary>
protected object ConvertFromLSL(object lslparm, Type type, string fname)
{
if(lslparm.GetType() == type)
return lslparm;
// ---------- String ----------
else if (lslparm is LSL_String)
{
if (type == typeof(string))
return (string)(LSL_String)lslparm;
// Need to check for UUID since keys are often treated as strings
if (type == typeof(UUID))
return new UUID((string)(LSL_String)lslparm);
}
// ---------- Integer ----------
else if (lslparm is LSL_Integer)
{
if (type == typeof(int) || type == typeof(float))
return (int)(LSL_Integer)lslparm;
}
// ---------- Float ----------
else if (lslparm is LSL_Float)
{
if (type == typeof(float))
return (float)(LSL_Float)lslparm;
}
// ---------- Key ----------
else if (lslparm is LSL_Key)
{
if (type == typeof(UUID))
return new UUID((LSL_Key)lslparm);
}
// ---------- Rotation ----------
else if (lslparm is LSL_Rotation)
{
if (type == typeof(OpenMetaverse.Quaternion))
{
return (OpenMetaverse.Quaternion)((LSL_Rotation)lslparm);
}
}
// ---------- Vector ----------
else if (lslparm is LSL_Vector)
{
if (type == typeof(OpenMetaverse.Vector3))
{
return (OpenMetaverse.Vector3)((LSL_Vector)lslparm);
}
}
// ---------- List ----------
else if (lslparm is LSL_List)
{
if (type == typeof(object[]))
{
object[] plist = ((LSL_List)lslparm).Data;
object[] result = new object[plist.Length];
for (int i = 0; i < plist.Length; i++)
{
if (plist[i] is LSL_String)
result[i] = (string)(LSL_String)plist[i];
else if (plist[i] is LSL_Integer)
result[i] = (int)(LSL_Integer)plist[i];
// The int check exists because of the many plain old int script constants in ScriptBase which
// are not LSL_Integers.
else if (plist[i] is int)
result[i] = plist[i];
else if (plist[i] is LSL_Float)
result[i] = (float)(LSL_Float)plist[i];
else if (plist[i] is LSL_Key)
result[i] = new UUID((LSL_Key)plist[i]);
else if (plist[i] is LSL_Rotation)
result[i] = (Quaternion)((LSL_Rotation)plist[i]);
else if (plist[i] is LSL_Vector)
result[i] = (Vector3)((LSL_Vector)plist[i]);
else
MODError(String.Format("{0}: unknown LSL list element type", fname));
}
return result;
}
}
MODError(String.Format("{0}: parameter type mismatch; expecting {1}, type(parm)={2}", fname, type.Name, lslparm.GetType()));
return null;
}
}
}
| |
//! \file ChainReactionCrypt.cs
//! \date Mon Mar 07 15:59:47 2016
//! \brief KiriKiri XP3 ecryption filter used in some games.
//
// Copyright (C) 2016-2018 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using GameRes.Compression;
using GameRes.Utility;
namespace GameRes.Formats.KiriKiri
{
// this encryption scheme encrypts first N bytes of file, where N varies depending on file's hash, and
// those variations are stored within "plugin/list.bin" file. by default N=512 (used when hash is not
// found within "list.bin").
//
// this implementation looks for "list.bin" upon archive open, parses it and remembers encryption
// threshold values in a dictionary.
//
// such implementation has some flaws, for one, it would fail if "list.bin" is stored within archive other
// than one being opened.
[Serializable]
public class ChainReactionCrypt : ICrypt
{
readonly string m_list_bin;
public ChainReactionCrypt () : this ("plugin/list.bin")
{
}
public ChainReactionCrypt (string list_file)
{
m_list_bin = list_file;
}
public override void Decrypt (Xp3Entry entry, long offset, byte[] values, int pos, int count)
{
uint limit = GetEncryptionLimit (entry);
if (offset >= limit)
return;
count = Math.Min ((int)(limit - offset), count);
uint key = entry.Hash;
int ofs = (int)offset;
for (int i = 0; i < count; ++i)
{
values[pos+i] ^= (byte)((ofs+i) ^ (byte)(key >> (((ofs+i) & 3) << 3)));
}
}
public override void Encrypt (Xp3Entry entry, long offset, byte[] values, int pos, int count)
{
throw new NotImplementedException (Strings.arcStrings.MsgEncNotImplemented);
// despite the fact that algorithm is symmetric, creating an archive without updating "list.bin"
// wouldn't make much sense
// Decrypt (entry, offset, values, pos, count);
}
protected virtual uint GetEncryptionLimit (Xp3Entry entry)
{
uint limit;
if (EncryptionThresholdMap != null && EncryptionThresholdMap.TryGetValue (entry.Hash, out limit))
return limit;
else
return 0x200;
}
[NonSerialized]
Dictionary<uint, uint> EncryptionThresholdMap;
public override void Init (ArcFile arc)
{
var bin = ReadListBin (arc, m_list_bin);
if (null == bin || bin.Length <= 0x30)
return;
Init (bin);
}
internal void Init (byte[] bin)
{
if (!Binary.AsciiEqual (bin, "\"\x0D\x0A"))
{
for (int i = 0; i < 3; ++i)
{
bin = DecodeListBin (bin);
if (null == bin)
return;
}
}
if (null == EncryptionThresholdMap)
EncryptionThresholdMap = new Dictionary<uint, uint>();
else
EncryptionThresholdMap.Clear();
ParseListBin (bin);
}
internal byte[] ReadListBin (ArcFile arc, string list_name)
{
var list_bin = arc.Dir.FirstOrDefault (e => e.Name == list_name) as Xp3Entry;
if (null == list_bin)
return null;
var bin = new byte[list_bin.UnpackedSize];
using (var input = arc.OpenEntry (list_bin))
input.Read (bin, 0, bin.Length);
return bin;
}
void ParseListBin (byte[] data)
{
using (var mem = new MemoryStream (data))
using (var input = new StreamReader (mem))
{
var converter = new UInt32Converter();
string line;
while ((line = input.ReadLine()) != null)
{
if (0 == line.Length || '0' != line[0])
continue;
var pair = line.Split (',');
if (pair.Length > 1)
{
uint hash = (uint)converter.ConvertFromString (pair[0]);
uint threshold = (uint)converter.ConvertFromString (pair[1]);
EncryptionThresholdMap[hash] = threshold;
}
}
}
}
static byte[] DecodeListBin (byte[] data)
{
var header = new byte[0x30];
DecodeDPD (data, 0, 0x30, header);
int packed_size = LittleEndian.ToInt32 (header, 0x0C);
int unpacked_size = LittleEndian.ToInt32 (header, 0x10);
if (packed_size <= 0 || packed_size > data.Length-0x30)
return null;
if (Binary.AsciiEqual (header, 0, "DPDC"))
{
var decrypted = new byte[packed_size];
DecodeDPD (data, 0x30, packed_size, decrypted);
return decrypted;
}
if (Binary.AsciiEqual (header, 0, "SZLC")) // LZSS
{
using (var input = new MemoryStream (data, 0x30, packed_size))
using (var lzss = new LzssReader (input, packed_size, unpacked_size))
{
lzss.Unpack();
return lzss.Data;
}
}
if (Binary.AsciiEqual (header, 0, "ELRC")) // RLE
{
var unpacked = new byte[unpacked_size];
int min_repeat = LittleEndian.ToInt32 (header, 0x1C);
DecodeRLE (data, 0x30, packed_size, unpacked, min_repeat);
return unpacked;
}
return null;
}
static void DecodeRLE (byte[] input, int offset, int length, byte[] output, int min_repeat)
{
int src = offset;
int src_end = offset+length;
int dst = 0;
while (src < src_end)
{
byte b = input[src++];
int repeat = 1;
while (repeat < min_repeat && src < src_end && input[src] == b)
{
++repeat;
++src;
}
if (repeat == min_repeat)
{
byte ctl = input[src++];
if (ctl > 0x7F)
repeat += input[src++] + ((ctl & 0x7F) << 8) + 0x80;
else
repeat += ctl;
}
for (int i = 0; i < repeat; ++i)
output[dst++] = b;
}
}
unsafe static void DecodeDPD (byte[] src, int offset, int length, byte[] dst)
{
if (offset > src.Length || length > dst.Length || length > src.Length - offset)
throw new IndexOutOfRangeException();
if (length < 8)
return;
int tail = length & 3;
if (tail != 0)
Buffer.BlockCopy (src, offset+length-tail, dst, length-tail, tail);
length /= 4;
fixed (byte* src8 = &src[offset], dst8 = dst)
{
uint* src32 = (uint*)src8;
uint* dst32 = (uint*)dst8;
for (int i = 0; i < length-1; ++i)
{
dst32[i] = src32[i] ^ src32[i+1];
}
dst32[length-1] = dst32[0] ^ src32[length-1];
}
}
}
[Serializable]
public class HachukanoCrypt : ChainReactionCrypt
{
public HachukanoCrypt () : base ("plugins/list.txt")
{
StartupTjsNotEncrypted = true;
}
protected override uint GetEncryptionLimit (Xp3Entry entry)
{
uint limit = base.GetEncryptionLimit (entry);
switch (limit)
{
case 0: return 0;
case 1: return 0x100;
case 2: return 0x200;
case 3: return entry.UnpackedSize;
default: return limit;
}
}
}
[Serializable]
public class ChocolatCrypt : ChainReactionCrypt
{
public ChocolatCrypt () : base ("plugins/list.txt")
{
StartupTjsNotEncrypted = true;
}
protected override uint GetEncryptionLimit (Xp3Entry entry)
{
uint limit = base.GetEncryptionLimit (entry);
switch (limit)
{
case 0: return 0;
case 2: return entry.UnpackedSize;
default: return 0x100;
}
}
}
[Serializable]
public class XanaduCrypt : ChainReactionCrypt
{
public XanaduCrypt () : base ("plugins/list.txt")
{
StartupTjsNotEncrypted = true;
}
public override void Init (ArcFile arc)
{
var bin = ReadListBin (arc, "list2.txt");
if (null == bin)
bin = ReadListBin (arc, "plugins/list.txt");
if (null == bin)
return;
Init (bin);
}
protected override uint GetEncryptionLimit (Xp3Entry entry)
{
uint limit = base.GetEncryptionLimit (entry);
switch (limit)
{
case 0: return 0;
case 2: return entry.UnpackedSize;
default: return 0x100;
}
}
public override void Decrypt (Xp3Entry entry, long offset, byte[] values, int pos, int count)
{
uint limit = GetEncryptionLimit (entry);
if (offset >= limit)
return;
count = Math.Min ((int)(limit - offset), count);
uint key = entry.Hash ^ ~0x03020100u;
int ofs = (int)offset;
byte extra = (byte)(((ofs & 0xFF) >> 2) << 2);
for (int i = 0; i < count; ++i)
{
if (((ofs + i) & 0xFF) == 0)
extra = 0;
else if (((ofs + i) & 3) == 0)
extra += 4;
values[pos+i] ^= (byte)((key >> (((ofs+i) & 3) << 3)) ^ extra);
}
}
}
[Serializable]
public class SisMikoCrypt : XanaduCrypt
{
public override void Decrypt (Xp3Entry entry, long offset, byte[] values, int pos, int count)
{
uint limit = GetEncryptionLimit (entry);
if (offset >= limit)
return;
count = Math.Min ((int)(limit - offset), count);
uint key = ~Binary.RotR (entry.Hash, 16);
int ofs = (int)offset;
for (int i = 0; i < count; ++i)
{
values[pos+i] ^= (byte)(key >> (((ofs+i) & 3) << 3));
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
namespace FileHelpers.Tests.CommonTests
{
[TestFixture]
public class IgnoreEmpties
{
[Test]
public void IgnoreEmpty1()
{
var engine = new FileHelperEngine<IgnoreEmptyType1>();
var res = TestCommon.ReadTest<IgnoreEmptyType1>(engine, "Good", "IgnoreEmpty1.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(8, engine.LineNumber);
}
[Test]
public void IgnoreEmpty2()
{
var engine = new FileHelperEngine<IgnoreEmptyType1>();
object[] res = TestCommon.ReadTest(engine, "Good", "IgnoreEmpty2.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(8, engine.LineNumber);
}
[Test]
public void IgnoreEmpty3()
{
var engine = new FileHelperEngine<IgnoreEmptyType1>();
var res = TestCommon.ReadTest<IgnoreEmptyType1>(engine, "Good", "IgnoreEmpty3.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(8, engine.LineNumber);
}
[Test]
public void IgnoreEmpty1Async()
{
var asyncEngine = new FileHelperAsyncEngine<IgnoreEmptyType1>();
var res = TestCommon.ReadAllAsync<IgnoreEmptyType1>(asyncEngine, "Good", "IgnoreEmpty1.txt");
Assert.AreEqual(4, res.Count);
Assert.AreEqual(8, asyncEngine.LineNumber);
}
[Test]
public void IgnoreEmpty3Async()
{
var asyncEngine = new FileHelperAsyncEngine<IgnoreEmptyType1>();
var res = TestCommon.ReadAllAsync<IgnoreEmptyType1>(asyncEngine, "Good", "IgnoreEmpty3.txt");
Assert.AreEqual(4, res.Count);
Assert.AreEqual(7, asyncEngine.LineNumber);
}
[Test]
public void IgnoreEmpty4Bad()
{
var engine = new FileHelperEngine<IgnoreEmptyType1>();
Assert.Throws<BadUsageException>(
() => TestCommon.ReadTest<IgnoreEmptyType1>(engine, "Good", "IgnoreEmpty4.txt"));
}
[Test]
public void IgnoreEmpty4BadAsync()
{
var asyncEngine = new FileHelperAsyncEngine<IgnoreEmptyType1>();
Assert.Throws<BadUsageException>(
() => TestCommon.ReadAllAsync<IgnoreEmptyType1>(asyncEngine, "Good", "IgnoreEmpty4.txt"));
}
[Test]
public void IgnoreEmpty4()
{
var engine = new FileHelperEngine<IgnoreEmptyType1Spaces>();
object[] res = TestCommon.ReadTest<IgnoreEmptyType1Spaces>(engine, "Good", "IgnoreEmpty4.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(7, engine.LineNumber);
}
[Test]
public void IgnoreEmpty5()
{
var engine = new FileHelperEngine<IgnoreEmptyType1Spaces>();
var res = TestCommon.ReadTest<IgnoreEmptyType1Spaces>(engine, "Good", "IgnoreEmpty5.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(7, engine.LineNumber);
}
[Test]
public void IgnoreComment1()
{
var engine = new FileHelperEngine<IgnoreCommentsType>();
object[] res = TestCommon.ReadTest<IgnoreCommentsType>(engine, "Good", "IgnoreComments1.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(7, engine.LineNumber);
}
[Test]
public void IgnoreComment1Async()
{
var asyncEngine = new FileHelperAsyncEngine<IgnoreCommentsType>();
var res = TestCommon.ReadAllAsync<IgnoreCommentsType>(asyncEngine, "Good", "IgnoreComments1.txt");
Assert.AreEqual(4, res.Count);
Assert.AreEqual(7, asyncEngine.LineNumber);
}
[Test]
public void IgnoreComment2()
{
var engine = new FileHelperEngine<IgnoreCommentsType>();
var res = TestCommon.ReadTest<IgnoreCommentsType>(engine, "Good", "IgnoreComments2.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(7, engine.LineNumber);
}
[Test]
public void IgnoreComment3()
{
var engine = new FileHelperEngine<IgnoreCommentsType2>();
var res = TestCommon.ReadTest<IgnoreCommentsType2>(engine, "Good", "IgnoreComments1.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(7, engine.LineNumber);
}
[Test]
public void IgnoreComment4()
{
var engine = new FileHelperEngine<IgnoreCommentsType2>();
Assert.Throws<ConvertException>(
() => TestCommon.ReadTest<IgnoreCommentsType2>(engine, "Good", "IgnoreComments2.txt"));
Assert.AreEqual(3, engine.LineNumber);
}
[FixedLengthRecord]
#pragma warning disable CS0618 // Type or member is obsolete
[IgnoreCommentedLines("//")]
#pragma warning restore CS0618 // Type or member is obsolete
public class IgnoreCommentsType
{
[FieldFixedLength(8)]
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime Field1;
[FieldFixedLength(3)]
public string Field2;
[FieldFixedLength(3)]
[FieldConverter(ConverterKind.Int32)]
public int Field3;
}
[FixedLengthRecord]
#pragma warning disable CS0618 // Type or member is obsolete
[IgnoreCommentedLines("//", false)]
#pragma warning restore CS0618 // Type or member is obsolete
public class IgnoreCommentsType2
{
[FieldFixedLength(8)]
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime Field1;
[FieldFixedLength(3)]
public string Field2;
[FieldFixedLength(3)]
[FieldConverter(ConverterKind.Int32)]
public int Field3;
}
[FixedLengthRecord]
[IgnoreEmptyLines]
public class IgnoreEmptyType1
{
[FieldFixedLength(8)]
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime Field1;
[FieldFixedLength(3)]
public string Field2;
[FieldFixedLength(3)]
[FieldConverter(ConverterKind.Int32)]
public int Field3;
}
[FixedLengthRecord]
[IgnoreEmptyLines(true)]
public class IgnoreEmptyType1Spaces
{
[FieldFixedLength(8)]
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime Field1;
[FieldFixedLength(3)]
public string Field2;
[FieldFixedLength(3)]
[FieldConverter(ConverterKind.Int32)]
public int Field3;
}
[DelimitedRecord("|")]
[IgnoreEmptyLines]
public class IgnoreEmptyType2
{
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime Field1;
[FieldFixedLength(3)]
public string Field2;
public int Field3;
}
}
}
| |
//
// System.Web.UI.WebControls.ListControl.cs
//
// Authors:
// Gaurav Vaish (gvaish@iitk.ac.in)
// Andreas Nahr (ClassDevelopment@A-SoftTech.com)
//
// (C) Gaurav Vaish (2002)
// (C) 2003 Andreas Nahr
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Web;
using System.Web.UI;
using System.Web.Util;
namespace System.Web.UI.WebControls
{
#if NET_2_0
[ControlValuePropertyAttribute ("SelectedValue")]
#else
[DefaultProperty("DataSource")]
#endif
[DefaultEvent("SelectedIndexChanged")]
[Designer ("System.Web.UI.Design.WebControls.ListControlDesigner, " + Consts.AssemblySystem_Design, typeof (IDesigner))]
[DataBindingHandler("System.Web.UI.Design.ListControlDataBindingHandler, " + Consts.AssemblySystem_Design)]
[ParseChildren(true, "Items")]
public abstract class ListControl :
#if NET_2_0
DataBoundControl, IEditableTextControl
#else
WebControl
#endif
{
private static readonly object SelectedIndexChangedEvent = new object();
#if NET_2_0
private static readonly object TextChangedEvent = new object();
#endif
#if !NET_2_0
private object dataSource;
#endif
private ListItemCollection items;
private int cachedSelectedIndex = -1;
private string cachedSelectedValue;
#if !NET_2_0
public ListControl(): base(HtmlTextWriterTag.Select)
{
}
#else
ArrayList selectedIndices;
protected override HtmlTextWriterTag TagKey {
get { return HtmlTextWriterTag.Select; }
}
#endif
[WebCategory ("Action")]
[WebSysDescription ("Raised when the selected index entry has changed.")]
public event EventHandler SelectedIndexChanged
{
add
{
Events.AddHandler(SelectedIndexChangedEvent, value);
}
remove
{
Events.RemoveHandler(SelectedIndexChangedEvent, value);
}
}
#if NET_2_0
[ThemeableAttribute (false)]
#endif
[DefaultValue (false), WebCategory ("Behavior")]
[WebSysDescription ("The control automatically posts back after changing the text.")]
public virtual bool AutoPostBack
{
get
{
object o = ViewState["AutoPostBack"];
if(o!=null)
return (bool)o;
return false;
}
set
{
ViewState["AutoPostBack"] = value;
}
}
#if !NET_2_0
[DefaultValue (""), WebCategory ("Data")]
[WebSysDescription ("The name of the table that is used for binding when a DataSource is specified.")]
public virtual string DataMember
{
get
{
object o = ViewState["DataMember"];
if(o!=null)
return (string)o;
return String.Empty;
}
set
{
ViewState["DataMember"] = value;
}
}
[DefaultValue (null), Bindable (true), WebCategory ("Data")]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription ("The DataSource that is used for data-binding.")]
public virtual object DataSource
{
get
{
return dataSource;
}
set
{
if(value == null || value is IListSource || value is IEnumerable) {
dataSource = value;
return;
}
throw new ArgumentException(HttpRuntime.FormatResourceString(ID, "Invalid DataSource Type"));
}
}
#endif
#if NET_2_0
[ThemeableAttribute (false)]
#endif
[DefaultValue (""), WebCategory ("Data")]
[WebSysDescription ("The field in the datatable that provides the text entry.")]
public virtual string DataTextField
{
get
{
object o = ViewState["DataTextField"];
if(o!=null)
return (string)o;
return String.Empty;
}
set
{
ViewState["DataTextField"] = value;
}
}
#if NET_2_0
[ThemeableAttribute (false)]
#endif
[DefaultValue (""), WebCategory ("Data")]
[WebSysDescription ("Specifies a formatting rule for the texts that are returned.")]
public virtual string DataTextFormatString
{
get
{
object o = ViewState["DataTextFormatString"];
if(o!=null)
return (string)o;
return String.Empty;
}
set
{
ViewState["DataTextFormatString"] = value;
}
}
#if NET_2_0
[ThemeableAttribute (false)]
#endif
[DefaultValue (""), WebCategory ("Data")]
[WebSysDescription ("The field in the datatable that provides the entry value.")]
public virtual string DataValueField
{
get
{
object o = ViewState["DataValueField"];
if(o!=null)
return (string)o;
return String.Empty;
}
set
{
ViewState["DataValueField"] = value;
}
}
#if NET_2_0
[Editor ("System.Web.UI.Design.WebControls.ListItemsCollectionEditor,System.Design, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
#endif
[DefaultValue (null), MergableProperty (false), WebCategory ("Misc")]
[PersistenceMode (PersistenceMode.InnerDefaultProperty)]
[WebSysDescription ("A collection of all items contained in this list.")]
public virtual ListItemCollection Items
{
get
{
if(items==null)
{
items = new ListItemCollection();
if(IsTrackingViewState)
{
items.TrackViewState();
}
}
return items;
}
}
#if NET_2_0
[ThemeableAttribute (false)]
#endif
[DefaultValue (0), Bindable (true), WebCategory ("Misc")]
[Browsable (false), DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription ("The index number of the currently selected ListItem.")]
public virtual int SelectedIndex
{
get {
ListItemCollection items = Items;
int last = items.Count;
for (int i = 0; i < last; i++) {
if (items [i].Selected)
return i;
}
return -1;
}
set {
if (Items.Count == 0)
{
cachedSelectedIndex = value;
return;
}
if ((value < -1) || (value >= Items.Count))
throw new ArgumentOutOfRangeException ();
ClearSelection ();
if (value != -1)
Items [value].Selected = true;
}
}
[DefaultValue (null), WebCategory ("Misc")]
[Browsable (false), DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription ("The currently selected ListItem.")]
public virtual ListItem SelectedItem
{
get
{
int idx = SelectedIndex;
if (idx < 0)
return null;
return Items [idx];
}
}
#if NET_1_1
#if NET_2_0
[ThemeableAttribute (false)]
[Bindable (true, BindingDirection.TwoWay)]
#else
[Bindable (true)]
#endif
[DefaultValue (""), WebCategory ("Misc")]
[Browsable (false), DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription ("The value of the currently selected ListItem.")]
public virtual string SelectedValue {
get {
int idx = SelectedIndex;
if (idx == -1)
return "";
return Items [idx].Value;
}
set {
ListItem item = null;
if (value != null) {
if (Items.Count > 0) {
item = Items.FindByValue (value);
if (item == null)
throw new ArgumentOutOfRangeException ("value");
} else {
cachedSelectedValue = value;
return;
}
}
ClearSelection ();
if (item != null)
item.Selected = true;
}
}
#endif
#if NET_2_0
[ThemeableAttribute (false)]
[DefaultValue (false), WebCategory ("Behavior")]
[WebSysDescription ("Determines if validation is performed when clicked.")]
public bool CausesValidation
{
get
{
Object cv = ViewState["CausesValidation"];
if(cv!=null)
return (Boolean)cv;
return true;
}
set
{
ViewState["CausesValidation"] = value;
}
}
[DefaultValueAttribute ("")]
[ThemeableAttribute (false)]
[WebCategoryAttribute ("Behavior")]
public string ValidationGroup {
get {
string text = (string)ViewState["ValidationGroup"];
if (text!=null) return text;
return String.Empty;
}
set {
ViewState["ValidationGroup"] = value;
}
}
[ThemeableAttribute (false)]
[WebCategory ("Behavior")]
[DefaultValueAttribute (false)]
public bool AppendDataBoundItems {
get {
Object cv = ViewState["AppendDataBoundItems"];
if (cv != null) return (bool) cv;
return false;
}
set {
ViewState["AppendDataBoundItems"] = value;
}
}
#endif
internal virtual ArrayList SelectedIndices
{
get
{
ArrayList si = new ArrayList();
for(int i=0; i < Items.Count; i++)
{
if(Items[i].Selected)
si.Add(i);
}
return si;
}
}
internal void Select(ArrayList indices)
{
ClearSelection();
foreach(object intObj in indices)
{
int index = (int)intObj;
if(index >= 0 && index < Items.Count)
Items[index].Selected = true;
}
}
public virtual void ClearSelection()
{
for(int i=0; i < Items.Count; i++)
{
Items[i].Selected = false;
}
}
#if NET_2_0
[ThemeableAttribute (false)]
[DefaultValueAttribute ("")]
[DesignerSerializationVisibilityAttribute (DesignerSerializationVisibility.Hidden)]
[BrowsableAttribute (false)]
[WebCategoryAttribute ("Behavior")]
public string Text {
get {
if (SelectedItem != null) return SelectedItem.Text;
else return null;
}
set {
for (int n=0; n < Items.Count; n++) {
if (Items[n].Text == value) {
SelectedIndex = n;
return;
}
}
SelectedIndex = -1;
}
}
public event EventHandler TextChanged
{
add {
Events.AddHandler (TextChangedEvent, value);
}
remove {
Events.RemoveHandler (TextChangedEvent, value);
}
}
protected virtual void OnTextChanged (EventArgs e)
{
if (Events != null) {
EventHandler eh = (EventHandler)(Events[TextChangedEvent]);
if (eh != null)
eh (this, e);
}
}
#endif
#if !NET_2_0
protected override void LoadViewState(object savedState)
{
//Order: BaseClass, Items (Collection), Indices
if(savedState != null && savedState is Triplet)
{
Triplet state = (Triplet)savedState;
base.LoadViewState(state.First);
Items.LoadViewState(state.Second);
object indices = state.Third;
if(indices != null)
{
Select((ArrayList)indices);
}
}
}
#else
protected override void LoadViewState(object savedState)
{
//Order: BaseClass, Items (Collection)
if(savedState != null && savedState is Pair)
{
Pair state = (Pair) savedState;
base.LoadViewState(state.First);
Items.LoadViewState(state.Second);
}
if (selectedIndices != null) {
Select (selectedIndices);
selectedIndices = null;
}
}
#endif
#if NET_2_0
protected override void PerformSelect ()
{
base.PerformSelect ();
}
protected override void PerformDataBinding (IEnumerable ds)
{
base.PerformDataBinding (ds);
if (!AppendDataBoundItems)
Items.Clear();
FillItems (ds);
}
#else
protected override void OnDataBinding(EventArgs e)
{
base.OnDataBinding(e);
IEnumerable ds = DataSourceHelper.GetResolvedDataSource (DataSource, DataMember);
if (ds != null)
Items.Clear ();
FillItems (ds);
}
#endif
void FillItems (IEnumerable ds)
{
if(ds != null) {
string dtf = DataTextField;
string dvf = DataValueField;
string dtfs = DataTextFormatString;
if (dtfs.Length == 0)
dtfs = "{0}";
bool dontUseProperties = (dtf.Length == 0 && dvf.Length == 0);
foreach (object current in ds) {
ListItem li = new ListItem();
if (dontUseProperties){
li.Text = String.Format (dtfs, current);
li.Value = current.ToString ();
Items.Add (li);
continue;
}
object o;
if (dtf.Length > 0) {
o = DataBinder.GetPropertyValue (current, dtf, dtfs);
li.Text = o.ToString ();
}
if (dvf.Length > 0) {
o = DataBinder.GetPropertyValue (current, dvf, null);
li.Value = o.ToString ();
}
Items.Add(li);
}
}
if (cachedSelectedValue != null) {
int index = Items.FindByValueInternal (cachedSelectedValue);
if (index == -1)
throw new ArgumentOutOfRangeException("value");
if (cachedSelectedIndex != -1 && cachedSelectedIndex != index)
throw new ArgumentException(HttpRuntime.FormatResourceString(
"Attributes_mutually_exclusive", "Selected Index", "Selected Value"));
SelectedIndex = index;
cachedSelectedIndex = -1;
cachedSelectedValue = null;
return;
}
if (cachedSelectedIndex != -1) {
SelectedIndex = cachedSelectedIndex;
cachedSelectedIndex = -1;
}
}
protected virtual void OnSelectedIndexChanged(EventArgs e)
{
if(Events!=null)
{
EventHandler eh = (EventHandler)(Events[SelectedIndexChangedEvent]);
if(eh!=null)
eh(this, e);
}
#if NET_2_0
OnTextChanged (e);
#endif
}
protected override void OnPreRender (EventArgs e)
{
base.OnPreRender(e);
}
#if !NET_2_0
protected override object SaveViewState()
{
//Order: BaseClass, Items (Collection), Indices
object vs = base.SaveViewState();
object itemSvs = Items.SaveViewState();
object indices = null;
if (SaveSelectedIndicesViewState)
indices = SelectedIndices;
if (vs != null || itemSvs != null || indices != null)
return new Triplet(vs, itemSvs, indices);
return null;
}
private bool SaveSelectedIndicesViewState {
get {
if (Events[SelectedIndexChangedEvent] == null && Enabled && Visible) {
Type t = GetType();
// If I am a derivative, let it take of storing the selected indices.
if (t == typeof(DropDownList) || t == typeof(ListBox) ||
t == typeof(CheckBoxList) || t == typeof(RadioButtonList))
return false;
}
return true;
}
}
#else
protected override object SaveViewState()
{
//Order: BaseClass, Items (Collection), Indices
object vs = base.SaveViewState();
object itemSvs = Items.SaveViewState();
if (vs != null || itemSvs != null)
return new Pair (vs, itemSvs);
return null;
}
#endif
protected override void TrackViewState()
{
base.TrackViewState();
Items.TrackViewState();
}
#if NET_2_0
protected override void OnInit (EventArgs e)
{
Page.RegisterRequiresControlState (this);
base.OnInit (e);
}
protected internal override void LoadControlState (object ob)
{
if (ob == null) return;
object[] state = (object[]) ob;
base.LoadControlState (state[0]);
selectedIndices = state[1] as ArrayList;
if (!EnableViewState) {
Select (selectedIndices);
selectedIndices = null;
}
}
protected internal override object SaveControlState ()
{
object bstate = base.SaveControlState ();
ArrayList mstate = SelectedIndices;
if (mstate.Count == 0) mstate = null;
if (bstate != null || mstate != null)
return new object[] { bstate, mstate };
else
return null;
}
protected internal virtual void VerifyMultiSelect ()
{
object o = ViewState ["SelectionMode"];
if (o != null && o.ToString () == "Single")
throw new HttpException ("Cannot_MultiSelect_In_Single_Mode");
}
protected override void RenderContents (HtmlTextWriter writer)
{
bool selMade = false;
foreach (ListItem current in Items){
writer.WriteBeginTag ("option");
if (current.Selected){
if (selMade) VerifyMultiSelect ();
selMade = true;
writer.WriteAttribute ("selected", "selected");
}
writer.WriteAttribute ("value", current.Value, true);
writer.Write ('>');
writer.Write (HttpUtility.HtmlEncode (current.Text));
writer.WriteEndTag ("option");
writer.WriteLine ();
}
}
#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.Buffers;
using System.Diagnostics;
using System.IO;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Security.Cryptography.Apple;
using System.Security.Cryptography.Asn1;
using Internal.Cryptography;
namespace System.Security.Cryptography
{
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
public partial class RSA : AsymmetricAlgorithm
{
public static new RSA Create()
{
return new RSAImplementation.RSASecurityTransforms();
}
}
#endif
internal static partial class RSAImplementation
{
public sealed partial class RSASecurityTransforms : RSA
{
private SecKeyPair _keys;
public RSASecurityTransforms()
: this(2048)
{
}
public RSASecurityTransforms(int keySize)
{
base.KeySize = keySize;
}
internal RSASecurityTransforms(SafeSecKeyRefHandle publicKey)
{
SetKey(SecKeyPair.PublicOnly(publicKey));
}
internal RSASecurityTransforms(SafeSecKeyRefHandle publicKey, SafeSecKeyRefHandle privateKey)
{
SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey));
}
public override KeySizes[] LegalKeySizes
{
get
{
return new KeySizes[]
{
// All values are in bits.
// 1024 was achieved via experimentation.
// 1024 and 1024+8 both generated successfully, 1024-8 produced errSecParam.
new KeySizes(minSize: 1024, maxSize: 16384, skipSize: 8),
};
}
}
public override int KeySize
{
get
{
return base.KeySize;
}
set
{
if (KeySize == value)
return;
// Set the KeySize before freeing the key so that an invalid value doesn't throw away the key
base.KeySize = value;
ThrowIfDisposed();
if (_keys != null)
{
_keys.Dispose();
_keys = null;
}
}
}
public override RSAParameters ExportParameters(bool includePrivateParameters)
{
// Apple requires all private keys to be exported encrypted, but since we're trying to export
// as parsed structures we will need to decrypt it for the user.
const string ExportPassword = "DotnetExportPassphrase";
SecKeyPair keys = GetKeys();
if (includePrivateParameters && keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_OpenInvalidHandle);
}
byte[] keyBlob = Interop.AppleCrypto.SecKeyExport(
includePrivateParameters ? keys.PrivateKey : keys.PublicKey,
exportPrivate: includePrivateParameters,
password: ExportPassword);
try
{
if (!includePrivateParameters)
{
// When exporting a key handle opened from a certificate, it seems to
// export as a PKCS#1 blob instead of an X509 SubjectPublicKeyInfo blob.
// So, check for that.
// NOTE: It doesn't affect macOS Mojave when SecCertificateCopyKey API
// is used.
RSAParameters key;
AsnReader reader = new AsnReader(keyBlob, AsnEncodingRules.BER);
AsnReader sequenceReader = reader.ReadSequence();
if (sequenceReader.PeekTag().Equals(Asn1Tag.Integer))
{
AlgorithmIdentifierAsn ignored = default;
RSAKeyFormatHelper.ReadRsaPublicKey(keyBlob, ignored, out key);
}
else
{
RSAKeyFormatHelper.ReadSubjectPublicKeyInfo(
keyBlob,
out int localRead,
out key);
Debug.Assert(localRead == keyBlob.Length);
}
return key;
}
else
{
RSAKeyFormatHelper.ReadEncryptedPkcs8(
keyBlob,
ExportPassword,
out int localRead,
out RSAParameters key);
return key;
}
}
finally
{
CryptographicOperations.ZeroMemory(keyBlob);
}
}
public override void ImportParameters(RSAParameters parameters)
{
ValidateParameters(parameters);
ThrowIfDisposed();
bool isPrivateKey = parameters.D != null;
if (isPrivateKey)
{
// Start with the private key, in case some of the private key fields
// don't match the public key fields.
//
// Public import should go off without a hitch.
SafeSecKeyRefHandle privateKey = ImportKey(parameters);
RSAParameters publicOnly = new RSAParameters
{
Modulus = parameters.Modulus,
Exponent = parameters.Exponent,
};
SafeSecKeyRefHandle publicKey;
try
{
publicKey = ImportKey(publicOnly);
}
catch
{
privateKey.Dispose();
throw;
}
SetKey(SecKeyPair.PublicPrivatePair(publicKey, privateKey));
}
else
{
SafeSecKeyRefHandle publicKey = ImportKey(parameters);
SetKey(SecKeyPair.PublicOnly(publicKey));
}
}
public override unsafe void ImportSubjectPublicKeyInfo(
ReadOnlySpan<byte> source,
out int bytesRead)
{
ThrowIfDisposed();
fixed (byte* ptr = &MemoryMarshal.GetReference(source))
{
using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length))
{
// Validate the DER value and get the number of bytes.
RSAKeyFormatHelper.ReadSubjectPublicKeyInfo(
manager.Memory,
out int localRead);
SafeSecKeyRefHandle publicKey = Interop.AppleCrypto.ImportEphemeralKey(source.Slice(0, localRead), false);
SetKey(SecKeyPair.PublicOnly(publicKey));
bytesRead = localRead;
}
}
}
public override unsafe void ImportRSAPublicKey(ReadOnlySpan<byte> source, out int bytesRead)
{
ThrowIfDisposed();
fixed (byte* ptr = &MemoryMarshal.GetReference(source))
{
using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length))
{
AsnReader reader = new AsnReader(manager.Memory, AsnEncodingRules.BER);
ReadOnlyMemory<byte> firstElement = reader.PeekEncodedValue();
SubjectPublicKeyInfoAsn spki = new SubjectPublicKeyInfoAsn
{
Algorithm = new AlgorithmIdentifierAsn
{
Algorithm = new Oid(Oids.Rsa),
Parameters = AlgorithmIdentifierAsn.ExplicitDerNull,
},
SubjectPublicKey = firstElement,
};
using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
{
spki.Encode(writer);
ImportSubjectPublicKeyInfo(writer.EncodeAsSpan(), out _);
}
bytesRead = firstElement.Length;
}
}
}
public override void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
ReadOnlySpan<byte> source,
out int bytesRead)
{
ThrowIfDisposed();
base.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out bytesRead);
}
public override void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
ReadOnlySpan<byte> source,
out int bytesRead)
{
ThrowIfDisposed();
base.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead);
}
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
if (padding == null)
{
throw new ArgumentNullException(nameof(padding));
}
ThrowIfDisposed();
// The size of encrypt is always the keysize (in ceiling-bytes)
int outputSize = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
byte[] output = new byte[outputSize];
if (!TryEncrypt(data, output, padding, out int bytesWritten))
{
Debug.Fail($"TryEncrypt with a preallocated buffer should not fail");
throw new CryptographicException();
}
Debug.Assert(bytesWritten == outputSize);
return output;
}
public override bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten)
{
if (padding == null)
{
throw new ArgumentNullException(nameof(padding));
}
ThrowIfDisposed();
int rsaSize = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
if (destination.Length < rsaSize)
{
bytesWritten = 0;
return false;
}
if (padding == RSAEncryptionPadding.Pkcs1 && data.Length > 0)
{
const int Pkcs1PaddingOverhead = 11;
int maxAllowed = rsaSize - Pkcs1PaddingOverhead;
if (data.Length > maxAllowed)
{
throw new CryptographicException(
SR.Format(SR.Cryptography_Encryption_MessageTooLong, maxAllowed));
}
return Interop.AppleCrypto.TryRsaEncrypt(
GetKeys().PublicKey,
data,
destination,
padding,
out bytesWritten);
}
RsaPaddingProcessor processor;
switch (padding.Mode)
{
case RSAEncryptionPaddingMode.Pkcs1:
processor = null;
break;
case RSAEncryptionPaddingMode.Oaep:
processor = RsaPaddingProcessor.OpenProcessor(padding.OaepHashAlgorithm);
break;
default:
throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
byte[] rented = CryptoPool.Rent(rsaSize);
Span<byte> tmp = new Span<byte>(rented, 0, rsaSize);
try
{
if (processor != null)
{
processor.PadOaep(data, tmp);
}
else
{
Debug.Assert(padding.Mode == RSAEncryptionPaddingMode.Pkcs1);
RsaPaddingProcessor.PadPkcs1Encryption(data, tmp);
}
return Interop.AppleCrypto.TryRsaEncryptionPrimitive(
GetKeys().PublicKey,
tmp,
destination,
out bytesWritten);
}
finally
{
CryptographicOperations.ZeroMemory(tmp);
CryptoPool.Return(rented, clearSize: 0);
}
}
public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
if (padding == null)
{
throw new ArgumentNullException(nameof(padding));
}
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
int modulusSizeInBytes = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
if (data.Length != modulusSizeInBytes)
{
throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize);
}
if (padding.Mode == RSAEncryptionPaddingMode.Pkcs1)
{
return Interop.AppleCrypto.RsaDecrypt(keys.PrivateKey, data, padding);
}
int maxOutputSize = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
byte[] rented = CryptoPool.Rent(maxOutputSize);
int bytesWritten = 0;
try
{
if (!TryDecrypt(keys.PrivateKey, data, rented, padding, out bytesWritten))
{
Debug.Fail($"TryDecrypt returned false with a modulus-sized destination");
throw new CryptographicException();
}
Span<byte> contentsSpan = new Span<byte>(rented, 0, bytesWritten);
return contentsSpan.ToArray();
}
finally
{
CryptoPool.Return(rented, bytesWritten);
}
}
public override bool TryDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten)
{
if (padding == null)
{
throw new ArgumentNullException(nameof(padding));
}
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
return TryDecrypt(keys.PrivateKey, data, destination, padding, out bytesWritten);
}
private bool TryDecrypt(
SafeSecKeyRefHandle privateKey,
ReadOnlySpan<byte> data,
Span<byte> destination,
RSAEncryptionPadding padding,
out int bytesWritten)
{
Debug.Assert(privateKey != null);
if (padding.Mode != RSAEncryptionPaddingMode.Pkcs1 &&
padding.Mode != RSAEncryptionPaddingMode.Oaep)
{
throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
int modulusSizeInBytes = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
if (data.Length != modulusSizeInBytes)
{
throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize);
}
if (padding.Mode == RSAEncryptionPaddingMode.Pkcs1 ||
padding == RSAEncryptionPadding.OaepSHA1)
{
return Interop.AppleCrypto.TryRsaDecrypt(privateKey, data, destination, padding, out bytesWritten);
}
Debug.Assert(padding.Mode == RSAEncryptionPaddingMode.Oaep);
RsaPaddingProcessor processor = RsaPaddingProcessor.OpenProcessor(padding.OaepHashAlgorithm);
byte[] rented = CryptoPool.Rent(modulusSizeInBytes);
Span<byte> unpaddedData = Span<byte>.Empty;
try
{
if (!Interop.AppleCrypto.TryRsaDecryptionPrimitive(privateKey, data, rented, out int paddedSize))
{
Debug.Fail($"Raw decryption failed with KeySize={KeySize} and a buffer length {rented.Length}");
throw new CryptographicException();
}
Debug.Assert(modulusSizeInBytes == paddedSize);
unpaddedData = new Span<byte>(rented, 0, paddedSize);
return processor.DepadOaep(unpaddedData, destination, out bytesWritten);
}
finally
{
CryptographicOperations.ZeroMemory(unpaddedData);
CryptoPool.Return(rented, clearSize: 0);
}
}
public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
if (hash == null)
throw new ArgumentNullException(nameof(hash));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw HashAlgorithmNameNullOrEmpty();
if (padding == null)
throw new ArgumentNullException(nameof(padding));
ThrowIfDisposed();
if (padding == RSASignaturePadding.Pkcs1)
{
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
int expectedSize;
Interop.AppleCrypto.PAL_HashAlgorithm palAlgId =
PalAlgorithmFromAlgorithmName(hashAlgorithm, out expectedSize);
if (hash.Length != expectedSize)
{
// Windows: NTE_BAD_DATA ("Bad Data.")
// OpenSSL: RSA_R_INVALID_MESSAGE_LENGTH ("invalid message length")
throw new CryptographicException(
SR.Format(
SR.Cryptography_BadHashSize_ForAlgorithm,
hash.Length,
expectedSize,
hashAlgorithm.Name));
}
return Interop.AppleCrypto.GenerateSignature(
keys.PrivateKey,
hash,
palAlgId);
}
// A signature will always be the keysize (in ceiling-bytes) in length.
int outputSize = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
byte[] output = new byte[outputSize];
if (!TrySignHash(hash, output, hashAlgorithm, padding, out int bytesWritten))
{
Debug.Fail("TrySignHash failed with a pre-allocated buffer");
throw new CryptographicException();
}
Debug.Assert(bytesWritten == outputSize);
return output;
}
public override bool TrySignHash(ReadOnlySpan<byte> hash, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten)
{
if (string.IsNullOrEmpty(hashAlgorithm.Name))
{
throw HashAlgorithmNameNullOrEmpty();
}
if (padding == null)
{
throw new ArgumentNullException(nameof(padding));
}
ThrowIfDisposed();
RsaPaddingProcessor processor = null;
if (padding.Mode == RSASignaturePaddingMode.Pss)
{
processor = RsaPaddingProcessor.OpenProcessor(hashAlgorithm);
}
else if (padding != RSASignaturePadding.Pkcs1)
{
throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
int keySize = KeySize;
int rsaSize = RsaPaddingProcessor.BytesRequiredForBitCount(keySize);
if (processor == null)
{
Interop.AppleCrypto.PAL_HashAlgorithm palAlgId =
PalAlgorithmFromAlgorithmName(hashAlgorithm, out int expectedSize);
if (hash.Length != expectedSize)
{
// Windows: NTE_BAD_DATA ("Bad Data.")
// OpenSSL: RSA_R_INVALID_MESSAGE_LENGTH ("invalid message length")
throw new CryptographicException(
SR.Format(
SR.Cryptography_BadHashSize_ForAlgorithm,
hash.Length,
expectedSize,
hashAlgorithm.Name));
}
if (destination.Length < rsaSize)
{
bytesWritten = 0;
return false;
}
return Interop.AppleCrypto.TryGenerateSignature(
keys.PrivateKey,
hash,
destination,
palAlgId,
out bytesWritten);
}
Debug.Assert(padding.Mode == RSASignaturePaddingMode.Pss);
if (destination.Length < rsaSize)
{
bytesWritten = 0;
return false;
}
byte[] rented = CryptoPool.Rent(rsaSize);
Span<byte> buf = new Span<byte>(rented, 0, rsaSize);
processor.EncodePss(hash, buf, keySize);
try
{
return Interop.AppleCrypto.TryRsaSignaturePrimitive(keys.PrivateKey, buf, destination, out bytesWritten);
}
finally
{
CryptographicOperations.ZeroMemory(buf);
CryptoPool.Return(rented, clearSize: 0);
}
}
public override bool VerifyHash(
byte[] hash,
byte[] signature,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding padding)
{
if (hash == null)
{
throw new ArgumentNullException(nameof(hash));
}
if (signature == null)
{
throw new ArgumentNullException(nameof(signature));
}
return VerifyHash((ReadOnlySpan<byte>)hash, (ReadOnlySpan<byte>)signature, hashAlgorithm, padding);
}
public override bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
if (string.IsNullOrEmpty(hashAlgorithm.Name))
{
throw HashAlgorithmNameNullOrEmpty();
}
if (padding == null)
{
throw new ArgumentNullException(nameof(padding));
}
ThrowIfDisposed();
if (padding == RSASignaturePadding.Pkcs1)
{
Interop.AppleCrypto.PAL_HashAlgorithm palAlgId =
PalAlgorithmFromAlgorithmName(hashAlgorithm, out int expectedSize);
return Interop.AppleCrypto.VerifySignature(GetKeys().PublicKey, hash, signature, palAlgId);
}
else if (padding.Mode == RSASignaturePaddingMode.Pss)
{
RsaPaddingProcessor processor = RsaPaddingProcessor.OpenProcessor(hashAlgorithm);
SafeSecKeyRefHandle publicKey = GetKeys().PublicKey;
int keySize = KeySize;
int rsaSize = RsaPaddingProcessor.BytesRequiredForBitCount(keySize);
if (signature.Length != rsaSize)
{
return false;
}
if (hash.Length != processor.HashLength)
{
return false;
}
byte[] rented = CryptoPool.Rent(rsaSize);
Span<byte> unwrapped = new Span<byte>(rented, 0, rsaSize);
try
{
if (!Interop.AppleCrypto.TryRsaVerificationPrimitive(
publicKey,
signature,
unwrapped,
out int bytesWritten))
{
Debug.Fail($"TryRsaVerificationPrimitive with a pre-allocated buffer");
throw new CryptographicException();
}
Debug.Assert(bytesWritten == rsaSize);
return processor.VerifyPss(hash, unwrapped, keySize);
}
finally
{
CryptographicOperations.ZeroMemory(unwrapped);
CryptoPool.Return(rented, clearSize: 0);
}
}
throw new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) =>
AsymmetricAlgorithmHelpers.HashData(data, offset, count, hashAlgorithm);
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) =>
AsymmetricAlgorithmHelpers.HashData(data, hashAlgorithm);
protected override bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) =>
AsymmetricAlgorithmHelpers.TryHashData(data, destination, hashAlgorithm, out bytesWritten);
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_keys != null)
{
// Do not set _keys to null, in order to prevent rehydration.
_keys.Dispose();
}
}
base.Dispose(disposing);
}
private static Interop.AppleCrypto.PAL_HashAlgorithm PalAlgorithmFromAlgorithmName(
HashAlgorithmName hashAlgorithmName,
out int hashSizeInBytes)
{
if (hashAlgorithmName == HashAlgorithmName.MD5)
{
hashSizeInBytes = 128 >> 3;
return Interop.AppleCrypto.PAL_HashAlgorithm.Md5;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA1)
{
hashSizeInBytes = 160 >> 3;
return Interop.AppleCrypto.PAL_HashAlgorithm.Sha1;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA256)
{
hashSizeInBytes = 256 >> 3;
return Interop.AppleCrypto.PAL_HashAlgorithm.Sha256;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA384)
{
hashSizeInBytes = 384 >> 3;
return Interop.AppleCrypto.PAL_HashAlgorithm.Sha384;
}
else if (hashAlgorithmName == HashAlgorithmName.SHA512)
{
hashSizeInBytes = 512 >> 3;
return Interop.AppleCrypto.PAL_HashAlgorithm.Sha512;
}
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithmName.Name);
}
private void ThrowIfDisposed()
{
SecKeyPair current = _keys;
if (current != null && current.PublicKey == null)
{
throw new ObjectDisposedException(nameof(RSA));
}
}
internal SecKeyPair GetKeys()
{
ThrowIfDisposed();
SecKeyPair current = _keys;
if (current != null)
{
return current;
}
SafeSecKeyRefHandle publicKey;
SafeSecKeyRefHandle privateKey;
Interop.AppleCrypto.RsaGenerateKey(KeySizeValue, out publicKey, out privateKey);
current = SecKeyPair.PublicPrivatePair(publicKey, privateKey);
_keys = current;
return current;
}
private void SetKey(SecKeyPair newKeyPair)
{
ThrowIfDisposed();
SecKeyPair current = _keys;
_keys = newKeyPair;
current?.Dispose();
if (newKeyPair != null)
{
KeySizeValue = Interop.AppleCrypto.GetSimpleKeySizeInBits(newKeyPair.PublicKey);
}
}
private static SafeSecKeyRefHandle ImportKey(RSAParameters parameters)
{
if (parameters.D != null)
{
using (AsnWriter pkcs1PrivateKey = RSAKeyFormatHelper.WritePkcs1PrivateKey(parameters))
{
return Interop.AppleCrypto.ImportEphemeralKey(pkcs1PrivateKey.EncodeAsSpan(), true);
}
}
else
{
using (AsnWriter pkcs1PublicKey = RSAKeyFormatHelper.WriteSubjectPublicKeyInfo(parameters))
{
return Interop.AppleCrypto.ImportEphemeralKey(pkcs1PublicKey.EncodeAsSpan(), false);
}
}
}
private static void ValidateParameters(in RSAParameters parameters)
{
if (parameters.Modulus == null || parameters.Exponent == null)
throw new CryptographicException(SR.Argument_InvalidValue);
if (!HasConsistentPrivateKey(parameters))
throw new CryptographicException(SR.Argument_InvalidValue);
}
private static bool HasConsistentPrivateKey(in RSAParameters parameters)
{
if (parameters.D == null)
{
if (parameters.P != null ||
parameters.DP != null ||
parameters.Q != null ||
parameters.DQ != null ||
parameters.InverseQ != null)
{
return false;
}
}
else
{
if (parameters.P == null ||
parameters.DP == null ||
parameters.Q == null ||
parameters.DQ == null ||
parameters.InverseQ == null)
{
return false;
}
}
return true;
}
}
private static Exception HashAlgorithmNameNullOrEmpty() =>
new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm");
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Text;
using CookieCollection = SocketHttpListener.Net.CookieCollection;
using HttpListenerResponse = SocketHttpListener.Net.HttpListenerResponse;
using HttpStatusCode = SocketHttpListener.Net.HttpStatusCode;
namespace SocketHttpListener
{
/// <summary>
/// Provides a set of static methods for the websocket-sharp.
/// </summary>
public static class Ext
{
#region Private Const Fields
private const string _tspecials = "()<>@,;:\\\"/[]?={} \t";
#endregion
#region Private Methods
private static byte [] compress (this byte [] value)
{
if (value.LongLength == 0)
//return new Byte [] { 0x00, 0x00, 0x00, 0xff, 0xff };
return value;
using (var input = new MemoryStream (value)) {
return input.compressToArray ();
}
}
private static MemoryStream compress (this Stream stream)
{
var output = new MemoryStream ();
if (stream.Length == 0)
return output;
stream.Position = 0;
using (var ds = new DeflateStream (output, CompressionMode.Compress, true)) {
stream.CopyTo (ds);
ds.Close (); // "BFINAL" set to 1.
output.Position = 0;
return output;
}
}
private static byte [] compressToArray (this Stream stream)
{
using (var comp = stream.compress ()) {
comp.Close ();
return comp.ToArray ();
}
}
private static byte [] decompress (this byte [] value)
{
if (value.LongLength == 0)
return value;
using (var input = new MemoryStream (value)) {
return input.decompressToArray ();
}
}
private static MemoryStream decompress (this Stream stream)
{
var output = new MemoryStream ();
if (stream.Length == 0)
return output;
stream.Position = 0;
using (var ds = new DeflateStream (stream, CompressionMode.Decompress, true)) {
ds.CopyTo (output, true);
return output;
}
}
private static byte [] decompressToArray (this Stream stream)
{
using (var decomp = stream.decompress ()) {
decomp.Close ();
return decomp.ToArray ();
}
}
private static byte [] readBytes (this Stream stream, byte [] buffer, int offset, int length)
{
var len = stream.Read (buffer, offset, length);
if (len < 1)
return buffer.SubArray (0, offset);
var tmp = 0;
while (len < length) {
tmp = stream.Read (buffer, offset + len, length - len);
if (tmp < 1)
break;
len += tmp;
}
return len < length
? buffer.SubArray (0, offset + len)
: buffer;
}
private static bool readBytes (
this Stream stream, byte [] buffer, int offset, int length, Stream dest)
{
var bytes = stream.readBytes (buffer, offset, length);
var len = bytes.Length;
dest.Write (bytes, 0, len);
return len == offset + length;
}
#endregion
#region Internal Methods
internal static byte [] Append (this ushort code, string reason)
{
using (var buffer = new MemoryStream ()) {
var tmp = code.ToByteArrayInternally (ByteOrder.Big);
buffer.Write (tmp, 0, 2);
if (reason != null && reason.Length > 0) {
tmp = Encoding.UTF8.GetBytes (reason);
buffer.Write (tmp, 0, tmp.Length);
}
buffer.Close ();
return buffer.ToArray ();
}
}
internal static string CheckIfClosable (this WebSocketState state)
{
return state == WebSocketState.Closing
? "While closing the WebSocket connection."
: state == WebSocketState.Closed
? "The WebSocket connection has already been closed."
: null;
}
internal static string CheckIfOpen (this WebSocketState state)
{
return state == WebSocketState.Connecting
? "A WebSocket connection isn't established."
: state == WebSocketState.Closing
? "While closing the WebSocket connection."
: state == WebSocketState.Closed
? "The WebSocket connection has already been closed."
: null;
}
internal static string CheckIfValidControlData (this byte [] data, string paramName)
{
return data.Length > 125
? String.Format ("'{0}' length must be less.", paramName)
: null;
}
internal static string CheckIfValidSendData (this byte [] data)
{
return data == null
? "'data' must not be null."
: null;
}
internal static string CheckIfValidSendData (this FileInfo file)
{
return file == null
? "'file' must not be null."
: null;
}
internal static string CheckIfValidSendData (this string data)
{
return data == null
? "'data' must not be null."
: null;
}
internal static string CheckIfValidServicePath (this string servicePath)
{
return servicePath == null || servicePath.Length == 0
? "'servicePath' must not be null or empty."
: servicePath [0] != '/'
? "'servicePath' not absolute path."
: servicePath.IndexOfAny (new [] {'?', '#'}) != -1
? "'servicePath' must not contain either or both query and fragment components."
: null;
}
internal static string CheckIfValidSessionID (this string id)
{
return id == null || id.Length == 0
? "'id' must not be null or empty."
: null;
}
internal static void Close (this HttpListenerResponse response, HttpStatusCode code)
{
response.StatusCode = (int) code;
response.OutputStream.Close ();
}
internal static byte [] Compress (this byte [] value, CompressionMethod method)
{
return method == CompressionMethod.Deflate
? value.compress ()
: value;
}
internal static Stream Compress (this Stream stream, CompressionMethod method)
{
return method == CompressionMethod.Deflate
? stream.compress ()
: stream;
}
internal static byte [] CompressToArray (this Stream stream, CompressionMethod method)
{
return method == CompressionMethod.Deflate
? stream.compressToArray ()
: stream.ToByteArray ();
}
internal static bool Contains<T> (this IEnumerable<T> source, Func<T, bool> condition)
{
foreach (T elm in source)
if (condition (elm))
return true;
return false;
}
internal static bool ContainsTwice (this string [] values)
{
var len = values.Length;
Func<int, bool> contains = null;
contains = index => {
if (index < len - 1) {
for (var i = index + 1; i < len; i++)
if (values [i] == values [index])
return true;
return contains (++index);
}
return false;
};
return contains (0);
}
internal static void CopyTo (this Stream src, Stream dest, bool setDefaultPosition)
{
var readLen = 0;
var bufferLen = 256;
var buffer = new byte [bufferLen];
while ((readLen = src.Read (buffer, 0, bufferLen)) > 0) {
dest.Write (buffer, 0, readLen);
}
if (setDefaultPosition)
dest.Position = 0;
}
internal static byte [] Decompress (this byte [] value, CompressionMethod method)
{
return method == CompressionMethod.Deflate
? value.decompress ()
: value;
}
internal static byte [] DecompressToArray (this Stream stream, CompressionMethod method)
{
return method == CompressionMethod.Deflate
? stream.decompressToArray ()
: stream.ToByteArray ();
}
/// <summary>
/// Determines whether the specified <see cref="int"/> equals the specified <see cref="char"/>,
/// and invokes the specified Action<int> delegate at the same time.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="value"/> equals <paramref name="c"/>;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="value">
/// An <see cref="int"/> to compare.
/// </param>
/// <param name="c">
/// A <see cref="char"/> to compare.
/// </param>
/// <param name="action">
/// An Action<int> delegate that references the method(s) called at
/// the same time as comparing. An <see cref="int"/> parameter to pass to
/// the method(s) is <paramref name="value"/>.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="value"/> isn't between 0 and 255.
/// </exception>
internal static bool EqualsWith (this int value, char c, Action<int> action)
{
if (value < 0 || value > 255)
throw new ArgumentOutOfRangeException ("value");
action (value);
return value == c - 0;
}
internal static string GetMessage (this CloseStatusCode code)
{
return code == CloseStatusCode.ProtocolError
? "A WebSocket protocol error has occurred."
: code == CloseStatusCode.IncorrectData
? "An incorrect data has been received."
: code == CloseStatusCode.Abnormal
? "An exception has occurred."
: code == CloseStatusCode.InconsistentData
? "An inconsistent data has been received."
: code == CloseStatusCode.PolicyViolation
? "A policy violation has occurred."
: code == CloseStatusCode.TooBig
? "A too big data has been received."
: code == CloseStatusCode.IgnoreExtension
? "WebSocket client did not receive expected extension(s)."
: code == CloseStatusCode.ServerError
? "WebSocket server got an internal error."
: code == CloseStatusCode.TlsHandshakeFailure
? "An error has occurred while handshaking."
: String.Empty;
}
internal static string GetNameInternal (this string nameAndValue, string separator)
{
var i = nameAndValue.IndexOf (separator);
return i > 0
? nameAndValue.Substring (0, i).Trim ()
: null;
}
internal static string GetValueInternal (this string nameAndValue, string separator)
{
var i = nameAndValue.IndexOf (separator);
return i >= 0 && i < nameAndValue.Length - 1
? nameAndValue.Substring (i + 1).Trim ()
: null;
}
internal static bool IsCompressionExtension (this string value)
{
return value.StartsWith ("permessage-");
}
internal static bool IsPortNumber (this int value)
{
return value > 0 && value < 65536;
}
internal static bool IsReserved (this ushort code)
{
return code == (ushort) CloseStatusCode.Undefined ||
code == (ushort) CloseStatusCode.NoStatusCode ||
code == (ushort) CloseStatusCode.Abnormal ||
code == (ushort) CloseStatusCode.TlsHandshakeFailure;
}
internal static bool IsReserved (this CloseStatusCode code)
{
return code == CloseStatusCode.Undefined ||
code == CloseStatusCode.NoStatusCode ||
code == CloseStatusCode.Abnormal ||
code == CloseStatusCode.TlsHandshakeFailure;
}
internal static bool IsText (this string value)
{
var len = value.Length;
for (var i = 0; i < len; i++) {
char c = value [i];
if (c < 0x20 && !"\r\n\t".Contains (c))
return false;
if (c == 0x7f)
return false;
if (c == '\n' && ++i < len) {
c = value [i];
if (!" \t".Contains (c))
return false;
}
}
return true;
}
internal static bool IsToken (this string value)
{
foreach (char c in value)
if (c < 0x20 || c >= 0x7f || _tspecials.Contains (c))
return false;
return true;
}
internal static string Quote (this string value)
{
return value.IsToken ()
? value
: String.Format ("\"{0}\"", value.Replace ("\"", "\\\""));
}
internal static byte [] ReadBytes (this Stream stream, int length)
{
return stream.readBytes (new byte [length], 0, length);
}
internal static byte [] ReadBytes (this Stream stream, long length, int bufferLength)
{
using (var result = new MemoryStream ()) {
var count = length / bufferLength;
var rem = (int) (length % bufferLength);
var buffer = new byte [bufferLength];
var end = false;
for (long i = 0; i < count; i++) {
if (!stream.readBytes (buffer, 0, bufferLength, result)) {
end = true;
break;
}
}
if (!end && rem > 0)
stream.readBytes (new byte [rem], 0, rem, result);
result.Close ();
return result.ToArray ();
}
}
internal static void ReadBytesAsync (
this Stream stream, int length, Action<byte []> completed, Action<Exception> error)
{
var buffer = new byte [length];
stream.BeginRead (
buffer,
0,
length,
ar => {
try {
var len = stream.EndRead (ar);
var bytes = len < 1
? new byte [0]
: len < length
? stream.readBytes (buffer, len, length - len)
: buffer;
if (completed != null)
completed (bytes);
}
catch (Exception ex) {
if (error != null)
error (ex);
}
},
null);
}
internal static string RemovePrefix (this string value, params string [] prefixes)
{
var i = 0;
foreach (var prefix in prefixes) {
if (value.StartsWith (prefix)) {
i = prefix.Length;
break;
}
}
return i > 0
? value.Substring (i)
: value;
}
internal static T [] Reverse<T> (this T [] array)
{
var len = array.Length;
T [] reverse = new T [len];
var end = len - 1;
for (var i = 0; i <= end; i++)
reverse [i] = array [end - i];
return reverse;
}
internal static IEnumerable<string> SplitHeaderValue (
this string value, params char [] separator)
{
var len = value.Length;
var separators = new string (separator);
var buffer = new StringBuilder (32);
var quoted = false;
var escaped = false;
char c;
for (var i = 0; i < len; i++) {
c = value [i];
if (c == '"') {
if (escaped)
escaped = !escaped;
else
quoted = !quoted;
}
else if (c == '\\') {
if (i < len - 1 && value [i + 1] == '"')
escaped = true;
}
else if (separators.Contains (c)) {
if (!quoted) {
yield return buffer.ToString ();
buffer.Length = 0;
continue;
}
}
else {
}
buffer.Append (c);
}
if (buffer.Length > 0)
yield return buffer.ToString ();
}
internal static byte [] ToByteArray (this Stream stream)
{
using (var output = new MemoryStream ()) {
stream.Position = 0;
stream.CopyTo (output);
output.Close ();
return output.ToArray ();
}
}
internal static byte [] ToByteArrayInternally (this ushort value, ByteOrder order)
{
var bytes = BitConverter.GetBytes (value);
if (!order.IsHostOrder ())
Array.Reverse (bytes);
return bytes;
}
internal static byte [] ToByteArrayInternally (this ulong value, ByteOrder order)
{
var bytes = BitConverter.GetBytes (value);
if (!order.IsHostOrder ())
Array.Reverse (bytes);
return bytes;
}
internal static CompressionMethod ToCompressionMethod (this string value)
{
foreach (CompressionMethod method in Enum.GetValues (typeof (CompressionMethod)))
if (method.ToExtensionString () == value)
return method;
return CompressionMethod.None;
}
internal static string ToExtensionString (this CompressionMethod method)
{
return method != CompressionMethod.None
? String.Format ("permessage-{0}", method.ToString ().ToLower ())
: String.Empty;
}
internal static System.Net.IPAddress ToIPAddress (this string hostNameOrAddress)
{
try {
var addrs = System.Net.Dns.GetHostAddresses (hostNameOrAddress);
return addrs [0];
}
catch {
return null;
}
}
internal static List<TSource> ToList<TSource> (this IEnumerable<TSource> source)
{
return new List<TSource> (source);
}
internal static ushort ToUInt16 (this byte [] src, ByteOrder srcOrder)
{
return BitConverter.ToUInt16 (src.ToHostOrder (srcOrder), 0);
}
internal static ulong ToUInt64 (this byte [] src, ByteOrder srcOrder)
{
return BitConverter.ToUInt64 (src.ToHostOrder (srcOrder), 0);
}
internal static string TrimEndSlash (this string value)
{
value = value.TrimEnd ('/');
return value.Length > 0
? value
: "/";
}
/// <summary>
/// Tries to create a <see cref="Uri"/> for WebSocket with the specified
/// <paramref name="uriString"/>.
/// </summary>
/// <returns>
/// <c>true</c> if a <see cref="Uri"/> is successfully created; otherwise, <c>false</c>.
/// </returns>
/// <param name="uriString">
/// A <see cref="string"/> that represents the WebSocket URL to try.
/// </param>
/// <param name="result">
/// When this method returns, a <see cref="Uri"/> that represents the WebSocket URL if
/// <paramref name="uriString"/> is valid; otherwise, <see langword="null"/>.
/// </param>
/// <param name="message">
/// When this method returns, a <see cref="string"/> that represents the error message if
/// <paramref name="uriString"/> is invalid; otherwise, <see cref="String.Empty"/>.
/// </param>
internal static bool TryCreateWebSocketUri (
this string uriString, out Uri result, out string message)
{
result = null;
if (uriString.Length == 0) {
message = "Must not be empty.";
return false;
}
var uri = uriString.ToUri ();
if (!uri.IsAbsoluteUri) {
message = "Must be the absolute URI: " + uriString;
return false;
}
var scheme = uri.Scheme;
if (scheme != "ws" && scheme != "wss") {
message = "The scheme part must be 'ws' or 'wss': " + scheme;
return false;
}
var fragment = uri.Fragment;
if (fragment.Length > 0) {
message = "Must not contain the fragment component: " + uriString;
return false;
}
var port = uri.Port;
if (port > 0) {
if (port > 65535) {
message = "The port part must be between 1 and 65535: " + port;
return false;
}
if ((scheme == "ws" && port == 443) || (scheme == "wss" && port == 80)) {
message = String.Format (
"Invalid pair of scheme and port: {0}, {1}", scheme, port);
return false;
}
}
else {
port = scheme == "ws" ? 80 : 443;
var url = String.Format (
"{0}://{1}:{2}{3}", scheme, uri.Host, port, uri.PathAndQuery);
uri = url.ToUri ();
}
result = uri;
message = String.Empty;
return true;
}
internal static string Unquote (this string value)
{
var start = value.IndexOf ('\"');
var end = value.LastIndexOf ('\"');
if (start < end)
value = value.Substring (start + 1, end - start - 1).Replace ("\\\"", "\"");
return value.Trim ();
}
internal static void WriteBytes (this Stream stream, byte [] value)
{
using (var src = new MemoryStream (value)) {
src.CopyTo (stream);
}
}
#endregion
#region Public Methods
/// <summary>
/// Determines whether the specified <see cref="string"/> contains any of characters
/// in the specified array of <see cref="char"/>.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="value"/> contains any of <paramref name="chars"/>;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="value">
/// A <see cref="string"/> to test.
/// </param>
/// <param name="chars">
/// An array of <see cref="char"/> that contains characters to find.
/// </param>
public static bool Contains (this string value, params char [] chars)
{
return chars == null || chars.Length == 0
? true
: value == null || value.Length == 0
? false
: value.IndexOfAny (chars) != -1;
}
/// <summary>
/// Determines whether the specified <see cref="NameValueCollection"/> contains the entry
/// with the specified <paramref name="name"/>.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="collection"/> contains the entry
/// with <paramref name="name"/>; otherwise, <c>false</c>.
/// </returns>
/// <param name="collection">
/// A <see cref="NameValueCollection"/> to test.
/// </param>
/// <param name="name">
/// A <see cref="string"/> that represents the key of the entry to find.
/// </param>
public static bool Contains (this NameValueCollection collection, string name)
{
return collection == null || collection.Count == 0
? false
: collection [name] != null;
}
/// <summary>
/// Determines whether the specified <see cref="NameValueCollection"/> contains the entry
/// with the specified both <paramref name="name"/> and <paramref name="value"/>.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="collection"/> contains the entry
/// with both <paramref name="name"/> and <paramref name="value"/>;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="collection">
/// A <see cref="NameValueCollection"/> to test.
/// </param>
/// <param name="name">
/// A <see cref="string"/> that represents the key of the entry to find.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that represents the value of the entry to find.
/// </param>
public static bool Contains (this NameValueCollection collection, string name, string value)
{
if (collection == null || collection.Count == 0)
return false;
var values = collection [name];
if (values == null)
return false;
foreach (var v in values.Split (','))
if (v.Trim ().Equals (value, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
/// <summary>
/// Emits the specified <see cref="EventHandler"/> delegate if it isn't <see langword="null"/>.
/// </summary>
/// <param name="eventHandler">
/// A <see cref="EventHandler"/> to emit.
/// </param>
/// <param name="sender">
/// An <see cref="object"/> from which emits this <paramref name="eventHandler"/>.
/// </param>
/// <param name="e">
/// A <see cref="EventArgs"/> that contains no event data.
/// </param>
public static void Emit (this EventHandler eventHandler, object sender, EventArgs e)
{
if (eventHandler != null)
eventHandler (sender, e);
}
/// <summary>
/// Emits the specified <c>EventHandler<TEventArgs></c> delegate
/// if it isn't <see langword="null"/>.
/// </summary>
/// <param name="eventHandler">
/// An <c>EventHandler<TEventArgs></c> to emit.
/// </param>
/// <param name="sender">
/// An <see cref="object"/> from which emits this <paramref name="eventHandler"/>.
/// </param>
/// <param name="e">
/// A <c>TEventArgs</c> that represents the event data.
/// </param>
/// <typeparam name="TEventArgs">
/// The type of the event data generated by the event.
/// </typeparam>
public static void Emit<TEventArgs> (
this EventHandler<TEventArgs> eventHandler, object sender, TEventArgs e)
where TEventArgs : EventArgs
{
if (eventHandler != null)
eventHandler (sender, e);
}
/// <summary>
/// Gets the collection of the HTTP cookies from the specified HTTP <paramref name="headers"/>.
/// </summary>
/// <returns>
/// A <see cref="Net.CookieCollection"/> that receives a collection of the HTTP cookies.
/// </returns>
/// <param name="headers">
/// A <see cref="NameValueCollection"/> that contains a collection of the HTTP headers.
/// </param>
/// <param name="response">
/// <c>true</c> if <paramref name="headers"/> is a collection of the response headers;
/// otherwise, <c>false</c>.
/// </param>
public static CookieCollection GetCookies (this NameValueCollection headers, bool response)
{
var name = response ? "Set-Cookie" : "Cookie";
return headers == null || !headers.Contains (name)
? new CookieCollection ()
: CookieCollection.Parse (headers [name], response);
}
/// <summary>
/// Gets the description of the specified HTTP status <paramref name="code"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the description of the HTTP status code.
/// </returns>
/// <param name="code">
/// One of <see cref="HttpStatusCode"/> enum values, indicates the HTTP status codes.
/// </param>
public static string GetDescription (this HttpStatusCode code)
{
return ((int) code).GetStatusDescription ();
}
/// <summary>
/// Gets the name from the specified <see cref="string"/> that contains a pair of name and
/// value separated by a separator string.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the name if any; otherwise, <c>null</c>.
/// </returns>
/// <param name="nameAndValue">
/// A <see cref="string"/> that contains a pair of name and value separated by a separator
/// string.
/// </param>
/// <param name="separator">
/// A <see cref="string"/> that represents a separator string.
/// </param>
public static string GetName (this string nameAndValue, string separator)
{
return (nameAndValue != null && nameAndValue.Length > 0) &&
(separator != null && separator.Length > 0)
? nameAndValue.GetNameInternal (separator)
: null;
}
/// <summary>
/// Gets the name and value from the specified <see cref="string"/> that contains a pair of
/// name and value separated by a separator string.
/// </summary>
/// <returns>
/// A <c>KeyValuePair<string, string></c> that represents the name and value if any.
/// </returns>
/// <param name="nameAndValue">
/// A <see cref="string"/> that contains a pair of name and value separated by a separator
/// string.
/// </param>
/// <param name="separator">
/// A <see cref="string"/> that represents a separator string.
/// </param>
public static KeyValuePair<string, string> GetNameAndValue (
this string nameAndValue, string separator)
{
var name = nameAndValue.GetName (separator);
var value = nameAndValue.GetValue (separator);
return name != null
? new KeyValuePair<string, string> (name, value)
: new KeyValuePair<string, string> (null, null);
}
/// <summary>
/// Gets the description of the specified HTTP status <paramref name="code"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the description of the HTTP status code.
/// </returns>
/// <param name="code">
/// An <see cref="int"/> that represents the HTTP status code.
/// </param>
public static string GetStatusDescription (this int code)
{
switch (code) {
case 100: return "Continue";
case 101: return "Switching Protocols";
case 102: return "Processing";
case 200: return "OK";
case 201: return "Created";
case 202: return "Accepted";
case 203: return "Non-Authoritative Information";
case 204: return "No Content";
case 205: return "Reset Content";
case 206: return "Partial Content";
case 207: return "Multi-Status";
case 300: return "Multiple Choices";
case 301: return "Moved Permanently";
case 302: return "Found";
case 303: return "See Other";
case 304: return "Not Modified";
case 305: return "Use Proxy";
case 307: return "Temporary Redirect";
case 400: return "Bad Request";
case 401: return "Unauthorized";
case 402: return "Payment Required";
case 403: return "Forbidden";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
case 406: return "Not Acceptable";
case 407: return "Proxy Authentication Required";
case 408: return "Request Timeout";
case 409: return "Conflict";
case 410: return "Gone";
case 411: return "Length Required";
case 412: return "Precondition Failed";
case 413: return "Request Entity Too Large";
case 414: return "Request-Uri Too Long";
case 415: return "Unsupported Media Type";
case 416: return "Requested Range Not Satisfiable";
case 417: return "Expectation Failed";
case 422: return "Unprocessable Entity";
case 423: return "Locked";
case 424: return "Failed Dependency";
case 500: return "Internal Server Error";
case 501: return "Not Implemented";
case 502: return "Bad Gateway";
case 503: return "Service Unavailable";
case 504: return "Gateway Timeout";
case 505: return "Http Version Not Supported";
case 507: return "Insufficient Storage";
}
return String.Empty;
}
/// <summary>
/// Gets the value from the specified <see cref="string"/> that contains a pair of name and
/// value separated by a separator string.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the value if any; otherwise, <c>null</c>.
/// </returns>
/// <param name="nameAndValue">
/// A <see cref="string"/> that contains a pair of name and value separated by a separator
/// string.
/// </param>
/// <param name="separator">
/// A <see cref="string"/> that represents a separator string.
/// </param>
public static string GetValue (this string nameAndValue, string separator)
{
return (nameAndValue != null && nameAndValue.Length > 0) &&
(separator != null && separator.Length > 0)
? nameAndValue.GetValueInternal (separator)
: null;
}
/// <summary>
/// Determines whether the specified <see cref="ByteOrder"/> is host
/// (this computer architecture) byte order.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="order"/> is host byte order;
/// otherwise, <c>false</c>.
/// </returns>
/// <param name="order">
/// One of the <see cref="ByteOrder"/> enum values, to test.
/// </param>
public static bool IsHostOrder (this ByteOrder order)
{
// true : !(true ^ true) or !(false ^ false)
// false: !(true ^ false) or !(false ^ true)
return !(BitConverter.IsLittleEndian ^ (order == ByteOrder.Little));
}
/// <summary>
/// Determines whether the specified <see cref="string"/> is a predefined scheme.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="value"/> is a predefined scheme; otherwise, <c>false</c>.
/// </returns>
/// <param name="value">
/// A <see cref="string"/> to test.
/// </param>
public static bool IsPredefinedScheme (this string value)
{
if (value == null || value.Length < 2)
return false;
var c = value [0];
if (c == 'h')
return value == "http" || value == "https";
if (c == 'w')
return value == "ws" || value == "wss";
if (c == 'f')
return value == "file" || value == "ftp";
if (c == 'n') {
c = value [1];
return c == 'e'
? value == "news" || value == "net.pipe" || value == "net.tcp"
: value == "nntp";
}
return (c == 'g' && value == "gopher") || (c == 'm' && value == "mailto");
}
/// <summary>
/// Determines whether the specified <see cref="string"/> is a URI string.
/// </summary>
/// <returns>
/// <c>true</c> if <paramref name="value"/> may be a URI string; otherwise, <c>false</c>.
/// </returns>
/// <param name="value">
/// A <see cref="string"/> to test.
/// </param>
public static bool MaybeUri (this string value)
{
if (value == null || value.Length == 0)
return false;
var i = value.IndexOf (':');
if (i == -1)
return false;
if (i >= 10)
return false;
return value.Substring (0, i).IsPredefinedScheme ();
}
/// <summary>
/// Retrieves a sub-array from the specified <paramref name="array"/>.
/// A sub-array starts at the specified element position.
/// </summary>
/// <returns>
/// An array of T that receives a sub-array, or an empty array of T if any problems
/// with the parameters.
/// </returns>
/// <param name="array">
/// An array of T that contains the data to retrieve a sub-array.
/// </param>
/// <param name="startIndex">
/// An <see cref="int"/> that contains the zero-based starting position of a sub-array
/// in <paramref name="array"/>.
/// </param>
/// <param name="length">
/// An <see cref="int"/> that contains the number of elements to retrieve a sub-array.
/// </param>
/// <typeparam name="T">
/// The type of elements in the <paramref name="array"/>.
/// </typeparam>
public static T [] SubArray<T> (this T [] array, int startIndex, int length)
{
if (array == null || array.Length == 0)
return new T [0];
if (startIndex < 0 || length <= 0)
return new T [0];
if (startIndex + length > array.Length)
return new T [0];
if (startIndex == 0 && array.Length == length)
return array;
T [] subArray = new T [length];
Array.Copy (array, startIndex, subArray, 0, length);
return subArray;
}
/// <summary>
/// Converts the order of the specified array of <see cref="byte"/> to the host byte order.
/// </summary>
/// <returns>
/// An array of <see cref="byte"/> converted from <paramref name="src"/>.
/// </returns>
/// <param name="src">
/// An array of <see cref="byte"/> to convert.
/// </param>
/// <param name="srcOrder">
/// One of the <see cref="ByteOrder"/> enum values, indicates the byte order of
/// <paramref name="src"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="src"/> is <see langword="null"/>.
/// </exception>
public static byte [] ToHostOrder (this byte [] src, ByteOrder srcOrder)
{
if (src == null)
throw new ArgumentNullException ("src");
return src.Length > 1 && !srcOrder.IsHostOrder ()
? src.Reverse ()
: src;
}
/// <summary>
/// Converts the specified <see cref="string"/> to a <see cref="Uri"/>.
/// </summary>
/// <returns>
/// A <see cref="Uri"/> converted from <paramref name="uriString"/>, or <see langword="null"/>
/// if <paramref name="uriString"/> isn't successfully converted.
/// </returns>
/// <param name="uriString">
/// A <see cref="string"/> to convert.
/// </param>
public static Uri ToUri (this string uriString)
{
Uri res;
return Uri.TryCreate (
uriString, uriString.MaybeUri () ? UriKind.Absolute : UriKind.Relative, out res)
? res
: null;
}
/// <summary>
/// URL-decodes the specified <see cref="string"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that receives the decoded string, or the <paramref name="value"/>
/// if it's <see langword="null"/> or empty.
/// </returns>
/// <param name="value">
/// A <see cref="string"/> to decode.
/// </param>
public static string UrlDecode (this string value)
{
return value == null || value.Length == 0
? value
: WebUtility.UrlDecode(value);
}
#endregion
}
}
| |
namespace Colorspace
{
public struct ColorRGB32Bit
{
private readonly byte _alpha;
private readonly byte _r;
private readonly byte _g;
private readonly byte _b;
public ColorRGB32Bit(byte alpha, byte r, byte g, byte b)
{
_alpha = alpha;
_r = r;
_g = g;
_b = b;
}
public ColorRGB32Bit(byte r, byte g, byte b) :
this( 0xff, r,g,b)
{
}
public ColorRGB32Bit(short a, short r, short g, short b)
{
_alpha = (byte)a;
_r = (byte)r;
_g = (byte)g;
_b = (byte)b;
}
public ColorRGB32Bit(byte alpha, ColorRGB32Bit c) :
this( alpha, c.R, c.G, c.B)
{
}
public ColorRGB32Bit(short r, short g, short b):
this((byte)0xff, (byte)r, (byte)g, (byte)b)
{
}
public ColorRGB32Bit(int rgb) :
this((uint)rgb)
{
}
public ColorRGB32Bit(uint rgb)
{
this._alpha = (byte)((rgb & 0xff000000) >> 24);
this._r = (byte)((rgb & 0x00ff0000) >> 16);
this._g = (byte)((rgb & 0x0000ff00) >> 8);
this._b = (byte)((rgb & 0x000000ff) >> 0);
}
public ColorRGB32Bit(ColorRGB color)
{
this._alpha = (byte)(System.Math.Round(color.Alpha * 255));
this._r = (byte)(System.Math.Round(color.R * 255));
this._g = (byte)(System.Math.Round(color.G * 255));
this._b = (byte)(System.Math.Round(color.B * 255));
}
public byte Alpha
{
get { return _alpha; }
}
public byte R
{
get { return _r; }
}
public byte G
{
get { return _g; }
}
public byte B
{
get { return _b; }
}
public override string ToString()
{
var s = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}({1},{2},{3},{4})",
typeof(ColorRGB32Bit).Name, this._alpha, this._r, this._g, this._b);
return s;
}
public static explicit operator int(ColorRGB32Bit color)
{
return color.ToInt();
}
public static explicit operator ColorRGB32Bit(int rgbint)
{
return new ColorRGB32Bit(rgbint);
}
public string ToWebColorString()
{
if (this.Alpha == 0xff)
{
const string format_string_rgb = "#{0:x2}{1:x2}{2:x2}";
string color_string = string.Format(System.Globalization.CultureInfo.InvariantCulture, format_string_rgb,
this.R, this.G, this.B);
return color_string;
}
else
{
const string format_string_rgba = "#{0:x2}{1:x2}{2:x2}{3:x2}";
string color_string = string.Format(System.Globalization.CultureInfo.InvariantCulture,
format_string_rgba, this.Alpha, this.R, this.G, this.B);
return color_string;
}
}
public override bool Equals(object other)
{
return other is ColorRGB32Bit && Equals((ColorRGB32Bit)other);
}
public static bool operator ==(ColorRGB32Bit lhs, ColorRGB32Bit rhs)
{
return lhs.Equals(rhs);
}
public static bool operator !=(ColorRGB32Bit lhs, ColorRGB32Bit rhs)
{
return !lhs.Equals(rhs);
}
private bool Equals(ColorRGB32Bit other)
{
return (this._alpha == other._alpha && this._r == other._r && this._g == other._g && this._b == other._b);
}
public override int GetHashCode()
{
return ToInt();
}
public int ToInt()
{
return (int)this.ToUInt();
}
public uint ToUInt()
{
return (uint)((this._alpha << 24) | (this._r << 16) | (this._g << 8) | (this._b));
}
/// <summary>
/// Parses a web color string of form "#ffffff"
/// </summary>
/// <param name="webcolor"></param>
/// <returns></returns>
public static ColorRGB32Bit ParseWebColorString(string webcolor)
{
var outputcolor = TryParseWebColorString(webcolor);
if (!outputcolor.HasValue)
{
string s = string.Format("Failed to parse color string \"{0}\"", webcolor);
throw new ColorException(s);
}
return outputcolor.Value;
}
/// <summary>
///
/// </summary>
/// <example>
/// Sample usage:
///
/// System.Drawing.Color c;
/// bool result = TryParseRGBWebColorString("#ffffff", ref c);
/// if (result)
/// {
/// //it was correctly parsed
/// }
/// else
/// {
/// //it was not correctly parsed
/// }
///
/// </example>
/// <param name="webcolor"></param>
///<returns></returns>
public static ColorRGB32Bit? TryParseWebColorString(string webcolor)
{
// fail if string is null
if (webcolor == null)
{
return null;
}
// fail if string is empty
if (webcolor.Length < 1)
{
return null;
}
// clean any leading or trailing whitespace
webcolor = webcolor.Trim();
// fail if string is empty
if (webcolor.Length < 1)
{
return null;
}
// strip leading # if it is there
while (webcolor.StartsWith("#"))
{
webcolor = webcolor.Substring(1);
}
// clean any leading or trailing whitespace
webcolor = webcolor.Trim();
// fail if string is empty
if (webcolor.Length < 1)
{
return null;
}
// fail if string doesn't have exactly 6 digits (this means alpha was not provided)
if (webcolor.Length != 6)
{
return null;
}
int current_color = 0;
bool result = System.Int32.TryParse(webcolor, System.Globalization.NumberStyles.HexNumber, null, out current_color);
if (webcolor.Length == 6)
{
// only six digits were given so add alpha
current_color = (int)(((uint)current_color) | ((uint) 0xff000000));
}
if (!result)
{
// fail if parsing didn't work
return null;
}
// at this point parsing worked
// the integer value is converted directly to an rgb value
var the_color = new ColorRGB32Bit(current_color);
return the_color;
}
}
}
| |
/*
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.IO;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
using System.Diagnostics;
namespace WPCordovaClassLib.Cordova.Commands
{
/// <summary>
/// Provides access to isolated storage
/// </summary>
public class File : BaseCommand
{
// Error codes
public const int NOT_FOUND_ERR = 1;
public const int SECURITY_ERR = 2;
public const int ABORT_ERR = 3;
public const int NOT_READABLE_ERR = 4;
public const int ENCODING_ERR = 5;
public const int NO_MODIFICATION_ALLOWED_ERR = 6;
public const int INVALID_STATE_ERR = 7;
public const int SYNTAX_ERR = 8;
public const int INVALID_MODIFICATION_ERR = 9;
public const int QUOTA_EXCEEDED_ERR = 10;
public const int TYPE_MISMATCH_ERR = 11;
public const int PATH_EXISTS_ERR = 12;
// File system options
public const int TEMPORARY = 0;
public const int PERSISTENT = 1;
public const int RESOURCE = 2;
public const int APPLICATION = 3;
/// <summary>
/// Temporary directory name
/// </summary>
private readonly string TMP_DIRECTORY_NAME = "tmp";
/// <summary>
/// Represents error code for callback
/// </summary>
[DataContract]
public class ErrorCode
{
/// <summary>
/// Error code
/// </summary>
[DataMember(IsRequired = true, Name = "code")]
public int Code { get; set; }
/// <summary>
/// Creates ErrorCode object
/// </summary>
public ErrorCode(int code)
{
this.Code = code;
}
}
/// <summary>
/// Represents File action options.
/// </summary>
[DataContract]
public class FileOptions
{
/// <summary>
/// File path
/// </summary>
///
private string _fileName;
[DataMember(Name = "fileName")]
public string FilePath
{
get
{
return this._fileName;
}
set
{
int index = value.IndexOfAny(new char[] { '#', '?' });
this._fileName = index > -1 ? value.Substring(0, index) : value;
}
}
/// <summary>
/// Full entryPath
/// </summary>
[DataMember(Name = "fullPath")]
public string FullPath { get; set; }
/// <summary>
/// Directory name
/// </summary>
[DataMember(Name = "dirName")]
public string DirectoryName { get; set; }
/// <summary>
/// Path to create file/directory
/// </summary>
[DataMember(Name = "path")]
public string Path { get; set; }
/// <summary>
/// The encoding to use to encode the file's content. Default is UTF8.
/// </summary>
[DataMember(Name = "encoding")]
public string Encoding { get; set; }
/// <summary>
/// Uri to get file
/// </summary>
///
private string _uri;
[DataMember(Name = "uri")]
public string Uri
{
get
{
return this._uri;
}
set
{
int index = value.IndexOfAny(new char[] { '#', '?' });
this._uri = index > -1 ? value.Substring(0, index) : value;
}
}
/// <summary>
/// Size to truncate file
/// </summary>
[DataMember(Name = "size")]
public long Size { get; set; }
/// <summary>
/// Data to write in file
/// </summary>
[DataMember(Name = "data")]
public string Data { get; set; }
/// <summary>
/// Position the writing starts with
/// </summary>
[DataMember(Name = "position")]
public int Position { get; set; }
/// <summary>
/// Type of file system requested
/// </summary>
[DataMember(Name = "type")]
public int FileSystemType { get; set; }
/// <summary>
/// New file/directory name
/// </summary>
[DataMember(Name = "newName")]
public string NewName { get; set; }
/// <summary>
/// Destination directory to copy/move file/directory
/// </summary>
[DataMember(Name = "parent")]
public string Parent { get; set; }
/// <summary>
/// Options for getFile/getDirectory methods
/// </summary>
[DataMember(Name = "options")]
public CreatingOptions CreatingOpt { get; set; }
/// <summary>
/// Creates options object with default parameters
/// </summary>
public FileOptions()
{
this.SetDefaultValues(new StreamingContext());
}
/// <summary>
/// Initializes default values for class fields.
/// Implemented in separate method because default constructor is not invoked during deserialization.
/// </summary>
/// <param name="context"></param>
[OnDeserializing()]
public void SetDefaultValues(StreamingContext context)
{
this.Encoding = "UTF-8";
this.FilePath = "";
this.FileSystemType = -1;
}
}
/// <summary>
/// Stores image info
/// </summary>
[DataContract]
public class FileMetadata
{
[DataMember(Name = "fileName")]
public string FileName { get; set; }
[DataMember(Name = "fullPath")]
public string FullPath { get; set; }
[DataMember(Name = "type")]
public string Type { get; set; }
[DataMember(Name = "lastModifiedDate")]
public string LastModifiedDate { get; set; }
[DataMember(Name = "size")]
public long Size { get; set; }
public FileMetadata(string filePath)
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if ((string.IsNullOrEmpty(filePath)) || (!isoFile.FileExists(filePath)))
{
throw new FileNotFoundException("File doesn't exist");
}
//TODO get file size the other way if possible
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.Read, isoFile))
{
this.Size = stream.Length;
}
this.FullPath = filePath;
this.FileName = System.IO.Path.GetFileName(filePath);
this.Type = MimeTypeMapper.GetMimeType(filePath);
this.LastModifiedDate = isoFile.GetLastWriteTime(filePath).DateTime.ToString();
}
}
}
/// <summary>
/// Represents file or directory modification metadata
/// </summary>
[DataContract]
public class ModificationMetadata
{
/// <summary>
/// Modification time
/// </summary>
[DataMember]
public string modificationTime { get; set; }
}
/// <summary>
/// Represents file or directory entry
/// </summary>
[DataContract]
public class FileEntry
{
/// <summary>
/// File type
/// </summary>
[DataMember(Name = "isFile")]
public bool IsFile { get; set; }
/// <summary>
/// Directory type
/// </summary>
[DataMember(Name = "isDirectory")]
public bool IsDirectory { get; set; }
/// <summary>
/// File/directory name
/// </summary>
[DataMember(Name = "name")]
public string Name { get; set; }
/// <summary>
/// Full path to file/directory
/// </summary>
[DataMember(Name = "fullPath")]
public string FullPath { get; set; }
public static FileEntry GetEntry(string filePath)
{
FileEntry entry = null;
try
{
entry = new FileEntry(filePath);
}
catch (Exception ex)
{
Debug.WriteLine("Exception in GetEntry for filePath :: " + filePath + " " + ex.Message);
}
return entry;
}
/// <summary>
/// Creates object and sets necessary properties
/// </summary>
/// <param name="filePath"></param>
public FileEntry(string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentException();
}
if(filePath.Contains(" "))
{
Debug.WriteLine("FilePath with spaces :: " + filePath);
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
this.IsFile = isoFile.FileExists(filePath);
this.IsDirectory = isoFile.DirectoryExists(filePath);
if (IsFile)
{
this.Name = Path.GetFileName(filePath);
}
else if (IsDirectory)
{
this.Name = this.GetDirectoryName(filePath);
if (string.IsNullOrEmpty(Name))
{
this.Name = "/";
}
}
else
{
throw new FileNotFoundException();
}
try
{
this.FullPath = filePath.Replace('\\', '/'); // new Uri(filePath).LocalPath;
}
catch (Exception)
{
this.FullPath = filePath;
}
}
}
/// <summary>
/// Extracts directory name from path string
/// Path should refer to a directory, for example \foo\ or /foo.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private string GetDirectoryName(string path)
{
if (String.IsNullOrEmpty(path))
{
return path;
}
string[] split = path.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
if (split.Length < 1)
{
return null;
}
else
{
return split[split.Length - 1];
}
}
}
/// <summary>
/// Represents info about requested file system
/// </summary>
[DataContract]
public class FileSystemInfo
{
/// <summary>
/// file system type
/// </summary>
[DataMember(Name = "name", IsRequired = true)]
public string Name { get; set; }
/// <summary>
/// Root directory entry
/// </summary>
[DataMember(Name = "root", EmitDefaultValue = false)]
public FileEntry Root { get; set; }
/// <summary>
/// Creates class instance
/// </summary>
/// <param name="name"></param>
/// <param name="rootEntry"> Root directory</param>
public FileSystemInfo(string name, FileEntry rootEntry = null)
{
Name = name;
Root = rootEntry;
}
}
[DataContract]
public class CreatingOptions
{
/// <summary>
/// Create file/directory if is doesn't exist
/// </summary>
[DataMember(Name = "create")]
public bool Create { get; set; }
/// <summary>
/// Generate an exception if create=true and file/directory already exists
/// </summary>
[DataMember(Name = "exclusive")]
public bool Exclusive { get; set; }
}
/// <summary>
/// File options
/// </summary>
private FileOptions fileOptions;
private bool LoadFileOptions(string options)
{
try
{
fileOptions = JSON.JsonHelper.Deserialize<FileOptions>(options);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return false;
}
return true;
}
// returns null value if it fails.
private string getSingleStringOption(string options)
{
string result = null;
try
{
result = JSON.JsonHelper.Deserialize<string[]>(options)[0];
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
}
return result;
}
/// <summary>
/// Gets amount of free space available for Isolated Storage
/// </summary>
/// <param name="options">No options is needed for this method</param>
public void getFreeDiskSpace(string options)
{
try
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, isoFile.AvailableFreeSpace));
}
}
catch (IsolatedStorageException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
}
}
/// <summary>
/// Check if file exists
/// </summary>
/// <param name="options">File path</param>
public void testFileExists(string options)
{
IsDirectoryOrFileExist(options, false);
}
/// <summary>
/// Check if directory exists
/// </summary>
/// <param name="options">directory name</param>
public void testDirectoryExists(string options)
{
IsDirectoryOrFileExist(options, true);
}
/// <summary>
/// Check if file or directory exist
/// </summary>
/// <param name="options">File path/Directory name</param>
/// <param name="isDirectory">Flag to recognize what we should check</param>
public void IsDirectoryOrFileExist(string options, bool isDirectory)
{
if (!LoadFileOptions(options))
{
return;
}
try
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
bool isExist;
if (isDirectory)
{
isExist = isoFile.DirectoryExists(fileOptions.DirectoryName);
}
else
{
isExist = isoFile.FileExists(fileOptions.FilePath);
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, isExist));
}
}
catch (IsolatedStorageException) // default handler throws INVALID_MODIFICATION_ERR
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
}
public void readAsDataURL(string options)
{
// exception+PluginResult are handled by getSingleStringOptions
string filePath = getSingleStringOption(options);
if (filePath != null)
{
try
{
string base64URL = null;
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoFile.FileExists(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
string mimeType = MimeTypeMapper.GetMimeType(filePath);
using (IsolatedStorageFileStream stream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
{
string base64String = GetFileContent(stream);
base64URL = "data:" + mimeType + ";base64," + base64String;
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, base64URL));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
}
}
}
public void readAsText(string options)
{
// TODO: try/catch
string[] optStrings = JSON.JsonHelper.Deserialize<string[]>(options);
string filePath = optStrings[0];
string encStr = optStrings[1];
try
{
string text;
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoFile.FileExists(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
Encoding encoding = Encoding.GetEncoding(encStr);
using (TextReader reader = new StreamReader(isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read), encoding))
{
text = reader.ReadToEnd();
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, text));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
}
}
/// <summary>
/// Reads application resource as a text
/// </summary>
/// <param name="options">Path to a resource</param>
public void readResourceAsText(string options)
{
string pathToResource;
try
{
string[] optStrings = JSON.JsonHelper.Deserialize<string[]>(options);
pathToResource = optStrings[0];
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
try
{
if (pathToResource.StartsWith("/"))
{
pathToResource = pathToResource.Remove(0, 1);
}
var resource = System.Windows.Application.GetResourceStream(new Uri(pathToResource, UriKind.Relative));
if (resource == null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
string text;
StreamReader streamReader = new StreamReader(resource.Stream);
text = streamReader.ReadToEnd();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, text));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
}
}
public void truncate(string options)
{
// TODO: try/catch
string[] optStrings = JSON.JsonHelper.Deserialize<string[]>(options);
string filePath = optStrings[0];
int size = int.Parse(optStrings[1]);
try
{
long streamLength = 0;
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoFile.FileExists(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile))
{
if (0 <= size && size <= stream.Length)
{
stream.SetLength(size);
}
streamLength = stream.Length;
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, streamLength));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
}
}
//write:["filePath","data","position"],
public void write(string options)
{
// TODO: try/catch
string[] optStrings = JSON.JsonHelper.Deserialize<string[]>(options);
string filePath = optStrings[0];
string data = optStrings[1];
int position = int.Parse(optStrings[2]);
try
{
if (string.IsNullOrEmpty(data))
{
Debug.WriteLine("Expected some data to be send in the write command to {0}", filePath);
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
// create the file if not exists
if (!isoFile.FileExists(filePath))
{
var file = isoFile.CreateFile(filePath);
file.Close();
}
using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile))
{
if (0 <= position && position <= stream.Length)
{
stream.SetLength(position);
}
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Seek(0, SeekOrigin.End);
writer.Write(data.ToCharArray());
}
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, data.Length));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
}
}
/// <summary>
/// Look up metadata about this entry.
/// </summary>
/// <param name="options">filePath to entry</param>
public void getMetadata(string options)
{
string filePath = getSingleStringOption(options);
if (filePath != null)
{
try
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.FileExists(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK,
new ModificationMetadata() { modificationTime = isoFile.GetLastWriteTime(filePath).DateTime.ToString() }));
}
else if (isoFile.DirectoryExists(filePath))
{
string modTime = isoFile.GetLastWriteTime(filePath).DateTime.ToString();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new ModificationMetadata() { modificationTime = modTime }));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
}
catch (IsolatedStorageException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
}
}
}
/// <summary>
/// Returns a File that represents the current state of the file that this FileEntry represents.
/// </summary>
/// <param name="filePath">filePath to entry</param>
/// <returns></returns>
public void getFileMetadata(string options)
{
string filePath = getSingleStringOption(options);
if (filePath != null)
{
try
{
FileMetadata metaData = new FileMetadata(filePath);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, metaData));
}
catch (IsolatedStorageException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR));
}
}
}
}
/// <summary>
/// Look up the parent DirectoryEntry containing this Entry.
/// If this Entry is the root of IsolatedStorage, its parent is itself.
/// </summary>
/// <param name="options"></param>
public void getParent(string options)
{
string filePath = getSingleStringOption(options);
if (filePath != null)
{
try
{
if (string.IsNullOrEmpty(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
FileEntry entry;
if (isoFile.FileExists(filePath) || isoFile.DirectoryExists(filePath))
{
string path = this.GetParentDirectory(filePath);
entry = FileEntry.GetEntry(path);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
}
}
public void remove(string options)
{
string filePath = getSingleStringOption(options);
if (filePath != null)
{
try
{
if (filePath == "/" || filePath == "" || filePath == @"\")
{
throw new Exception("Cannot delete root file system") ;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.FileExists(filePath))
{
isoFile.DeleteFile(filePath);
}
else
{
if (isoFile.DirectoryExists(filePath))
{
isoFile.DeleteDirectory(filePath);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
}
}
}
}
public void removeRecursively(string options)
{
string filePath = getSingleStringOption(options);
if (filePath != null)
{
if (string.IsNullOrEmpty(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
}
else
{
removeDirRecursively(filePath);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
}
}
public void readEntries(string options)
{
string filePath = getSingleStringOption(options);
if (filePath != null)
{
try
{
if (string.IsNullOrEmpty(filePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.DirectoryExists(filePath))
{
string path = File.AddSlashToDirectory(filePath);
List<FileEntry> entries = new List<FileEntry>();
string[] files = isoFile.GetFileNames(path + "*");
string[] dirs = isoFile.GetDirectoryNames(path + "*");
foreach (string file in files)
{
entries.Add(FileEntry.GetEntry(path + file));
}
foreach (string dir in dirs)
{
entries.Add(FileEntry.GetEntry(path + dir + "/"));
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entries));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
}
}
}
}
public void requestFileSystem(string options)
{
// TODO: try/catch
double[] optVals = JSON.JsonHelper.Deserialize<double[]>(options);
double fileSystemType = optVals[0];
double size = optVals[1];
IsolatedStorageFile.GetUserStoreForApplication();
if (size > (10 * 1024 * 1024)) // 10 MB, compiler will clean this up!
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR));
return;
}
try
{
if (size != 0)
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
long availableSize = isoFile.AvailableFreeSpace;
if (size > availableSize)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR));
return;
}
}
}
if (fileSystemType == PERSISTENT)
{
// TODO: this should be in it's own folder to prevent overwriting of the app assets, which are also in ISO
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("persistent", FileEntry.GetEntry("/"))));
}
else if (fileSystemType == TEMPORARY)
{
using (IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoStorage.FileExists(TMP_DIRECTORY_NAME))
{
isoStorage.CreateDirectory(TMP_DIRECTORY_NAME);
}
}
string tmpFolder = "/" + TMP_DIRECTORY_NAME + "/";
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("temporary", FileEntry.GetEntry(tmpFolder))));
}
else if (fileOptions.FileSystemType == RESOURCE)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("resource")));
}
else if (fileOptions.FileSystemType == APPLICATION)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("application")));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
}
}
}
public void resolveLocalFileSystemURI(string options)
{
string uri = getSingleStringOption(options).Split('?')[0];
if (uri != null)
{
// a single '/' is valid, however, '/someDir' is not, but '/tmp//somedir' is valid
if (uri.StartsWith("/") && uri.IndexOf("//") < 0 && uri != "/")
{
Debug.WriteLine("Starts with / ::: " + uri);
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR));
return;
}
try
{
// fix encoded spaces
string path = Uri.UnescapeDataString(uri);
FileEntry uriEntry = FileEntry.GetEntry(path);
if (uriEntry != null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, uriEntry));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
}
}
}
}
public void copyTo(string options)
{
TransferTo(options, false);
}
public void moveTo(string options)
{
TransferTo(options, true);
}
public void getFile(string options)
{
GetFileOrDirectory(options, false);
}
public void getDirectory(string options)
{
GetFileOrDirectory(options, true);
}
#region internal functionality
/// <summary>
/// Retrieves the parent directory name of the specified path,
/// </summary>
/// <param name="path">Path</param>
/// <returns>Parent directory name</returns>
private string GetParentDirectory(string path)
{
if (String.IsNullOrEmpty(path) || path == "/")
{
return "/";
}
if (path.EndsWith(@"/") || path.EndsWith(@"\"))
{
return this.GetParentDirectory(Path.GetDirectoryName(path));
}
string result = Path.GetDirectoryName(path);
if (result == null)
{
result = "/";
}
return result;
}
private void removeDirRecursively(string fullPath)
{
try
{
if (fullPath == "/")
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
return;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.DirectoryExists(fullPath))
{
string tempPath = File.AddSlashToDirectory(fullPath);
string[] files = isoFile.GetFileNames(tempPath + "*");
if (files.Length > 0)
{
foreach (string file in files)
{
isoFile.DeleteFile(tempPath + file);
}
}
string[] dirs = isoFile.GetDirectoryNames(tempPath + "*");
if (dirs.Length > 0)
{
foreach (string dir in dirs)
{
removeDirRecursively(tempPath + dir);
}
}
isoFile.DeleteDirectory(fullPath);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
}
}
}
private bool CanonicalCompare(string pathA, string pathB)
{
string a = pathA.Replace("//", "/");
string b = pathB.Replace("//", "/");
return a.Equals(b, StringComparison.OrdinalIgnoreCase);
}
/*
* copyTo:["fullPath","parent", "newName"],
* moveTo:["fullPath","parent", "newName"],
*/
private void TransferTo(string options, bool move)
{
// TODO: try/catch
string[] optStrings = JSON.JsonHelper.Deserialize<string[]>(options);
string fullPath = optStrings[0];
string parent = optStrings[1];
string newFileName = optStrings[2];
char[] invalids = Path.GetInvalidPathChars();
if (newFileName.IndexOfAny(invalids) > -1 || newFileName.IndexOf(":") > -1 )
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR));
return;
}
try
{
if ((parent == null) || (string.IsNullOrEmpty(parent)) || (string.IsNullOrEmpty(fullPath)))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
string parentPath = File.AddSlashToDirectory(parent);
string currentPath = fullPath;
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
bool isFileExist = isoFile.FileExists(currentPath);
bool isDirectoryExist = isoFile.DirectoryExists(currentPath);
bool isParentExist = isoFile.DirectoryExists(parentPath);
if ( ( !isFileExist && !isDirectoryExist ) || !isParentExist )
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
string newName;
string newPath;
if (isFileExist)
{
newName = (string.IsNullOrEmpty(newFileName))
? Path.GetFileName(currentPath)
: newFileName;
newPath = Path.Combine(parentPath, newName);
// sanity check ..
// cannot copy file onto itself
if (CanonicalCompare(newPath,currentPath)) //(parent + newFileName))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR));
return;
}
else if (isoFile.DirectoryExists(newPath))
{
// there is already a folder with the same name, operation is not allowed
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR));
return;
}
else if (isoFile.FileExists(newPath))
{ // remove destination file if exists, in other case there will be exception
isoFile.DeleteFile(newPath);
}
if (move)
{
isoFile.MoveFile(currentPath, newPath);
}
else
{
isoFile.CopyFile(currentPath, newPath, true);
}
}
else
{
newName = (string.IsNullOrEmpty(newFileName))
? currentPath
: newFileName;
newPath = Path.Combine(parentPath, newName);
if (move)
{
// remove destination directory if exists, in other case there will be exception
// target directory should be empty
if (!newPath.Equals(currentPath) && isoFile.DirectoryExists(newPath))
{
isoFile.DeleteDirectory(newPath);
}
isoFile.MoveDirectory(currentPath, newPath);
}
else
{
CopyDirectory(currentPath, newPath, isoFile);
}
}
FileEntry entry = FileEntry.GetEntry(newPath);
if (entry != null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
}
}
}
private bool HandleException(Exception ex)
{
bool handled = false;
if (ex is SecurityException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, SECURITY_ERR));
handled = true;
}
else if (ex is FileNotFoundException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
handled = true;
}
else if (ex is ArgumentException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR));
handled = true;
}
else if (ex is IsolatedStorageException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR));
handled = true;
}
else if (ex is DirectoryNotFoundException)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
handled = true;
}
return handled;
}
private void CopyDirectory(string sourceDir, string destDir, IsolatedStorageFile isoFile)
{
string path = File.AddSlashToDirectory(sourceDir);
bool bExists = isoFile.DirectoryExists(destDir);
if (!bExists)
{
isoFile.CreateDirectory(destDir);
}
destDir = File.AddSlashToDirectory(destDir);
string[] files = isoFile.GetFileNames(path + "*");
if (files.Length > 0)
{
foreach (string file in files)
{
isoFile.CopyFile(path + file, destDir + file,true);
}
}
string[] dirs = isoFile.GetDirectoryNames(path + "*");
if (dirs.Length > 0)
{
foreach (string dir in dirs)
{
CopyDirectory(path + dir, destDir + dir, isoFile);
}
}
}
private void GetFileOrDirectory(string options, bool getDirectory)
{
FileOptions fOptions = new FileOptions();
try
{
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
fOptions.FullPath = args[0];
fOptions.Path = args[1];
fOptions.CreatingOpt = JSON.JsonHelper.Deserialize<CreatingOptions>(args[2]);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
try
{
if ((string.IsNullOrEmpty(fOptions.Path)) || (string.IsNullOrEmpty(fOptions.FullPath)))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
string path;
if (fOptions.Path.Split(':').Length > 2)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR));
return;
}
try
{
path = Path.Combine(fOptions.FullPath + "/", fOptions.Path);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR));
return;
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
bool isFile = isoFile.FileExists(path);
bool isDirectory = isoFile.DirectoryExists(path);
bool create = (fOptions.CreatingOpt == null) ? false : fOptions.CreatingOpt.Create;
bool exclusive = (fOptions.CreatingOpt == null) ? false : fOptions.CreatingOpt.Exclusive;
if (create)
{
if (exclusive && (isoFile.FileExists(path) || isoFile.DirectoryExists(path)))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, PATH_EXISTS_ERR));
return;
}
// need to make sure the parent exists
// it is an error to create a directory whose immediate parent does not yet exist
// see issue: https://issues.apache.org/jira/browse/CB-339
string[] pathParts = path.Split('/');
string builtPath = pathParts[0];
for (int n = 1; n < pathParts.Length - 1; n++)
{
builtPath += "/" + pathParts[n];
if (!isoFile.DirectoryExists(builtPath))
{
Debug.WriteLine(String.Format("Error :: Parent folder \"{0}\" does not exist, when attempting to create \"{1}\"",builtPath,path));
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
}
if ((getDirectory) && (!isDirectory))
{
isoFile.CreateDirectory(path);
}
else
{
if ((!getDirectory) && (!isFile))
{
IsolatedStorageFileStream fileStream = isoFile.CreateFile(path);
fileStream.Close();
}
}
}
else
{
if ((!isFile) && (!isDirectory))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
return;
}
if (((getDirectory) && (!isDirectory)) || ((!getDirectory) && (!isFile)))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, TYPE_MISMATCH_ERR));
return;
}
}
FileEntry entry = FileEntry.GetEntry(path);
if (entry != null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR));
}
}
}
catch (Exception ex)
{
if (!this.HandleException(ex))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR));
}
}
}
private static string AddSlashToDirectory(string dirPath)
{
if (dirPath.EndsWith("/"))
{
return dirPath;
}
else
{
return dirPath + "/";
}
}
/// <summary>
/// Returns file content in a form of base64 string
/// </summary>
/// <param name="stream">File stream</param>
/// <returns>Base64 representation of the file</returns>
private string GetFileContent(Stream stream)
{
int streamLength = (int)stream.Length;
byte[] fileData = new byte[streamLength + 1];
stream.Read(fileData, 0, streamLength);
stream.Close();
return Convert.ToBase64String(fileData);
}
#endregion
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections;
using System.IO;
#if !(NET_1_1)
using System.Collections.Generic;
#endif
using log4net;
using FluorineFx.Messaging.Api;
using FluorineFx.Messaging.Api.Messaging;
using FluorineFx.Messaging.Api.Stream;
using FluorineFx.Messaging.Api.Statistics;
using FluorineFx.Messaging.Api.Event;
using FluorineFx.Messaging.Rtmp.Messaging;
using FluorineFx.Messaging.Rtmp.Event;
using FluorineFx.Messaging.Rtmp.Stream;
using FluorineFx.Messaging.Rtmp.Stream.Codec;
using FluorineFx.Messaging.Rtmp.Stream.Consumer;
using FluorineFx.Messaging.Rtmp.Stream.Messages;
using FluorineFx.Messaging.Messages;
using FluorineFx.Collections;
namespace FluorineFx.Messaging.Rtmp.Stream
{
/// <summary>
/// Represents live stream broadcasted from client. As Flash Media Server, supports
/// recording mode for live streams, that is, broadcasted stream has broadcast mode. It can be either
/// "live" or "record" and latter causes server-side application to record broadcasted stream.
///
/// Note that recorded streams are recorded as FLV files. The same is correct for audio, because
/// NellyMoser codec that Flash Player uses prohibits on-the-fly transcoding to audio formats like MP3
/// without paying of licensing fee or buying SDK.
///
/// This type of stream uses two different pipes for live streaming and recording.
/// </summary>
class ClientBroadcastStream : AbstractClientStream,
IClientBroadcastStream, IFilter, IPushableConsumer, IPipeConnectionListener, IEventDispatcher, IClientBroadcastStreamStatistics
{
private static ILog log = LogManager.GetLogger(typeof(ClientBroadcastStream));
/// <summary>
/// Stores absolute time for video stream.
/// </summary>
private int _audioTime = -1;
/// <summary>
/// Total number of bytes received.
/// </summary>
private long _bytesReceived;
/// <summary>
/// Is there need to check video codec?
/// </summary>
private bool _checkVideoCodec = false;
/// <summary>
/// Data is sent by chunks, each of them has size.
/// </summary>
private int _chunkSize = 0;
/// <summary>
/// Is this stream still active?
/// </summary>
private bool _closed = false;
/// <summary>
/// Output endpoint that providers use.
/// </summary>
private IMessageOutput _connMsgOut;
/// <summary>
/// Stores absolute time for data stream.
/// </summary>
private int _dataTime = -1;
/// <summary>
/// Stores timestamp of first packet.
/// </summary>
private int _firstPacketTime = -1;
/// <summary>
/// Pipe for live streaming
/// </summary>
private IPipe _livePipe;
/// <summary>
/// Stream published name.
/// </summary>
private string _publishedName;
/// <summary>
/// Whether we are recording or not.
/// </summary>
private bool _recording = false;
/// <summary>
/// FileConsumer used to output recording to disk.
/// </summary>
private FileConsumer _recordingFile;
/// <summary>
/// The filename we are recording to.
/// </summary>
private string _recordingFilename;
/// <summary>
/// Pipe for recording.
/// </summary>
private IPipe _recordPipe;
/// <summary>
/// Is there need to send start notification?
/// </summary>
private bool _sendStartNotification = true;
/// <summary>
/// Stores statistics about subscribers.
/// </summary>
private StatisticsCounter _subscriberStats = new StatisticsCounter();
/// <summary>
/// Factory object for video codecs.
/// </summary>
private VideoCodecFactory _videoCodecFactory = null;
/// <summary>
/// Stores absolute time for audio stream.
/// </summary>
private int _videoTime = -1;
/// <summary>
/// Minimum stream time
/// </summary>
private int _minStreamTime = 0;
/// <summary>
/// Listeners to get notified about received packets.
/// Set(IStreamListener)
/// </summary>
private CopyOnWriteArraySet _listeners = new CopyOnWriteArraySet();
/// <summary>
/// Gets or sets minimum stream time.
/// </summary>
public int MinStreamTime
{
get { return _minStreamTime; }
set { _minStreamTime = value; }
}
private void CheckSendNotifications(IEvent evt)
{
IEventListener source = evt.Source;
SendStartNotifications(source);
}
private void SendStartNotifications(IEventListener source)
{
if (_sendStartNotification)
{
// Notify handler that stream starts recording/publishing
_sendStartNotification = false;
if (source is IConnection)
{
IScope scope = (source as IConnection).Scope;
if (scope.HasHandler)
{
Object handler = scope.Handler;
if (handler is IStreamAwareScopeHandler)
{
if (_recording)
{
(handler as IStreamAwareScopeHandler).StreamRecordStart(this);
}
else
{
(handler as IStreamAwareScopeHandler).StreamPublishStart(this);
}
}
}
}
// Send start notifications
SendPublishStartNotify();
if (_recording)
{
SendRecordStartNotify();
}
NotifyBroadcastStart();
}
}
/// <summary>
/// Sends publish start notifications.
/// </summary>
private void SendPublishStartNotify()
{
StatusASO publishStatus = new StatusASO(StatusASO.NS_PUBLISH_START);
publishStatus.clientid = this.StreamId;
publishStatus.details = this.PublishedName;
StatusMessage startMsg = new StatusMessage();
startMsg.body = publishStatus;
try
{
_connMsgOut.PushMessage(startMsg);
}
catch(System.IO.IOException ex)
{
log.Error("Error while pushing message.", ex);
}
}
/// <summary>
/// Sends publish stop notifications.
/// </summary>
private void SendPublishStopNotify()
{
StatusASO stopStatus = new StatusASO(StatusASO.NS_UNPUBLISHED_SUCCESS);
stopStatus.clientid = this.StreamId;
stopStatus.details = this.PublishedName;
StatusMessage stopMsg = new StatusMessage();
stopMsg.body = stopStatus;
try
{
_connMsgOut.PushMessage(stopMsg);
}
catch (System.IO.IOException ex)
{
log.Error("Error while pushing message.", ex);
}
}
/// <summary>
/// Sends record start notifications.
/// </summary>
private void SendRecordStartNotify()
{
StatusASO recordStatus = new StatusASO(StatusASO.NS_RECORD_START);
recordStatus.clientid = this.StreamId;
recordStatus.details = this.PublishedName;
StatusMessage startMsg = new StatusMessage();
startMsg.body = recordStatus;
try
{
_connMsgOut.PushMessage(startMsg);
}
catch (System.IO.IOException ex)
{
log.Error("Error while pushing message.", ex);
}
}
/// <summary>
/// Sends record stop notifications.
/// </summary>
private void SendRecordStopNotify()
{
StatusASO stopStatus = new StatusASO(StatusASO.NS_RECORD_STOP);
stopStatus.clientid = this.StreamId;
stopStatus.details = this.PublishedName;
StatusMessage startMsg = new StatusMessage();
startMsg.body = stopStatus;
try
{
_connMsgOut.PushMessage(startMsg);
}
catch (System.IO.IOException ex)
{
log.Error("Error while pushing message.", ex);
}
}
/// <summary>
/// Sends record failed notifications.
/// </summary>
/// <param name="reason"></param>
private void SendRecordFailedNotify(string reason)
{
StatusASO failedStatus = new StatusASO(StatusASO.NS_RECORD_FAILED);
failedStatus.level = StatusASO.ERROR;
failedStatus.clientid = this.StreamId;
failedStatus.details = this.PublishedName;
failedStatus.description = reason;
StatusMessage failedMsg = new StatusMessage();
failedMsg.body = failedStatus;
try
{
_connMsgOut.PushMessage(failedMsg);
}
catch (IOException ex)
{
log.Error("Error while pushing message.", ex);
}
}
/// <summary>
/// Notifies handler on stream broadcast start.
/// </summary>
private void NotifyBroadcastStart()
{
IStreamAwareScopeHandler handler = GetStreamAwareHandler();
if (handler != null)
{
try
{
handler.StreamBroadcastStart(this);
}
catch (Exception ex)
{
log.Error("Error notify streamBroadcastStart", ex);
}
}
}
/// <summary>
/// Notifies handler on stream broadcast stop.
/// </summary>
private void NotifyBroadcastClose()
{
IStreamAwareScopeHandler handler = GetStreamAwareHandler();
if (handler != null)
{
try
{
handler.StreamBroadcastClose(this);
}
catch (Exception ex)
{
log.Error("Error notify streamBroadcastStop", ex);
}
}
}
/// <summary>
/// Send OOB control message with chunk size.
/// </summary>
private void NotifyChunkSize()
{
if (_chunkSize > 0 && _livePipe != null)
{
OOBControlMessage setChunkSize = new OOBControlMessage();
setChunkSize.Target = "ConnectionConsumer";
setChunkSize.ServiceName = "chunkSize";
setChunkSize.ServiceParameterMap["chunkSize"] = _chunkSize;
_livePipe.SendOOBControlMessage(this.Provider, setChunkSize);
}
}
/// <summary>
/// Closes stream, unsubscribes provides, sends stoppage notifications and broadcast close notification.
/// </summary>
public override void Close()
{
lock (this.SyncRoot)
{
if (_closed)
return;// Already closed
_closed = true;
if (_livePipe != null)
_livePipe.Unsubscribe(this as IProvider);
if (_recordPipe != null)
_recordPipe.Unsubscribe(this as IProvider);
if (_recording)
SendRecordStopNotify();
SendPublishStopNotify();
// TODO: can we send the client something to make sure he stops sending data?
_connMsgOut.Unsubscribe(this);
NotifyBroadcastClose();
}
}
#region IClientBroadcastStream Members
public void StartPublishing()
{
// We send the start messages before the first packet is received.
// This is required so FME actually starts publishing.
SendStartNotifications(FluorineFx.Context.FluorineContext.Current.Connection);
}
public IClientBroadcastStreamStatistics Statistics
{
get { return this; }
}
#endregion
#region IBroadcastStream Members
/// <summary>
/// Saves broadcasted stream.
/// </summary>
/// <param name="name"></param>
/// <param name="isAppend"></param>
public void SaveAs(string name, bool isAppend)
{
if (log.IsDebugEnabled)
log.Debug("SaveAs - name: " + name + " append: " + isAppend);
// Get stream scope
IStreamCapableConnection connection = this.Connection;
if (connection == null)
{
// TODO: throw other exception here?
throw new IOException("Stream is no longer connected");
}
IScope scope = connection.Scope;
// Get stream filename generator
IStreamFilenameGenerator generator = ScopeUtils.GetScopeService(scope, typeof(IStreamFilenameGenerator)) as IStreamFilenameGenerator;
// Generate filename
string filename = generator.GenerateFilename(scope, name, ".flv", GenerationType.RECORD);
// Get file for that filename
FileInfo file;
if (generator.ResolvesToAbsolutePath)
file = new FileInfo(filename);
else
file = scope.Context.GetResource(filename).File;
// If append mode is on...
if (!isAppend)
{
if (file.Exists)
{
// Per livedoc of FCS/FMS:
// When "live" or "record" is used,
// any previously recorded stream with the same stream URI is deleted.
file.Delete();
}
}
else
{
if (!file.Exists)
{
// Per livedoc of FCS/FMS:
// If a recorded stream at the same URI does not already exist,
// "append" creates the stream as though "record" was passed.
isAppend = false;
}
}
//Requery
file = new FileInfo(file.FullName);
if (!file.Exists)
{
// Make sure the destination directory exists
string directory = Path.GetDirectoryName(file.FullName);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
}
if (!file.Exists)
{
using (FileStream fs = file.Create()) { }
}
if (log.IsDebugEnabled)
{
log.Debug("Recording file: " + file.FullName);
}
_recordingFile = new FileConsumer(scope, file);
#if !(NET_1_1)
Dictionary<string, object> parameterMap = new Dictionary<string, object>();
#else
Hashtable parameterMap = new Hashtable();
#endif
if (isAppend)
{
parameterMap.Add("mode", "append");
}
else
{
parameterMap.Add("mode", "record");
}
_recordPipe.Subscribe(_recordingFile, parameterMap);
_recording = true;
_recordingFilename = filename;
}
public string SaveFilename
{
get { return _recordingFilename; }
}
/// <summary>
/// Name that used for publishing. Set at client side when begin to broadcast with NetStream#publish.
/// </summary>
public string PublishedName
{
get
{
return _publishedName;
}
set
{
if (log.IsDebugEnabled)
log.Debug("setPublishedName: " + value);
_publishedName = value;
}
}
public IProvider Provider
{
get { return this; }
}
/// <summary>
/// Add a listener to be notified about received packets.
/// </summary>
/// <param name="listener">The listener to add.</param>
public void AddStreamListener(IStreamListener listener)
{
_listeners.Add(listener);
}
/// <summary>
/// Return registered stream listeners.
/// </summary>
/// <returns>The registered listeners.</returns>
public ICollection GetStreamListeners()
{
return _listeners;
}
/// <summary>
/// Remove a listener from being notified about received packets.
/// </summary>
/// <param name="listener">The listener to remove.</param>
public void RemoveStreamListener(IStreamListener listener)
{
_listeners.Remove(listener);
}
#endregion
#region IMessageComponent Members
/// <summary>
/// Out-of-band control message handler.
/// </summary>
/// <param name="source">OOB message source.</param>
/// <param name="pipe">Pipe that used to send OOB message.</param>
/// <param name="oobCtrlMsg">Out-of-band control message.</param>
public void OnOOBControlMessage(IMessageComponent source, IPipe pipe, OOBControlMessage oobCtrlMsg)
{
if (!"ClientBroadcastStream".Equals(oobCtrlMsg.Target))
return;
if ("chunkSize".Equals(oobCtrlMsg.ServiceName))
{
_chunkSize = (int)oobCtrlMsg.ServiceParameterMap["chunkSize"];
NotifyChunkSize();
}
}
#endregion
#region IPushableConsumer Members
public void PushMessage(IPipe pipe, IMessage message)
{
//not implemented
}
#endregion
#region IPipeConnectionListener Members
/// <summary>
/// Pipe connection event handler.
/// </summary>
/// <param name="evt">Pipe connection event.</param>
public void OnPipeConnectionEvent(PipeConnectionEvent evt)
{
switch (evt.Type)
{
case PipeConnectionEvent.PROVIDER_CONNECT_PUSH:
if (evt.Provider == this && evt.Source != _connMsgOut && (evt.ParameterMap == null || !evt.ParameterMap.ContainsKey("record")))
{
_livePipe = evt.Source as IPipe;
foreach (IConsumer consumer in _livePipe.GetConsumers())
{
_subscriberStats.Increment();
}
}
break;
case PipeConnectionEvent.PROVIDER_DISCONNECT:
if (_livePipe == evt.Source)
{
_livePipe = null;
}
break;
case PipeConnectionEvent.CONSUMER_CONNECT_PUSH:
if (_livePipe == evt.Source)
{
NotifyChunkSize();
}
_subscriberStats.Increment();
break;
case PipeConnectionEvent.CONSUMER_DISCONNECT:
_subscriberStats.Decrement();
break;
default:
break;
}
}
#endregion
#region IEventDispatcher Members
public void DispatchEvent(IEvent evt)
{
if (!(evt is IRtmpEvent)
&& (evt.EventType != EventType.STREAM_CONTROL)
&& (evt.EventType != EventType.STREAM_DATA) || _closed)
{
// ignored event
if (log.IsDebugEnabled)
{
log.Debug("DispatchEvent: " + evt.EventType);
}
return;
}
// Get stream codec
IStreamCodecInfo codecInfo = this.CodecInfo;
StreamCodecInfo info = null;
if (codecInfo is StreamCodecInfo)
{
info = codecInfo as StreamCodecInfo;
}
IRtmpEvent rtmpEvent = evt as IRtmpEvent;
if (rtmpEvent == null)
{
if (log.IsDebugEnabled)
log.Debug("IRtmpEvent expected in event dispatch");
return;
}
int eventTime = -1;
// If this is first packet save it's timestamp
if (_firstPacketTime == -1)
{
_firstPacketTime = rtmpEvent.Timestamp;
if (log.IsDebugEnabled)
log.Debug(string.Format("CBS: {0} firstPacketTime={1} {2}", this.Name, _firstPacketTime, rtmpEvent.Header.IsTimerRelative ? "(rel)" : "(abs)"));
}
if (rtmpEvent is IStreamData && (rtmpEvent as IStreamData).Data != null)
{
_bytesReceived += (rtmpEvent as IStreamData).Data.Limit;
}
if (rtmpEvent is AudioData)
{
if (info != null)
{
info.HasAudio = true;
}
if (rtmpEvent.Header.IsTimerRelative)
{
if (_audioTime == 0)
log.Warn(string.Format("First Audio timestamp is relative! {0}", rtmpEvent.Timestamp));
_audioTime += rtmpEvent.Timestamp;
}
else
{
_audioTime = rtmpEvent.Timestamp;
}
eventTime = _audioTime;
}
else if (rtmpEvent is VideoData)
{
IVideoStreamCodec videoStreamCodec = null;
if (_videoCodecFactory != null && _checkVideoCodec)
{
videoStreamCodec = _videoCodecFactory.GetVideoCodec((rtmpEvent as VideoData).Data);
if (codecInfo is StreamCodecInfo)
{
(codecInfo as StreamCodecInfo).VideoCodec = videoStreamCodec;
}
_checkVideoCodec = false;
}
else if (codecInfo != null)
{
videoStreamCodec = codecInfo.VideoCodec;
}
if (videoStreamCodec != null)
{
videoStreamCodec.AddData((rtmpEvent as VideoData).Data);
}
if (info != null)
{
info.HasVideo = true;
}
if (rtmpEvent.Header.IsTimerRelative)
{
if (_videoTime == 0)
log.Warn(string.Format("First Video timestamp is relative! {0}", rtmpEvent.Timestamp));
_videoTime += rtmpEvent.Timestamp;
}
else
{
_videoTime = rtmpEvent.Timestamp;
// Flash player may send first VideoData with old-absolute timestamp.
// This ruins the stream's timebase in FileConsumer.
// We don't want to discard the packet, as it may be a video keyframe.
// Generally a Data or Audio packet has set the timebase to a reasonable value,
// Eventually a new/correct absolute time will come on the video channel.
// We could put this logic between livePipe and filePipe;
// This would work for Audio Data as well, but have not seen the need.
int cts = Math.Max(_audioTime, _dataTime);
cts = Math.Max(cts, _minStreamTime);
int fudge = 20;
// Accept some slightly (20ms) retro timestamps [this may not be needed,
// the publish Data should strictly precede the video data]
if (_videoTime + fudge < cts)
{
if (log.IsDebugEnabled)
log.Debug(string.Format("DispatchEvent: adjust archaic videoTime, from: {0} to {1}", _videoTime, cts));
_videoTime = cts;
}
}
eventTime = _videoTime;
}
else if (rtmpEvent is Invoke)
{
if (rtmpEvent.Header.IsTimerRelative)
{
if (_dataTime == 0)
log.Warn(string.Format("First data [Invoke] timestamp is relative! {0}", rtmpEvent.Timestamp));
_dataTime += rtmpEvent.Timestamp;
}
else
{
_dataTime = rtmpEvent.Timestamp;
}
return;
}
else if (rtmpEvent is Notify)
{
if (rtmpEvent.Header.IsTimerRelative)
{
if (_dataTime == 0)
log.Warn(string.Format("First data [Notify] timestamp is relative! {0}", rtmpEvent.Timestamp));
_dataTime += rtmpEvent.Timestamp;
}
else
{
_dataTime = rtmpEvent.Timestamp;
}
eventTime = _dataTime;
}
// Notify event listeners
CheckSendNotifications(evt);
// Create new RTMP message, initialize it and push through pipe
FluorineFx.Messaging.Rtmp.Stream.Messages.RtmpMessage msg = new FluorineFx.Messaging.Rtmp.Stream.Messages.RtmpMessage();
msg.body = rtmpEvent;
msg.body.Timestamp = eventTime;
try
{
if (_livePipe != null)
_livePipe.PushMessage(msg);
if( _recordPipe != null )
_recordPipe.PushMessage(msg);
}
catch (System.IO.IOException ex)
{
SendRecordFailedNotify(ex.Message);
Stop();
}
// Notify listeners about received packet
if (rtmpEvent is IStreamPacket)
{
foreach (IStreamListener listener in GetStreamListeners())
{
try
{
listener.PacketReceived(this, rtmpEvent as IStreamPacket);
}
catch (Exception ex)
{
log.Error(string.Format("Error while notifying listener {0}", listener), ex);
}
}
}
}
#endregion
#region IClientBroadcastStreamStatistics Members
public int TotalSubscribers
{
get { return _subscriberStats.Total; }
}
public int MaxSubscribers
{
get { return _subscriberStats.Max; }
}
public int ActiveSubscribers
{
get { return _subscriberStats.Current; }
}
public long BytesReceived
{
get { return _bytesReceived; }
}
#endregion
#region IStreamStatistics Members
public int CurrentTimestamp
{
get { return Math.Max(Math.Max(_videoTime, _audioTime), _dataTime); }
}
#endregion
#region IStatisticsBase Members
#endregion
public override void Start()
{
lock (this.SyncRoot)
{
IConsumerService consumerManager = this.Scope.GetService(typeof(IConsumerService)) as IConsumerService;
try
{
//_videoCodecFactory = new VideoCodecFactory();
_videoCodecFactory = this.Scope.GetService(typeof(VideoCodecFactory)) as VideoCodecFactory;
_checkVideoCodec = true;
}
catch (Exception ex)
{
log.Warn("No video codec factory available.", ex);
}
_firstPacketTime = _audioTime = _videoTime = _dataTime = -1;
_connMsgOut = consumerManager.GetConsumerOutput(this);
_connMsgOut.Subscribe(this, null);
_recordPipe = new InMemoryPushPushPipe();
#if !(NET_1_1)
Dictionary<string, object> recordParameterMap = new Dictionary<string, object>();
#else
Hashtable recordParameterMap = new Hashtable();
#endif
// Clear record flag
recordParameterMap.Add("record", null);
_recordPipe.Subscribe(this as IProvider, recordParameterMap);
_recording = false;
_recordingFilename = null;
this.CodecInfo = new StreamCodecInfo();
_closed = false;
_bytesReceived = 0;
_creationTime = System.Environment.TickCount;
}
}
public override void Stop()
{
lock (this.SyncRoot)
{
StopRecording();
Close();
}
}
/// <summary>
/// Stops any currently active recordings.
/// </summary>
public void StopRecording()
{
if (_recording)
{
_recording = false;
_recordingFilename = null;
_recordPipe.Unsubscribe(_recordingFile);
SendRecordStopNotify();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void SubtractSByte()
{
var test = new SimpleBinaryOpTest__SubtractSByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__SubtractSByte
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(SByte);
private static SByte[] _data1 = new SByte[ElementCount];
private static SByte[] _data2 = new SByte[ElementCount];
private static Vector128<SByte> _clsVar1;
private static Vector128<SByte> _clsVar2;
private Vector128<SByte> _fld1;
private Vector128<SByte> _fld2;
private SimpleBinaryOpTest__DataTable<SByte> _dataTable;
static SimpleBinaryOpTest__SubtractSByte()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__SubtractSByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<SByte>(_data1, _data2, new SByte[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Subtract(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Subtract(
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Subtract(
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Subtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr);
var result = Sse2.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse2.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse2.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__SubtractSByte();
var result = Sse2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Subtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<SByte> left, Vector128<SByte> right, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[ElementCount];
SByte[] inArray2 = new SByte[ElementCount];
SByte[] outArray = new SByte[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[ElementCount];
SByte[] inArray2 = new SByte[ElementCount];
SByte[] outArray = new SByte[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "")
{
if ((sbyte)(left[0] - right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((sbyte)(left[i] - right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Subtract)}<SByte>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Util
{
using Lucene.Net.Support;
using ByteArrayDataInput = Lucene.Net.Store.ByteArrayDataInput;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using DocIdSet = Lucene.Net.Search.DocIdSet;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using MonotonicAppendingLongBuffer = Lucene.Net.Util.Packed.MonotonicAppendingLongBuffer;
using PackedInts = Lucene.Net.Util.Packed.PackedInts;
/// <summary>
/// <seealso cref="DocIdSet"/> implementation based on word-aligned hybrid encoding on
/// words of 8 bits.
/// <p>this implementation doesn't support random-access but has a fast
/// <seealso cref="DocIdSetIterator"/> which can advance in logarithmic time thanks to
/// an index.</p>
/// <p>The compression scheme is simplistic and should work well with sparse and
/// very dense doc id sets while being only slightly larger than a
/// <seealso cref="FixedBitSet"/> for incompressible sets (overhead<2% in the worst
/// case) in spite of the index.</p>
/// <p><b>Format</b>: The format is byte-aligned. An 8-bits word is either clean,
/// meaning composed only of zeros or ones, or dirty, meaning that it contains
/// between 1 and 7 bits set. The idea is to encode sequences of clean words
/// using run-length encoding and to leave sequences of dirty words as-is.</p>
/// <table>
/// <tr><th>Token</th><th>Clean length+</th><th>Dirty length+</th><th>Dirty words</th></tr>
/// <tr><td>1 byte</td><td>0-n bytes</td><td>0-n bytes</td><td>0-n bytes</td></tr>
/// </table>
/// <ul>
/// <li><b>Token</b> encodes whether clean means full of zeros or ones in the
/// first bit, the number of clean words minus 2 on the next 3 bits and the
/// number of dirty words on the last 4 bits. The higher-order bit is a
/// continuation bit, meaning that the number is incomplete and needs additional
/// bytes to be read.</li>
/// <li><b>Clean length+</b>: If clean length has its higher-order bit set,
/// you need to read a <seealso cref="DataInput#readVInt() vint"/>, shift it by 3 bits on
/// the left side and add it to the 3 bits which have been read in the token.</li>
/// <li><b>Dirty length+</b> works the same way as <b>Clean length+</b> but
/// on 4 bits and for the length of dirty words.</li>
/// <li><b>Dirty words</b> are the dirty words, there are <b>Dirty length</b>
/// of them.</li>
/// </ul>
/// <p>this format cannot encode sequences of less than 2 clean words and 0 dirty
/// word. The reason is that if you find a single clean word, you should rather
/// encode it as a dirty word. this takes the same space as starting a new
/// sequence (since you need one byte for the token) but will be lighter to
/// decode. There is however an exception for the first sequence. Since the first
/// sequence may start directly with a dirty word, the clean length is encoded
/// directly, without subtracting 2.</p>
/// <p>There is an additional restriction on the format: the sequence of dirty
/// words is not allowed to contain two consecutive clean words. this restriction
/// exists to make sure no space is wasted and to make sure iterators can read
/// the next doc ID by reading at most 2 dirty words.</p>
/// @lucene.experimental
/// </summary>
public sealed class WAH8DocIdSet : DocIdSet
{
// Minimum index interval, intervals below this value can't guarantee anymore
// that this set implementation won't be significantly larger than a FixedBitSet
// The reason is that a single sequence saves at least one byte and an index
// entry requires at most 8 bytes (2 ints) so there shouldn't be more than one
// index entry every 8 sequences
private const int MIN_INDEX_INTERVAL = 8;
/// <summary>
/// Default index interval. </summary>
public const int DEFAULT_INDEX_INTERVAL = 24;
private static readonly MonotonicAppendingLongBuffer SINGLE_ZERO_BUFFER = new MonotonicAppendingLongBuffer(1, 64, PackedInts.COMPACT);
private static WAH8DocIdSet EMPTY = new WAH8DocIdSet(new byte[0], 0, 1, SINGLE_ZERO_BUFFER, SINGLE_ZERO_BUFFER);
static WAH8DocIdSet()
{
SINGLE_ZERO_BUFFER.Add(0L);
SINGLE_ZERO_BUFFER.Freeze();
}
private static readonly IComparer<Iterator> SERIALIZED_LENGTH_COMPARATOR = new ComparatorAnonymousInnerClassHelper();
private class ComparatorAnonymousInnerClassHelper : IComparer<Iterator>
{
public ComparatorAnonymousInnerClassHelper()
{
}
public virtual int Compare(Iterator wi1, Iterator wi2)
{
return wi1.@in.Length() - wi2.@in.Length();
}
}
/// <summary>
/// Same as <seealso cref="#intersect(Collection, int)"/> with the default index interval. </summary>
public static WAH8DocIdSet Intersect(ICollection<WAH8DocIdSet> docIdSets)
{
return Intersect(docIdSets, DEFAULT_INDEX_INTERVAL);
}
/// <summary>
/// Compute the intersection of the provided sets. this method is much faster than
/// computing the intersection manually since it operates directly at the byte level.
/// </summary>
public static WAH8DocIdSet Intersect(ICollection<WAH8DocIdSet> docIdSets, int indexInterval)
{
switch (docIdSets.Count)
{
case 0:
throw new System.ArgumentException("There must be at least one set to intersect");
case 1:
var iter = docIdSets.GetEnumerator();
iter.MoveNext();
return iter.Current;
}
// The logic below is similar to ConjunctionScorer
int numSets = docIdSets.Count;
var iterators = new Iterator[numSets];
int i = 0;
foreach (WAH8DocIdSet set in docIdSets)
{
var it = (Iterator)set.GetIterator();
iterators[i++] = it;
}
Array.Sort(iterators, SERIALIZED_LENGTH_COMPARATOR);
WordBuilder builder = (WordBuilder)(new WordBuilder()).SetIndexInterval(indexInterval);
int wordNum = 0;
while (true)
{
// Advance the least costly iterator first
iterators[0].AdvanceWord(wordNum);
wordNum = iterators[0].WordNum;
if (wordNum == DocIdSetIterator.NO_MORE_DOCS)
{
break;
}
byte word = iterators[0].Word;
for (i = 1; i < numSets; ++i)
{
if (iterators[i].WordNum < wordNum)
{
iterators[i].AdvanceWord(wordNum);
}
if (iterators[i].WordNum > wordNum)
{
wordNum = iterators[i].WordNum;
goto mainContinue;
}
Debug.Assert(iterators[i].WordNum == wordNum);
word &= iterators[i].Word;
if (word == 0)
{
// There are common words, but they don't share any bit
++wordNum;
goto mainContinue;
}
}
// Found a common word
Debug.Assert(word != 0);
builder.AddWord(wordNum, word);
++wordNum;
mainContinue: ;
}
//mainBreak:
return builder.Build();
}
/// <summary>
/// Same as <seealso cref="#union(Collection, int)"/> with the default index interval. </summary>
public static WAH8DocIdSet Union(ICollection<WAH8DocIdSet> docIdSets)
{
return Union(docIdSets, DEFAULT_INDEX_INTERVAL);
}
/// <summary>
/// Compute the union of the provided sets. this method is much faster than
/// computing the union manually since it operates directly at the byte level.
/// </summary>
public static WAH8DocIdSet Union(ICollection<WAH8DocIdSet> docIdSets, int indexInterval)
{
switch (docIdSets.Count)
{
case 0:
return EMPTY;
case 1:
var iter = docIdSets.GetEnumerator();
iter.MoveNext();
return iter.Current;
}
// The logic below is very similar to DisjunctionScorer
int numSets = docIdSets.Count;
PriorityQueue<Iterator> iterators = new PriorityQueueAnonymousInnerClassHelper(numSets);
foreach (WAH8DocIdSet set in docIdSets)
{
Iterator iterator = (Iterator)set.GetIterator();
iterator.NextWord();
iterators.Add(iterator);
}
Iterator top = iterators.Top();
if (top.WordNum == int.MaxValue)
{
return EMPTY;
}
int wordNum = top.WordNum;
byte word = top.Word;
WordBuilder builder = (WordBuilder)(new WordBuilder()).SetIndexInterval(indexInterval);
while (true)
{
top.NextWord();
iterators.UpdateTop();
top = iterators.Top();
if (top.WordNum == wordNum)
{
word |= top.Word;
}
else
{
builder.AddWord(wordNum, word);
if (top.WordNum == int.MaxValue)
{
break;
}
wordNum = top.WordNum;
word = top.Word;
}
}
return builder.Build();
}
private class PriorityQueueAnonymousInnerClassHelper : PriorityQueue<WAH8DocIdSet.Iterator>
{
public PriorityQueueAnonymousInnerClassHelper(int numSets)
: base(numSets)
{
}
public override bool LessThan(Iterator a, Iterator b)
{
return a.WordNum < b.WordNum;
}
}
internal static int WordNum(int docID)
{
Debug.Assert(docID >= 0);
return (int)((uint)docID >> 3);
}
/// <summary>
/// Word-based builder. </summary>
public class WordBuilder
{
internal readonly GrowableByteArrayDataOutput @out;
internal readonly GrowableByteArrayDataOutput DirtyWords;
internal int Clean;
internal int LastWordNum;
internal int NumSequences;
internal int IndexInterval_Renamed;
internal int Cardinality;
internal bool Reverse;
internal WordBuilder()
{
@out = new GrowableByteArrayDataOutput(1024);
DirtyWords = new GrowableByteArrayDataOutput(128);
Clean = 0;
LastWordNum = -1;
NumSequences = 0;
IndexInterval_Renamed = DEFAULT_INDEX_INTERVAL;
Cardinality = 0;
}
/// <summary>
/// Set the index interval. Smaller index intervals improve performance of
/// <seealso cref="DocIdSetIterator#advance(int)"/> but make the <seealso cref="DocIdSet"/>
/// larger. An index interval <code>i</code> makes the index add an overhead
/// which is at most <code>4/i</code>, but likely much less.The default index
/// interval is <code>8</code>, meaning the index has an overhead of at most
/// 50%. To disable indexing, you can pass <seealso cref="Integer#MAX_VALUE"/> as an
/// index interval.
/// </summary>
public virtual object SetIndexInterval(int indexInterval)
{
if (indexInterval < MIN_INDEX_INTERVAL)
{
throw new System.ArgumentException("indexInterval must be >= " + MIN_INDEX_INTERVAL);
}
this.IndexInterval_Renamed = indexInterval;
return this;
}
internal virtual void WriteHeader(bool reverse, int cleanLength, int dirtyLength)
{
int cleanLengthMinus2 = cleanLength - 2;
Debug.Assert(cleanLengthMinus2 >= 0);
Debug.Assert(dirtyLength >= 0);
int token = ((cleanLengthMinus2 & 0x03) << 4) | (dirtyLength & 0x07);
if (reverse)
{
token |= 1 << 7;
}
if (cleanLengthMinus2 > 0x03)
{
token |= 1 << 6;
}
if (dirtyLength > 0x07)
{
token |= 1 << 3;
}
@out.WriteByte((byte)(sbyte)token);
if (cleanLengthMinus2 > 0x03)
{
@out.WriteVInt((int)((uint)cleanLengthMinus2 >> 2));
}
if (dirtyLength > 0x07)
{
@out.WriteVInt((int)((uint)dirtyLength >> 3));
}
}
internal virtual bool SequenceIsConsistent()
{
for (int i = 1; i < DirtyWords.Length; ++i)
{
Debug.Assert(DirtyWords.Bytes[i - 1] != 0 || DirtyWords.Bytes[i] != 0);
Debug.Assert((byte)DirtyWords.Bytes[i - 1] != 0xFF || (byte)DirtyWords.Bytes[i] != 0xFF);
}
return true;
}
internal virtual void WriteSequence()
{
Debug.Assert(SequenceIsConsistent());
try
{
WriteHeader(Reverse, Clean, DirtyWords.Length);
}
catch (System.IO.IOException cannotHappen)
{
throw new InvalidOperationException(cannotHappen.ToString(), cannotHappen);
}
@out.WriteBytes(DirtyWords.Bytes, 0, DirtyWords.Length);
DirtyWords.Length = 0;
++NumSequences;
}
internal virtual void AddWord(int wordNum, byte word)
{
Debug.Assert(wordNum > LastWordNum);
Debug.Assert(word != 0);
if (!Reverse)
{
if (LastWordNum == -1)
{
Clean = 2 + wordNum; // special case for the 1st sequence
DirtyWords.WriteByte(word);
}
else
{
switch (wordNum - LastWordNum)
{
case 1:
if (word == 0xFF && (byte)DirtyWords.Bytes[DirtyWords.Length - 1] == 0xFF)
{
--DirtyWords.Length;
WriteSequence();
Reverse = true;
Clean = 2;
}
else
{
DirtyWords.WriteByte(word);
}
break;
case 2:
DirtyWords.WriteByte(0);
DirtyWords.WriteByte(word);
break;
default:
WriteSequence();
Clean = wordNum - LastWordNum - 1;
DirtyWords.WriteByte(word);
break;
}
}
}
else
{
Debug.Assert(LastWordNum >= 0);
switch (wordNum - LastWordNum)
{
case 1:
if (word == 0xFF)
{
if (DirtyWords.Length == 0)
{
++Clean;
}
else if ((byte)DirtyWords.Bytes[DirtyWords.Length - 1] == 0xFF)
{
--DirtyWords.Length;
WriteSequence();
Clean = 2;
}
else
{
DirtyWords.WriteByte(word);
}
}
else
{
DirtyWords.WriteByte(word);
}
break;
case 2:
DirtyWords.WriteByte(0);
DirtyWords.WriteByte(word);
break;
default:
WriteSequence();
Reverse = false;
Clean = wordNum - LastWordNum - 1;
DirtyWords.WriteByte(word);
break;
}
}
LastWordNum = wordNum;
Cardinality += BitUtil.BitCount(word);
}
/// <summary>
/// Build a new <seealso cref="WAH8DocIdSet"/>. </summary>
public virtual WAH8DocIdSet Build()
{
if (Cardinality == 0)
{
Debug.Assert(LastWordNum == -1);
return EMPTY;
}
WriteSequence();
byte[] data = Arrays.CopyOf((byte[])(Array)@out.Bytes, @out.Length);
// Now build the index
int valueCount = (NumSequences - 1) / IndexInterval_Renamed + 1;
MonotonicAppendingLongBuffer indexPositions, indexWordNums;
if (valueCount <= 1)
{
indexPositions = indexWordNums = SINGLE_ZERO_BUFFER;
}
else
{
const int pageSize = 128;
int initialPageCount = (valueCount + pageSize - 1) / pageSize;
MonotonicAppendingLongBuffer positions = new MonotonicAppendingLongBuffer(initialPageCount, pageSize, PackedInts.COMPACT);
MonotonicAppendingLongBuffer wordNums = new MonotonicAppendingLongBuffer(initialPageCount, pageSize, PackedInts.COMPACT);
positions.Add(0L);
wordNums.Add(0L);
Iterator it = new Iterator(data, Cardinality, int.MaxValue, SINGLE_ZERO_BUFFER, SINGLE_ZERO_BUFFER);
Debug.Assert(it.@in.Position == 0);
Debug.Assert(it.WordNum == -1);
for (int i = 1; i < valueCount; ++i)
{
// skip indexInterval sequences
for (int j = 0; j < IndexInterval_Renamed; ++j)
{
bool readSequence = it.ReadSequence();
Debug.Assert(readSequence);
it.SkipDirtyBytes();
}
int position = it.@in.Position;
int wordNum = it.WordNum;
positions.Add(position);
wordNums.Add(wordNum + 1);
}
positions.Freeze();
wordNums.Freeze();
indexPositions = positions;
indexWordNums = wordNums;
}
return new WAH8DocIdSet(data, Cardinality, IndexInterval_Renamed, indexPositions, indexWordNums);
}
}
/// <summary>
/// A builder for <seealso cref="WAH8DocIdSet"/>s. </summary>
public sealed class Builder : WordBuilder
{
internal int LastDocID;
internal int WordNum, Word;
/// <summary>
/// Sole constructor </summary>
public Builder()
: base()
{
LastDocID = -1;
WordNum = -1;
Word = 0;
}
/// <summary>
/// Add a document to this builder. Documents must be added in order. </summary>
public Builder Add(int docID)
{
if (docID <= LastDocID)
{
throw new System.ArgumentException("Doc ids must be added in-order, got " + docID + " which is <= lastDocID=" + LastDocID);
}
int wordNum = WordNum(docID);
if (this.WordNum == -1)
{
this.WordNum = wordNum;
Word = 1 << (docID & 0x07);
}
else if (wordNum == this.WordNum)
{
Word |= 1 << (docID & 0x07);
}
else
{
AddWord(this.WordNum, (byte)Word);
this.WordNum = wordNum;
Word = 1 << (docID & 0x07);
}
LastDocID = docID;
return this;
}
/// <summary>
/// Add the content of the provided <seealso cref="DocIdSetIterator"/>. </summary>
public Builder Add(DocIdSetIterator disi)
{
for (int doc = disi.NextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = disi.NextDoc())
{
Add(doc);
}
return this;
}
public override object SetIndexInterval(int indexInterval)
{
return (Builder)base.SetIndexInterval(indexInterval);
}
public override WAH8DocIdSet Build()
{
if (this.WordNum != -1)
{
AddWord(WordNum, (byte)Word);
}
return base.Build();
}
}
// where the doc IDs are stored
private readonly byte[] Data;
private readonly int Cardinality_Renamed;
private readonly int IndexInterval;
// index for advance(int)
private readonly MonotonicAppendingLongBuffer Positions, WordNums; // wordNums[i] starts at the sequence at positions[i]
internal WAH8DocIdSet(byte[] data, int cardinality, int indexInterval, MonotonicAppendingLongBuffer positions, MonotonicAppendingLongBuffer wordNums)
{
this.Data = data;
this.Cardinality_Renamed = cardinality;
this.IndexInterval = indexInterval;
this.Positions = positions;
this.WordNums = wordNums;
}
public override bool Cacheable
{
get
{
return true;
}
}
public override DocIdSetIterator GetIterator()
{
return new Iterator(Data, Cardinality_Renamed, IndexInterval, Positions, WordNums);
}
internal static int ReadCleanLength(ByteArrayDataInput @in, int token)
{
int len = ((int)((uint)token >> 4)) & 0x07;
int startPosition = @in.Position;
if ((len & 0x04) != 0)
{
len = (len & 0x03) | (@in.ReadVInt() << 2);
}
if (startPosition != 1)
{
len += 2;
}
return len;
}
internal static int ReadDirtyLength(ByteArrayDataInput @in, int token)
{
int len = token & 0x0F;
if ((len & 0x08) != 0)
{
len = (len & 0x07) | (@in.ReadVInt() << 3);
}
return len;
}
public class Iterator : DocIdSetIterator
{
/* Using the index can be costly for close targets. */
internal static int IndexThreshold(int cardinality, int indexInterval)
{
// Short sequences encode for 3 words (2 clean words and 1 dirty byte),
// don't advance if we are going to read less than 3 x indexInterval
// sequences
long indexThreshold = 3L * 3 * indexInterval;
return (int)Math.Min(int.MaxValue, indexThreshold);
}
internal readonly ByteArrayDataInput @in;
internal readonly int Cardinality;
internal readonly int IndexInterval;
internal readonly MonotonicAppendingLongBuffer Positions, WordNums;
internal readonly int IndexThreshold_Renamed;
internal int AllOnesLength;
internal int DirtyLength;
internal int WordNum; // byte offset
internal byte Word; // current word
internal int BitList; // list of bits set in the current word
internal int SequenceNum; // in which sequence are we?
internal int DocID_Renamed;
internal Iterator(byte[] data, int cardinality, int indexInterval, MonotonicAppendingLongBuffer positions, MonotonicAppendingLongBuffer wordNums)
{
this.@in = new ByteArrayDataInput(data);
this.Cardinality = cardinality;
this.IndexInterval = indexInterval;
this.Positions = positions;
this.WordNums = wordNums;
WordNum = -1;
Word = 0;
BitList = 0;
SequenceNum = -1;
DocID_Renamed = -1;
IndexThreshold_Renamed = IndexThreshold(cardinality, indexInterval);
}
internal virtual bool ReadSequence()
{
if (@in.Eof())
{
WordNum = int.MaxValue;
return false;
}
int token = @in.ReadByte() & 0xFF;
if ((token & (1 << 7)) == 0)
{
int cleanLength = ReadCleanLength(@in, token);
WordNum += cleanLength;
}
else
{
AllOnesLength = ReadCleanLength(@in, token);
}
DirtyLength = ReadDirtyLength(@in, token);
Debug.Assert(@in.Length() - @in.Position >= DirtyLength, @in.Position + " " + @in.Length() + " " + DirtyLength);
++SequenceNum;
return true;
}
internal virtual void SkipDirtyBytes(int count)
{
Debug.Assert(count >= 0);
Debug.Assert(count <= AllOnesLength + DirtyLength);
WordNum += count;
if (count <= AllOnesLength)
{
AllOnesLength -= count;
}
else
{
count -= AllOnesLength;
AllOnesLength = 0;
@in.SkipBytes(count);
DirtyLength -= count;
}
}
internal virtual void SkipDirtyBytes()
{
WordNum += AllOnesLength + DirtyLength;
@in.SkipBytes(DirtyLength);
AllOnesLength = 0;
DirtyLength = 0;
}
internal virtual void NextWord()
{
if (AllOnesLength > 0)
{
Word = 0xFF;
++WordNum;
--AllOnesLength;
return;
}
if (DirtyLength > 0)
{
Word = @in.ReadByte();
++WordNum;
--DirtyLength;
if (Word != 0)
{
return;
}
if (DirtyLength > 0)
{
Word = @in.ReadByte();
++WordNum;
--DirtyLength;
Debug.Assert(Word != 0); // never more than one consecutive 0
return;
}
}
if (ReadSequence())
{
NextWord();
}
}
internal virtual int ForwardBinarySearch(int targetWordNum)
{
// advance forward and double the window at each step
int indexSize = (int)WordNums.Size();
int lo = SequenceNum / IndexInterval, hi = lo + 1;
Debug.Assert(SequenceNum == -1 || WordNums.Get(lo) <= WordNum);
Debug.Assert(lo + 1 == WordNums.Size() || WordNums.Get(lo + 1) > WordNum);
while (true)
{
if (hi >= indexSize)
{
hi = indexSize - 1;
break;
}
else if (WordNums.Get(hi) >= targetWordNum)
{
break;
}
int newLo = hi;
hi += (hi - lo) << 1;
lo = newLo;
}
// we found a window containing our target, let's binary search now
while (lo <= hi)
{
int mid = (int)((uint)(lo + hi) >> 1);
int midWordNum = (int)WordNums.Get(mid);
if (midWordNum <= targetWordNum)
{
lo = mid + 1;
}
else
{
hi = mid - 1;
}
}
Debug.Assert(WordNums.Get(hi) <= targetWordNum);
Debug.Assert(hi + 1 == WordNums.Size() || WordNums.Get(hi + 1) > targetWordNum);
return hi;
}
internal virtual void AdvanceWord(int targetWordNum)
{
Debug.Assert(targetWordNum > WordNum);
int delta = targetWordNum - WordNum;
if (delta <= AllOnesLength + DirtyLength + 1)
{
SkipDirtyBytes(delta - 1);
}
else
{
SkipDirtyBytes();
Debug.Assert(DirtyLength == 0);
if (delta > IndexThreshold_Renamed)
{
// use the index
int i = ForwardBinarySearch(targetWordNum);
int position = (int)Positions.Get(i);
if (position > @in.Position) // if the binary search returned a backward offset, don't move
{
WordNum = (int)WordNums.Get(i) - 1;
@in.Position = position;
SequenceNum = i * IndexInterval - 1;
}
}
while (true)
{
if (!ReadSequence())
{
return;
}
delta = targetWordNum - WordNum;
if (delta <= AllOnesLength + DirtyLength + 1)
{
if (delta > 1)
{
SkipDirtyBytes(delta - 1);
}
break;
}
SkipDirtyBytes();
}
}
NextWord();
}
public override int DocID()
{
return DocID_Renamed;
}
public override int NextDoc()
{
if (BitList != 0) // there are remaining bits in the current word
{
DocID_Renamed = (WordNum << 3) | ((BitList & 0x0F) - 1);
BitList = (int)((uint)BitList >> 4);
return DocID_Renamed;
}
NextWord();
if (WordNum == int.MaxValue)
{
return DocID_Renamed = NO_MORE_DOCS;
}
BitList = BitUtil.BitList(Word);
Debug.Assert(BitList != 0);
DocID_Renamed = (WordNum << 3) | ((BitList & 0x0F) - 1);
BitList = (int)((uint)BitList >> 4);
return DocID_Renamed;
}
public override int Advance(int target)
{
Debug.Assert(target > DocID_Renamed);
int targetWordNum = WordNum(target);
if (targetWordNum > this.WordNum)
{
AdvanceWord(targetWordNum);
BitList = BitUtil.BitList(Word);
}
return SlowAdvance(target);
}
public override long Cost()
{
return Cardinality;
}
}
/// <summary>
/// Return the number of documents in this <seealso cref="DocIdSet"/> in constant time. </summary>
public int Cardinality()
{
return Cardinality_Renamed;
}
/// <summary>
/// Return the memory usage of this class in bytes. </summary>
public long RamBytesUsed()
{
return RamUsageEstimator.AlignObjectSize(3 * RamUsageEstimator.NUM_BYTES_OBJECT_REF + 2 * RamUsageEstimator.NUM_BYTES_INT) + RamUsageEstimator.SizeOf(Data) + Positions.RamBytesUsed() + WordNums.RamBytesUsed();
}
}
}
| |
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
// [RequireComponent(typeof (AudioSource))]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private bool m_IsWalking;
[SerializeField] private float m_WalkSpeed;
[SerializeField] private float m_RunSpeed;
[SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
[SerializeField] private float m_JumpSpeed;
[SerializeField] private float m_StickToGroundForce;
[SerializeField] private float m_GravityMultiplier;
[SerializeField] private MouseLook m_MouseLook;
[SerializeField] private bool m_UseFovKick;
[SerializeField] private FOVKick m_FovKick = new FOVKick();
[SerializeField] private bool m_UseHeadBob;
[SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
[SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
[SerializeField] private float m_StepInterval;
// [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from.
//[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground.
//[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
//private AudioSource m_AudioSource;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
// m_AudioSource = GetComponent<AudioSource>();
m_MouseLook.Init(transform , m_Camera.transform);
}
// Update is called once per frame
private void Update()
{
RotateView();
// the jump state needs to read here to make sure it is not missed
if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
{
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
{
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound()
{
// m_AudioSource.clip = m_LandSound;
// m_AudioSource.Play();
m_NextStep = m_StepCycle + .5f;
}
private void FixedUpdate()
{
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
m_CharacterController.height/2f);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
m_MoveDir.x = desiredMove.x*speed;
m_MoveDir.z = desiredMove.z*speed;
if (m_CharacterController.isGrounded)
{
m_MoveDir.y = -m_StickToGroundForce;
if (m_Jump)
{
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound();
m_Jump = false;
m_Jumping = true;
}
}
else
{
m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
}
private void PlayJumpSound()
{
// m_AudioSource.clip = m_JumpSound;
// m_AudioSource.Play();
}
private void ProgressStepCycle(float speed)
{
if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
// PlayFootStepAudio();
}
/* private void PlayFootStepAudio()
{
if (!m_CharacterController.isGrounded)
{
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = m_AudioSource.clip;
}*/
private void UpdateCameraPosition(float speed)
{
Vector3 newCameraPosition;
if (!m_UseHeadBob)
{
return;
}
if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
{
m_Camera.transform.localPosition =
m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
(speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}
else
{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed)
{
// Read input
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
float vertical = CrossPlatformInputManager.GetAxis("Vertical");
bool waswalking = m_IsWalking;
#if !MOBILE_INPUT
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (m_Input.sqrMagnitude > 1)
{
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
{
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView()
{
m_MouseLook.LookRotation (transform, m_Camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if (m_CollisionFlags == CollisionFlags.Below)
{
return;
}
if (body == null || body.isKinematic)
{
return;
}
body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
}
}
}
| |
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Topshelf.Hosts
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using Logging;
using Runtime;
public class InstallHost :
Host
{
static readonly LogWriter _log = HostLogger.Get<InstallHost>();
readonly HostEnvironment _environment;
readonly InstallHostSettings _installSettings;
readonly IEnumerable<Action<InstallHostSettings>> _postActions;
readonly IEnumerable<Action<InstallHostSettings>> _preActions;
readonly IEnumerable<Action<InstallHostSettings>> _postRollbackActions;
readonly IEnumerable<Action<InstallHostSettings>> _preRollbackActions;
readonly HostSettings _settings;
readonly bool _sudo;
public InstallHost(HostEnvironment environment, HostSettings settings, HostStartMode startMode,
IEnumerable<string> dependencies,
Credentials credentials, IEnumerable<Action<InstallHostSettings>> preActions,
IEnumerable<Action<InstallHostSettings>> postActions,
IEnumerable<Action<InstallHostSettings>> preRollbackActions,
IEnumerable<Action<InstallHostSettings>> postRollbackActions,
bool sudo)
{
_environment = environment;
_settings = settings;
_installSettings = new InstallServiceSettingsImpl(settings, credentials, startMode, dependencies.ToArray());
_preActions = preActions;
_postActions = postActions;
_preRollbackActions = preRollbackActions;
_postRollbackActions = postRollbackActions;
_sudo = sudo;
}
public InstallHostSettings InstallSettings
{
get { return _installSettings; }
}
public HostSettings Settings
{
get { return _settings; }
}
public TopshelfExitCode Run()
{
if (_environment.IsServiceInstalled(_settings.ServiceName))
{
_log.ErrorFormat("The {0} service is already installed.", _settings.ServiceName);
return TopshelfExitCode.ServiceAlreadyInstalled;
}
if (!_environment.IsAdministrator)
{
if (_sudo)
{
if (_environment.RunAsAdministrator())
return TopshelfExitCode.Ok;
}
_log.ErrorFormat("The {0} service can only be installed as an administrator", _settings.ServiceName);
return TopshelfExitCode.SudoRequired;
}
_log.DebugFormat("Attempting to install '{0}'", _settings.ServiceName);
_environment.InstallService(_installSettings, ExecutePreActions, ExecutePostActions, ExecutePreRollbackActions, ExecutePostRollbackActions);
return TopshelfExitCode.Ok;
}
void ExecutePreActions(InstallHostSettings settings)
{
foreach (Action<InstallHostSettings> action in _preActions)
{
action(_installSettings);
}
}
void ExecutePostActions()
{
foreach (Action<InstallHostSettings> action in _postActions)
{
action(_installSettings);
}
}
void ExecutePreRollbackActions()
{
foreach (Action<InstallHostSettings> action in _preRollbackActions)
{
action(_installSettings);
}
}
void ExecutePostRollbackActions()
{
foreach (Action<InstallHostSettings> action in _postRollbackActions)
{
action(_installSettings);
}
}
class InstallServiceSettingsImpl :
InstallHostSettings
{
private Credentials _credentials;
readonly string[] _dependencies;
readonly HostSettings _settings;
readonly HostStartMode _startMode;
public InstallServiceSettingsImpl(HostSettings settings, Credentials credentials, HostStartMode startMode,
string[] dependencies)
{
_credentials = credentials;
_settings = settings;
_startMode = startMode;
_dependencies = dependencies;
}
public string Name
{
get { return _settings.Name; }
}
public string DisplayName
{
get { return _settings.DisplayName; }
}
public string Description
{
get { return _settings.Description; }
}
public string InstanceName
{
get { return _settings.InstanceName; }
}
public string ServiceName
{
get { return _settings.ServiceName; }
}
public bool CanPauseAndContinue
{
get { return _settings.CanPauseAndContinue; }
}
public bool CanShutdown
{
get { return _settings.CanShutdown; }
}
public bool CanSessionChanged
{
get { return _settings.CanSessionChanged; }
}
/// <summary>
/// True if the service handles power change events
/// </summary>
public bool CanHandlePowerEvent
{
get { return _settings.CanHandlePowerEvent; }
}
public Credentials Credentials
{
get { return _credentials; }
set { _credentials = value; }
}
public string[] Dependencies
{
get { return _dependencies; }
}
public HostStartMode StartMode
{
get { return _startMode; }
}
public TimeSpan StartTimeOut
{
get { return _settings.StartTimeOut; }
}
public TimeSpan StopTimeOut
{
get { return _settings.StopTimeOut; }
}
public Action<Exception> ExceptionCallback
{
get { return _settings.ExceptionCallback; }
}
public UnhandledExceptionPolicyCode UnhandledExceptionPolicy
{
get { return _settings.UnhandledExceptionPolicy; }
}
public bool CanHandleCtrlBreak
{
get { return _settings.CanHandleCtrlBreak; }
}
}
}
}
| |
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Markup;
using Microsoft.WindowsAPICodePack.Controls;
using Microsoft.WindowsAPICodePack.Dialogs.Controls;
using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Shell.Resources;
using MS.WindowsAPICodePack.Internal;
using System.Collections.Generic;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Defines the abstract base class for the common file dialogs.
/// </summary>
[ContentProperty("Controls")]
public abstract class CommonFileDialog : IDialogControlHost, IDisposable
{
/// <summary>
/// The collection of names selected by the user.
/// </summary>
protected IEnumerable<string> FileNameCollection
{
get
{
foreach (string name in filenames)
{
yield return name;
}
}
}
private Collection<string> filenames;
internal readonly Collection<IShellItem> items;
internal DialogShowState showState = DialogShowState.PreShow;
private IFileDialog nativeDialog;
private IFileDialogCustomize customize;
private NativeDialogEventSink nativeEventSink;
private bool? canceled;
private bool resetSelections;
private IntPtr parentWindow = IntPtr.Zero;
private bool filterSet; // filters can only be set once
#region Constructors
/// <summary>
/// Creates a new instance of this class.
/// </summary>
protected CommonFileDialog()
{
if (!CoreHelpers.RunningOnVista)
{
throw new PlatformNotSupportedException(LocalizedMessages.CommonFileDialogRequiresVista);
}
filenames = new Collection<string>();
filters = new CommonFileDialogFilterCollection();
items = new Collection<IShellItem>();
controls = new CommonFileDialogControlCollection<CommonFileDialogControl>(this);
}
/// <summary>
/// Creates a new instance of this class with the specified title.
/// </summary>
/// <param name="title">The title to display in the dialog.</param>
protected CommonFileDialog(string title)
: this()
{
this.title = title;
}
#endregion
// Template method to allow derived dialog to create actual
// specific COM coclass (e.g. FileOpenDialog or FileSaveDialog).
internal abstract void InitializeNativeFileDialog();
internal abstract IFileDialog GetNativeFileDialog();
internal abstract void PopulateWithFileNames(Collection<string> names);
internal abstract void PopulateWithIShellItems(Collection<IShellItem> shellItems);
internal abstract void CleanUpNativeFileDialog();
internal abstract ShellNativeMethods.FileOpenOptions GetDerivedOptionFlags(ShellNativeMethods.FileOpenOptions flags);
#region Public API
// Events.
/// <summary>
/// Raised just before the dialog is about to return with a result. Occurs when the user clicks on the Open
/// or Save button on a file dialog box.
/// </summary>
public event CancelEventHandler FileOk;
/// <summary>
/// Raised just before the user navigates to a new folder.
/// </summary>
public event EventHandler<CommonFileDialogFolderChangeEventArgs> FolderChanging;
/// <summary>
/// Raised when the user navigates to a new folder.
/// </summary>
public event EventHandler FolderChanged;
/// <summary>
/// Raised when the user changes the selection in the dialog's view.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Raised when the dialog is opened to notify the application of the initial chosen filetype.
/// </summary>
public event EventHandler FileTypeChanged;
/// <summary>
/// Raised when the dialog is opening.
/// </summary>
public event EventHandler DialogOpening;
private CommonFileDialogControlCollection<CommonFileDialogControl> controls;
/// <summary>
/// Gets the collection of controls for the dialog.
/// </summary>
public CommonFileDialogControlCollection<CommonFileDialogControl> Controls
{
get { return controls; }
}
private CommonFileDialogFilterCollection filters;
/// <summary>
/// Gets the filters used by the dialog.
/// </summary>
public CommonFileDialogFilterCollection Filters
{
get { return filters; }
}
private string title;
/// <summary>
/// Gets or sets the dialog title.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
public string Title
{
get { return title; }
set
{
title = value;
if (NativeDialogShowing) { nativeDialog.SetTitle(value); }
}
}
// This is the first of many properties that are backed by the FOS_*
// bitflag options set with IFileDialog.SetOptions().
// SetOptions() fails
// if called while dialog is showing (e.g. from a callback).
private bool ensureFileExists;
/// <summary>
/// Gets or sets a value that determines whether the file must exist beforehand.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value. <b>true</b> if the file must exist.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
public bool EnsureFileExists
{
get { return ensureFileExists; }
set
{
ThrowIfDialogShowing(LocalizedMessages.EnsureFileExistsCannotBeChanged);
ensureFileExists = value;
}
}
private bool ensurePathExists;
/// <summary>
/// Gets or sets a value that specifies whether the returned file must be in an existing folder.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value. <b>true</b> if the file must exist.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
public bool EnsurePathExists
{
get { return ensurePathExists; }
set
{
ThrowIfDialogShowing(LocalizedMessages.EnsurePathExistsCannotBeChanged);
ensurePathExists = value;
}
}
private bool ensureValidNames;
/// <summary>Gets or sets a value that determines whether to validate file names.
/// </summary>
///<value>A <see cref="System.Boolean"/> value. <b>true </b>to check for situations that would prevent an application from opening the selected file, such as sharing violations or access denied errors.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
///
public bool EnsureValidNames
{
get { return ensureValidNames; }
set
{
ThrowIfDialogShowing(LocalizedMessages.EnsureValidNamesCannotBeChanged);
ensureValidNames = value;
}
}
private bool ensureReadOnly;
/// <summary>
/// Gets or sets a value that determines whether read-only items are returned.
/// Default value for CommonOpenFileDialog is true (allow read-only files) and
/// CommonSaveFileDialog is false (don't allow read-only files).
/// </summary>
/// <value>A <see cref="System.Boolean"/> value. <b>true</b> includes read-only items.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
public bool EnsureReadOnly
{
get { return ensureReadOnly; }
set
{
ThrowIfDialogShowing(LocalizedMessages.EnsureReadonlyCannotBeChanged);
ensureReadOnly = value;
}
}
private bool restoreDirectory;
/// <summary>
/// Gets or sets a value that determines the restore directory.
/// </summary>
/// <remarks></remarks>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
public bool RestoreDirectory
{
get { return restoreDirectory; }
set
{
ThrowIfDialogShowing(LocalizedMessages.RestoreDirectoryCannotBeChanged);
restoreDirectory = value;
}
}
private bool showPlacesList = true;
/// <summary>
/// Gets or sets a value that controls whether
/// to show or hide the list of pinned places that
/// the user can choose.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value. <b>true</b> if the list is visible; otherwise <b>false</b>.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
public bool ShowPlacesList
{
get { return showPlacesList; }
set
{
ThrowIfDialogShowing(LocalizedMessages.ShowPlacesListCannotBeChanged);
showPlacesList = value;
}
}
private bool addToMruList = true;
/// <summary>
/// Gets or sets a value that controls whether to show or hide the list of places where the user has recently opened or saved items.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
public bool AddToMostRecentlyUsedList
{
get { return addToMruList; }
set
{
ThrowIfDialogShowing(LocalizedMessages.AddToMostRecentlyUsedListCannotBeChanged);
addToMruList = value;
}
}
private bool showHiddenItems;
///<summary>
/// Gets or sets a value that controls whether to show hidden items.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value.<b>true</b> to show the items; otherwise <b>false</b>.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
public bool ShowHiddenItems
{
get { return showHiddenItems; }
set
{
ThrowIfDialogShowing(LocalizedMessages.ShowHiddenItemsCannotBeChanged);
showHiddenItems = value;
}
}
private bool allowPropertyEditing;
/// <summary>
/// Gets or sets a value that controls whether
/// properties can be edited.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value. </value>
public bool AllowPropertyEditing
{
get { return allowPropertyEditing; }
set { allowPropertyEditing = value; }
}
private bool navigateToShortcut = true;
///<summary>
/// Gets or sets a value that controls whether shortcuts should be treated as their target items, allowing an application to open a .lnk file.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value. <b>true</b> indicates that shortcuts should be treated as their targets. </value>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
public bool NavigateToShortcut
{
get { return navigateToShortcut; }
set
{
ThrowIfDialogShowing(LocalizedMessages.NavigateToShortcutCannotBeChanged);
navigateToShortcut = value;
}
}
/// <summary>
/// Gets or sets the default file extension to be added to file names. If the value is null
/// or string.Empty, the extension is not added to the file names.
/// </summary>
public string DefaultExtension { get; set; }
/// <summary>
/// Gets the index for the currently selected file type.
/// </summary>
public int SelectedFileTypeIndex
{
get
{
uint fileType;
if (nativeDialog != null)
{
nativeDialog.GetFileTypeIndex(out fileType);
return (int)fileType;
}
return -1;
}
}
/// <summary>
/// Tries to set the File(s) Type Combo to match the value in
/// 'DefaultExtension'. Only doing this if 'this' is a Save dialog
/// as it makes no sense to do this if only Opening a file.
/// </summary>
///
/// <param name="dialog">The native/IFileDialog instance.</param>
///
private void SyncFileTypeComboToDefaultExtension(IFileDialog dialog)
{
// make sure it's a Save dialog and that there is a default
// extension to sync to.
if (!(this is CommonSaveFileDialog) || DefaultExtension == null ||
filters.Count <= 0)
{
return;
}
CommonFileDialogFilter filter = null;
for (uint filtersCounter = 0; filtersCounter < filters.Count; filtersCounter++)
{
filter = (CommonFileDialogFilter)filters[(int)filtersCounter];
if (filter.Extensions.Contains(DefaultExtension))
{
// set the docType combo to match this
// extension. property is a 1-based index.
dialog.SetFileTypeIndex(filtersCounter + 1);
// we're done, exit for
break;
}
}
}
/// <summary>
/// Gets the selected filename.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be used when multiple files are selected.</exception>
public string FileName
{
get
{
CheckFileNamesAvailable();
if (filenames.Count > 1)
{
throw new InvalidOperationException(LocalizedMessages.CommonFileDialogMultipleFiles);
}
string returnFilename = filenames[0];
// "If extension is a null reference (Nothing in Visual
// Basic), the returned string contains the specified
// path with its extension removed." Since we do not want
// to remove any existing extension, make sure the
// DefaultExtension property is NOT null.
// if we should, and there is one to set...
if (!string.IsNullOrEmpty(DefaultExtension))
{
returnFilename = System.IO.Path.ChangeExtension(returnFilename, DefaultExtension);
}
return returnFilename;
}
}
/// <summary>
/// Gets the selected item as a ShellObject.
/// </summary>
/// <value>A <see cref="Microsoft.WindowsAPICodePack.Shell.ShellObject"></see> object.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be used when multiple files
/// are selected.</exception>
public ShellObject FileAsShellObject
{
get
{
CheckFileItemsAvailable();
if (items.Count > 1)
{
throw new InvalidOperationException(LocalizedMessages.CommonFileDialogMultipleItems);
}
if (items.Count == 0) { return null; }
return ShellObjectFactory.Create(items[0]);
}
}
/// <summary>
/// Adds a location, such as a folder, library, search connector, or known folder, to the list of
/// places available for a user to open or save items. This method actually adds an item
/// to the <b>Favorite Links</b> or <b>Places</b> section of the Open/Save dialog.
/// </summary>
/// <param name="place">The item to add to the places list.</param>
/// <param name="location">One of the enumeration values that indicates placement of the item in the list.</param>
public void AddPlace(ShellContainer place, FileDialogAddPlaceLocation location)
{
if (place == null)
{
throw new ArgumentNullException("place");
}
// Get our native dialog
if (nativeDialog == null)
{
InitializeNativeFileDialog();
nativeDialog = GetNativeFileDialog();
}
// Add the shellitem to the places list
if (nativeDialog != null)
{
nativeDialog.AddPlace(place.NativeShellItem, (ShellNativeMethods.FileDialogAddPlacement)location);
}
}
/// <summary>
/// Adds a location (folder, library, search connector, known folder) to the list of
/// places available for the user to open or save items. This method actually adds an item
/// to the <b>Favorite Links</b> or <b>Places</b> section of the Open/Save dialog. Overload method
/// takes in a string for the path.
/// </summary>
/// <param name="path">The item to add to the places list.</param>
/// <param name="location">One of the enumeration values that indicates placement of the item in the list.</param>
public void AddPlace(string path, FileDialogAddPlaceLocation location)
{
if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); }
// Get our native dialog
if (nativeDialog == null)
{
InitializeNativeFileDialog();
nativeDialog = GetNativeFileDialog();
}
// Create a native shellitem from our path
IShellItem2 nativeShellItem;
Guid guid = new Guid(ShellIIDGuid.IShellItem2);
int retCode = ShellNativeMethods.SHCreateItemFromParsingName(path, IntPtr.Zero, ref guid, out nativeShellItem);
if (!CoreErrorHelper.Succeeded(retCode))
{
throw new CommonControlException(LocalizedMessages.CommonFileDialogCannotCreateShellItem, Marshal.GetExceptionForHR(retCode));
}
// Add the shellitem to the places list
if (nativeDialog != null)
{
nativeDialog.AddPlace(nativeShellItem, (ShellNativeMethods.FileDialogAddPlacement)location);
}
}
// Null = use default directory.
private string initialDirectory;
/// <summary>
/// Gets or sets the initial directory displayed when the dialog is shown.
/// A null or empty string indicates that the dialog is using the default directory.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
public string InitialDirectory
{
get { return initialDirectory; }
set { initialDirectory = value; }
}
private ShellContainer initialDirectoryShellContainer;
/// <summary>
/// Gets or sets a location that is always selected when the dialog is opened,
/// regardless of previous user action. A null value implies that the dialog is using
/// the default location.
/// </summary>
public ShellContainer InitialDirectoryShellContainer
{
get { return initialDirectoryShellContainer; }
set { initialDirectoryShellContainer = value; }
}
private string defaultDirectory;
/// <summary>
/// Sets the folder and path used as a default if there is not a recently used folder value available.
/// </summary>
public string DefaultDirectory
{
get { return defaultDirectory; }
set { defaultDirectory = value; }
}
private ShellContainer defaultDirectoryShellContainer;
/// <summary>
/// Sets the location (<see cref="Microsoft.WindowsAPICodePack.Shell.ShellContainer">ShellContainer</see>
/// used as a default if there is not a recently used folder value available.
/// </summary>
public ShellContainer DefaultDirectoryShellContainer
{
get { return defaultDirectoryShellContainer; }
set { defaultDirectoryShellContainer = value; }
}
// Null = use default identifier.
private Guid cookieIdentifier;
/// <summary>
/// Gets or sets a value that enables a calling application
/// to associate a GUID with a dialog's persisted state.
/// </summary>
public Guid CookieIdentifier
{
get { return cookieIdentifier; }
set { cookieIdentifier = value; }
}
/// <summary>
/// Displays the dialog.
/// </summary>
/// <param name="ownerWindowHandle">Window handle of any top-level window that will own the modal dialog box.</param>
/// <returns>A <see cref="CommonFileDialogResult"/> object.</returns>
public CommonFileDialogResult ShowDialog(IntPtr ownerWindowHandle)
{
if (ownerWindowHandle == IntPtr.Zero)
{
throw new ArgumentException(LocalizedMessages.CommonFileDialogInvalidHandle, "ownerWindowHandle");
}
// Set the parent / owner window
parentWindow = ownerWindowHandle;
// Show the modal dialog
return ShowDialog();
}
/// <summary>
/// Displays the dialog.
/// </summary>
/// <param name="window">Top-level WPF window that will own the modal dialog box.</param>
/// <returns>A <see cref="CommonFileDialogResult"/> object.</returns>
public CommonFileDialogResult ShowDialog(Window window)
{
if (window == null)
{
throw new ArgumentNullException("window");
}
// Set the parent / owner window
parentWindow = (new WindowInteropHelper(window)).Handle;
// Show the modal dialog
return ShowDialog();
}
/// <summary>
/// Displays the dialog.
/// </summary>
/// <returns>A <see cref="CommonFileDialogResult"/> object.</returns>
public CommonFileDialogResult ShowDialog()
{
CommonFileDialogResult result;
// Fetch derived native dialog (i.e. Save or Open).
InitializeNativeFileDialog();
nativeDialog = GetNativeFileDialog();
// Apply outer properties to native dialog instance.
ApplyNativeSettings(nativeDialog);
InitializeEventSink(nativeDialog);
// Clear user data if Reset has been called
// since the last show.
if (resetSelections)
{
resetSelections = false;
}
// Show dialog.
showState = DialogShowState.Showing;
int hresult = nativeDialog.Show(parentWindow);
showState = DialogShowState.Closed;
// Create return information.
if (CoreErrorHelper.Matches(hresult, (int)HResult.Win32ErrorCanceled))
{
canceled = true;
result = CommonFileDialogResult.Cancel;
filenames.Clear();
}
else
{
canceled = false;
result = CommonFileDialogResult.Ok;
// Populate filenames if user didn't cancel.
PopulateWithFileNames(filenames);
// Populate the actual IShellItems
PopulateWithIShellItems(items);
}
return result;
}
/// <summary>
/// Removes the current selection.
/// </summary>
public void ResetUserSelections()
{
resetSelections = true;
}
/// <summary>
/// Default file name.
/// </summary>
public string DefaultFileName { get; set; }
#endregion
#region Configuration
private void InitializeEventSink(IFileDialog nativeDlg)
{
// Check if we even need to have a sink.
if (FileOk != null
|| FolderChanging != null
|| FolderChanged != null
|| SelectionChanged != null
|| FileTypeChanged != null
|| DialogOpening != null
|| (controls != null && controls.Count > 0))
{
uint cookie;
nativeEventSink = new NativeDialogEventSink(this);
nativeDlg.Advise(nativeEventSink, out cookie);
nativeEventSink.Cookie = cookie;
}
}
private void ApplyNativeSettings(IFileDialog dialog)
{
Debug.Assert(dialog != null, "No dialog instance to configure");
if (parentWindow == IntPtr.Zero)
{
if (System.Windows.Application.Current != null && System.Windows.Application.Current.MainWindow != null)
{
parentWindow = (new WindowInteropHelper(System.Windows.Application.Current.MainWindow)).Handle;
}
else if (System.Windows.Forms.Application.OpenForms.Count > 0)
{
parentWindow = System.Windows.Forms.Application.OpenForms[0].Handle;
}
}
Guid guid = new Guid(ShellIIDGuid.IShellItem2);
// Apply option bitflags.
dialog.SetOptions(CalculateNativeDialogOptionFlags());
// Other property sets.
if (title != null) { dialog.SetTitle(title); }
if (initialDirectoryShellContainer != null)
{
dialog.SetFolder(((ShellObject)initialDirectoryShellContainer).NativeShellItem);
}
if (defaultDirectoryShellContainer != null)
{
dialog.SetDefaultFolder(((ShellObject)defaultDirectoryShellContainer).NativeShellItem);
}
if (!string.IsNullOrEmpty(initialDirectory))
{
// Create a native shellitem from our path
IShellItem2 initialDirectoryShellItem;
ShellNativeMethods.SHCreateItemFromParsingName(initialDirectory, IntPtr.Zero, ref guid, out initialDirectoryShellItem);
// If we get a real shell item back,
// then use that as the initial folder - otherwise,
// we'll allow the dialog to revert to the default folder.
// (OR should we fail loudly?)
if (initialDirectoryShellItem != null)
dialog.SetFolder(initialDirectoryShellItem);
}
if (!string.IsNullOrEmpty(defaultDirectory))
{
// Create a native shellitem from our path
IShellItem2 defaultDirectoryShellItem;
ShellNativeMethods.SHCreateItemFromParsingName(defaultDirectory, IntPtr.Zero, ref guid, out defaultDirectoryShellItem);
// If we get a real shell item back,
// then use that as the initial folder - otherwise,
// we'll allow the dialog to revert to the default folder.
// (OR should we fail loudly?)
if (defaultDirectoryShellItem != null)
{
dialog.SetDefaultFolder(defaultDirectoryShellItem);
}
}
// Apply file type filters, if available.
if (filters.Count > 0 && !filterSet)
{
dialog.SetFileTypes(
(uint)filters.Count,
filters.GetAllFilterSpecs());
filterSet = true;
SyncFileTypeComboToDefaultExtension(dialog);
}
if (cookieIdentifier != Guid.Empty)
{
dialog.SetClientGuid(ref cookieIdentifier);
}
// Set the default extension
if (!string.IsNullOrEmpty(DefaultExtension))
{
dialog.SetDefaultExtension(DefaultExtension);
}
// Set the default filename
dialog.SetFileName(DefaultFileName);
}
private ShellNativeMethods.FileOpenOptions CalculateNativeDialogOptionFlags()
{
// We start with only a few flags set by default,
// then go from there based on the current state
// of the managed dialog's property values.
ShellNativeMethods.FileOpenOptions flags = ShellNativeMethods.FileOpenOptions.NoTestFileCreate;
// Call to derived (concrete) dialog to
// set dialog-specific flags.
flags = GetDerivedOptionFlags(flags);
// Apply other optional flags.
if (ensureFileExists)
{
flags |= ShellNativeMethods.FileOpenOptions.FileMustExist;
}
if (ensurePathExists)
{
flags |= ShellNativeMethods.FileOpenOptions.PathMustExist;
}
if (!ensureValidNames)
{
flags |= ShellNativeMethods.FileOpenOptions.NoValidate;
}
if (!EnsureReadOnly)
{
flags |= ShellNativeMethods.FileOpenOptions.NoReadOnlyReturn;
}
if (restoreDirectory)
{
flags |= ShellNativeMethods.FileOpenOptions.NoChangeDirectory;
}
if (!showPlacesList)
{
flags |= ShellNativeMethods.FileOpenOptions.HidePinnedPlaces;
}
if (!addToMruList)
{
flags |= ShellNativeMethods.FileOpenOptions.DontAddToRecent;
}
if (showHiddenItems)
{
flags |= ShellNativeMethods.FileOpenOptions.ForceShowHidden;
}
if (!navigateToShortcut)
{
flags |= ShellNativeMethods.FileOpenOptions.NoDereferenceLinks;
}
return flags;
}
#endregion
#region IDialogControlHost Members
private static void GenerateNotImplementedException()
{
throw new NotImplementedException(LocalizedMessages.NotImplementedException);
}
/// <summary>
/// Returns if change to the colleciton is allowed.
/// </summary>
/// <returns>true if collection change is allowed.</returns>
public virtual bool IsCollectionChangeAllowed()
{
return true;
}
/// <summary>
/// Applies changes to the collection.
/// </summary>
public virtual void ApplyCollectionChanged()
{
// Query IFileDialogCustomize interface before adding controls
GetCustomizedFileDialog();
// Populate all the custom controls and add them to the dialog
foreach (CommonFileDialogControl control in controls)
{
if (!control.IsAdded)
{
control.HostingDialog = this;
control.Attach(customize);
control.IsAdded = true;
}
}
}
/// <summary>
/// Determines if changes to a specific property are allowed.
/// </summary>
/// <param name="propertyName">The name of the property.</param>
/// <param name="control">The control propertyName applies to.</param>
/// <returns>true if the property change is allowed.</returns>
public virtual bool IsControlPropertyChangeAllowed(string propertyName, DialogControl control)
{
CommonFileDialog.GenerateNotImplementedException();
return false;
}
/// <summary>
/// Called when a control currently in the collection
/// has a property changed.
/// </summary>
/// <param name="propertyName">The name of the property changed.</param>
/// <param name="control">The control whose property has changed.</param>
public virtual void ApplyControlPropertyChange(string propertyName, DialogControl control)
{
if (control == null)
{
throw new ArgumentNullException("control");
}
CommonFileDialogControl dialogControl = null;
if (propertyName == "Text")
{
CommonFileDialogTextBox textBox = control as CommonFileDialogTextBox;
if (textBox != null)
{
customize.SetEditBoxText(control.Id, textBox.Text);
}
else
{
customize.SetControlLabel(control.Id, textBox.Text);
}
}
else if (propertyName == "Visible" && (dialogControl = control as CommonFileDialogControl) != null)
{
ShellNativeMethods.ControlState state;
customize.GetControlState(control.Id, out state);
if (dialogControl.Visible == true)
{
state |= ShellNativeMethods.ControlState.Visible;
}
else if (dialogControl.Visible == false)
{
state &= ~ShellNativeMethods.ControlState.Visible;
}
customize.SetControlState(control.Id, state);
}
else if (propertyName == "Enabled" && dialogControl != null)
{
ShellNativeMethods.ControlState state;
customize.GetControlState(control.Id, out state);
if (dialogControl.Enabled == true)
{
state |= ShellNativeMethods.ControlState.Enable;
}
else if (dialogControl.Enabled == false)
{
state &= ~ShellNativeMethods.ControlState.Enable;
}
customize.SetControlState(control.Id, state);
}
else if (propertyName == "SelectedIndex")
{
CommonFileDialogRadioButtonList list;
CommonFileDialogComboBox box;
if ((list = control as CommonFileDialogRadioButtonList) != null)
{
customize.SetSelectedControlItem(list.Id, list.SelectedIndex);
}
else if ((box = control as CommonFileDialogComboBox) != null)
{
customize.SetSelectedControlItem(box.Id, box.SelectedIndex);
}
}
else if (propertyName == "IsChecked")
{
CommonFileDialogCheckBox checkBox = control as CommonFileDialogCheckBox;
if (checkBox != null)
{
customize.SetCheckButtonState(checkBox.Id, checkBox.IsChecked);
}
}
}
#endregion
#region Helpers
/// <summary>
/// Ensures that the user has selected one or more files.
/// </summary>
/// <permission cref="System.InvalidOperationException">
/// The dialog has not been dismissed yet or the dialog was cancelled.
/// </permission>
protected void CheckFileNamesAvailable()
{
if (showState != DialogShowState.Closed)
{
throw new InvalidOperationException(LocalizedMessages.CommonFileDialogNotClosed);
}
if (canceled.GetValueOrDefault())
{
throw new InvalidOperationException(LocalizedMessages.CommonFileDialogCanceled);
}
Debug.Assert(filenames.Count != 0,
"FileNames empty - shouldn't happen unless dialog canceled or not yet shown.");
}
/// <summary>
/// Ensures that the user has selected one or more files.
/// </summary>
/// <permission cref="System.InvalidOperationException">
/// The dialog has not been dismissed yet or the dialog was cancelled.
/// </permission>
protected void CheckFileItemsAvailable()
{
if (showState != DialogShowState.Closed)
{
throw new InvalidOperationException(LocalizedMessages.CommonFileDialogNotClosed);
}
if (canceled.GetValueOrDefault())
{
throw new InvalidOperationException(LocalizedMessages.CommonFileDialogCanceled);
}
Debug.Assert(items.Count != 0,
"Items list empty - shouldn't happen unless dialog canceled or not yet shown.");
}
private bool NativeDialogShowing
{
get
{
return (nativeDialog != null)
&& (showState == DialogShowState.Showing || showState == DialogShowState.Closing);
}
}
internal static string GetFileNameFromShellItem(IShellItem item)
{
string filename = null;
IntPtr pszString = IntPtr.Zero;
HResult hr = item.GetDisplayName(ShellNativeMethods.ShellItemDesignNameOptions.DesktopAbsoluteParsing, out pszString);
if (hr == HResult.Ok && pszString != IntPtr.Zero)
{
filename = Marshal.PtrToStringAuto(pszString);
Marshal.FreeCoTaskMem(pszString);
}
return filename;
}
internal static IShellItem GetShellItemAt(IShellItemArray array, int i)
{
IShellItem result;
uint index = (uint)i;
array.GetItemAt(index, out result);
return result;
}
/// <summary>
/// Throws an exception when the dialog is showing preventing
/// a requested change to a property or the visible set of controls.
/// </summary>
/// <param name="message">The message to include in the exception.</param>
/// <permission cref="System.InvalidOperationException"> The dialog is in an
/// invalid state to perform the requested operation.</permission>
protected void ThrowIfDialogShowing(string message)
{
if (NativeDialogShowing)
{
throw new InvalidOperationException(message);
}
}
/// <summary>
/// Get the IFileDialogCustomize interface, preparing to add controls.
/// </summary>
private void GetCustomizedFileDialog()
{
if (customize == null)
{
if (nativeDialog == null)
{
InitializeNativeFileDialog();
nativeDialog = GetNativeFileDialog();
}
customize = (IFileDialogCustomize)nativeDialog;
}
}
#endregion
#region CheckChanged handling members
/// <summary>
/// Raises the <see cref="CommonFileDialog.FileOk"/> event just before the dialog is about to return with a result.
/// </summary>
/// <param name="e">The event data.</param>
protected virtual void OnFileOk(CancelEventArgs e)
{
CancelEventHandler handler = FileOk;
if (handler != null)
{
handler(this, e);
}
}
/// <summary>
/// Raises the <see cref="FolderChanging"/> to stop navigation to a particular location.
/// </summary>
/// <param name="e">Cancelable event arguments.</param>
protected virtual void OnFolderChanging(CommonFileDialogFolderChangeEventArgs e)
{
EventHandler<CommonFileDialogFolderChangeEventArgs> handler = FolderChanging;
if (handler != null)
{
handler(this, e);
}
}
/// <summary>
/// Raises the <see cref="CommonFileDialog.FolderChanged"/> event when the user navigates to a new folder.
/// </summary>
/// <param name="e">The event data.</param>
protected virtual void OnFolderChanged(EventArgs e)
{
EventHandler handler = FolderChanged;
if (handler != null)
{
handler(this, e);
}
}
/// <summary>
/// Raises the <see cref="CommonFileDialog.SelectionChanged"/> event when the user changes the selection in the dialog's view.
/// </summary>
/// <param name="e">The event data.</param>
protected virtual void OnSelectionChanged(EventArgs e)
{
EventHandler handler = SelectionChanged;
if (handler != null)
{
handler(this, e);
}
}
/// <summary>
/// Raises the <see cref="CommonFileDialog.FileTypeChanged"/> event when the dialog is opened to notify the
/// application of the initial chosen filetype.
/// </summary>
/// <param name="e">The event data.</param>
protected virtual void OnFileTypeChanged(EventArgs e)
{
EventHandler handler = FileTypeChanged;
if (handler != null)
{
handler(this, e);
}
}
/// <summary>
/// Raises the <see cref="CommonFileDialog.DialogOpening"/> event when the dialog is opened.
/// </summary>
/// <param name="e">The event data.</param>
protected virtual void OnOpening(EventArgs e)
{
EventHandler handler = DialogOpening;
if (handler != null)
{
handler(this, e);
}
}
#endregion
#region NativeDialogEventSink Nested Class
private class NativeDialogEventSink : IFileDialogEvents, IFileDialogControlEvents
{
private CommonFileDialog parent;
private bool firstFolderChanged = true;
public NativeDialogEventSink(CommonFileDialog commonDialog)
{
this.parent = commonDialog;
}
public uint Cookie { get; set; }
public HResult OnFileOk(IFileDialog pfd)
{
CancelEventArgs args = new CancelEventArgs();
parent.OnFileOk(args);
if (!args.Cancel)
{
// Make sure all custom properties are sync'ed
if (parent.Controls != null)
{
foreach (CommonFileDialogControl control in parent.Controls)
{
CommonFileDialogTextBox textBox;
CommonFileDialogGroupBox groupBox; ;
if ((textBox = control as CommonFileDialogTextBox) != null)
{
textBox.SyncValue();
textBox.Closed = true;
}
// Also check subcontrols
else if ((groupBox = control as CommonFileDialogGroupBox) != null)
{
foreach (CommonFileDialogControl subcontrol in groupBox.Items)
{
CommonFileDialogTextBox textbox = subcontrol as CommonFileDialogTextBox;
if (textbox != null)
{
textbox.SyncValue();
textbox.Closed = true;
}
}
}
}
}
}
return (args.Cancel ? HResult.False : HResult.Ok);
}
public HResult OnFolderChanging(IFileDialog pfd, IShellItem psiFolder)
{
CommonFileDialogFolderChangeEventArgs args = new CommonFileDialogFolderChangeEventArgs(
CommonFileDialog.GetFileNameFromShellItem(psiFolder));
if (!firstFolderChanged) { parent.OnFolderChanging(args); }
return (args.Cancel ? HResult.False : HResult.Ok);
}
public void OnFolderChange(IFileDialog pfd)
{
if (firstFolderChanged)
{
firstFolderChanged = false;
parent.OnOpening(EventArgs.Empty);
}
else
{
parent.OnFolderChanged(EventArgs.Empty);
}
}
public void OnSelectionChange(IFileDialog pfd)
{
parent.OnSelectionChanged(EventArgs.Empty);
}
public void OnShareViolation(
IFileDialog pfd,
IShellItem psi,
out ShellNativeMethods.FileDialogEventShareViolationResponse pResponse)
{
// Do nothing: we will ignore share violations,
// and don't register
// for them, so this method should never be called.
pResponse = ShellNativeMethods.FileDialogEventShareViolationResponse.Accept;
}
public void OnTypeChange(IFileDialog pfd)
{
parent.OnFileTypeChanged(EventArgs.Empty);
}
public void OnOverwrite(IFileDialog pfd, IShellItem psi, out ShellNativeMethods.FileDialogEventOverwriteResponse pResponse)
{
// Don't accept or reject the dialog, keep default settings
pResponse = ShellNativeMethods.FileDialogEventOverwriteResponse.Default;
}
public void OnItemSelected(IFileDialogCustomize pfdc, int dwIDCtl, int dwIDItem)
{
// Find control
DialogControl control = this.parent.controls.GetControlbyId(dwIDCtl);
ICommonFileDialogIndexedControls controlInterface;
CommonFileDialogMenu menu;
// Process ComboBox and/or RadioButtonList
if ((controlInterface = control as ICommonFileDialogIndexedControls) != null)
{
// Update selected item and raise SelectedIndexChanged event
controlInterface.SelectedIndex = dwIDItem;
controlInterface.RaiseSelectedIndexChangedEvent();
}
// Process Menu
else if ((menu = control as CommonFileDialogMenu) != null)
{
// Find the menu item that was clicked and invoke it's click event
foreach (CommonFileDialogMenuItem item in menu.Items)
{
if (item.Id == dwIDItem)
{
item.RaiseClickEvent();
break;
}
}
}
}
public void OnButtonClicked(IFileDialogCustomize pfdc, int dwIDCtl)
{
// Find control
DialogControl control = this.parent.controls.GetControlbyId(dwIDCtl);
CommonFileDialogButton button = control as CommonFileDialogButton;
// Call corresponding event
if (button != null)
{
button.RaiseClickEvent();
}
}
public void OnCheckButtonToggled(IFileDialogCustomize pfdc, int dwIDCtl, bool bChecked)
{
// Find control
DialogControl control = this.parent.controls.GetControlbyId(dwIDCtl);
CommonFileDialogCheckBox box = control as CommonFileDialogCheckBox;
// Update control and call corresponding event
if (box != null)
{
box.IsChecked = bChecked;
box.RaiseCheckedChangedEvent();
}
}
public void OnControlActivating(IFileDialogCustomize pfdc, int dwIDCtl)
{
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Releases the unmanaged resources used by the CommonFileDialog class and optionally
/// releases the managed resources.
/// </summary>
/// <param name="disposing"><b>true</b> to release both managed and unmanaged resources;
/// <b>false</b> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
CleanUpNativeFileDialog();
}
}
/// <summary>
/// Releases the resources used by the current instance of the CommonFileDialog class.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
/// <summary>
/// Indicates whether this feature is supported on the current platform.
/// </summary>
public static bool IsPlatformSupported
{
get
{
// We need Windows Vista onwards ...
return CoreHelpers.RunningOnVista;
}
}
}
}
| |
namespace Nancy.Tests.Unit
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Xunit;
using Xunit.Extensions;
public class DynamicDictionaryFixture
{
private readonly dynamic dictionary;
public DynamicDictionaryFixture()
{
this.dictionary = new DynamicDictionary();
this.dictionary["TestString"] = "Testing";
this.dictionary["TestInt"] = 2;
}
[Fact]
public void Should_create_instance_from_dictionary()
{
// Given
var values = new Dictionary<string, object>
{
{ "foo", 10 },
{ "bar", "some value" },
};
// When
dynamic instance = DynamicDictionary.Create(values);
// Then
((int)GetIntegerValue(instance.foo)).ShouldEqual(10);
((string)GetStringValue(instance.bar)).ShouldEqual("some value");
}
[Fact]
public void Should_strip_dash_from_name_when_using_indexer_to_add_value()
{
// Given
this.dictionary["foo-bar"] = 10;
// When
int result = GetIntegerValue(this.dictionary.foobar);
// Then
result.ShouldEqual(10);
}
[Fact]
public void Should_be_able_to_retrieve_value_for_key_containing_dash_when_using_indexer()
{
// Given
this.dictionary["foo-bar"] = 10;
// When
int result = GetIntegerValue(this.dictionary["foo-bar"]);
// Then
result.ShouldEqual(10);
}
[Fact]
public void Should_be_able_to_retrive_value_stores_with_dash_using_key_without_dash_when_using_indexer()
{
// Given
this.dictionary["foo-bar"] = 10;
// When
int result = GetIntegerValue(this.dictionary["foobar"]);
// Then
result.ShouldEqual(10);
}
[Fact]
public void Should_be_able_to_retrive_value_stores_using_dash_using_key_with_dash_when_using_indexer()
{
// Given
this.dictionary["foobar"] = 10;
// When
int result = GetIntegerValue(this.dictionary["foo-bar"]);
// Then
result.ShouldEqual(10);
}
[Fact]
public void Should_retrieving_non_existing_index_should_return_empty_value()
{
// Given
var value = this.dictionary["nonexisting"];
// When
bool result = value.HasValue;
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_retrieving_non_existing_member_should_return_empty_value()
{
// Given
var value = this.dictionary.nonexisting;
// When
bool result = value.HasValue;
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_implicitly_cast_to_string_when_value_is_retrieved_as_member()
{
// Given
this.dictionary.value = "foo";
// When
string result = GetStringValue(this.dictionary.value);
// Then
result.ShouldEqual("foo");
}
[Fact]
public void Should_implicitly_cast_to_string_when_value_is_retrieved_as_index()
{
// Given
this.dictionary.value = "foo";
// When
string result = GetStringValue(this.dictionary["value"]);
// Then
result.ShouldEqual("foo");
}
[Fact]
public void Should_implicitly_cast_to_integer_when_value_is_retrieved_as_member()
{
// Given
this.dictionary.value = 10;
// When
int result = GetIntegerValue(this.dictionary.value);
// Then
result.ShouldEqual(10);
}
[Fact]
public void Should_implicitly_cast_to_integer_when_value_is_retrieved_as_index()
{
// Given
this.dictionary.value = 10;
// When
int result = GetIntegerValue(this.dictionary["value"]);
// Then
result.ShouldEqual(10);
}
[Fact]
public void Should_implicitly_cast_to_integer_when_value_is_string_and_is_retrieved_as_member()
{
// Given
this.dictionary.value = "10";
// When
int result = GetIntegerValue(this.dictionary.value);
// Then
result.ShouldEqual(10);
}
[Fact]
public void Should_implicitly_cast_to_integer_when_value_is_string_and_is_retrieved_as_index()
{
// Given
this.dictionary.value = "10";
// When
int result = GetIntegerValue(this.dictionary["value"]);
// Then
result.ShouldEqual(10);
}
[Fact]
public void Should_implicitly_cast_to_guid_when_value_is_retrieved_as_member()
{
// Given
var id = Guid.NewGuid();
this.dictionary.value = id;
// When
Guid result = GetGuidValue(this.dictionary.value);
// Then
result.ShouldEqual(id);
}
[Fact]
public void Should_implicitly_cast_to_guid_when_value_is_retrieved_as_index()
{
// Given
var id = Guid.NewGuid();
this.dictionary.value = id;
// When
Guid result = GetGuidValue(this.dictionary["value"]);
// Then
result.ShouldEqual(id);
}
[Fact]
public void Should_implicitly_cast_to_guid_when_value_is_string_and_is_retrieved_as_member()
{
// Given
var id = Guid.NewGuid();
this.dictionary.value = id.ToString("N");
// When
Guid result = GetGuidValue(this.dictionary.value);
// Then
result.ShouldEqual(id);
}
[Fact]
public void Should_implicitly_cast_to_guid_when_value_is_string_and_is_retrieved_as_index()
{
// Given
var id = Guid.NewGuid();
this.dictionary.value = id.ToString("N");
// When
Guid result = GetGuidValue(this.dictionary["value"]);
// Then
result.ShouldEqual(id);
}
[Fact]
public void Should_implicitly_cast_to_datetime_when_value_is_retrieved_as_member()
{
// Given
var date = DateTime.Now;
this.dictionary.value = date;
// When
DateTime result = GetDateTimeValue(this.dictionary.value);
// Then
result.ShouldEqual(date);
}
[Fact]
public void Should_implicitly_cast_to_datetime_when_value_is_retrieved_as_index()
{
// Given
var date = DateTime.Now;
this.dictionary.value = date;
// When
DateTime result = GetDateTimeValue(this.dictionary["value"]);
// Then
result.ShouldEqual(date);
}
[Fact]
public void Should_implicitly_cast_to_datetime_when_value_is_string_and_is_retrieved_as_member()
{
// Given
var date = DateTime.Now;
this.dictionary.value = date.ToString();
// When
DateTime result = GetDateTimeValue(this.dictionary.value);
// Then
result.ShouldEqual(date);
}
[Fact]
public void Should_implicitly_cast_to_datetime_when_value_is_string_and_is_retrieved_as_index()
{
// Given
var date = DateTime.Now;
this.dictionary.value = date.ToString();
// When
DateTime result = GetDateTimeValue(this.dictionary["value"]);
// Then
result.ShouldEqual(date);
}
[Fact]
public void Should_implicitly_cast_to_timespan_when_value_is_retrieved_as_member()
{
// Given
var span = new TimeSpan(1, 2, 3, 4);
this.dictionary.value = span;
// When
TimeSpan result = GetTimeSpanValue(this.dictionary.value);
// Then
result.ShouldEqual(span);
}
[Fact]
public void Should_implicitly_cast_to_timespan_when_value_is_retrieved_as_index()
{
// Given
var span = new TimeSpan(1, 2, 3, 4);
this.dictionary.value = span;
// When
TimeSpan result = GetTimeSpanValue(this.dictionary["value"]);
// Then
result.ShouldEqual(span);
}
[Fact]
public void Should_implicitly_cast_to_timespan_when_value_is_string_and_is_retrieved_as_member()
{
// Given
var span = new TimeSpan(1, 2, 3, 4);
this.dictionary.value = span.ToString();
// When
TimeSpan result = GetTimeSpanValue(this.dictionary.value);
// Then
result.ShouldEqual(span);
}
[Fact]
public void Should_implicitly_cast_to_timespan_when_value_is_string_and_is_retrieved_as_index()
{
// Given
var span = new TimeSpan(1, 2, 3, 4);
this.dictionary.value = span.ToString();
// When
TimeSpan result = GetTimeSpanValue(this.dictionary["value"]);
// Then
result.ShouldEqual(span);
}
[Fact]
public void Should_implicitly_cast_to_long_when_value_is_retrieved_as_member()
{
// Given
this.dictionary.value = 10L;
// When
long result = GetLongValue(this.dictionary.value);
// Then
result.ShouldEqual(10L);
}
[Fact]
public void Should_implicitly_cast_to_long_when_value_is_retrieved_as_index()
{
// Given
this.dictionary.value = 10L;
// When
long result = GetLongValue(this.dictionary["value"]);
// Then
result.ShouldEqual(10L);
}
[Fact]
public void Should_implicitly_cast_to_long_when_value_is_string_and_is_retrieved_as_member()
{
// Given
this.dictionary.value = "10";
// When
long result = GetLongValue(this.dictionary.value);
// Then
result.ShouldEqual(10L);
}
[Fact]
public void Should_implicitly_cast_to_long_when_value_is_string_and_is_retrieved_as_index()
{
// Given
this.dictionary.value = "10";
// When
long result = GetLongValue(this.dictionary["value"]);
// Then
result.ShouldEqual(10L);
}
[Fact]
public void Should_implicitly_cast_to_float_when_value_is_retrieved_as_member()
{
// Given
this.dictionary.value = 10f;
// When
float result = GetFloatValue(this.dictionary.value);
// Then
result.ShouldEqual(10f);
}
[Fact]
public void Should_implicitly_cast_to_float_when_value_is_retrieved_as_index()
{
// Given
this.dictionary.value = 10f;
// When
float result = GetFloatValue(this.dictionary["value"]);
// Then
result.ShouldEqual(10f);
}
[Fact]
public void Should_implicitly_cast_to_float_when_value_is_string_and_is_retrieved_as_member()
{
// Given
this.dictionary.value = "10";
// When
float result = GetFloatValue(this.dictionary.value);
// Then
result.ShouldEqual(10f);
}
[Fact]
public void Should_implicitly_cast_to_float_when_value_is_string_and_is_retrieved_as_index()
{
// Given
this.dictionary.value = "10";
// When
float result = GetFloatValue(this.dictionary["value"]);
// Then
result.ShouldEqual(10f);
}
[Fact]
public void Should_implicitly_cast_to_decimal_when_value_is_retrieved_as_member()
{
// Given
this.dictionary.value = 10m;
// When
decimal result = GetDecimalValue(this.dictionary.value);
// Then
result.ShouldEqual(10m);
}
[Fact]
public void Should_implicitly_cast_to_decimal_when_value_is_retrieved_as_index()
{
// Given
this.dictionary.value = 10m;
// When
decimal result = GetDecimalValue(this.dictionary["value"]);
// Then
result.ShouldEqual(10m);
}
[Fact]
public void Should_implicitly_cast_to_decimal_when_value_is_string_and_is_retrieved_as_member()
{
// Given
this.dictionary.value = "10";
// When
decimal result = GetDecimalValue(this.dictionary.value);
// Then
result.ShouldEqual(10m);
}
[Fact]
public void Should_implicitly_cast_to_decimal_when_value_is_string_and_is_retrieved_as_index()
{
// Given
this.dictionary.value = "10";
// When
decimal result = GetDecimalValue(this.dictionary["value"]);
// Then
result.ShouldEqual(10m);
}
[Fact]
public void Should_implicitly_cast_to_double_when_value_is_retrieved_as_member()
{
// Given
this.dictionary.value = 10d;
// When
double result = GetDoubleValue(this.dictionary.value);
// Then
result.ShouldEqual(10d);
}
[Fact]
public void Should_implicitly_cast_to_double_when_value_is_retrieved_as_index()
{
// Given
this.dictionary.value = 10d;
// When
double result = GetDoubleValue(this.dictionary["value"]);
// Then
result.ShouldEqual(10d);
}
[Fact]
public void Should_implicitly_cast_to_double_when_value_is_string_and_is_retrieved_as_member()
{
// Given
this.dictionary.value = "10";
// When
double result = GetDoubleValue(this.dictionary.value);
// Then
result.ShouldEqual(10d);
}
[Fact]
public void Should_implicitly_cast_to_double_when_value_is_string_and_is_retrieved_as_index()
{
// Given
this.dictionary.value = "10";
// When
double result = GetDoubleValue(this.dictionary["value"]);
// Then
result.ShouldEqual(10d);
}
private static double GetDoubleValue(double value)
{
return value;
}
private static decimal GetDecimalValue(decimal value)
{
return value;
}
private static float GetFloatValue(float value)
{
return value;
}
private static long GetLongValue(long value)
{
return value;
}
private static TimeSpan GetTimeSpanValue(TimeSpan value)
{
return value;
}
private static DateTime GetDateTimeValue(DateTime value)
{
return value;
}
private static Guid GetGuidValue(Guid value)
{
return value;
}
private static int GetIntegerValue(int value)
{
return value;
}
private static string GetStringValue(string value)
{
return value;
}
[Fact]
public void Should_return_actual_string_value_when_tostring_called_on_string_entry()
{
// Given, When
string result = dictionary.TestString.ToString();
// Then
result.ShouldEqual("Testing");
}
[Fact]
public void Should_return_string_representation_of_value_when_tostring_called_on_int_entry()
{
// Given, When
string result = dictionary.TestInt.ToString();
// Then
result.ShouldEqual("2");
}
[Fact]
public void Should_support_dynamic_properties()
{
// Given
dynamic parameters = new DynamicDictionary();
parameters.test = 10;
// When
var value = (int)parameters.test;
// Then
value.ShouldEqual(10);
}
[Fact]
public void Should_support_dynamic_casting_of_properties_to_ints()
{
//Given
dynamic parameters = new DynamicDictionary();
parameters.test = "10";
// When
var value = (int)parameters.test;
// Then
value.ShouldEqual(10);
}
[Fact]
public void Should_support_dynamic_casting_of_properties_to_guids()
{
//Given
dynamic parameters = new DynamicDictionary();
var guid = Guid.NewGuid();
parameters.test = guid.ToString();
// When
var value = (Guid)parameters.test;
// Then
value.ShouldEqual(guid);
}
[Fact]
public void Should_support_dynamic_casting_of_properties_to_timespans()
{
//Given
dynamic parameters = new DynamicDictionary();
parameters.test = new TimeSpan(1, 2, 3, 4).ToString();
// When
var value = (TimeSpan)parameters.test;
// Then
value.ShouldEqual(new TimeSpan(1, 2, 3, 4));
}
[Fact]
public void Should_support_dynamic_casting_of_properties_to_datetimes()
{
//Given
dynamic parameters = new DynamicDictionary();
parameters.test = new DateTime(2001, 3, 4);
// When
var value = (DateTime)parameters.test;
// Then
value.ShouldEqual(new DateTime(2001, 3, 4));
}
[Fact]
public void Should_support_dynamic_casting_of_nullable_properties()
{
//Given
dynamic parameters = new DynamicDictionary();
var guid = Guid.NewGuid();
parameters.test = guid.ToString();
// When
var value = (Guid?)parameters.test;
// Then
value.ShouldEqual(guid);
}
[Fact]
public void Should_support_implicit_casting()
{
// Given
dynamic parameters = new DynamicDictionary();
parameters.test = "10";
// When
int value = parameters.test;
// Then
value.ShouldEqual(10);
}
[Fact]
public void Should_support_casting_when_using_indexer_to_set_values()
{
// Given
dynamic parameters = new DynamicDictionary();
parameters["test"] = "10";
// When
int value = parameters.test;
// Then
value.ShouldEqual(10);
}
[Fact]
public void Should_support_GetDynamicMemberNames()
{
// Given
dynamic parameters = new DynamicDictionary();
parameters["test"] = "10";
parameters["rest"] = "20";
// When
var names = ((DynamicDictionary)parameters).GetDynamicMemberNames();
// Then
Assert.True(names.SequenceEqual(new[] { "test", "rest" }));
}
[Fact]
public void Should_be_able_to_enumerate_keys()
{
// Given
dynamic parameters = new DynamicDictionary();
parameters["test"] = "10";
parameters["rest"] = "20";
// When
var names = new List<string>();
foreach (var name in parameters)
{
names.Add(name);
}
// Then
Assert.True(names.SequenceEqual(new[] { "test", "rest" }));
}
[Fact]
public void String_dictionary_values_are_Json_serialized_as_strings()
{
dynamic value = "42";
var input = new DynamicDictionaryValue(value);
var sut = new Nancy.Json.JavaScriptSerializer();
var actual = sut.Serialize(input);
actual.ShouldEqual(@"""42""");
}
[Fact]
public void Integer_dictionary_values_are_Json_serialized_as_integers()
{
dynamic value = 42;
var input = new DynamicDictionaryValue(value);
var sut = new Nancy.Json.JavaScriptSerializer();
var actual = sut.Serialize(input);
actual.ShouldEqual(@"42");
}
[Theory]
[InlineData(2)]
[InlineData(5)]
public void Should_return_correct_count(int expectedNumberOfEntries)
{
// Given
var input = new DynamicDictionary();
// When
for (var i = 0; i < expectedNumberOfEntries; i++)
{
input[i.ToString(CultureInfo.InvariantCulture)] = i;
}
// Then
input.Count.ShouldEqual(expectedNumberOfEntries);
}
[Fact]
public void Should_add_value_when_invoking_string_dynamic_overload_of_add_method()
{
// Given
var input = new DynamicDictionary();
// When
input.Add("test", 10);
var value = (int)input["test"];
// Then
value.ShouldEqual(10);
}
[Fact]
public void Should_add_value_when_invoking_keyvaluepair_overload_of_add_method()
{
// Given
var input = new DynamicDictionary();
// When
input.Add(new KeyValuePair<string, dynamic>("test", 10));
var value = (int)input["test"];
// Then
value.ShouldEqual(10);
}
[Theory]
[InlineData("test1", true)]
[InlineData("test2", false)]
public void Should_return_correct_value_for_containskey(string key, bool expectedResult)
{
// Given
var input = new DynamicDictionary();
input["test1"] = 10;
// When
var result = input.ContainsKey(key);
// Then
result.ShouldEqual(expectedResult);
}
[Fact]
public void Should_return_all_keys()
{
// Given
var input = new DynamicDictionary();
input["test1"] = 10;
input["test2"] = 10;
// When
var result = input.Keys;
// Then
result.ShouldHave(x => x.Equals("test1"));
result.ShouldHave(x => x.Equals("test2"));
}
[Fact]
public void Should_return_false_when_trygetvalue_could_not_find_key()
{
// Given
var input = new DynamicDictionary();
object output;
// When
var result = input.TryGetValue("test", out output);
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_true_when_trygetvalue_could_find_key()
{
// Given
var input = new DynamicDictionary();
input["test"] = 10;
object output;
// When
var result = input.TryGetValue("test", out output);
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_return_value_when_trygetvalue_could_find_key()
{
// Given
var input = new DynamicDictionary();
input["test"] = 10;
dynamic output;
// When
input.TryGetValue("test", out output);
// Then
((int)output).ShouldEqual(10);
}
[Fact]
public void Should_return_all_values()
{
// Given
var input = new DynamicDictionary();
input["test1"] = 10;
input["test2"] = "test2";
// When
var result = input.Values;
// Then
result.ShouldHave(x => ((int)x).Equals(10));
result.ShouldHave(x => ((string)x).Equals("test2"));
}
[Fact]
public void Should_remove_all_values_when_clear_is_invoked()
{
// Given
var input = new DynamicDictionary();
input["test1"] = 10;
input["test2"] = "test2";
// When
input.Clear();
// Then
input.Count.ShouldEqual(0);
}
[Fact]
public void Should_return_false_when_contains_does_not_find_match()
{
// Given
var input = new DynamicDictionary();
input["test1"] = 10;
// When
var result = input.Contains(new KeyValuePair<string, dynamic>("test1", 11));
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_true_when_contains_does_find_match()
{
// Given
var input = new DynamicDictionary();
input["test1"] = 10;
// When
var result = input.Contains(new KeyValuePair<string, dynamic>("test1", 10));
// Then
result.ShouldBeTrue();
}
[Theory]
[InlineData(0)]
[InlineData(2)]
public void Should_copy_to_destination_array_from_given_index_when_copyto_is_invoked(int arrayIndex)
{
// Given
var input = new DynamicDictionary();
input["test"] = 1;
var output =
new KeyValuePair<string, dynamic>[4];
// When
input.CopyTo(output, arrayIndex);
// Then
output[arrayIndex].Key.ShouldEqual(input.Keys.First());
((int)output[arrayIndex].Value).ShouldEqual((int)input.Values.First());
}
[Fact]
public void Should_return_false_for_isreadonly()
{
// Given
var input = new DynamicDictionary();
// When
var result = input.IsReadOnly;
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_remove_item_when_string_overload_of_remove_method_is_invoked()
{
// Given
var input = new DynamicDictionary();
input["test"] = 10;
// When
input.Remove("test");
// Then
input.ContainsKey("test").ShouldBeFalse();
}
[Fact]
public void Should_return_true_when_string_overload_of_remove_method_can_match_key()
{
var input = new DynamicDictionary();
input["test"] = 10;
// When
var result = input.Remove("test");
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_return_false_when_string_overload_of_remove_method_cannot_match_key()
{
var input = new DynamicDictionary();
input["test"] = 10;
// When
var result = input.Remove("test1");
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_remove_item_when_keyvaluepair_overload_of_remove_method_is_invoked()
{
// Given
var input = new DynamicDictionary();
input["test"] = 10;
// When
input.Remove(new KeyValuePair<string, dynamic>("test", 10));
// Then
input.ContainsKey("test").ShouldBeFalse();
}
[Fact]
public void Should_return_true_when_keyvaluepair_overload_of_remove_method_can_match_key()
{
var input = new DynamicDictionary();
input["test"] = 10;
// When
var result = input.Remove(new KeyValuePair<string, dynamic>("test", 10));
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_return_false_when_keyvaluepair_overload_of_remove_method_cannot_match_key()
{
var input = new DynamicDictionary();
input["test"] = 10;
// When
var result = input.Remove(new KeyValuePair<string, dynamic>("test1", 10));
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_remove_natural_key()
{
// Given
var input = new DynamicDictionary();
input.Add("a-b-c", "hello");
//when
input.Remove("a-b-c");
//then
input.ContainsKey("abc").ShouldBeFalse();
}
[Fact]
public void Should_return_dictionary_from_dynamic_dictionary()
{
//Given
var input = new DynamicDictionary();
//When
var result = input.ToDictionary();
//Then
Assert.IsType(typeof(Dictionary<string, object>), result);
}
[Fact]
public void Should_return_dynamic_values_as_objects()
{
//Given/When
var result = this.dictionary.ToDictionary();
//Then
Assert.IsType(typeof(long), GetLongValue(result["TestInt"]));
Assert.IsType(typeof(string), GetStringValue(result["TestString"]));
}
[Fact]
public void Should_return_dynamic_objects_as_objects()
{
//Given
var input = new DynamicDictionary();
input.Add("Test", new { Title = "Fred", Number = 123 });
//When
var result = input.ToDictionary();
//Then
Assert.Equal("Fred", ((dynamic)result["Test"]).Title);
Assert.Equal(123, ((dynamic)result["Test"]).Number);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Globalization;
using Microsoft.Win32.SafeHandles;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace System.Net
{
internal static partial class CertificateValidationPal
{
private static readonly object s_lockObject = new object();
private static X509Store s_userCertStore;
internal static SslPolicyErrors VerifyCertificateProperties(
X509Chain chain,
X509Certificate2 remoteCertificate,
bool checkCertName,
bool isServer,
string hostName)
{
SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None;
if (!chain.Build(remoteCertificate))
{
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors;
}
if (checkCertName)
{
if (string.IsNullOrEmpty(hostName))
{
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch;
}
else
{
int hostnameMatch;
using (SafeX509Handle certHandle = Interop.Crypto.X509Duplicate(remoteCertificate.Handle))
{
IPAddress hostnameAsIp;
if (IPAddress.TryParse(hostName, out hostnameAsIp))
{
byte[] addressBytes = hostnameAsIp.GetAddressBytes();
hostnameMatch = Interop.Crypto.CheckX509IpAddress(
certHandle,
addressBytes,
addressBytes.Length,
hostName,
hostName.Length);
}
else
{
// The IdnMapping converts Unicode input into the IDNA punycode sequence.
// It also does host case normalization. The bypass logic would be something
// like "all characters being within [a-z0-9.-]+"
//
// Since it's not documented as being thread safe, create a new one each time.
IdnMapping mapping = new IdnMapping();
string matchName = mapping.GetAscii(hostName);
hostnameMatch = Interop.Crypto.CheckX509Hostname(certHandle, matchName, matchName.Length);
}
}
if (hostnameMatch != 1)
{
Debug.Assert(hostnameMatch == 0, "hostnameMatch should be (0,1) was " + hostnameMatch);
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch;
}
}
}
return sslPolicyErrors;
}
//
// Extracts a remote certificate upon request.
//
internal static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityContext, out X509Certificate2Collection remoteCertificateStore)
{
remoteCertificateStore = null;
bool gotReference = false;
if (securityContext == null)
{
return null;
}
GlobalLog.Enter("CertificateValidationPal.Unix SecureChannel#" + Logging.HashString(securityContext) + "::GetRemoteCertificate()");
X509Certificate2 result = null;
SafeFreeCertContext remoteContext = null;
try
{
int errorCode = QueryContextRemoteCertificate(securityContext, out remoteContext);
if (remoteContext != null && !remoteContext.IsInvalid)
{
remoteContext.DangerousAddRef(ref gotReference);
result = new X509Certificate2(remoteContext.DangerousGetHandle());
}
remoteCertificateStore = new X509Certificate2Collection();
using (SafeSharedX509StackHandle chainStack =
Interop.OpenSsl.GetPeerCertificateChain(securityContext.SslContext))
{
if (!chainStack.IsInvalid)
{
int count = Interop.Crypto.GetX509StackFieldCount(chainStack);
for (int i = 0; i < count; i++)
{
IntPtr certPtr = Interop.Crypto.GetX509StackField(chainStack, i);
if (certPtr != IntPtr.Zero)
{
// X509Certificate2(IntPtr) calls X509_dup, so the reference is appropriately tracked.
X509Certificate2 chainCert = new X509Certificate2(certPtr);
remoteCertificateStore.Add(chainCert);
}
}
}
}
}
finally
{
if (gotReference)
{
remoteContext.DangerousRelease();
}
if (remoteContext != null)
{
remoteContext.Dispose();
}
}
if (Logging.On)
{
Logging.PrintInfo(Logging.Web, SR.Format(SR.net_log_remote_certificate, (result == null ? "null" : result.ToString(true))));
}
GlobalLog.Leave("CertificateValidationPal.Unix SecureChannel#" + Logging.HashString(securityContext) + "::GetRemoteCertificate()", (result == null ? "null" : result.Subject));
return result;
}
//
// Used only by client SSL code, never returns null.
//
internal static string[] GetRequestCertificateAuthorities(SafeDeleteContext securityContext)
{
using (SafeSharedX509NameStackHandle names = Interop.Ssl.SslGetClientCAList(securityContext.SslContext))
{
if (names.IsInvalid)
{
return Array.Empty<string>();
}
int nameCount = Interop.Crypto.GetX509NameStackFieldCount(names);
if (nameCount == 0)
{
return Array.Empty<string>();
}
string[] clientAuthorityNames = new string[nameCount];
for (int i = 0; i < nameCount; i++)
{
using (SafeSharedX509NameHandle nameHandle = Interop.Crypto.GetX509NameStackField(names, i))
{
X500DistinguishedName dn = Interop.Crypto.LoadX500Name(nameHandle);
clientAuthorityNames[i] = dn.Name;
}
}
return clientAuthorityNames;
}
}
internal static X509Store EnsureStoreOpened(bool isMachineStore)
{
if (isMachineStore)
{
// There's not currently a LocalMachine\My store on Unix, so don't bother trying
// and having to deal with the exception.
//
// https://github.com/dotnet/corefx/issues/3690 tracks the lack of this store.
return null;
}
return EnsureStoreOpened(ref s_userCertStore, StoreLocation.CurrentUser);
}
private static X509Store EnsureStoreOpened(ref X509Store storeField, StoreLocation storeLocation)
{
X509Store store = Volatile.Read(ref storeField);
if (store == null)
{
lock (s_lockObject)
{
store = Volatile.Read(ref storeField);
if (store == null)
{
try
{
store = new X509Store(StoreName.My, storeLocation);
store.Open(OpenFlags.ReadOnly);
Volatile.Write(ref storeField, store);
GlobalLog.Print(
"CertModule::EnsureStoreOpened() storeLocation:" + storeLocation +
" returned store:" + store.GetHashCode().ToString("x"));
}
catch (CryptographicException e)
{
GlobalLog.Assert(
"CertModule::EnsureStoreOpened()",
"Failed to open cert store, location:" + storeLocation + " exception:" + e);
throw;
}
}
}
}
return store;
}
private static int QueryContextRemoteCertificate(SafeDeleteContext securityContext, out SafeFreeCertContext remoteCertContext)
{
remoteCertContext = null;
try
{
SafeX509Handle remoteCertificate = Interop.OpenSsl.GetPeerCertificate(securityContext.SslContext);
// Note that cert ownership is transferred to SafeFreeCertContext
remoteCertContext = new SafeFreeCertContext(remoteCertificate);
return 0;
}
catch
{
return -1;
}
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculus.com/licenses/LICENSE-3.3
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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.
************************************************************************************/
#if !UNITY_5_3_OR_NEWER
#error Oculus Utilities require Unity 5.3 or higher.
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using VR = UnityEngine.VR;
/// <summary>
/// Configuration data for Oculus virtual reality.
/// </summary>
public class OVRManager : MonoBehaviour
{
public enum TrackingOrigin
{
EyeLevel = OVRPlugin.TrackingOrigin.EyeLevel,
FloorLevel = OVRPlugin.TrackingOrigin.FloorLevel,
}
public enum EyeTextureFormat
{
Default = OVRPlugin.EyeTextureFormat.Default,
R16G16B16A16_FP = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP,
R11G11B10_FP = OVRPlugin.EyeTextureFormat.R11G11B10_FP,
}
/// <summary>
/// Gets the singleton instance.
/// </summary>
public static OVRManager instance { get; private set; }
/// <summary>
/// Gets a reference to the active display.
/// </summary>
public static OVRDisplay display { get; private set; }
/// <summary>
/// Gets a reference to the active sensor.
/// </summary>
public static OVRTracker tracker { get; private set; }
/// <summary>
/// Gets a reference to the active boundary system.
/// </summary>
public static OVRBoundary boundary { get; private set; }
private static OVRProfile _profile;
/// <summary>
/// Gets the current profile, which contains information about the user's settings and body dimensions.
/// </summary>
public static OVRProfile profile
{
get {
if (_profile == null)
_profile = new OVRProfile();
return _profile;
}
}
private IEnumerable<Camera> disabledCameras;
float prevTimeScale;
/// <summary>
/// Occurs when an HMD attached.
/// </summary>
public static event Action HMDAcquired;
/// <summary>
/// Occurs when an HMD detached.
/// </summary>
public static event Action HMDLost;
/// <summary>
/// Occurs when an HMD is put on the user's head.
/// </summary>
public static event Action HMDMounted;
/// <summary>
/// Occurs when an HMD is taken off the user's head.
/// </summary>
public static event Action HMDUnmounted;
/// <summary>
/// Occurs when VR Focus is acquired.
/// </summary>
public static event Action VrFocusAcquired;
/// <summary>
/// Occurs when VR Focus is lost.
/// </summary>
public static event Action VrFocusLost;
/// <summary>
/// Occurs when the active Audio Out device has changed and a restart is needed.
/// </summary>
public static event Action AudioOutChanged;
/// <summary>
/// Occurs when the active Audio In device has changed and a restart is needed.
/// </summary>
public static event Action AudioInChanged;
/// <summary>
/// Occurs when the sensor gained tracking.
/// </summary>
public static event Action TrackingAcquired;
/// <summary>
/// Occurs when the sensor lost tracking.
/// </summary>
public static event Action TrackingLost;
/// <summary>
/// Occurs when Health & Safety Warning is dismissed.
/// </summary>
//Disable the warning about it being unused. It's deprecated.
#pragma warning disable 0067
[Obsolete]
public static event Action HSWDismissed;
#pragma warning restore
private static bool _isHmdPresentCached = false;
private static bool _isHmdPresent = false;
private static bool _wasHmdPresent = false;
/// <summary>
/// If true, a head-mounted display is connected and present.
/// </summary>
public static bool isHmdPresent
{
get {
if (!_isHmdPresentCached)
{
_isHmdPresentCached = true;
_isHmdPresent = OVRPlugin.hmdPresent;
}
return _isHmdPresent;
}
private set {
_isHmdPresentCached = true;
_isHmdPresent = value;
}
}
/// <summary>
/// Gets the audio output device identifier.
/// </summary>
/// <description>
/// On Windows, this is a string containing the GUID of the IMMDevice for the Windows audio endpoint to use.
/// </description>
public static string audioOutId
{
get { return OVRPlugin.audioOutId; }
}
/// <summary>
/// Gets the audio input device identifier.
/// </summary>
/// <description>
/// On Windows, this is a string containing the GUID of the IMMDevice for the Windows audio endpoint to use.
/// </description>
public static string audioInId
{
get { return OVRPlugin.audioInId; }
}
private static bool _hasVrFocusCached = false;
private static bool _hasVrFocus = false;
private static bool _hadVrFocus = false;
/// <summary>
/// If true, the app has VR Focus.
/// </summary>
public static bool hasVrFocus
{
get {
if (!_hasVrFocusCached)
{
_hasVrFocusCached = true;
_hasVrFocus = OVRPlugin.hasVrFocus;
}
return _hasVrFocus;
}
private set {
_hasVrFocusCached = true;
_hasVrFocus = value;
}
}
/// <summary>
/// If true, then the Oculus health and safety warning (HSW) is currently visible.
/// </summary>
[Obsolete]
public static bool isHSWDisplayed { get { return false; } }
/// <summary>
/// If the HSW has been visible for the necessary amount of time, this will make it disappear.
/// </summary>
[Obsolete]
public static void DismissHSWDisplay() {}
/// <summary>
/// If true, chromatic de-aberration will be applied, improving the image at the cost of texture bandwidth.
/// </summary>
public bool chromatic
{
get {
if (!isHmdPresent)
return false;
return OVRPlugin.chromatic;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.chromatic = value;
}
}
/// <summary>
/// If true, both eyes will see the same image, rendered from the center eye pose, saving performance.
/// </summary>
public bool monoscopic
{
get {
if (!isHmdPresent)
return true;
return OVRPlugin.monoscopic;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.monoscopic = value;
}
}
/// <summary>
/// If true, distortion rendering work is submitted a quarter-frame early to avoid pipeline stalls and increase CPU-GPU parallelism.
/// </summary>
public bool queueAhead = true;
/// <summary>
/// If true, Unity will use the optimal antialiasing level for quality/performance on the current hardware.
/// </summary>
public bool useRecommendedMSAALevel = false;
/// <summary>
/// If true, dynamic resolution will be enabled
/// </summary>
public bool enableAdaptiveResolution = false;
/// <summary>
/// Max RenderScale the app can reach under adaptive resolution mode ( enableAdaptiveResolution = ture );
/// </summary>
[RangeAttribute(0.5f, 2.0f)]
public float maxRenderScale = 1.0f;
/// <summary>
/// Min RenderScale the app can reach under adaptive resolution mode ( enableAdaptiveResolution = ture );
/// </summary>
[RangeAttribute(0.5f, 2.0f)]
public float minRenderScale = 0.7f;
/// <summary>
/// The number of expected display frames per rendered frame.
/// </summary>
public int vsyncCount
{
get {
if (!isHmdPresent)
return 1;
return OVRPlugin.vsyncCount;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.vsyncCount = value;
}
}
/// <summary>
/// Gets the current battery level.
/// </summary>
/// <returns><c>battery level in the range [0.0,1.0]</c>
/// <param name="batteryLevel">Battery level.</param>
public static float batteryLevel
{
get {
if (!isHmdPresent)
return 1f;
return OVRPlugin.batteryLevel;
}
}
/// <summary>
/// Gets the current battery temperature.
/// </summary>
/// <returns><c>battery temperature in Celsius</c>
/// <param name="batteryTemperature">Battery temperature.</param>
public static float batteryTemperature
{
get {
if (!isHmdPresent)
return 0f;
return OVRPlugin.batteryTemperature;
}
}
/// <summary>
/// Gets the current battery status.
/// </summary>
/// <returns><c>battery status</c>
/// <param name="batteryStatus">Battery status.</param>
public static int batteryStatus
{
get {
if (!isHmdPresent)
return -1;
return (int)OVRPlugin.batteryStatus;
}
}
/// <summary>
/// Gets the current volume level.
/// </summary>
/// <returns><c>volume level in the range [0,1].</c>
public static float volumeLevel
{
get {
if (!isHmdPresent)
return 0f;
return OVRPlugin.systemVolume;
}
}
/// <summary>
/// Gets or sets the current CPU performance level (0-2). Lower performance levels save more power.
/// </summary>
public static int cpuLevel
{
get {
if (!isHmdPresent)
return 2;
return OVRPlugin.cpuLevel;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.cpuLevel = value;
}
}
/// <summary>
/// Gets or sets the current GPU performance level (0-2). Lower performance levels save more power.
/// </summary>
public static int gpuLevel
{
get {
if (!isHmdPresent)
return 2;
return OVRPlugin.gpuLevel;
}
set {
if (!isHmdPresent)
return;
OVRPlugin.gpuLevel = value;
}
}
/// <summary>
/// If true, the CPU and GPU are currently throttled to save power and/or reduce the temperature.
/// </summary>
public static bool isPowerSavingActive
{
get {
if (!isHmdPresent)
return false;
return OVRPlugin.powerSaving;
}
}
/// <summary>
/// Gets or sets the eye texture format.
/// This feature is only for UNITY_5_6_OR_NEWER
/// </summary>
public static EyeTextureFormat eyeTextureFormat
{
get
{
return (OVRManager.EyeTextureFormat)OVRPlugin.GetDesiredEyeTextureFormat();
}
set
{
OVRPlugin.SetDesiredEyeTextureFormat((OVRPlugin.EyeTextureFormat)value);
}
}
[SerializeField]
private OVRManager.TrackingOrigin _trackingOriginType = OVRManager.TrackingOrigin.EyeLevel;
/// <summary>
/// Defines the current tracking origin type.
/// </summary>
public OVRManager.TrackingOrigin trackingOriginType
{
get {
if (!isHmdPresent)
return _trackingOriginType;
return (OVRManager.TrackingOrigin)OVRPlugin.GetTrackingOriginType();
}
set {
if (!isHmdPresent)
return;
if (OVRPlugin.SetTrackingOriginType((OVRPlugin.TrackingOrigin)value))
{
// Keep the field exposed in the Unity Editor synchronized with any changes.
_trackingOriginType = value;
}
}
}
/// <summary>
/// If true, head tracking will affect the position of each OVRCameraRig's cameras.
/// </summary>
public bool usePositionTracking = true;
/// <summary>
/// If true, the distance between the user's eyes will affect the position of each OVRCameraRig's cameras.
/// </summary>
public bool useIPDInPositionTracking = true;
/// <summary>
/// If true, each scene load will cause the head pose to reset.
/// </summary>
public bool resetTrackerOnLoad = false;
/// <summary>
/// True if the current platform supports virtual reality.
/// </summary>
public bool isSupportedPlatform { get; private set; }
private static bool _isUserPresentCached = false;
private static bool _isUserPresent = false;
private static bool _wasUserPresent = false;
/// <summary>
/// True if the user is currently wearing the display.
/// </summary>
public bool isUserPresent
{
get {
if (!_isUserPresentCached)
{
_isUserPresentCached = true;
_isUserPresent = OVRPlugin.userPresent;
}
return _isUserPresent;
}
private set {
_isUserPresentCached = true;
_isUserPresent = value;
}
}
private static bool prevAudioOutIdIsCached = false;
private static bool prevAudioInIdIsCached = false;
private static string prevAudioOutId = string.Empty;
private static string prevAudioInId = string.Empty;
private static bool wasPositionTracked = false;
#region Unity Messages
private void Awake()
{
// Only allow one instance at runtime.
if (instance != null)
{
enabled = false;
DestroyImmediate(this);
return;
}
instance = this;
Debug.Log("Unity v" + Application.unityVersion + ", " +
"Oculus Utilities v" + OVRPlugin.wrapperVersion + ", " +
"OVRPlugin v" + OVRPlugin.version + ", " +
"SDK v" + OVRPlugin.nativeSDKVersion + ".");
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
var supportedTypes =
UnityEngine.Rendering.GraphicsDeviceType.Direct3D11.ToString() + ", " +
UnityEngine.Rendering.GraphicsDeviceType.Direct3D12.ToString();
if (!supportedTypes.Contains(SystemInfo.graphicsDeviceType.ToString()))
Debug.LogWarning("VR rendering requires one of the following device types: (" + supportedTypes + "). Your graphics device: " + SystemInfo.graphicsDeviceType.ToString());
#endif
// Detect whether this platform is a supported platform
RuntimePlatform currPlatform = Application.platform;
isSupportedPlatform |= currPlatform == RuntimePlatform.Android;
//isSupportedPlatform |= currPlatform == RuntimePlatform.LinuxPlayer;
isSupportedPlatform |= currPlatform == RuntimePlatform.OSXEditor;
isSupportedPlatform |= currPlatform == RuntimePlatform.OSXPlayer;
isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsEditor;
isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsPlayer;
if (!isSupportedPlatform)
{
Debug.LogWarning("This platform is unsupported");
return;
}
#if UNITY_ANDROID && !UNITY_EDITOR
// We want to set up our touchpad messaging system
OVRTouchpad.Create();
// Turn off chromatic aberration by default to save texture bandwidth.
chromatic = false;
#endif
if (display == null)
display = new OVRDisplay();
if (tracker == null)
tracker = new OVRTracker();
if (boundary == null)
boundary = new OVRBoundary();
if (resetTrackerOnLoad)
display.RecenterPose();
// Disable the occlusion mesh by default until open issues with the preview window are resolved.
OVRPlugin.occlusionMesh = false;
}
private void Update()
{
if (OVRPlugin.shouldQuit)
Application.Quit();
if (OVRPlugin.shouldRecenter)
OVRManager.display.RecenterPose();
if (trackingOriginType != _trackingOriginType)
trackingOriginType = _trackingOriginType;
tracker.isEnabled = usePositionTracking;
OVRPlugin.useIPDInPositionTracking = useIPDInPositionTracking;
// Dispatch HMD events.
isHmdPresent = OVRPlugin.hmdPresent;
if (useRecommendedMSAALevel && QualitySettings.antiAliasing != display.recommendedMSAALevel)
{
Debug.Log("The current MSAA level is " + QualitySettings.antiAliasing +
", but the recommended MSAA level is " + display.recommendedMSAALevel +
". Switching to the recommended level.");
QualitySettings.antiAliasing = display.recommendedMSAALevel;
}
if (_wasHmdPresent && !isHmdPresent)
{
try
{
if (HMDLost != null)
HMDLost();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
if (!_wasHmdPresent && isHmdPresent)
{
try
{
if (HMDAcquired != null)
HMDAcquired();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
_wasHmdPresent = isHmdPresent;
// Dispatch HMD mounted events.
isUserPresent = OVRPlugin.userPresent;
if (_wasUserPresent && !isUserPresent)
{
try
{
if (HMDUnmounted != null)
HMDUnmounted();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
if (!_wasUserPresent && isUserPresent)
{
try
{
if (HMDMounted != null)
HMDMounted();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
_wasUserPresent = isUserPresent;
// Dispatch VR Focus events.
hasVrFocus = OVRPlugin.hasVrFocus;
if (_hadVrFocus && !hasVrFocus)
{
try
{
if (VrFocusLost != null)
VrFocusLost();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
if (!_hadVrFocus && hasVrFocus)
{
try
{
if (VrFocusAcquired != null)
VrFocusAcquired();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
_hadVrFocus = hasVrFocus;
// Changing effective rendering resolution dynamically according performance
#if (UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN) && UNITY_5 && !(UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3)
if (enableAdaptiveResolution)
{
if (VR.VRSettings.renderScale < maxRenderScale)
{
// Allocate renderScale to max to avoid re-allocation
VR.VRSettings.renderScale = maxRenderScale;
}
else
{
// Adjusting maxRenderScale in case app started with a larger renderScale value
maxRenderScale = Mathf.Max(maxRenderScale, VR.VRSettings.renderScale);
}
float minViewportScale = minRenderScale / VR.VRSettings.renderScale;
float recommendedViewportScale = OVRPlugin.GetEyeRecommendedResolutionScale() / VR.VRSettings.renderScale;
recommendedViewportScale = Mathf.Clamp(recommendedViewportScale, minViewportScale, 1.0f);
VR.VRSettings.renderViewportScale = recommendedViewportScale;
}
#endif
// Dispatch Audio Device events.
string audioOutId = OVRPlugin.audioOutId;
if (!prevAudioOutIdIsCached)
{
prevAudioOutId = audioOutId;
prevAudioOutIdIsCached = true;
}
else if (audioOutId != prevAudioOutId)
{
try
{
if (AudioOutChanged != null)
AudioOutChanged();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
prevAudioOutId = audioOutId;
}
string audioInId = OVRPlugin.audioInId;
if (!prevAudioInIdIsCached)
{
prevAudioInId = audioInId;
prevAudioInIdIsCached = true;
}
else if (audioInId != prevAudioInId)
{
try
{
if (AudioInChanged != null)
AudioInChanged();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
prevAudioInId = audioInId;
}
// Dispatch tracking events.
if (wasPositionTracked && !tracker.isPositionTracked)
{
try
{
if (TrackingLost != null)
TrackingLost();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
if (!wasPositionTracked && tracker.isPositionTracked)
{
try
{
if (TrackingAcquired != null)
TrackingAcquired();
}
catch (Exception e)
{
Debug.LogError("Caught Exception: " + e);
}
}
wasPositionTracked = tracker.isPositionTracked;
display.Update();
OVRInput.Update();
}
private void LateUpdate()
{
OVRHaptics.Process();
}
private void FixedUpdate()
{
OVRInput.FixedUpdate();
}
/// <summary>
/// Leaves the application/game and returns to the launcher/dashboard
/// </summary>
public void ReturnToLauncher()
{
// show the platform UI quit prompt
OVRManager.PlatformUIConfirmQuit();
}
#endregion
public static void PlatformUIConfirmQuit()
{
if (!isHmdPresent)
return;
OVRPlugin.ShowUI(OVRPlugin.PlatformUI.ConfirmQuit);
}
public static void PlatformUIGlobalMenu()
{
if (!isHmdPresent)
return;
OVRPlugin.ShowUI(OVRPlugin.PlatformUI.GlobalMenu);
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Houses Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KGHDataSet : EduHubDataSet<KGH>
{
/// <inheritdoc />
public override string Name { get { return "KGH"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal KGHDataSet(EduHubContext Context)
: base(Context)
{
Index_CAMPUS = new Lazy<NullDictionary<int?, IReadOnlyList<KGH>>>(() => this.ToGroupedNullDictionary(i => i.CAMPUS));
Index_KGHKEY = new Lazy<Dictionary<string, KGH>>(() => this.ToDictionary(i => i.KGHKEY));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="KGH" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="KGH" /> fields for each CSV column header</returns>
internal override Action<KGH, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<KGH, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "KGHKEY":
mapper[i] = (e, v) => e.KGHKEY = v;
break;
case "DESCRIPTION":
mapper[i] = (e, v) => e.DESCRIPTION = v;
break;
case "CAMPUS":
mapper[i] = (e, v) => e.CAMPUS = v == null ? (int?)null : int.Parse(v);
break;
case "ACTIVE":
mapper[i] = (e, v) => e.ACTIVE = v;
break;
case "HOUSE_SIZE":
mapper[i] = (e, v) => e.HOUSE_SIZE = v == null ? (short?)null : short.Parse(v);
break;
case "MALES":
mapper[i] = (e, v) => e.MALES = v == null ? (short?)null : short.Parse(v);
break;
case "FEMALES":
mapper[i] = (e, v) => e.FEMALES = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F01":
mapper[i] = (e, v) => e.AGE_F01 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F02":
mapper[i] = (e, v) => e.AGE_F02 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F03":
mapper[i] = (e, v) => e.AGE_F03 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F04":
mapper[i] = (e, v) => e.AGE_F04 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F05":
mapper[i] = (e, v) => e.AGE_F05 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F06":
mapper[i] = (e, v) => e.AGE_F06 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F07":
mapper[i] = (e, v) => e.AGE_F07 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F08":
mapper[i] = (e, v) => e.AGE_F08 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F09":
mapper[i] = (e, v) => e.AGE_F09 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F10":
mapper[i] = (e, v) => e.AGE_F10 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F11":
mapper[i] = (e, v) => e.AGE_F11 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F12":
mapper[i] = (e, v) => e.AGE_F12 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F13":
mapper[i] = (e, v) => e.AGE_F13 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F14":
mapper[i] = (e, v) => e.AGE_F14 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F15":
mapper[i] = (e, v) => e.AGE_F15 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F16":
mapper[i] = (e, v) => e.AGE_F16 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F17":
mapper[i] = (e, v) => e.AGE_F17 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F18":
mapper[i] = (e, v) => e.AGE_F18 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F19":
mapper[i] = (e, v) => e.AGE_F19 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_F20":
mapper[i] = (e, v) => e.AGE_F20 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M01":
mapper[i] = (e, v) => e.AGE_M01 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M02":
mapper[i] = (e, v) => e.AGE_M02 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M03":
mapper[i] = (e, v) => e.AGE_M03 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M04":
mapper[i] = (e, v) => e.AGE_M04 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M05":
mapper[i] = (e, v) => e.AGE_M05 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M06":
mapper[i] = (e, v) => e.AGE_M06 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M07":
mapper[i] = (e, v) => e.AGE_M07 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M08":
mapper[i] = (e, v) => e.AGE_M08 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M09":
mapper[i] = (e, v) => e.AGE_M09 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M10":
mapper[i] = (e, v) => e.AGE_M10 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M11":
mapper[i] = (e, v) => e.AGE_M11 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M12":
mapper[i] = (e, v) => e.AGE_M12 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M13":
mapper[i] = (e, v) => e.AGE_M13 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M14":
mapper[i] = (e, v) => e.AGE_M14 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M15":
mapper[i] = (e, v) => e.AGE_M15 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M16":
mapper[i] = (e, v) => e.AGE_M16 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M17":
mapper[i] = (e, v) => e.AGE_M17 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M18":
mapper[i] = (e, v) => e.AGE_M18 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M19":
mapper[i] = (e, v) => e.AGE_M19 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_M20":
mapper[i] = (e, v) => e.AGE_M20 = v == null ? (short?)null : short.Parse(v);
break;
case "SELF_DESCRIBED":
mapper[i] = (e, v) => e.SELF_DESCRIBED = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S01":
mapper[i] = (e, v) => e.AGE_S01 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S02":
mapper[i] = (e, v) => e.AGE_S02 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S03":
mapper[i] = (e, v) => e.AGE_S03 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S04":
mapper[i] = (e, v) => e.AGE_S04 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S05":
mapper[i] = (e, v) => e.AGE_S05 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S06":
mapper[i] = (e, v) => e.AGE_S06 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S07":
mapper[i] = (e, v) => e.AGE_S07 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S08":
mapper[i] = (e, v) => e.AGE_S08 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S09":
mapper[i] = (e, v) => e.AGE_S09 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S10":
mapper[i] = (e, v) => e.AGE_S10 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S11":
mapper[i] = (e, v) => e.AGE_S11 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S12":
mapper[i] = (e, v) => e.AGE_S12 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S13":
mapper[i] = (e, v) => e.AGE_S13 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S14":
mapper[i] = (e, v) => e.AGE_S14 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S15":
mapper[i] = (e, v) => e.AGE_S15 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S16":
mapper[i] = (e, v) => e.AGE_S16 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S17":
mapper[i] = (e, v) => e.AGE_S17 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S18":
mapper[i] = (e, v) => e.AGE_S18 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S19":
mapper[i] = (e, v) => e.AGE_S19 = v == null ? (short?)null : short.Parse(v);
break;
case "AGE_S20":
mapper[i] = (e, v) => e.AGE_S20 = v == null ? (short?)null : short.Parse(v);
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="KGH" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="KGH" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="KGH" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{KGH}"/> of entities</returns>
internal override IEnumerable<KGH> ApplyDeltaEntities(IEnumerable<KGH> Entities, List<KGH> DeltaEntities)
{
HashSet<string> Index_KGHKEY = new HashSet<string>(DeltaEntities.Select(i => i.KGHKEY));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.KGHKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_KGHKEY.Remove(entity.KGHKEY);
if (entity.KGHKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<int?, IReadOnlyList<KGH>>> Index_CAMPUS;
private Lazy<Dictionary<string, KGH>> Index_KGHKEY;
#endregion
#region Index Methods
/// <summary>
/// Find KGH by CAMPUS field
/// </summary>
/// <param name="CAMPUS">CAMPUS value used to find KGH</param>
/// <returns>List of related KGH entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<KGH> FindByCAMPUS(int? CAMPUS)
{
return Index_CAMPUS.Value[CAMPUS];
}
/// <summary>
/// Attempt to find KGH by CAMPUS field
/// </summary>
/// <param name="CAMPUS">CAMPUS value used to find KGH</param>
/// <param name="Value">List of related KGH entities</param>
/// <returns>True if the list of related KGH entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByCAMPUS(int? CAMPUS, out IReadOnlyList<KGH> Value)
{
return Index_CAMPUS.Value.TryGetValue(CAMPUS, out Value);
}
/// <summary>
/// Attempt to find KGH by CAMPUS field
/// </summary>
/// <param name="CAMPUS">CAMPUS value used to find KGH</param>
/// <returns>List of related KGH entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<KGH> TryFindByCAMPUS(int? CAMPUS)
{
IReadOnlyList<KGH> value;
if (Index_CAMPUS.Value.TryGetValue(CAMPUS, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find KGH by KGHKEY field
/// </summary>
/// <param name="KGHKEY">KGHKEY value used to find KGH</param>
/// <returns>Related KGH entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KGH FindByKGHKEY(string KGHKEY)
{
return Index_KGHKEY.Value[KGHKEY];
}
/// <summary>
/// Attempt to find KGH by KGHKEY field
/// </summary>
/// <param name="KGHKEY">KGHKEY value used to find KGH</param>
/// <param name="Value">Related KGH entity</param>
/// <returns>True if the related KGH entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByKGHKEY(string KGHKEY, out KGH Value)
{
return Index_KGHKEY.Value.TryGetValue(KGHKEY, out Value);
}
/// <summary>
/// Attempt to find KGH by KGHKEY field
/// </summary>
/// <param name="KGHKEY">KGHKEY value used to find KGH</param>
/// <returns>Related KGH entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KGH TryFindByKGHKEY(string KGHKEY)
{
KGH value;
if (Index_KGHKEY.Value.TryGetValue(KGHKEY, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a KGH table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KGH]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[KGH](
[KGHKEY] varchar(10) NOT NULL,
[DESCRIPTION] varchar(30) NULL,
[CAMPUS] int NULL,
[ACTIVE] varchar(1) NULL,
[HOUSE_SIZE] smallint NULL,
[MALES] smallint NULL,
[FEMALES] smallint NULL,
[AGE_F01] smallint NULL,
[AGE_F02] smallint NULL,
[AGE_F03] smallint NULL,
[AGE_F04] smallint NULL,
[AGE_F05] smallint NULL,
[AGE_F06] smallint NULL,
[AGE_F07] smallint NULL,
[AGE_F08] smallint NULL,
[AGE_F09] smallint NULL,
[AGE_F10] smallint NULL,
[AGE_F11] smallint NULL,
[AGE_F12] smallint NULL,
[AGE_F13] smallint NULL,
[AGE_F14] smallint NULL,
[AGE_F15] smallint NULL,
[AGE_F16] smallint NULL,
[AGE_F17] smallint NULL,
[AGE_F18] smallint NULL,
[AGE_F19] smallint NULL,
[AGE_F20] smallint NULL,
[AGE_M01] smallint NULL,
[AGE_M02] smallint NULL,
[AGE_M03] smallint NULL,
[AGE_M04] smallint NULL,
[AGE_M05] smallint NULL,
[AGE_M06] smallint NULL,
[AGE_M07] smallint NULL,
[AGE_M08] smallint NULL,
[AGE_M09] smallint NULL,
[AGE_M10] smallint NULL,
[AGE_M11] smallint NULL,
[AGE_M12] smallint NULL,
[AGE_M13] smallint NULL,
[AGE_M14] smallint NULL,
[AGE_M15] smallint NULL,
[AGE_M16] smallint NULL,
[AGE_M17] smallint NULL,
[AGE_M18] smallint NULL,
[AGE_M19] smallint NULL,
[AGE_M20] smallint NULL,
[SELF_DESCRIBED] smallint NULL,
[AGE_S01] smallint NULL,
[AGE_S02] smallint NULL,
[AGE_S03] smallint NULL,
[AGE_S04] smallint NULL,
[AGE_S05] smallint NULL,
[AGE_S06] smallint NULL,
[AGE_S07] smallint NULL,
[AGE_S08] smallint NULL,
[AGE_S09] smallint NULL,
[AGE_S10] smallint NULL,
[AGE_S11] smallint NULL,
[AGE_S12] smallint NULL,
[AGE_S13] smallint NULL,
[AGE_S14] smallint NULL,
[AGE_S15] smallint NULL,
[AGE_S16] smallint NULL,
[AGE_S17] smallint NULL,
[AGE_S18] smallint NULL,
[AGE_S19] smallint NULL,
[AGE_S20] smallint NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [KGH_Index_KGHKEY] PRIMARY KEY CLUSTERED (
[KGHKEY] ASC
)
);
CREATE NONCLUSTERED INDEX [KGH_Index_CAMPUS] ON [dbo].[KGH]
(
[CAMPUS] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGH]') AND name = N'KGH_Index_CAMPUS')
ALTER INDEX [KGH_Index_CAMPUS] ON [dbo].[KGH] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGH]') AND name = N'KGH_Index_CAMPUS')
ALTER INDEX [KGH_Index_CAMPUS] ON [dbo].[KGH] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KGH"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="KGH"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KGH> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<string> Index_KGHKEY = new List<string>();
foreach (var entity in Entities)
{
Index_KGHKEY.Add(entity.KGHKEY);
}
builder.AppendLine("DELETE [dbo].[KGH] WHERE");
// Index_KGHKEY
builder.Append("[KGHKEY] IN (");
for (int index = 0; index < Index_KGHKEY.Count; index++)
{
if (index != 0)
builder.Append(", ");
// KGHKEY
var parameterKGHKEY = $"@p{parameterIndex++}";
builder.Append(parameterKGHKEY);
command.Parameters.Add(parameterKGHKEY, SqlDbType.VarChar, 10).Value = Index_KGHKEY[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KGH data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KGH data set</returns>
public override EduHubDataSetDataReader<KGH> GetDataSetDataReader()
{
return new KGHDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KGH data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KGH data set</returns>
public override EduHubDataSetDataReader<KGH> GetDataSetDataReader(List<KGH> Entities)
{
return new KGHDataReader(new EduHubDataSetLoadedReader<KGH>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class KGHDataReader : EduHubDataSetDataReader<KGH>
{
public KGHDataReader(IEduHubDataSetReader<KGH> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 71; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // KGHKEY
return Current.KGHKEY;
case 1: // DESCRIPTION
return Current.DESCRIPTION;
case 2: // CAMPUS
return Current.CAMPUS;
case 3: // ACTIVE
return Current.ACTIVE;
case 4: // HOUSE_SIZE
return Current.HOUSE_SIZE;
case 5: // MALES
return Current.MALES;
case 6: // FEMALES
return Current.FEMALES;
case 7: // AGE_F01
return Current.AGE_F01;
case 8: // AGE_F02
return Current.AGE_F02;
case 9: // AGE_F03
return Current.AGE_F03;
case 10: // AGE_F04
return Current.AGE_F04;
case 11: // AGE_F05
return Current.AGE_F05;
case 12: // AGE_F06
return Current.AGE_F06;
case 13: // AGE_F07
return Current.AGE_F07;
case 14: // AGE_F08
return Current.AGE_F08;
case 15: // AGE_F09
return Current.AGE_F09;
case 16: // AGE_F10
return Current.AGE_F10;
case 17: // AGE_F11
return Current.AGE_F11;
case 18: // AGE_F12
return Current.AGE_F12;
case 19: // AGE_F13
return Current.AGE_F13;
case 20: // AGE_F14
return Current.AGE_F14;
case 21: // AGE_F15
return Current.AGE_F15;
case 22: // AGE_F16
return Current.AGE_F16;
case 23: // AGE_F17
return Current.AGE_F17;
case 24: // AGE_F18
return Current.AGE_F18;
case 25: // AGE_F19
return Current.AGE_F19;
case 26: // AGE_F20
return Current.AGE_F20;
case 27: // AGE_M01
return Current.AGE_M01;
case 28: // AGE_M02
return Current.AGE_M02;
case 29: // AGE_M03
return Current.AGE_M03;
case 30: // AGE_M04
return Current.AGE_M04;
case 31: // AGE_M05
return Current.AGE_M05;
case 32: // AGE_M06
return Current.AGE_M06;
case 33: // AGE_M07
return Current.AGE_M07;
case 34: // AGE_M08
return Current.AGE_M08;
case 35: // AGE_M09
return Current.AGE_M09;
case 36: // AGE_M10
return Current.AGE_M10;
case 37: // AGE_M11
return Current.AGE_M11;
case 38: // AGE_M12
return Current.AGE_M12;
case 39: // AGE_M13
return Current.AGE_M13;
case 40: // AGE_M14
return Current.AGE_M14;
case 41: // AGE_M15
return Current.AGE_M15;
case 42: // AGE_M16
return Current.AGE_M16;
case 43: // AGE_M17
return Current.AGE_M17;
case 44: // AGE_M18
return Current.AGE_M18;
case 45: // AGE_M19
return Current.AGE_M19;
case 46: // AGE_M20
return Current.AGE_M20;
case 47: // SELF_DESCRIBED
return Current.SELF_DESCRIBED;
case 48: // AGE_S01
return Current.AGE_S01;
case 49: // AGE_S02
return Current.AGE_S02;
case 50: // AGE_S03
return Current.AGE_S03;
case 51: // AGE_S04
return Current.AGE_S04;
case 52: // AGE_S05
return Current.AGE_S05;
case 53: // AGE_S06
return Current.AGE_S06;
case 54: // AGE_S07
return Current.AGE_S07;
case 55: // AGE_S08
return Current.AGE_S08;
case 56: // AGE_S09
return Current.AGE_S09;
case 57: // AGE_S10
return Current.AGE_S10;
case 58: // AGE_S11
return Current.AGE_S11;
case 59: // AGE_S12
return Current.AGE_S12;
case 60: // AGE_S13
return Current.AGE_S13;
case 61: // AGE_S14
return Current.AGE_S14;
case 62: // AGE_S15
return Current.AGE_S15;
case 63: // AGE_S16
return Current.AGE_S16;
case 64: // AGE_S17
return Current.AGE_S17;
case 65: // AGE_S18
return Current.AGE_S18;
case 66: // AGE_S19
return Current.AGE_S19;
case 67: // AGE_S20
return Current.AGE_S20;
case 68: // LW_DATE
return Current.LW_DATE;
case 69: // LW_TIME
return Current.LW_TIME;
case 70: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // DESCRIPTION
return Current.DESCRIPTION == null;
case 2: // CAMPUS
return Current.CAMPUS == null;
case 3: // ACTIVE
return Current.ACTIVE == null;
case 4: // HOUSE_SIZE
return Current.HOUSE_SIZE == null;
case 5: // MALES
return Current.MALES == null;
case 6: // FEMALES
return Current.FEMALES == null;
case 7: // AGE_F01
return Current.AGE_F01 == null;
case 8: // AGE_F02
return Current.AGE_F02 == null;
case 9: // AGE_F03
return Current.AGE_F03 == null;
case 10: // AGE_F04
return Current.AGE_F04 == null;
case 11: // AGE_F05
return Current.AGE_F05 == null;
case 12: // AGE_F06
return Current.AGE_F06 == null;
case 13: // AGE_F07
return Current.AGE_F07 == null;
case 14: // AGE_F08
return Current.AGE_F08 == null;
case 15: // AGE_F09
return Current.AGE_F09 == null;
case 16: // AGE_F10
return Current.AGE_F10 == null;
case 17: // AGE_F11
return Current.AGE_F11 == null;
case 18: // AGE_F12
return Current.AGE_F12 == null;
case 19: // AGE_F13
return Current.AGE_F13 == null;
case 20: // AGE_F14
return Current.AGE_F14 == null;
case 21: // AGE_F15
return Current.AGE_F15 == null;
case 22: // AGE_F16
return Current.AGE_F16 == null;
case 23: // AGE_F17
return Current.AGE_F17 == null;
case 24: // AGE_F18
return Current.AGE_F18 == null;
case 25: // AGE_F19
return Current.AGE_F19 == null;
case 26: // AGE_F20
return Current.AGE_F20 == null;
case 27: // AGE_M01
return Current.AGE_M01 == null;
case 28: // AGE_M02
return Current.AGE_M02 == null;
case 29: // AGE_M03
return Current.AGE_M03 == null;
case 30: // AGE_M04
return Current.AGE_M04 == null;
case 31: // AGE_M05
return Current.AGE_M05 == null;
case 32: // AGE_M06
return Current.AGE_M06 == null;
case 33: // AGE_M07
return Current.AGE_M07 == null;
case 34: // AGE_M08
return Current.AGE_M08 == null;
case 35: // AGE_M09
return Current.AGE_M09 == null;
case 36: // AGE_M10
return Current.AGE_M10 == null;
case 37: // AGE_M11
return Current.AGE_M11 == null;
case 38: // AGE_M12
return Current.AGE_M12 == null;
case 39: // AGE_M13
return Current.AGE_M13 == null;
case 40: // AGE_M14
return Current.AGE_M14 == null;
case 41: // AGE_M15
return Current.AGE_M15 == null;
case 42: // AGE_M16
return Current.AGE_M16 == null;
case 43: // AGE_M17
return Current.AGE_M17 == null;
case 44: // AGE_M18
return Current.AGE_M18 == null;
case 45: // AGE_M19
return Current.AGE_M19 == null;
case 46: // AGE_M20
return Current.AGE_M20 == null;
case 47: // SELF_DESCRIBED
return Current.SELF_DESCRIBED == null;
case 48: // AGE_S01
return Current.AGE_S01 == null;
case 49: // AGE_S02
return Current.AGE_S02 == null;
case 50: // AGE_S03
return Current.AGE_S03 == null;
case 51: // AGE_S04
return Current.AGE_S04 == null;
case 52: // AGE_S05
return Current.AGE_S05 == null;
case 53: // AGE_S06
return Current.AGE_S06 == null;
case 54: // AGE_S07
return Current.AGE_S07 == null;
case 55: // AGE_S08
return Current.AGE_S08 == null;
case 56: // AGE_S09
return Current.AGE_S09 == null;
case 57: // AGE_S10
return Current.AGE_S10 == null;
case 58: // AGE_S11
return Current.AGE_S11 == null;
case 59: // AGE_S12
return Current.AGE_S12 == null;
case 60: // AGE_S13
return Current.AGE_S13 == null;
case 61: // AGE_S14
return Current.AGE_S14 == null;
case 62: // AGE_S15
return Current.AGE_S15 == null;
case 63: // AGE_S16
return Current.AGE_S16 == null;
case 64: // AGE_S17
return Current.AGE_S17 == null;
case 65: // AGE_S18
return Current.AGE_S18 == null;
case 66: // AGE_S19
return Current.AGE_S19 == null;
case 67: // AGE_S20
return Current.AGE_S20 == null;
case 68: // LW_DATE
return Current.LW_DATE == null;
case 69: // LW_TIME
return Current.LW_TIME == null;
case 70: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // KGHKEY
return "KGHKEY";
case 1: // DESCRIPTION
return "DESCRIPTION";
case 2: // CAMPUS
return "CAMPUS";
case 3: // ACTIVE
return "ACTIVE";
case 4: // HOUSE_SIZE
return "HOUSE_SIZE";
case 5: // MALES
return "MALES";
case 6: // FEMALES
return "FEMALES";
case 7: // AGE_F01
return "AGE_F01";
case 8: // AGE_F02
return "AGE_F02";
case 9: // AGE_F03
return "AGE_F03";
case 10: // AGE_F04
return "AGE_F04";
case 11: // AGE_F05
return "AGE_F05";
case 12: // AGE_F06
return "AGE_F06";
case 13: // AGE_F07
return "AGE_F07";
case 14: // AGE_F08
return "AGE_F08";
case 15: // AGE_F09
return "AGE_F09";
case 16: // AGE_F10
return "AGE_F10";
case 17: // AGE_F11
return "AGE_F11";
case 18: // AGE_F12
return "AGE_F12";
case 19: // AGE_F13
return "AGE_F13";
case 20: // AGE_F14
return "AGE_F14";
case 21: // AGE_F15
return "AGE_F15";
case 22: // AGE_F16
return "AGE_F16";
case 23: // AGE_F17
return "AGE_F17";
case 24: // AGE_F18
return "AGE_F18";
case 25: // AGE_F19
return "AGE_F19";
case 26: // AGE_F20
return "AGE_F20";
case 27: // AGE_M01
return "AGE_M01";
case 28: // AGE_M02
return "AGE_M02";
case 29: // AGE_M03
return "AGE_M03";
case 30: // AGE_M04
return "AGE_M04";
case 31: // AGE_M05
return "AGE_M05";
case 32: // AGE_M06
return "AGE_M06";
case 33: // AGE_M07
return "AGE_M07";
case 34: // AGE_M08
return "AGE_M08";
case 35: // AGE_M09
return "AGE_M09";
case 36: // AGE_M10
return "AGE_M10";
case 37: // AGE_M11
return "AGE_M11";
case 38: // AGE_M12
return "AGE_M12";
case 39: // AGE_M13
return "AGE_M13";
case 40: // AGE_M14
return "AGE_M14";
case 41: // AGE_M15
return "AGE_M15";
case 42: // AGE_M16
return "AGE_M16";
case 43: // AGE_M17
return "AGE_M17";
case 44: // AGE_M18
return "AGE_M18";
case 45: // AGE_M19
return "AGE_M19";
case 46: // AGE_M20
return "AGE_M20";
case 47: // SELF_DESCRIBED
return "SELF_DESCRIBED";
case 48: // AGE_S01
return "AGE_S01";
case 49: // AGE_S02
return "AGE_S02";
case 50: // AGE_S03
return "AGE_S03";
case 51: // AGE_S04
return "AGE_S04";
case 52: // AGE_S05
return "AGE_S05";
case 53: // AGE_S06
return "AGE_S06";
case 54: // AGE_S07
return "AGE_S07";
case 55: // AGE_S08
return "AGE_S08";
case 56: // AGE_S09
return "AGE_S09";
case 57: // AGE_S10
return "AGE_S10";
case 58: // AGE_S11
return "AGE_S11";
case 59: // AGE_S12
return "AGE_S12";
case 60: // AGE_S13
return "AGE_S13";
case 61: // AGE_S14
return "AGE_S14";
case 62: // AGE_S15
return "AGE_S15";
case 63: // AGE_S16
return "AGE_S16";
case 64: // AGE_S17
return "AGE_S17";
case 65: // AGE_S18
return "AGE_S18";
case 66: // AGE_S19
return "AGE_S19";
case 67: // AGE_S20
return "AGE_S20";
case 68: // LW_DATE
return "LW_DATE";
case 69: // LW_TIME
return "LW_TIME";
case 70: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "KGHKEY":
return 0;
case "DESCRIPTION":
return 1;
case "CAMPUS":
return 2;
case "ACTIVE":
return 3;
case "HOUSE_SIZE":
return 4;
case "MALES":
return 5;
case "FEMALES":
return 6;
case "AGE_F01":
return 7;
case "AGE_F02":
return 8;
case "AGE_F03":
return 9;
case "AGE_F04":
return 10;
case "AGE_F05":
return 11;
case "AGE_F06":
return 12;
case "AGE_F07":
return 13;
case "AGE_F08":
return 14;
case "AGE_F09":
return 15;
case "AGE_F10":
return 16;
case "AGE_F11":
return 17;
case "AGE_F12":
return 18;
case "AGE_F13":
return 19;
case "AGE_F14":
return 20;
case "AGE_F15":
return 21;
case "AGE_F16":
return 22;
case "AGE_F17":
return 23;
case "AGE_F18":
return 24;
case "AGE_F19":
return 25;
case "AGE_F20":
return 26;
case "AGE_M01":
return 27;
case "AGE_M02":
return 28;
case "AGE_M03":
return 29;
case "AGE_M04":
return 30;
case "AGE_M05":
return 31;
case "AGE_M06":
return 32;
case "AGE_M07":
return 33;
case "AGE_M08":
return 34;
case "AGE_M09":
return 35;
case "AGE_M10":
return 36;
case "AGE_M11":
return 37;
case "AGE_M12":
return 38;
case "AGE_M13":
return 39;
case "AGE_M14":
return 40;
case "AGE_M15":
return 41;
case "AGE_M16":
return 42;
case "AGE_M17":
return 43;
case "AGE_M18":
return 44;
case "AGE_M19":
return 45;
case "AGE_M20":
return 46;
case "SELF_DESCRIBED":
return 47;
case "AGE_S01":
return 48;
case "AGE_S02":
return 49;
case "AGE_S03":
return 50;
case "AGE_S04":
return 51;
case "AGE_S05":
return 52;
case "AGE_S06":
return 53;
case "AGE_S07":
return 54;
case "AGE_S08":
return 55;
case "AGE_S09":
return 56;
case "AGE_S10":
return 57;
case "AGE_S11":
return 58;
case "AGE_S12":
return 59;
case "AGE_S13":
return 60;
case "AGE_S14":
return 61;
case "AGE_S15":
return 62;
case "AGE_S16":
return 63;
case "AGE_S17":
return 64;
case "AGE_S18":
return 65;
case "AGE_S19":
return 66;
case "AGE_S20":
return 67;
case "LW_DATE":
return 68;
case "LW_TIME":
return 69;
case "LW_USER":
return 70;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using Fairweather.Service;
namespace Common.Sage
{
public static partial class Sage_Fields
{
public static class StockRecord
{
static public Array_ro<Sage_Field> Barcode_Fields {
get {
return new[] {
COMMODITY_CODE,
CUSTOM_1,
CUSTOM_2,
CUSTOM_3,
LOCATION,
SUPPLIER_PART_NUMBER,
WEB_DESCRIPTION,
WEB_LONGDESCRIPTION,
WEB_IMAGE
};
}
}
// autogenerated: C:\Users\Fairweather\Desktop\sage_strings.pl
public static readonly Sage_Field
ASSEMBLY_LEVEL = Short("ASSEMBLY_LEVEL", "Assembly Level", 2) // Opt
, AVERAGE_COST_PRICE = Double("AVERAGE_COST_PRICE", "Average Cost Price", 8) // Opt
, BUDGET_QTY_SOLD_BF = Double("BUDGET_QTY_SOLD_BF", "Brought Forward Budget Quantity Sold", 8) // Opt
, BUDGET_QTY_SOLD_FUTURE = Double("BUDGET_QTY_SOLD_FUTURE", "Future Budget Quantity Sold", 8) // Opt
, BUDGET_QTY_SOLD_MTH1 = Double("BUDGET_QTY_SOLD_MTH1", "Month 1 Budget Quantity Sold", 8) // Opt
, BUDGET_QTY_SOLD_MTH10 = Double("BUDGET_QTY_SOLD_MTH10", "Month 10 Budget Quantity Sold", 8) // Opt
, BUDGET_QTY_SOLD_MTH11 = Double("BUDGET_QTY_SOLD_MTH11", "Month 11 Budget Quantity Sold", 8) // Opt
, BUDGET_QTY_SOLD_MTH12 = Double("BUDGET_QTY_SOLD_MTH12", "Month 12 Budget Quantity Sold", 8) // Opt
, BUDGET_QTY_SOLD_MTH2 = Double("BUDGET_QTY_SOLD_MTH2", "Month 2 Budget Quantity Sold", 8) // Opt
, BUDGET_QTY_SOLD_MTH3 = Double("BUDGET_QTY_SOLD_MTH3", "Month 3 Budget Quantity Sold", 8) // Opt
, BUDGET_QTY_SOLD_MTH4 = Double("BUDGET_QTY_SOLD_MTH4", "Month 4 Budget Quantity Sold", 8) // Opt
, BUDGET_QTY_SOLD_MTH5 = Double("BUDGET_QTY_SOLD_MTH5", "Month 5 Budget Quantity Sold", 8) // Opt
, BUDGET_QTY_SOLD_MTH6 = Double("BUDGET_QTY_SOLD_MTH6", "Month 6 Budget Quantity Sold", 8) // Opt
, BUDGET_QTY_SOLD_MTH7 = Double("BUDGET_QTY_SOLD_MTH7", "Month 7 Budget Quantity Sold", 8) // Opt
, BUDGET_QTY_SOLD_MTH8 = Double("BUDGET_QTY_SOLD_MTH8", "Month 8 Budget Quantity Sold", 8) // Opt
, BUDGET_QTY_SOLD_MTH9 = Double("BUDGET_QTY_SOLD_MTH9", "Month 9 Budget Quantity Sold", 8) // Opt
, BUDGET_SALES_BF = Double("BUDGET_SALES_BF", "Brought Forward Budget Sales", 8) // Opt
, BUDGET_SALES_FUTURE = Double("BUDGET_SALES_FUTURE", "Future Budget Sales", 8) // Opt
, BUDGET_SALES_MTH1 = Double("BUDGET_SALES_MTH1", "Month 1 Budget Sales", 8) // Opt
, BUDGET_SALES_MTH10 = Double("BUDGET_SALES_MTH10", "Month 10 Budget Sales", 8) // Opt
, BUDGET_SALES_MTH11 = Double("BUDGET_SALES_MTH11", "Month 11 Budget Sales", 8) // Opt
, BUDGET_SALES_MTH12 = Double("BUDGET_SALES_MTH12", "Month 12 Budget Sales", 8) // Opt
, BUDGET_SALES_MTH2 = Double("BUDGET_SALES_MTH2", "Month 2 Budget Sales", 8) // Opt
, BUDGET_SALES_MTH3 = Double("BUDGET_SALES_MTH3", "Month 3 Budget Sales", 8) // Opt
, BUDGET_SALES_MTH4 = Double("BUDGET_SALES_MTH4", "Month 4 Budget Sales", 8) // Opt
, BUDGET_SALES_MTH5 = Double("BUDGET_SALES_MTH5", "Month 5 Budget Sales", 8) // Opt
, BUDGET_SALES_MTH6 = Double("BUDGET_SALES_MTH6", "Month 6 Budget Sales", 8) // Opt
, BUDGET_SALES_MTH7 = Double("BUDGET_SALES_MTH7", "Month 7 Budget Sales", 8) // Opt
, BUDGET_SALES_MTH8 = Double("BUDGET_SALES_MTH8", "Month 8 Budget Sales", 8) // Opt
, BUDGET_SALES_MTH9 = Double("BUDGET_SALES_MTH9", "Month 9 Budget Sales", 8) // Opt
, COMMODITY_CODE = String("COMMODITY_CODE", "Commodity Code", 30) // Opt
, COMPONENT_CODE_1 = String("COMPONENT_CODE_1", "Component Stock Code 1", 30) // Opt
, COMPONENT_CODE_10 = String("COMPONENT_CODE_10", "Component Stock Code 10", 30) // Opt
, COMPONENT_CODE_2 = String("COMPONENT_CODE_2", "Component Stock Code 2", 30) // Opt
, COMPONENT_CODE_3 = String("COMPONENT_CODE_3", "Component Stock Code 3", 30) // Opt
, COMPONENT_CODE_4 = String("COMPONENT_CODE_4", "Component Stock Code 4", 30) // Opt
, COMPONENT_CODE_5 = String("COMPONENT_CODE_5", "Component Stock Code 5", 30) // Opt
, COMPONENT_CODE_6 = String("COMPONENT_CODE_6", "Component Stock Code 6", 30) // Opt
, COMPONENT_CODE_7 = String("COMPONENT_CODE_7", "Component Stock Code 7", 30) // Opt
, COMPONENT_CODE_8 = String("COMPONENT_CODE_8", "Component Stock Code 8", 30) // Opt
, COMPONENT_CODE_9 = String("COMPONENT_CODE_9", "Component Stock Code 9", 30) // Opt
, COMPONENT_QTY_1 = Double("COMPONENT_QTY_1", "Component 1 Quantity", 8) // Opt
, COMPONENT_QTY_10 = Double("COMPONENT_QTY_10", "Component 10 Quantity", 8) // Opt
, COMPONENT_QTY_2 = Double("COMPONENT_QTY_2", "Component 2 Quantity", 8) // Opt
, COMPONENT_QTY_3 = Double("COMPONENT_QTY_3", "Component 3 Quantity", 8) // Opt
, COMPONENT_QTY_4 = Double("COMPONENT_QTY_4", "Component 4 Quantity", 8) // Opt
, COMPONENT_QTY_5 = Double("COMPONENT_QTY_5", "Component 5 Quantity", 8) // Opt
, COMPONENT_QTY_6 = Double("COMPONENT_QTY_6", "Component 6 Quantity", 8) // Opt
, COMPONENT_QTY_7 = Double("COMPONENT_QTY_7", "Component 7 Quantity", 8) // Opt
, COMPONENT_QTY_8 = Double("COMPONENT_QTY_8", "Component 8 Quantity", 8) // Opt
, COMPONENT_QTY_9 = Double("COMPONENT_QTY_9", "Component 9 Quantity", 8) // Opt
, COST_BF = Double("COST_BF", "Brought Forward Costs", 8) // Opt
, COST_FUTURE = Double("COST_FUTURE", "Future Costs", 8) // Opt
, COST_MTH1 = Double("COST_MTH1", "Month 1 Costs", 8) // Opt
, COST_MTH10 = Double("COST_MTH10", "Month 10 Costs", 8) // Opt
, COST_MTH11 = Double("COST_MTH11", "Month 11 Costs", 8) // Opt
, COST_MTH12 = Double("COST_MTH12", "Month 12 Costs", 8) // Opt
, COST_MTH2 = Double("COST_MTH2", "Month 2 Costs", 8) // Opt
, COST_MTH3 = Double("COST_MTH3", "Month 3 Costs", 8) // Opt
, COST_MTH4 = Double("COST_MTH4", "Month 4 Costs", 8) // Opt
, COST_MTH5 = Double("COST_MTH5", "Month 5 Costs", 8) // Opt
, COST_MTH6 = Double("COST_MTH6", "Month 6 Costs", 8) // Opt
, COST_MTH7 = Double("COST_MTH7", "Month 7 Costs", 8) // Opt
, COST_MTH8 = Double("COST_MTH8", "Month 8 Costs", 8) // Opt
, COST_MTH9 = Double("COST_MTH9", "Month 9 Costs", 8) // Opt
, CUSTOM_1 = String("CUSTOM_1", "Custom Field 1", 60) // Opt
, CUSTOM_2 = String("CUSTOM_2", "Custom Field 2", 60) // Opt
, CUSTOM_3 = String("CUSTOM_3", "Custom Field 3", 60) // Opt
, DELETED_FLAG = Short("DELETED_FLAG", "Reserved for Future Use", 2) // Opt
, DEPT_NUMBER = Short("DEPT_NUMBER", "Department Number", 2) // Opt
, DESCRIPTION = String("DESCRIPTION", "Description", 60) // Opt
, DISC_A_LEVEL_10_QTY = Double("DISC_A_LEVEL_10_QTY", "Discount Table A, Break Level 10, Quantity", 8) // Opt
, DISC_A_LEVEL_10_RATE = Double("DISC_A_LEVEL_10_RATE", "Discount Table A, Break Level 10, Rate", 8) // Opt
, DISC_A_LEVEL_1_QTY = Double("DISC_A_LEVEL_1_QTY", "Discount Table A, Break Level 1, Quantity", 8) // Opt
, DISC_A_LEVEL_1_RATE = Double("DISC_A_LEVEL_1_RATE", "Discount Table A, Break Level 1, Rate", 8) // Opt
, DISC_A_LEVEL_2_QTY = Double("DISC_A_LEVEL_2_QTY", "Discount Table A, Break Level 2, Quantity", 8) // Opt
, DISC_A_LEVEL_2_RATE = Double("DISC_A_LEVEL_2_RATE", "Discount Table A, Break Level 2, Rate", 8) // Opt
, DISC_A_LEVEL_3_QTY = Double("DISC_A_LEVEL_3_QTY", "Discount Table A, Break Level 3, Quantity", 8) // Opt
, DISC_A_LEVEL_3_RATE = Double("DISC_A_LEVEL_3_RATE", "Discount Table A, Break Level 3, Rate", 8) // Opt
, DISC_A_LEVEL_4_QTY = Double("DISC_A_LEVEL_4_QTY", "Discount Table A, Break Level 4, Quantity", 8) // Opt
, DISC_A_LEVEL_4_RATE = Double("DISC_A_LEVEL_4_RATE", "Discount Table A, Break Level 4, Rate", 8) // Opt
, DISC_A_LEVEL_5_QTY = Double("DISC_A_LEVEL_5_QTY", "Discount Table A, Break Level 5, Quantity", 8) // Opt
, DISC_A_LEVEL_5_RATE = Double("DISC_A_LEVEL_5_RATE", "Discount Table A, Break Level 5, Rate", 8) // Opt
, DISC_A_LEVEL_6_QTY = Double("DISC_A_LEVEL_6_QTY", "Discount Table A, Break Level 6, Quantity", 8) // Opt
, DISC_A_LEVEL_6_RATE = Double("DISC_A_LEVEL_6_RATE", "Discount Table A, Break Level 6, Rate", 8) // Opt
, DISC_A_LEVEL_7_QTY = Double("DISC_A_LEVEL_7_QTY", "Discount Table A, Break Level 7, Quantity", 8) // Opt
, DISC_A_LEVEL_7_RATE = Double("DISC_A_LEVEL_7_RATE", "Discount Table A, Break Level 7, Rate", 8) // Opt
, DISC_A_LEVEL_8_QTY = Double("DISC_A_LEVEL_8_QTY", "Discount Table A, Break Level 8, Quantity", 8) // Opt
, DISC_A_LEVEL_8_RATE = Double("DISC_A_LEVEL_8_RATE", "Discount Table A, Break Level 8, Rate", 8) // Opt
, DISC_A_LEVEL_9_QTY = Double("DISC_A_LEVEL_9_QTY", "Discount Table A, Break Level 9, Quantity", 8) // Opt
, DISC_A_LEVEL_9_RATE = Double("DISC_A_LEVEL_9_RATE", "Discount Table A, Break Level 9, Rate", 8) // Opt
, DISC_B_LEVEL_10_QTY = Double("DISC_B_LEVEL_10_QTY", "Discount Table B, Break Level 10, Quantity", 8) // Opt
, DISC_B_LEVEL_10_RATE = Double("DISC_B_LEVEL_10_RATE", "Discount Table B, Break Level 10, Rate", 8) // Opt
, DISC_B_LEVEL_1_QTY = Double("DISC_B_LEVEL_1_QTY", "Discount Table B, Break Level 1, Quantity", 8) // Opt
, DISC_B_LEVEL_1_RATE = Double("DISC_B_LEVEL_1_RATE", "Discount Table B, Break Level 1, Rate", 8) // Opt
, DISC_B_LEVEL_2_QTY = Double("DISC_B_LEVEL_2_QTY", "Discount Table B, Break Level 2, Quantity", 8) // Opt
, DISC_B_LEVEL_2_RATE = Double("DISC_B_LEVEL_2_RATE", "Discount Table B, Break Level 2, Rate", 8) // Opt
, DISC_B_LEVEL_3_QTY = Double("DISC_B_LEVEL_3_QTY", "Discount Table B, Break Level 3, Quantity", 8) // Opt
, DISC_B_LEVEL_3_RATE = Double("DISC_B_LEVEL_3_RATE", "Discount Table B, Break Level 3, Rate", 8) // Opt
, DISC_B_LEVEL_4_QTY = Double("DISC_B_LEVEL_4_QTY", "Discount Table B, Break Level 4, Quantity", 8) // Opt
, DISC_B_LEVEL_4_RATE = Double("DISC_B_LEVEL_4_RATE", "Discount Table B, Break Level 4, Rate", 8) // Opt
, DISC_B_LEVEL_5_QTY = Double("DISC_B_LEVEL_5_QTY", "Discount Table B, Break Level 5, Quantity", 8) // Opt
, DISC_B_LEVEL_5_RATE = Double("DISC_B_LEVEL_5_RATE", "Discount Table B, Break Level 5, Rate", 8) // Opt
, DISC_B_LEVEL_6_QTY = Double("DISC_B_LEVEL_6_QTY", "Discount Table B, Break Level 6, Quantity", 8) // Opt
, DISC_B_LEVEL_6_RATE = Double("DISC_B_LEVEL_6_RATE", "Discount Table B, Break Level 6, Rate", 8) // Opt
, DISC_B_LEVEL_7_QTY = Double("DISC_B_LEVEL_7_QTY", "Discount Table B, Break Level 7, Quantity", 8) // Opt
, DISC_B_LEVEL_7_RATE = Double("DISC_B_LEVEL_7_RATE", "Discount Table B, Break Level 7, Rate", 8) // Opt
, DISC_B_LEVEL_8_QTY = Double("DISC_B_LEVEL_8_QTY", "Discount Table B, Break Level 8, Quantity", 8) // Opt
, DISC_B_LEVEL_8_RATE = Double("DISC_B_LEVEL_8_RATE", "Discount Table B, Break Level 8, Rate", 8) // Opt
, DISC_B_LEVEL_9_QTY = Double("DISC_B_LEVEL_9_QTY", "Discount Table B, Break Level 9, Quantity", 8) // Opt
, DISC_B_LEVEL_9_RATE = Double("DISC_B_LEVEL_9_RATE", "Discount Table B, Break Level 9, Rate", 8) // Opt
, DISC_C_LEVEL_10_QTY = Double("DISC_C_LEVEL_10_QTY", "Discount Table C, Break Level 10, Quantity", 8) // Opt
, DISC_C_LEVEL_10_RATE = Double("DISC_C_LEVEL_10_RATE", "Discount Table C, Break Level 10, Rate", 8) // Opt
, DISC_C_LEVEL_1_QTY = Double("DISC_C_LEVEL_1_QTY", "Discount Table C, Break Level 1, Quantity", 8) // Opt
, DISC_C_LEVEL_1_RATE = Double("DISC_C_LEVEL_1_RATE", "Discount Table C, Break Level 1, Rate", 8) // Opt
, DISC_C_LEVEL_2_QTY = Double("DISC_C_LEVEL_2_QTY", "Discount Table C, Break Level 2, Quantity", 8) // Opt
, DISC_C_LEVEL_2_RATE = Double("DISC_C_LEVEL_2_RATE", "Discount Table C, Break Level 2, Rate", 8) // Opt
, DISC_C_LEVEL_3_QTY = Double("DISC_C_LEVEL_3_QTY", "Discount Table C, Break Level 3, Quantity", 8) // Opt
, DISC_C_LEVEL_3_RATE = Double("DISC_C_LEVEL_3_RATE", "Discount Table C, Break Level 3, Rate", 8) // Opt
, DISC_C_LEVEL_4_QTY = Double("DISC_C_LEVEL_4_QTY", "Discount Table C, Break Level 4, Quantity", 8) // Opt
, DISC_C_LEVEL_4_RATE = Double("DISC_C_LEVEL_4_RATE", "Discount Table C, Break Level 4, Rate", 8) // Opt
, DISC_C_LEVEL_5_QTY = Double("DISC_C_LEVEL_5_QTY", "Discount Table C, Break Level 5, Quantity", 8) // Opt
, DISC_C_LEVEL_5_RATE = Double("DISC_C_LEVEL_5_RATE", "Discount Table C, Break Level 5, Rate", 8) // Opt
, DISC_C_LEVEL_6_QTY = Double("DISC_C_LEVEL_6_QTY", "Discount Table C, Break Level 6, Quantity", 8) // Opt
, DISC_C_LEVEL_6_RATE = Double("DISC_C_LEVEL_6_RATE", "Discount Table C, Break Level 6, Rate", 8) // Opt
, DISC_C_LEVEL_7_QTY = Double("DISC_C_LEVEL_7_QTY", "Discount Table C, Break Level 7, Quantity", 8) // Opt
, DISC_C_LEVEL_7_RATE = Double("DISC_C_LEVEL_7_RATE", "Discount Table C, Break Level 7, Rate", 8) // Opt
, DISC_C_LEVEL_8_QTY = Double("DISC_C_LEVEL_8_QTY", "Discount Table C, Break Level 8, Quantity", 8) // Opt
, DISC_C_LEVEL_8_RATE = Double("DISC_C_LEVEL_8_RATE", "Discount Table C, Break Level 8, Rate", 8) // Opt
, DISC_C_LEVEL_9_QTY = Double("DISC_C_LEVEL_9_QTY", "Discount Table C, Break Level 9, Quantity", 8) // Opt
, DISC_C_LEVEL_9_RATE = Double("DISC_C_LEVEL_9_RATE", "Discount Table C, Break Level 9, Rate", 8) // Opt
, DISC_D_LEVEL_10_QTY = Double("DISC_D_LEVEL_10_QTY", "Discount Table D, Break Level 10, Quantity", 8) // Opt
, DISC_D_LEVEL_10_RATE = Double("DISC_D_LEVEL_10_RATE", "Discount Table D, Break Level 10, Rate", 8) // Opt
, DISC_D_LEVEL_1_QTY = Double("DISC_D_LEVEL_1_QTY", "Discount Table D, Break Level 1, Quantity", 8) // Opt
, DISC_D_LEVEL_1_RATE = Double("DISC_D_LEVEL_1_RATE", "Discount Table D, Break Level 1, Rate", 8) // Opt
, DISC_D_LEVEL_2_QTY = Double("DISC_D_LEVEL_2_QTY", "Discount Table D, Break Level 2, Quantity", 8) // Opt
, DISC_D_LEVEL_2_RATE = Double("DISC_D_LEVEL_2_RATE", "Discount Table D, Break Level 2, Rate", 8) // Opt
, DISC_D_LEVEL_3_QTY = Double("DISC_D_LEVEL_3_QTY", "Discount Table D, Break Level 3, Quantity", 8) // Opt
, DISC_D_LEVEL_3_RATE = Double("DISC_D_LEVEL_3_RATE", "Discount Table D, Break Level 3, Rate", 8) // Opt
, DISC_D_LEVEL_4_QTY = Double("DISC_D_LEVEL_4_QTY", "Discount Table D, Break Level 4, Quantity", 8) // Opt
, DISC_D_LEVEL_4_RATE = Double("DISC_D_LEVEL_4_RATE", "Discount Table D, Break Level 4, Rate", 8) // Opt
, DISC_D_LEVEL_5_QTY = Double("DISC_D_LEVEL_5_QTY", "Discount Table D, Break Level 5, Quantity", 8) // Opt
, DISC_D_LEVEL_5_RATE = Double("DISC_D_LEVEL_5_RATE", "Discount Table D, Break Level 5, Rate", 8) // Opt
, DISC_D_LEVEL_6_QTY = Double("DISC_D_LEVEL_6_QTY", "Discount Table D, Break Level 6, Quantity", 8) // Opt
, DISC_D_LEVEL_6_RATE = Double("DISC_D_LEVEL_6_RATE", "Discount Table D, Break Level 6, Rate", 8) // Opt
, DISC_D_LEVEL_7_QTY = Double("DISC_D_LEVEL_7_QTY", "Discount Table D, Break Level 7, Quantity", 8) // Opt
, DISC_D_LEVEL_7_RATE = Double("DISC_D_LEVEL_7_RATE", "Discount Table D, Break Level 7, Rate", 8) // Opt
, DISC_D_LEVEL_8_QTY = Double("DISC_D_LEVEL_8_QTY", "Discount Table D, Break Level 8, Quantity", 8) // Opt
, DISC_D_LEVEL_8_RATE = Double("DISC_D_LEVEL_8_RATE", "Discount Table D, Break Level 8, Rate", 8) // Opt
, DISC_D_LEVEL_9_QTY = Double("DISC_D_LEVEL_9_QTY", "Discount Table D, Break Level 9, Quantity", 8) // Opt
, DISC_D_LEVEL_9_RATE = Double("DISC_D_LEVEL_9_RATE", "Discount Table D, Break Level 9, Rate", 8) // Opt
, DISC_E_LEVEL_10_QTY = Double("DISC_E_LEVEL_10_QTY", "Discount Table E, Break Level 10, Quantity", 8) // Opt
, DISC_E_LEVEL_10_RATE = Double("DISC_E_LEVEL_10_RATE", "Discount Table E, Break Level 10, Rate", 8) // Opt
, DISC_E_LEVEL_1_QTY = Double("DISC_E_LEVEL_1_QTY", "Discount Table E, Break Level 1, Quantity", 8) // Opt
, DISC_E_LEVEL_1_RATE = Double("DISC_E_LEVEL_1_RATE", "Discount Table E, Break Level 1, Rate", 8) // Opt
, DISC_E_LEVEL_2_QTY = Double("DISC_E_LEVEL_2_QTY", "Discount Table E, Break Level 2, Quantity", 8) // Opt
, DISC_E_LEVEL_2_RATE = Double("DISC_E_LEVEL_2_RATE", "Discount Table E, Break Level 2, Rate", 8) // Opt
, DISC_E_LEVEL_3_QTY = Double("DISC_E_LEVEL_3_QTY", "Discount Table E, Break Level 3, Quantity", 8) // Opt
, DISC_E_LEVEL_3_RATE = Double("DISC_E_LEVEL_3_RATE", "Discount Table E, Break Level 3, Rate", 8) // Opt
, DISC_E_LEVEL_4_QTY = Double("DISC_E_LEVEL_4_QTY", "Discount Table E, Break Level 4, Quantity", 8) // Opt
, DISC_E_LEVEL_4_RATE = Double("DISC_E_LEVEL_4_RATE", "Discount Table E, Break Level 4, Rate", 8) // Opt
, DISC_E_LEVEL_5_QTY = Double("DISC_E_LEVEL_5_QTY", "Discount Table E, Break Level 5, Quantity", 8) // Opt
, DISC_E_LEVEL_5_RATE = Double("DISC_E_LEVEL_5_RATE", "Discount Table E, Break Level 5, Rate", 8) // Opt
, DISC_E_LEVEL_6_QTY = Double("DISC_E_LEVEL_6_QTY", "Discount Table E, Break Level 6, Quantity", 8) // Opt
, DISC_E_LEVEL_6_RATE = Double("DISC_E_LEVEL_6_RATE", "Discount Table E, Break Level 6, Rate", 8) // Opt
, DISC_E_LEVEL_7_QTY = Double("DISC_E_LEVEL_7_QTY", "Discount Table E, Break Level 7, Quantity", 8) // Opt
, DISC_E_LEVEL_7_RATE = Double("DISC_E_LEVEL_7_RATE", "Discount Table E, Break Level 7, Rate", 8) // Opt
, DISC_E_LEVEL_8_QTY = Double("DISC_E_LEVEL_8_QTY", "Discount Table E, Break Level 8, Quantity", 8) // Opt
, DISC_E_LEVEL_8_RATE = Double("DISC_E_LEVEL_8_RATE", "Discount Table E, Break Level 8, Rate", 8) // Opt
, DISC_E_LEVEL_9_QTY = Double("DISC_E_LEVEL_9_QTY", "Discount Table E, Break Level 9, Quantity", 8) // Opt
, DISC_E_LEVEL_9_RATE = Double("DISC_E_LEVEL_9_RATE", "Discount Table E, Break Level 9, Rate", 8) // Opt
, EXTERNAL_USAGE = Int("EXTERNAL_USAGE", "Number of External Usages", 4) // Opt
, FIRST_TRAN = Int("FIRST_TRAN", "Record Number of First Transaction", 4) // Opt
, IGNORE_STK_LVL_FLAG = SByte("IGNORE_STK_LVL_FLAG", "Ignore Stock Levels Flag", 1) // Opt
, ITEM_TYPE = SByte("ITEM_TYPE", "Item Type", 1) // Opt
, LAST_PURCHASE_DATE = Date("LAST_PURCHASE_DATE", "Last Purchase Date", 2) // Opt
, LAST_PURCHASE_PRICE = Double("LAST_PURCHASE_PRICE", "Last Purchase Price", 8) // Opt
, LAST_SALE_DATE = Date("LAST_SALE_DATE", "Last Sales Date", 2) // Opt
, LAST_TRAN = Int("LAST_TRAN", "Record Number of Last Transaction", 4) // Opt
, LINK_LEVEL = Short("LINK_LEVEL", "Link Level", 2) // Opt
, LOCATION = String("LOCATION", "Location", 16) // Opt
, NO_OF_TRAN = Int("NO_OF_TRAN", "Number of Transactions", 4) // Opt
, NOMINAL_CODE = String("NOMINAL_CODE", "Nominal Code", 8) // Opt
, PRIOR_YR_COST_BF = Double("PRIOR_YR_COST_BF", "Prior Year Brought Forward Costs", 8) // Opt
, PRIOR_YR_COST_FUTURE = Double("PRIOR_YR_COST_FUTURE", "Prior Year Future Costs", 8) // Opt
, PRIOR_YR_COST_MTH1 = Double("PRIOR_YR_COST_MTH1", "Prior Year Month 1 Costs", 8) // Opt
, PRIOR_YR_COST_MTH10 = Double("PRIOR_YR_COST_MTH10", "Prior Year Month 10 Costs", 8) // Opt
, PRIOR_YR_COST_MTH11 = Double("PRIOR_YR_COST_MTH11", "Prior Year Month 11 Costs", 8) // Opt
, PRIOR_YR_COST_MTH12 = Double("PRIOR_YR_COST_MTH12", "Prior Year Month 12 Costs", 8) // Opt
, PRIOR_YR_COST_MTH2 = Double("PRIOR_YR_COST_MTH2", "Prior Year Month 2 Costs", 8) // Opt
, PRIOR_YR_COST_MTH3 = Double("PRIOR_YR_COST_MTH3", "Prior Year Month 3 Costs", 8) // Opt
, PRIOR_YR_COST_MTH4 = Double("PRIOR_YR_COST_MTH4", "Prior Year Month 4 Costs", 8) // Opt
, PRIOR_YR_COST_MTH5 = Double("PRIOR_YR_COST_MTH5", "Prior Year Month 5 Costs", 8) // Opt
, PRIOR_YR_COST_MTH6 = Double("PRIOR_YR_COST_MTH6", "Prior Year Month 6 Costs", 8) // Opt
, PRIOR_YR_COST_MTH7 = Double("PRIOR_YR_COST_MTH7", "Prior Year Month 7 Costs", 8) // Opt
, PRIOR_YR_COST_MTH8 = Double("PRIOR_YR_COST_MTH8", "Prior Year Month 8 Costs", 8) // Opt
, PRIOR_YR_COST_MTH9 = Double("PRIOR_YR_COST_MTH9", "Prior Year Month 9 Costs", 8) // Opt
, PRIOR_YR_QTY_SOLD_BF = Double("PRIOR_YR_QTY_SOLD_BF", "Prior Year Brought Forward Quantity Sold", 8) // Opt
, PRIOR_YR_QTY_SOLD_FUTURE = Double("PRIOR_YR_QTY_SOLD_FUTURE", "Prior Year Future Quantity Sold", 8) // Opt
, PRIOR_YR_QTY_SOLD_MTH1 = Double("PRIOR_YR_QTY_SOLD_MTH1", "Prior Year Month 1 Quantity Sold", 8) // Opt
, PRIOR_YR_QTY_SOLD_MTH10 = Double("PRIOR_YR_QTY_SOLD_MTH10", "Prior Year Month 10 Quantity Sold", 8) // Opt
, PRIOR_YR_QTY_SOLD_MTH11 = Double("PRIOR_YR_QTY_SOLD_MTH11", "Prior Year Month 11 Quantity Sold", 8) // Opt
, PRIOR_YR_QTY_SOLD_MTH12 = Double("PRIOR_YR_QTY_SOLD_MTH12", "Prior Year Month 12 Quantity Sold", 8) // Opt
, PRIOR_YR_QTY_SOLD_MTH2 = Double("PRIOR_YR_QTY_SOLD_MTH2", "Prior Year Month 2 Quantity Sold", 8) // Opt
, PRIOR_YR_QTY_SOLD_MTH3 = Double("PRIOR_YR_QTY_SOLD_MTH3", "Prior Year Month 3 Quantity Sold", 8) // Opt
, PRIOR_YR_QTY_SOLD_MTH4 = Double("PRIOR_YR_QTY_SOLD_MTH4", "Prior Year Month 4 Quantity Sold", 8) // Opt
, PRIOR_YR_QTY_SOLD_MTH5 = Double("PRIOR_YR_QTY_SOLD_MTH5", "Prior Year Month 5 Quantity Sold", 8) // Opt
, PRIOR_YR_QTY_SOLD_MTH6 = Double("PRIOR_YR_QTY_SOLD_MTH6", "Prior Year Month 6 Quantity Sold", 8) // Opt
, PRIOR_YR_QTY_SOLD_MTH7 = Double("PRIOR_YR_QTY_SOLD_MTH7", "Prior Year Month 7 Quantity Sold", 8) // Opt
, PRIOR_YR_QTY_SOLD_MTH8 = Double("PRIOR_YR_QTY_SOLD_MTH8", "Prior Year Month 8 Quantity Sold", 8) // Opt
, PRIOR_YR_QTY_SOLD_MTH9 = Double("PRIOR_YR_QTY_SOLD_MTH9", "Prior Year Month 9 Quantity Sold", 8) // Opt
, PRIOR_YR_SALES_BF = Double("PRIOR_YR_SALES_BF", "Prior Year Brought Forward Sales", 8) // Opt
, PRIOR_YR_SALES_FUTURE = Double("PRIOR_YR_SALES_FUTURE", "Prior Year Future Sales", 8) // Opt
, PRIOR_YR_SALES_MTH1 = Double("PRIOR_YR_SALES_MTH1", "Prior Year Month 1 Sales", 8) // Opt
, PRIOR_YR_SALES_MTH10 = Double("PRIOR_YR_SALES_MTH10", "Prior Year Month 10 Sales", 8) // Opt
, PRIOR_YR_SALES_MTH11 = Double("PRIOR_YR_SALES_MTH11", "Prior Year Month 11 Sales", 8) // Opt
, PRIOR_YR_SALES_MTH12 = Double("PRIOR_YR_SALES_MTH12", "Prior Year Month 12 Sales", 8) // Opt
, PRIOR_YR_SALES_MTH2 = Double("PRIOR_YR_SALES_MTH2", "Prior Year Month 2 Sales", 8) // Opt
, PRIOR_YR_SALES_MTH3 = Double("PRIOR_YR_SALES_MTH3", "Prior Year Month 3 Sales", 8) // Opt
, PRIOR_YR_SALES_MTH4 = Double("PRIOR_YR_SALES_MTH4", "Prior Year Month 4 Sales", 8) // Opt
, PRIOR_YR_SALES_MTH5 = Double("PRIOR_YR_SALES_MTH5", "Prior Year Month 5 Sales", 8) // Opt
, PRIOR_YR_SALES_MTH6 = Double("PRIOR_YR_SALES_MTH6", "Prior Year Month 6 Sales", 8) // Opt
, PRIOR_YR_SALES_MTH7 = Double("PRIOR_YR_SALES_MTH7", "Prior Year Month 7 Sales", 8) // Opt
, PRIOR_YR_SALES_MTH8 = Double("PRIOR_YR_SALES_MTH8", "Prior Year Month 8 Sales", 8) // Opt
, PRIOR_YR_SALES_MTH9 = Double("PRIOR_YR_SALES_MTH9", "Prior Year Month 9 Sales", 8) // Opt
, PURCHASE_REF = String("PURCHASE_REF", "Supplier's Account Reference", 8) // Opt
, QTY_ALLOCATED = Double("QTY_ALLOCATED", "Quantity Allocated", 8) // Opt
, QTY_IN_STOCK = Double("QTY_IN_STOCK", "Quantity In Stock", 8) // Opt
, QTY_LAST_ORDER = Double("QTY_LAST_ORDER", "Last Order Quantity", 8) // Opt
, QTY_LAST_STOCK_TAKE = Double("QTY_LAST_STOCK_TAKE", "Last Stock Take Quantity", 8) // Opt
, QTY_ON_ORDER = Double("QTY_ON_ORDER", "Quantity On Order", 8) // Opt
, QTY_REORDER = Double("QTY_REORDER", "Reorder Quantity", 8) // Opt
, QTY_REORDER_LEVEL = Double("QTY_REORDER_LEVEL", "Reorder Level", 8) // Opt
, QTY_SOLD_BF = Double("QTY_SOLD_BF", "Brought Forward Quantity Sold", 8) // Opt
, QTY_SOLD_FUTURE = Double("QTY_SOLD_FUTURE", "Future Quantity Sold", 8) // Opt
, QTY_SOLD_MTH1 = Double("QTY_SOLD_MTH1", "Month 1 Quantity Sold", 8) // Opt
, QTY_SOLD_MTH10 = Double("QTY_SOLD_MTH10", "Month 10 Quantity Sold", 8) // Opt
, QTY_SOLD_MTH11 = Double("QTY_SOLD_MTH11", "Month 11 Quantity Sold", 8) // Opt
, QTY_SOLD_MTH12 = Double("QTY_SOLD_MTH12", "Month 12 Quantity Sold", 8) // Opt
, QTY_SOLD_MTH2 = Double("QTY_SOLD_MTH2", "Month 2 Quantity Sold", 8) // Opt
, QTY_SOLD_MTH3 = Double("QTY_SOLD_MTH3", "Month 3 Quantity Sold", 8) // Opt
, QTY_SOLD_MTH4 = Double("QTY_SOLD_MTH4", "Month 4 Quantity Sold", 8) // Opt
, QTY_SOLD_MTH5 = Double("QTY_SOLD_MTH5", "Month 5 Quantity Sold", 8) // Opt
, QTY_SOLD_MTH6 = Double("QTY_SOLD_MTH6", "Month 6 Quantity Sold", 8) // Opt
, QTY_SOLD_MTH7 = Double("QTY_SOLD_MTH7", "Month 7 Quantity Sold", 8) // Opt
, QTY_SOLD_MTH8 = Double("QTY_SOLD_MTH8", "Month 8 Quantity Sold", 8) // Opt
, QTY_SOLD_MTH9 = Double("QTY_SOLD_MTH9", "Month 9 Quantity Sold", 8) // Opt
, SALES_BF = Double("SALES_BF", "Brought Forward Sales", 8) // Opt
, SALES_FUTURE = Double("SALES_FUTURE", "Future Sales", 8) // Opt
, SALES_MTH1 = Double("SALES_MTH1", "Month 1 Sales", 8) // Opt
, SALES_MTH10 = Double("SALES_MTH10", "Month 10 Sales", 8) // Opt
, SALES_MTH11 = Double("SALES_MTH11", "Month 11 Sales", 8) // Opt
, SALES_MTH12 = Double("SALES_MTH12", "Month 12 Sales", 8) // Opt
, SALES_MTH2 = Double("SALES_MTH2", "Month 2 Sales", 8) // Opt
, SALES_MTH3 = Double("SALES_MTH3", "Month 3 Sales", 8) // Opt
, SALES_MTH4 = Double("SALES_MTH4", "Month 4 Sales", 8) // Opt
, SALES_MTH5 = Double("SALES_MTH5", "Month 5 Sales", 8) // Opt
, SALES_MTH6 = Double("SALES_MTH6", "Month 6 Sales", 8) // Opt
, SALES_MTH7 = Double("SALES_MTH7", "Month 7 Sales", 8) // Opt
, SALES_MTH8 = Double("SALES_MTH8", "Month 8 Sales", 8) // Opt
, SALES_MTH9 = Double("SALES_MTH9", "Month 9 Sales", 8) // Opt
, SALES_PRICE = Double("SALES_PRICE", "Sale Price", 8) // Opt
, STOCK_CAT = Short("STOCK_CAT", "Stock Category Number", 2) // Opt
, STOCK_CODE = String("STOCK_CODE", "Stock Code", 30) // Req
, STOCK_TAKE_DATE = Date("STOCK_TAKE_DATE", "Stock Take Date", 2) // Opt
, SUPPLIER_PART_NUMBER = String("SUPPLIER_PART_NUMBER", "Supplier's Part Number", 16) // Opt
, TAX_CODE = Double("TAX_CODE", "Tax Code", 2) // Opt
, UNIT_OF_SALE = String("UNIT_OF_SALE", "Unit of Sale", 8) // Opt
, UNIT_WEIGHT = String("UNIT_WEIGHT", "Unit of Weight", 8) // Opt
, WEB_DESCRIPTION = String("WEB_DESCRIPTION", "Web Description", 60) // Opt
, WEB_IMAGE = String("WEB_IMAGE", "Web Image Filename", 60) // Opt
, WEB_LONGDESCRIPTION = String("WEB_LONGDESCRIPTION", "Web Long Description", 1023) // Opt
, WEB_PUBLISH = Short("WEB_PUBLISH", "Web Publish Flag", 2) // Opt
, WEB_SPECIAL_OFFER = Short("WEB_SPECIAL_OFFER", "Web Special Offer", 2) // Opt
;
static public readonly Dict_ro<string, Sage_Field>
Fields = Make(ASSEMBLY_LEVEL
, AVERAGE_COST_PRICE
, BUDGET_QTY_SOLD_BF
, BUDGET_QTY_SOLD_FUTURE
, BUDGET_QTY_SOLD_MTH1
, BUDGET_QTY_SOLD_MTH10
, BUDGET_QTY_SOLD_MTH11
, BUDGET_QTY_SOLD_MTH12
, BUDGET_QTY_SOLD_MTH2
, BUDGET_QTY_SOLD_MTH3
, BUDGET_QTY_SOLD_MTH4
, BUDGET_QTY_SOLD_MTH5
, BUDGET_QTY_SOLD_MTH6
, BUDGET_QTY_SOLD_MTH7
, BUDGET_QTY_SOLD_MTH8
, BUDGET_QTY_SOLD_MTH9
, BUDGET_SALES_BF
, BUDGET_SALES_FUTURE
, BUDGET_SALES_MTH1
, BUDGET_SALES_MTH10
, BUDGET_SALES_MTH11
, BUDGET_SALES_MTH12
, BUDGET_SALES_MTH2
, BUDGET_SALES_MTH3
, BUDGET_SALES_MTH4
, BUDGET_SALES_MTH5
, BUDGET_SALES_MTH6
, BUDGET_SALES_MTH7
, BUDGET_SALES_MTH8
, BUDGET_SALES_MTH9
, COMMODITY_CODE
, COMPONENT_CODE_1
, COMPONENT_CODE_10
, COMPONENT_CODE_2
, COMPONENT_CODE_3
, COMPONENT_CODE_4
, COMPONENT_CODE_5
, COMPONENT_CODE_6
, COMPONENT_CODE_7
, COMPONENT_CODE_8
, COMPONENT_CODE_9
, COMPONENT_QTY_1
, COMPONENT_QTY_10
, COMPONENT_QTY_2
, COMPONENT_QTY_3
, COMPONENT_QTY_4
, COMPONENT_QTY_5
, COMPONENT_QTY_6
, COMPONENT_QTY_7
, COMPONENT_QTY_8
, COMPONENT_QTY_9
, COST_BF
, COST_FUTURE
, COST_MTH1
, COST_MTH10
, COST_MTH11
, COST_MTH12
, COST_MTH2
, COST_MTH3
, COST_MTH4
, COST_MTH5
, COST_MTH6
, COST_MTH7
, COST_MTH8
, COST_MTH9
, CUSTOM_1
, CUSTOM_2
, CUSTOM_3
, DELETED_FLAG
, DEPT_NUMBER
, DESCRIPTION
, DISC_A_LEVEL_10_QTY
, DISC_A_LEVEL_10_RATE
, DISC_A_LEVEL_1_QTY
, DISC_A_LEVEL_1_RATE
, DISC_A_LEVEL_2_QTY
, DISC_A_LEVEL_2_RATE
, DISC_A_LEVEL_3_QTY
, DISC_A_LEVEL_3_RATE
, DISC_A_LEVEL_4_QTY
, DISC_A_LEVEL_4_RATE
, DISC_A_LEVEL_5_QTY
, DISC_A_LEVEL_5_RATE
, DISC_A_LEVEL_6_QTY
, DISC_A_LEVEL_6_RATE
, DISC_A_LEVEL_7_QTY
, DISC_A_LEVEL_7_RATE
, DISC_A_LEVEL_8_QTY
, DISC_A_LEVEL_8_RATE
, DISC_A_LEVEL_9_QTY
, DISC_A_LEVEL_9_RATE
, DISC_B_LEVEL_10_QTY
, DISC_B_LEVEL_10_RATE
, DISC_B_LEVEL_1_QTY
, DISC_B_LEVEL_1_RATE
, DISC_B_LEVEL_2_QTY
, DISC_B_LEVEL_2_RATE
, DISC_B_LEVEL_3_QTY
, DISC_B_LEVEL_3_RATE
, DISC_B_LEVEL_4_QTY
, DISC_B_LEVEL_4_RATE
, DISC_B_LEVEL_5_QTY
, DISC_B_LEVEL_5_RATE
, DISC_B_LEVEL_6_QTY
, DISC_B_LEVEL_6_RATE
, DISC_B_LEVEL_7_QTY
, DISC_B_LEVEL_7_RATE
, DISC_B_LEVEL_8_QTY
, DISC_B_LEVEL_8_RATE
, DISC_B_LEVEL_9_QTY
, DISC_B_LEVEL_9_RATE
, DISC_C_LEVEL_10_QTY
, DISC_C_LEVEL_10_RATE
, DISC_C_LEVEL_1_QTY
, DISC_C_LEVEL_1_RATE
, DISC_C_LEVEL_2_QTY
, DISC_C_LEVEL_2_RATE
, DISC_C_LEVEL_3_QTY
, DISC_C_LEVEL_3_RATE
, DISC_C_LEVEL_4_QTY
, DISC_C_LEVEL_4_RATE
, DISC_C_LEVEL_5_QTY
, DISC_C_LEVEL_5_RATE
, DISC_C_LEVEL_6_QTY
, DISC_C_LEVEL_6_RATE
, DISC_C_LEVEL_7_QTY
, DISC_C_LEVEL_7_RATE
, DISC_C_LEVEL_8_QTY
, DISC_C_LEVEL_8_RATE
, DISC_C_LEVEL_9_QTY
, DISC_C_LEVEL_9_RATE
, DISC_D_LEVEL_10_QTY
, DISC_D_LEVEL_10_RATE
, DISC_D_LEVEL_1_QTY
, DISC_D_LEVEL_1_RATE
, DISC_D_LEVEL_2_QTY
, DISC_D_LEVEL_2_RATE
, DISC_D_LEVEL_3_QTY
, DISC_D_LEVEL_3_RATE
, DISC_D_LEVEL_4_QTY
, DISC_D_LEVEL_4_RATE
, DISC_D_LEVEL_5_QTY
, DISC_D_LEVEL_5_RATE
, DISC_D_LEVEL_6_QTY
, DISC_D_LEVEL_6_RATE
, DISC_D_LEVEL_7_QTY
, DISC_D_LEVEL_7_RATE
, DISC_D_LEVEL_8_QTY
, DISC_D_LEVEL_8_RATE
, DISC_D_LEVEL_9_QTY
, DISC_D_LEVEL_9_RATE
, DISC_E_LEVEL_10_QTY
, DISC_E_LEVEL_10_RATE
, DISC_E_LEVEL_1_QTY
, DISC_E_LEVEL_1_RATE
, DISC_E_LEVEL_2_QTY
, DISC_E_LEVEL_2_RATE
, DISC_E_LEVEL_3_QTY
, DISC_E_LEVEL_3_RATE
, DISC_E_LEVEL_4_QTY
, DISC_E_LEVEL_4_RATE
, DISC_E_LEVEL_5_QTY
, DISC_E_LEVEL_5_RATE
, DISC_E_LEVEL_6_QTY
, DISC_E_LEVEL_6_RATE
, DISC_E_LEVEL_7_QTY
, DISC_E_LEVEL_7_RATE
, DISC_E_LEVEL_8_QTY
, DISC_E_LEVEL_8_RATE
, DISC_E_LEVEL_9_QTY
, DISC_E_LEVEL_9_RATE
, EXTERNAL_USAGE
, FIRST_TRAN
, IGNORE_STK_LVL_FLAG
, ITEM_TYPE
, LAST_PURCHASE_DATE
, LAST_PURCHASE_PRICE
, LAST_SALE_DATE
, LAST_TRAN
, LINK_LEVEL
, LOCATION
, NO_OF_TRAN
, NOMINAL_CODE
, PRIOR_YR_COST_BF
, PRIOR_YR_COST_FUTURE
, PRIOR_YR_COST_MTH1
, PRIOR_YR_COST_MTH10
, PRIOR_YR_COST_MTH11
, PRIOR_YR_COST_MTH12
, PRIOR_YR_COST_MTH2
, PRIOR_YR_COST_MTH3
, PRIOR_YR_COST_MTH4
, PRIOR_YR_COST_MTH5
, PRIOR_YR_COST_MTH6
, PRIOR_YR_COST_MTH7
, PRIOR_YR_COST_MTH8
, PRIOR_YR_COST_MTH9
, PRIOR_YR_QTY_SOLD_BF
, PRIOR_YR_QTY_SOLD_FUTURE
, PRIOR_YR_QTY_SOLD_MTH1
, PRIOR_YR_QTY_SOLD_MTH10
, PRIOR_YR_QTY_SOLD_MTH11
, PRIOR_YR_QTY_SOLD_MTH12
, PRIOR_YR_QTY_SOLD_MTH2
, PRIOR_YR_QTY_SOLD_MTH3
, PRIOR_YR_QTY_SOLD_MTH4
, PRIOR_YR_QTY_SOLD_MTH5
, PRIOR_YR_QTY_SOLD_MTH6
, PRIOR_YR_QTY_SOLD_MTH7
, PRIOR_YR_QTY_SOLD_MTH8
, PRIOR_YR_QTY_SOLD_MTH9
, PRIOR_YR_SALES_BF
, PRIOR_YR_SALES_FUTURE
, PRIOR_YR_SALES_MTH1
, PRIOR_YR_SALES_MTH10
, PRIOR_YR_SALES_MTH11
, PRIOR_YR_SALES_MTH12
, PRIOR_YR_SALES_MTH2
, PRIOR_YR_SALES_MTH3
, PRIOR_YR_SALES_MTH4
, PRIOR_YR_SALES_MTH5
, PRIOR_YR_SALES_MTH6
, PRIOR_YR_SALES_MTH7
, PRIOR_YR_SALES_MTH8
, PRIOR_YR_SALES_MTH9
, PURCHASE_REF
, QTY_ALLOCATED
, QTY_IN_STOCK
, QTY_LAST_ORDER
, QTY_LAST_STOCK_TAKE
, QTY_ON_ORDER
, QTY_REORDER
, QTY_REORDER_LEVEL
, QTY_SOLD_BF
, QTY_SOLD_FUTURE
, QTY_SOLD_MTH1
, QTY_SOLD_MTH10
, QTY_SOLD_MTH11
, QTY_SOLD_MTH12
, QTY_SOLD_MTH2
, QTY_SOLD_MTH3
, QTY_SOLD_MTH4
, QTY_SOLD_MTH5
, QTY_SOLD_MTH6
, QTY_SOLD_MTH7
, QTY_SOLD_MTH8
, QTY_SOLD_MTH9
, SALES_BF
, SALES_FUTURE
, SALES_MTH1
, SALES_MTH10
, SALES_MTH11
, SALES_MTH12
, SALES_MTH2
, SALES_MTH3
, SALES_MTH4
, SALES_MTH5
, SALES_MTH6
, SALES_MTH7
, SALES_MTH8
, SALES_MTH9
, SALES_PRICE
, STOCK_CAT
, STOCK_CODE
, STOCK_TAKE_DATE
, SUPPLIER_PART_NUMBER
, TAX_CODE
, UNIT_OF_SALE
, UNIT_WEIGHT
, WEB_DESCRIPTION
, WEB_IMAGE
, WEB_LONGDESCRIPTION
, WEB_PUBLISH
, WEB_SPECIAL_OFFER
);
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Site.Areas.Account.Models
{
extern alias MSDataServicesClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using System.Web.WebPages;
using AccountManagement;
using Adxstudio.Xrm;
using Adxstudio.Xrm.AspNet.Cms;
using Adxstudio.Xrm.AspNet.Identity;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Web;
using Adxstudio.Xrm.AspNet.Mvc;
using Adxstudio.Xrm.Configuration;
using Adxstudio.Xrm.Services;
using MSDataServicesClient::System.Data.Services.Client;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Client;
/// <summary>
/// Validating the Registration details
/// </summary>
public class LoginManager
{
/// <summary>
/// Initializes a new instance of the <see cref="LoginManager" /> class.
/// </summary>
/// <param name="httpContext">The context.</param>
/// <param name="controller">The controller.</param>
public LoginManager(HttpContextBase httpContext, Controller controller = null)
{
this.HttpContext = httpContext;
this.Controller = controller;
this.Error = new List<string>();
this.SetAuthSettings();
}
/// <summary>
/// Token Cache Key
/// </summary>
private const string TokenCacheKey = "EssGraphAuthToken";
/// <summary>
/// Token refresh retry count
/// </summary>
private const int TokenRetryCount = 3;
/// <summary>
/// Graph Cache total minutes
/// </summary>
private const int GraphCacheTtlMinutes = 5;
/// <summary>
/// Http Context base
/// </summary>
public HttpContextBase HttpContext { get; private set; }
/// <summary>
/// Login Controller
/// </summary>
public Controller Controller { get; private set; }
/// <summary>
/// Holds error messages retrieved while validations
/// </summary>
public List<string> Error { get; private set; }
/// <summary>
/// Holds Authentication settings required for the page
/// </summary>
public Adxstudio.Xrm.AspNet.Mvc.AuthenticationSettings AuthSettings { get; private set; }
/// <summary>
/// Application Invitation Manager local variable
/// </summary>
private ApplicationInvitationManager invitationManager;
/// <summary>
/// Application Invitation Manager
/// </summary>
public ApplicationInvitationManager InvitationManager
{
get
{
return this.invitationManager ?? this.HttpContext.GetOwinContext().Get<ApplicationInvitationManager>();
}
set
{
this.invitationManager = value;
}
}
/// <summary>
/// Application User Manager local variable
/// </summary>
private ApplicationUserManager userManager;
/// <summary>
/// Application User Manager
/// </summary>
public ApplicationUserManager UserManager
{
get
{
return this.userManager ?? this.HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
set
{
this.userManager = value;
}
}
/// <summary>
/// Application Website Manager local variable
/// </summary>
private ApplicationWebsiteManager websiteManager;
/// <summary>
/// Application Website Manager
/// </summary>
public ApplicationWebsiteManager WebsiteManager
{
get
{
return this.websiteManager ?? this.HttpContext.GetOwinContext().Get<ApplicationWebsiteManager>();
}
set
{
this.websiteManager = value;
}
}
/// <summary>
/// Application SignIn Manager local variable
/// </summary>
private ApplicationSignInManager signInManager;
/// <summary>
/// Application SignIn Manager
/// </summary>
public ApplicationSignInManager SignInManager
{
get
{
return this.signInManager ?? this.HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
set
{
this.signInManager = value;
}
}
/// <summary>
/// Identity Errors to get error descriptions
/// </summary>
public CrmIdentityErrorDescriber IdentityErrors { get; set; }
/// <summary>
/// Authentication Manager
/// </summary>
public IAuthenticationManager AuthenticationManager
{
get
{
return this.HttpContext.GetOwinContext().Authentication;
}
}
/// <summary>
/// Application Startup Settings Manager local variable
/// </summary>
private ApplicationStartupSettingsManager startupSettingsManager;
/// <summary>
/// Application Startup Settings Manager
/// </summary>
public ApplicationStartupSettingsManager StartupSettingsManager
{
get
{
return this.startupSettingsManager ?? this.HttpContext.GetOwinContext().Get<ApplicationStartupSettingsManager>();
}
private set
{
this.startupSettingsManager = value;
}
}
/// <summary>
/// Gets Graph Client
/// </summary>
/// <param name="loginInfo">login info</param>
/// <param name="graphRoot">graph root</param>
/// <param name="tenantId">tenant id</param>
/// <returns>retuns Active Directory Client</returns>
private Microsoft.Azure.ActiveDirectory.GraphClient.ActiveDirectoryClient GetGraphClient(ExternalLoginInfo loginInfo, string graphRoot, string tenantId)
{
var accessCodeClaim = loginInfo.ExternalIdentity.FindFirst("AccessCode");
var accessCode = accessCodeClaim?.Value;
return new Microsoft.Azure.ActiveDirectory.GraphClient.ActiveDirectoryClient(
new Uri(graphRoot + "/" + tenantId),
async () => await this.TokenManager.GetTokenAsync(accessCode));
}
/// <summary>
/// token Manager
/// </summary>
private Lazy<CrmTokenManager> tokenManager = new Lazy<CrmTokenManager>(CreateCrmTokenManager);
/// <summary>
/// Create Crm TokenManager
/// </summary>
/// <returns>Crm Token Manager</returns>
private static CrmTokenManager CreateCrmTokenManager()
{
return new CrmTokenManager(PortalSettings.Instance.Authentication, PortalSettings.Instance.Certificate, PortalSettings.Instance.Graph.RootUrl);
}
/// <summary>
/// Token Manager property
/// </summary>
private ICrmTokenManager TokenManager => this.tokenManager.Value;
/// <summary>
/// ToEmail: Gets the email for the graph user
/// </summary>
/// <param name="graphUser">graph user</param>
/// <returns>returns email id</returns>
public static string ToEmail(Microsoft.Azure.ActiveDirectory.GraphClient.IUser graphUser)
{
if (!string.IsNullOrWhiteSpace(graphUser.Mail))
{
return graphUser.Mail;
}
return graphUser.OtherMails != null ? graphUser.OtherMails.FirstOrDefault() : graphUser.UserPrincipalName;
}
/// <summary>
/// Apply Claims Mapping
/// </summary>
/// <param name="user">Application User</param>
/// <param name="loginInfo">Login Info</param>
/// <param name="claimsMapping">Claims mapping</param>
private static void ApplyClaimsMapping(ApplicationUser user, ExternalLoginInfo loginInfo, string claimsMapping)
{
try
{
if (user != null && !string.IsNullOrWhiteSpace(claimsMapping))
{
foreach (var pair in claimsMapping.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
var pieces = pair.Split('=');
var claimValue = loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type == pieces[1]);
if (pieces.Length == 2
&& !user.Entity.Attributes.ContainsKey(pieces[0])
&& claimValue != null)
{
user.Entity.SetAttributeValue(pieces[0], claimValue.Value);
user.IsDirty = true;
}
}
}
}
catch (Exception ex)
{
WebEventSource.Log.GenericErrorException(ex);
}
}
/// <summary>
/// Get Auth Settings
/// </summary>
/// <returns>Return Auth Settings</returns>
private void SetAuthSettings()
{
var isLocal = this.HttpContext.IsDebuggingEnabled && this.HttpContext.Request.IsLocal;
var website = this.HttpContext.GetWebsite();
this.AuthSettings = website.GetAuthenticationSettings(isLocal);
}
/// <summary>
/// Add validation errors
/// </summary>
/// <param name="error">error identified</param>
public void AddErrors(IdentityError error)
{
this.AddErrors(IdentityResult.Failed(error.Description));
}
/// <summary>
/// Format error
/// </summary>
/// <param name="result">error description</param>
public void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
if (this.Controller != null)
{
this.Controller.ModelState.AddModelError(string.Empty, error);
}
else
{
this.Error.Add(string.Concat(this.Error.Count == 0 ? string.Empty : "<li>", error, this.Error.Count == 0 ? "\n" : "</li>\n"));
}
}
}
/// <summary>
/// Validate Email
/// </summary>
/// <param name="email">email value to validate</param>
/// <returns>returns true if validated</returns>
public bool ValidateEmail(string email)
{
try
{
MailAddress m = new MailAddress(email);
return true;
}
catch (FormatException)
{
return false;
}
}
/// <summary>
/// To ContactId
/// </summary>
/// <param name="invitation">Application Invitation</param>
/// <returns>returns Invitation entity reference</returns>
public EntityReference ToContactId(ApplicationInvitation invitation)
{
return invitation != null && invitation.InvitedContact != null
? new EntityReference(invitation.InvitedContact.LogicalName, invitation.InvitedContact.Id) { Name = invitation.Email }
: null;
}
/// <summary>
/// Find Invitation value by Code Async
/// </summary>
/// <param name="invitationCode">invitation code</param>
/// <returns>returns application invitation value</returns>
public async Task<ApplicationInvitation> FindInvitationByCodeAsync(string invitationCode)
{
if (string.IsNullOrWhiteSpace(invitationCode))
{
return null;
}
return await this.InvitationManager.FindByCodeAsync(invitationCode);
}
/// <summary>
/// Sign In Async
/// </summary>
/// <param name="user">user value</param>
/// <param name="returnUrl">return url</param>
/// <param name="isPersistent">is persistent value</param>
/// <param name="rememberBrowser">remeber browser value</param>
/// <returns>action result</returns>
public async Task<Enums.RedirectTo> SignInAsync(ApplicationUser user, string returnUrl, bool isPersistent = false, bool rememberBrowser = false)
{
await this.SignInManager.SignInAsync(user, isPersistent, rememberBrowser);
return await this.RedirectOnPostAuthenticate(returnUrl, null);
}
/// <summary>
/// Updates the current request language based on user preferences. If needed, updates the return URL as well.
/// </summary>
/// <param name="user">Application User that is currently being logged in.</param>
/// <param name="returnUrl">Return URL to be updated if needed.</param>
private void UpdateCurrentLanguage(ApplicationUser user, ref string returnUrl)
{
var languageContext = this.HttpContext.GetContextLanguageInfo();
if (languageContext.IsCrmMultiLanguageEnabled)
{
// At this point, ContextLanguageInfo.UserPreferredLanguage is not set, as the user is technically not yet logged in
// As this is a one-time operation, accessing adx_preferredlanguageid here directly instead of modifying CrmUser
var preferredLanguage = user.Entity.GetAttributeValue<EntityReference>("adx_preferredlanguageid");
if (preferredLanguage != null)
{
var websiteLangauges = languageContext.ActiveWebsiteLanguages.ToArray();
// Only consider published website languages for users
var newLanguage = languageContext.GetWebsiteLanguageByPortalLanguageId(preferredLanguage.Id, websiteLangauges, true);
if (newLanguage != null)
{
if (ContextLanguageInfo.DisplayLanguageCodeInUrl && !string.IsNullOrEmpty(returnUrl))
{
returnUrl = languageContext.FormatUrlWithLanguage(false, newLanguage.Code, returnUrl.AsAbsoluteUri(this.HttpContext.Request.Url));
}
}
}
}
}
/// <summary>
/// Redirect page on post Authentication
/// </summary>
/// <param name="returnUrl">return Url</param>
/// <param name="invitationCode">invitation code</param>
/// <param name="loginInfo">login information</param>
/// <param name="cancellationToken">cancellation token</param>
/// <returns>Action result</returns>
private async Task<Enums.RedirectTo> RedirectOnPostAuthenticate(string returnUrl, string invitationCode, ExternalLoginInfo loginInfo = null, CancellationToken cancellationToken = default(CancellationToken))
{
var identity = this.AuthenticationManager.AuthenticationResponseGrant.Identity;
var userId = identity.GetUserId();
var user = await this.UserManager.FindByIdAsync(userId);
if (user != null && loginInfo != null)
{
var options = await this.StartupSettingsManager.GetAuthenticationOptionsExtendedAsync(loginInfo, cancellationToken);
var claimsMapping = options?.LoginClaimsMapping;
if (!string.IsNullOrWhiteSpace(claimsMapping))
{
ApplyClaimsMapping(user, loginInfo, claimsMapping);
}
}
return await this.RedirectOnPostAuthenticate(user, returnUrl, invitationCode, loginInfo, cancellationToken);
}
/// <summary>
/// Post Authentication, redirect to appropirate page.
/// </summary>
/// <param name="user">Application user</param>
/// <param name="returnUrl">return url</param>
/// <param name="invitationCode">invitation code</param>
/// <param name="loginInfo">Login info</param>
/// <param name="cancellationToken">cancellation token</param>
/// <returns>return enum</returns>
private async Task<Enums.RedirectTo> RedirectOnPostAuthenticate(ApplicationUser user, string returnUrl, string invitationCode, ExternalLoginInfo loginInfo = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (user != null)
{
this.UpdateCurrentLanguage(user, ref returnUrl);
this.UpdateLastSuccessfulLogin(user);
await this.ApplyGraphUser(user, loginInfo, cancellationToken);
if (user.IsDirty)
{
await this.UserManager.UpdateAsync(user);
user.IsDirty = false;
}
IdentityResult redeemResult;
var invitation = await this.FindInvitationByCodeAsync(invitationCode);
if (invitation != null)
{
// Redeem invitation for the existing/registered contact
redeemResult = await this.InvitationManager.RedeemAsync(invitation, user, this.HttpContext.Request.UserHostAddress);
}
else if (!string.IsNullOrWhiteSpace(invitationCode))
{
redeemResult = IdentityResult.Failed(this.IdentityErrors.InvalidInvitationCode().Description);
}
else
{
redeemResult = IdentityResult.Success;
}
if (!redeemResult.Succeeded)
{
return Enums.RedirectTo.Redeem;
}
if (!this.DisplayModeIsActive() && (user.HasProfileAlert || user.ProfileModifiedOn == null))
{
return Enums.RedirectTo.Profile;
}
}
return Enums.RedirectTo.Local;
}
/// <summary>
/// Updates date and time of last successful login
/// </summary>
/// <param name="user">Application User that is currently being logged in.</param>
private void UpdateLastSuccessfulLogin(ApplicationUser user)
{
if (!this.AuthSettings.LoginTrackingEnabled)
{
return;
}
user.Entity.SetAttributeValue("adx_identity_lastsuccessfullogin", DateTime.UtcNow);
user.IsDirty = true;
}
/// <summary>
/// Apply Graph User
/// </summary>
/// <param name="user">Application user</param>
/// <param name="loginInfo">Login Info</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>async task</returns>
private async Task ApplyGraphUser(ApplicationUser user, ExternalLoginInfo loginInfo, CancellationToken cancellationToken)
{
if (loginInfo != null
&& this.StartupSettingsManager.AzureAdOptions != null
&& !string.IsNullOrWhiteSpace(this.StartupSettingsManager.AzureAdOptions.AuthenticationType)
&& !string.IsNullOrWhiteSpace(PortalSettings.Instance.Graph.RootUrl)
&& string.IsNullOrWhiteSpace(user.FirstName)
&& string.IsNullOrWhiteSpace(user.LastName)
&& string.IsNullOrWhiteSpace(user.Email))
{
var authenticationType = await this.StartupSettingsManager.GetAuthenticationTypeAsync(loginInfo, cancellationToken);
if (this.StartupSettingsManager.AzureAdOptions.AuthenticationType == authenticationType)
{
// update the contact using Graph
try
{
var graphUser = await this.GetGraphUser(loginInfo);
user.FirstName = graphUser.GivenName;
user.LastName = graphUser.Surname;
user.Email = ToEmail(graphUser);
user.IsDirty = true;
}
catch (Exception ex)
{
var guid = WebEventSource.Log.GenericErrorException(ex);
this.Error.Add(string.Format(ResourceManager.GetString("Generic_Error_Message"), guid));
}
}
}
}
/// <summary>
/// Check whether Display Mode Is Active or not
/// </summary>
/// <returns>returns true/false</returns>
private bool DisplayModeIsActive()
{
return DisplayModeProvider.Instance
.GetAvailableDisplayModesForContext(this.HttpContext, null)
.OfType<HostNameSettingDisplayMode>()
.Any();
}
/// <summary>
/// Gets Graph User
/// </summary>
/// <param name="loginInfo">Login information</param>
/// <returns>user value</returns>
private async Task<Microsoft.Azure.ActiveDirectory.GraphClient.IUser> GetGraphUser(ExternalLoginInfo loginInfo)
{
var userCacheKey = $"{loginInfo.Login.ProviderKey}_graphUser";
var userAuthResultCacheKey = $"{loginInfo.Login.ProviderKey}_userAuthResult";
// if the user's already gone through the Graph check, this will be set with the error that happened
if (this.HttpContext.Cache[userAuthResultCacheKey] != null)
{
return null;
}
// if the cache here is null, we haven't retrieved the Graph user yet. retrieve it
if (this.HttpContext.Cache[userCacheKey] == null)
{
return await this.GetGraphUser(loginInfo, userCacheKey, userAuthResultCacheKey);
}
return (Microsoft.Azure.ActiveDirectory.GraphClient.IUser)this.HttpContext.Cache[userCacheKey];
}
/// <summary>
/// Gets Graphical User
/// </summary>
/// <param name="loginInfo">login information</param>
/// <param name="userCacheKey">User Cache key value</param>
/// <param name="userAuthResultCacheKey">User authentication cache key</param>
/// <returns>User value</returns>
private async Task<Microsoft.Azure.ActiveDirectory.GraphClient.IUser> GetGraphUser(ExternalLoginInfo loginInfo, string userCacheKey, string userAuthResultCacheKey)
{
var client = this.GetGraphClient(loginInfo,
PortalSettings.Instance.Authentication.RootUrl,
PortalSettings.Instance.Authentication.TenantId);
Microsoft.Azure.ActiveDirectory.GraphClient.IUser user = null;
// retry tokenRetryCount times to retrieve the users. each time it fails, it will nullify the cache and try again
for (var x = 0; x < TokenRetryCount; x++)
{
try
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Attempting to retrieve user from Graph with NameIdentifier {loginInfo.Login.ProviderKey}.");
// when we call this, the client will try to retrieve a token from GetAuthTokenTask()
user = await client.Me.ExecuteAsync();
// if we get here then everything is alright. stop looping
break;
}
catch (AggregateException ex)
{
var handled = false;
foreach (var innerEx in ex.InnerExceptions)
{
if (innerEx.InnerException == null)
{
break;
}
// if the exception can be cast to a DataServiceClientException
// NOTE: the version of Microsoft.Data.Services.Client MUST match the one Microsoft.Azure.ActiveDirectory.GraphClient uses (currently 5.6.4.0. 5.7.0.0 won't cast the exception correctly.)
var clientException = innerEx.InnerException as DataServiceClientException;
if (clientException?.StatusCode == (int)HttpStatusCode.Unauthorized)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Current GraphClient auth token didn't seem to work. Discarding...");
// the token didn't seem to work. throw away cached token to retrieve new one
this.HttpContext.Cache.Remove(TokenCacheKey);
handled = true;
}
}
if (!handled)
{
throw;
}
}
}
// if users is null here, we have a config problem where we can't get correct auth tokens despite repeated attempts
if (user == null)
{
this.OutputGraphError(Enums.AzureADGraphAuthResults.AuthConfigProblem, userAuthResultCacheKey, loginInfo);
return null;
}
// add cache entry for graph user object. it will expire in GraphCacheTtlMinutes minutes
HttpRuntime.Cache.Add(userCacheKey, user, null, DateTime.MaxValue, TimeSpan.FromMinutes(GraphCacheTtlMinutes), CacheItemPriority.Normal, null);
return user;
}
/// <summary>
/// Adds error occured while creating Graph user to trace
/// </summary>
/// <param name="result">Azure AD Graph Authentication Results</param>
/// <param name="userAuthResultCacheKey">User authentication result cache key</param>
/// <param name="loginInfo">Login information</param>
/// <returns>Azure AD graph authentication results</returns>
private Enums.AzureADGraphAuthResults OutputGraphError(Enums.AzureADGraphAuthResults result, string userAuthResultCacheKey, ExternalLoginInfo loginInfo)
{
// add cache entry for graph check result. it will expire in GraphCacheTtlMinutes minutes
HttpRuntime.Cache.Add(userAuthResultCacheKey, result, null, DateTime.MaxValue, TimeSpan.FromMinutes(GraphCacheTtlMinutes), CacheItemPriority.Normal, null);
switch (result)
{
case Enums.AzureADGraphAuthResults.UserNotFound:
ADXTrace.Instance.TraceError(TraceCategory.Application, $"Azure AD didn't have the user with the specified NameIdentifier: {loginInfo.Login.ProviderKey}");
return Enums.AzureADGraphAuthResults.UserNotFound;
case Enums.AzureADGraphAuthResults.UserHasNoEmail:
ADXTrace.Instance.TraceError(TraceCategory.Application, "UPN was not set on user.");
return Enums.AzureADGraphAuthResults.UserHasNoEmail;
case Enums.AzureADGraphAuthResults.NoValidLicense:
ADXTrace.Instance.TraceError(TraceCategory.Application, $"No valid license was found assigned to the user: {loginInfo.Login.ProviderKey}");
return Enums.AzureADGraphAuthResults.NoValidLicense;
case Enums.AzureADGraphAuthResults.AuthConfigProblem:
ADXTrace.Instance.TraceError(TraceCategory.Application, "There's a critical problem with retrieving Graph auth tokens.");
return Enums.AzureADGraphAuthResults.AuthConfigProblem;
}
ADXTrace.Instance.TraceError(TraceCategory.Application, $"An unknown graph error occurred. Passed through UserNotFound, UserHasNoEmail, and NoValidLicense. NameIdentifier: {loginInfo.Login.ProviderKey}");
return Enums.AzureADGraphAuthResults.UnknownError;
}
}
}
| |
using RootSystem = System;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Microsoft.Kinect.Face
{
//
// Microsoft.Kinect.Face.Point
//
[RootSystem.Runtime.InteropServices.StructLayout(RootSystem.Runtime.InteropServices.LayoutKind.Sequential)]
public struct Point
{
public float X { get; set; }
public float Y { get; set; }
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode();
}
public override bool Equals(object obj)
{
if (!(obj is Point))
{
return false;
}
return this.Equals((Point)obj);
}
public bool Equals(Point obj)
{
return X.Equals(obj.X) && Y.Equals(obj.Y);
}
public static bool operator ==(Point a, Point b)
{
return a.Equals(b);
}
public static bool operator !=(Point a, Point b)
{
return !(a.Equals(b));
}
}
//
// Microsoft.Kinect.Face.Color
//
[RootSystem.Runtime.InteropServices.StructLayout(RootSystem.Runtime.InteropServices.LayoutKind.Sequential)]
public struct Color
{
public byte A { get; set; }
public byte R { get; set; }
public byte G { get; set; }
public byte B { get; set; }
public override int GetHashCode()
{
return A.GetHashCode() ^ R.GetHashCode() ^ G.GetHashCode() ^ B.GetHashCode();
}
public override bool Equals(object obj)
{
if (!(obj is Color))
{
return false;
}
return this.Equals((Color)obj);
}
public bool Equals(Color obj)
{
return A.Equals(obj.A) && R.Equals(obj.R) && G.Equals(obj.G) && B.Equals(obj.B);
}
public static bool operator ==(Color a, Color b)
{
return a.Equals(b);
}
public static bool operator !=(Color a, Color b)
{
return !(a.Equals(b));
}
}
//
// Microsoft.Kinect.Face.FaceModel
//
public sealed partial class FaceModel
{
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern RootSystem.IntPtr Microsoft_Kinect_Face_FaceModel_ctor(float scale, Microsoft.Kinect.Face.FaceShapeDeformations[] faceShapeDeformationsKeys, float[] faceShapeDeformationsValues, int faceShapeDeformationsSize);
public static FaceModel Create(float scale, RootSystem.Collections.Generic.Dictionary<Microsoft.Kinect.Face.FaceShapeDeformations, float> faceShapeDeformations)
{
int _faceShapeDeformationsKeys_idx=0;
var _faceShapeDeformationsKeys = new Microsoft.Kinect.Face.FaceShapeDeformations[faceShapeDeformations.Keys.Count];
foreach(var key in faceShapeDeformations.Keys)
{
_faceShapeDeformationsKeys[_faceShapeDeformationsKeys_idx] = (Microsoft.Kinect.Face.FaceShapeDeformations)key;
_faceShapeDeformationsKeys_idx++;
}
int _faceShapeDeformationsValues_idx=0;
var _faceShapeDeformationsValues = new float[faceShapeDeformations.Values.Count];
foreach(var value in faceShapeDeformations.Values)
{
_faceShapeDeformationsValues[_faceShapeDeformationsValues_idx] = (float)value;
_faceShapeDeformationsValues_idx++;
}
RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_FaceModel_ctor(scale, _faceShapeDeformationsKeys, _faceShapeDeformationsValues, faceShapeDeformations.Count);
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Microsoft.Kinect.Face.FaceModel>(
objectPointer, n => new Microsoft.Kinect.Face.FaceModel(n));
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern RootSystem.IntPtr Microsoft_Kinect_Face_FaceModel_ctor1();
public static FaceModel Create()
{
RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_FaceModel_ctor1();
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Microsoft.Kinect.Face.FaceModel>(
objectPointer, n => new Microsoft.Kinect.Face.FaceModel(n));
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern RootSystem.IntPtr Microsoft_Kinect_Face_FaceModel_get_HairColor(RootSystem.IntPtr pNative);
public Microsoft.Kinect.Face.Color HairColor
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("FaceModel");
}
var objectPointer = Microsoft_Kinect_Face_FaceModel_get_HairColor(_pNative);
Helper.ExceptionHelper.CheckLastError();
var obj = (Microsoft.Kinect.Face.Color)RootSystem.Runtime.InteropServices.Marshal.PtrToStructure(objectPointer, typeof(Microsoft.Kinect.Face.Color));
Microsoft.Kinect.Face.KinectFaceUnityAddinUtils.FreeMemory(objectPointer);
return obj;
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern RootSystem.IntPtr Microsoft_Kinect_Face_FaceModel_get_SkinColor(RootSystem.IntPtr pNative);
public Microsoft.Kinect.Face.Color SkinColor
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("FaceModel");
}
var objectPointer = Microsoft_Kinect_Face_FaceModel_get_SkinColor(_pNative);
Helper.ExceptionHelper.CheckLastError();
var obj = (Microsoft.Kinect.Face.Color)RootSystem.Runtime.InteropServices.Marshal.PtrToStructure(objectPointer, typeof(Microsoft.Kinect.Face.Color));
Microsoft.Kinect.Face.KinectFaceUnityAddinUtils.FreeMemory(objectPointer);
return obj;
}
}
}
//
// Microsoft.Kinect.Face.FaceFrameResult
//
public sealed partial class FaceFrameResult
{
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern int Microsoft_Kinect_Face_FaceFrameResult_get_FacePointsInColorSpace(RootSystem.IntPtr pNative, [RootSystem.Runtime.InteropServices.Out] Microsoft.Kinect.Face.FacePointType[] outKeys, [RootSystem.Runtime.InteropServices.Out] Microsoft.Kinect.Face.Point[] outValues, int outCollectionSize);
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern int Microsoft_Kinect_Face_FaceFrameResult_get_FacePointsInColorSpace_Length(RootSystem.IntPtr pNative);
public RootSystem.Collections.Generic.Dictionary<Microsoft.Kinect.Face.FacePointType, Microsoft.Kinect.Face.Point> FacePointsInColorSpace
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("FaceFrameResult");
}
int outCollectionSize = Microsoft_Kinect_Face_FaceFrameResult_get_FacePointsInColorSpace_Length(_pNative);
var outKeys = new Microsoft.Kinect.Face.FacePointType[outCollectionSize];
var outValues = new Microsoft.Kinect.Face.Point[outCollectionSize];
var managedDictionary = new RootSystem.Collections.Generic.Dictionary<Microsoft.Kinect.Face.FacePointType, Microsoft.Kinect.Face.Point>();
outCollectionSize = Microsoft_Kinect_Face_FaceFrameResult_get_FacePointsInColorSpace(_pNative, outKeys, outValues, outCollectionSize);
Helper.ExceptionHelper.CheckLastError();
for(int i=0;i<outCollectionSize;i++)
{
managedDictionary.Add(outKeys[i], outValues[i]);
}
return managedDictionary;
}
}
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern int Microsoft_Kinect_Face_FaceFrameResult_get_FacePointsInInfraredSpace(RootSystem.IntPtr pNative, [RootSystem.Runtime.InteropServices.Out] Microsoft.Kinect.Face.FacePointType[] outKeys, [RootSystem.Runtime.InteropServices.Out] Microsoft.Kinect.Face.Point[] outValues, int outCollectionSize);
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern int Microsoft_Kinect_Face_FaceFrameResult_get_FacePointsInInfraredSpace_Length(RootSystem.IntPtr pNative);
public RootSystem.Collections.Generic.Dictionary<Microsoft.Kinect.Face.FacePointType, Microsoft.Kinect.Face.Point> FacePointsInInfraredSpace
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("FaceFrameResult");
}
int outCollectionSize = Microsoft_Kinect_Face_FaceFrameResult_get_FacePointsInInfraredSpace_Length(_pNative);
var outKeys = new Microsoft.Kinect.Face.FacePointType[outCollectionSize];
var outValues = new Microsoft.Kinect.Face.Point[outCollectionSize];
var managedDictionary = new RootSystem.Collections.Generic.Dictionary<Microsoft.Kinect.Face.FacePointType, Microsoft.Kinect.Face.Point>();
outCollectionSize = Microsoft_Kinect_Face_FaceFrameResult_get_FacePointsInInfraredSpace(_pNative, outKeys, outValues, outCollectionSize);
Helper.ExceptionHelper.CheckLastError();
for(int i=0;i<outCollectionSize;i++)
{
managedDictionary.Add(outKeys[i], outValues[i]);
}
return managedDictionary;
}
}
}
//
// Microsoft.Kinect.Face.FaceAlignment
//
public sealed partial class FaceAlignment
{
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention = RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern RootSystem.IntPtr Microsoft_Kinect_Face_FaceAlignment_ctor();
public static FaceAlignment Create()
{
RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_FaceAlignment_ctor();
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Microsoft.Kinect.Face.FaceAlignment>(
objectPointer, n => new Microsoft.Kinect.Face.FaceAlignment(n));
}
}
//
// Microsoft.Kinect.Face.FaceFrameSource
//
public sealed partial class FaceFrameSource
{
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention = RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern RootSystem.IntPtr Microsoft_Kinect_Face_FaceFrameSource_ctor(RootSystem.IntPtr sensor, ulong initialTrackingId, Microsoft.Kinect.Face.FaceFrameFeatures initialFaceFrameFeatures);
public static FaceFrameSource Create(Windows.Kinect.KinectSensor sensor, ulong initialTrackingId, Microsoft.Kinect.Face.FaceFrameFeatures initialFaceFrameFeatures)
{
RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_FaceFrameSource_ctor(Helper.NativeWrapper.GetNativePtr(sensor), initialTrackingId, initialFaceFrameFeatures);
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Microsoft.Kinect.Face.FaceFrameSource>(
objectPointer, n => new Microsoft.Kinect.Face.FaceFrameSource(n));
}
}
//
// Microsoft.Kinect.Face.HighDefinitionFaceFrameSource
//
public sealed partial class HighDefinitionFaceFrameSource
{
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention = RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern RootSystem.IntPtr Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_ctor(RootSystem.IntPtr sensor);
public static HighDefinitionFaceFrameSource Create(Windows.Kinect.KinectSensor sensor)
{
RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_HighDefinitionFaceFrameSource_ctor(Helper.NativeWrapper.GetNativePtr(sensor));
Helper.ExceptionHelper.CheckLastError();
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Microsoft.Kinect.Face.HighDefinitionFaceFrameSource>(
objectPointer, n => new Microsoft.Kinect.Face.HighDefinitionFaceFrameSource(n));
}
}
//
// Microsoft.Kinect.Face.FaceModelBuilder
//
public sealed partial class FaceModelBuilder
{
[RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private delegate void Microsoft_Kinect_Face_FaceModelData_Delegate_Indexed(RootSystem.IntPtr result, [RootSystem.Runtime.InteropServices.MarshalAs(RootSystem.Runtime.InteropServices.UnmanagedType.LPWStr)] string guid);
private static Helper.ThreadSafeDictionary<string, RootSystem.Action<Microsoft.Kinect.Face.FaceModelData>> Microsoft_Kinect_Face_FaceModelData_Delegate_SuccessCallbacks = new Helper.ThreadSafeDictionary<string, RootSystem.Action<Microsoft.Kinect.Face.FaceModelData>>();
[AOT.MonoPInvokeCallback(typeof(Microsoft_Kinect_Face_FaceModelData_Delegate_Indexed))]
private static void Microsoft_Kinect_Face_FaceModelData_Delegate_Success(RootSystem.IntPtr result, string guid)
{
List<Helper.SmartGCHandle> pins;
if(PinnedObjects.TryGetValue(guid, out pins))
{
foreach(var pin in pins)
{
pin.Dispose();
}
PinnedObjects.Remove(guid);
}
RootSystem.Action<Microsoft.Kinect.Face.FaceModelData> callback = null;
if(Microsoft_Kinect_Face_FaceModelData_Delegate_SuccessCallbacks.TryGetValue(guid, out callback))
{
var faceModelData = Helper.NativeObjectCache.CreateOrGetObject<Microsoft.Kinect.Face.FaceModelData>(result, n => new Microsoft.Kinect.Face.FaceModelData(n));
Helper.EventPump.Instance.Enqueue(() => callback(faceModelData));
}
ErrorCallbacks.Remove(guid);
Microsoft_Kinect_Face_FaceModelData_Delegate_SuccessCallbacks.Remove(guid);
}
[RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private delegate void Error_Delegate_Indexed(int err, [RootSystem.Runtime.InteropServices.MarshalAs(RootSystem.Runtime.InteropServices.UnmanagedType.LPWStr)] string guid);
private static Helper.ThreadSafeDictionary<string, RootSystem.Action<int>> ErrorCallbacks = new Helper.ThreadSafeDictionary<string, RootSystem.Action<int>>();
private static Helper.CollectionMap<string, RootSystem.Collections.Generic.List<Helper.SmartGCHandle>> PinnedObjects = new Helper.CollectionMap<string, RootSystem.Collections.Generic.List<Helper.SmartGCHandle>>();
[AOT.MonoPInvokeCallback(typeof(Error_Delegate_Indexed))]
private static void Error_Delegate_Failure(int err, [RootSystem.Runtime.InteropServices.MarshalAs(RootSystem.Runtime.InteropServices.UnmanagedType.LPWStr)] string guid)
{
RootSystem.Action<int> callback = null;
if(ErrorCallbacks.TryGetValue(guid, out callback))
{
Helper.EventPump.Instance.Enqueue(() => callback(err));
}
ErrorCallbacks.Remove(guid);
Microsoft_Kinect_Face_FaceModelData_Delegate_SuccessCallbacks.Remove(guid);
}
private static Microsoft_Kinect_Face_FaceModelData_Delegate_Indexed CollectAsyncSuccessDelegate = Microsoft_Kinect_Face_FaceModelData_Delegate_Success;
private static Error_Delegate_Indexed CollectAsyncFailureDelegate = Error_Delegate_Failure;
[RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)]
private static extern void Microsoft_Kinect_Face_FaceModelBuilder_CollectFaceDataAsync_Indexed(RootSystem.IntPtr pNative, Microsoft_Kinect_Face_FaceModelData_Delegate_Indexed success, Error_Delegate_Indexed failure, [RootSystem.Runtime.InteropServices.MarshalAs(RootSystem.Runtime.InteropServices.UnmanagedType.LPWStr)] string guid);
public void CollectFaceDataAsync(RootSystem.Action<Microsoft.Kinect.Face.FaceModelData> success, RootSystem.Action<int> failure)
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("FaceModelBuilder");
}
RootSystem.Guid g = RootSystem.Guid.NewGuid();
if(success != null)
{
Microsoft_Kinect_Face_FaceModelData_Delegate_SuccessCallbacks.Add(g.ToString(), success);
}
if(failure != null)
{
ErrorCallbacks.Add(g.ToString(), failure);
}
Microsoft_Kinect_Face_FaceModelBuilder_CollectFaceDataAsync_Indexed(_pNative, CollectAsyncSuccessDelegate, CollectAsyncFailureDelegate, g.ToString());
Helper.ExceptionHelper.CheckLastError();
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Vhd
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
/// <summary>
/// Represents a VHD-backed disk.
/// </summary>
public sealed class Disk : VirtualDisk
{
/// <summary>
/// The list of files that make up the disk.
/// </summary>
private List<DiscUtils.Tuple<DiskImageFile, Ownership>> _files;
/// <summary>
/// The stream representing the disk's contents.
/// </summary>
private SparseStream _content;
/// <summary>
/// Initializes a new instance of the Disk class. Differencing disks are not supported.
/// </summary>
/// <param name="stream">The stream to read.</param>
/// <param name="ownsStream">Indicates if the new instance should control the lifetime of the stream.</param>
public Disk(Stream stream, Ownership ownsStream)
{
_files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>();
_files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(new DiskImageFile(stream, ownsStream), Ownership.Dispose));
if (_files[0].First.NeedsParent)
{
throw new NotSupportedException("Differencing disks cannot be opened from a stream");
}
}
/// <summary>
/// Initializes a new instance of the Disk class. Differencing disks are supported.
/// </summary>
/// <param name="path">The path to the disk image.</param>
public Disk(string path)
{
DiskImageFile file = new DiskImageFile(path, FileAccess.ReadWrite);
_files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>();
_files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, Ownership.Dispose));
ResolveFileChain();
}
/// <summary>
/// Initializes a new instance of the Disk class. Differencing disks are supported.
/// </summary>
/// <param name="path">The path to the disk image.</param>
/// <param name="access">The access requested to the disk.</param>
public Disk(string path, FileAccess access)
{
DiskImageFile file = new DiskImageFile(path, access);
_files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>();
_files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, Ownership.Dispose));
ResolveFileChain();
}
/// <summary>
/// Initializes a new instance of the Disk class. Differencing disks are supported.
/// </summary>
/// <param name="fileSystem">The file system containing the disk.</param>
/// <param name="path">The file system relative path to the disk.</param>
/// <param name="access">The access requested to the disk.</param>
public Disk(DiscFileSystem fileSystem, string path, FileAccess access)
{
FileLocator fileLocator = new DiscFileLocator(fileSystem, Utilities.GetDirectoryFromPath(path));
DiskImageFile file = new DiskImageFile(fileLocator, Utilities.GetFileFromPath(path), access);
_files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>();
_files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, Ownership.Dispose));
ResolveFileChain();
}
/// <summary>
/// Initializes a new instance of the Disk class.
/// </summary>
/// <param name="files">The set of image files.</param>
/// <param name="ownsFiles">Indicates if the new instance controls the lifetime of the image files.</param>
/// <remarks>The disks should be ordered with the first file referencing the second, etc. The final
/// file must not require any parent.</remarks>
public Disk(IList<DiskImageFile> files, Ownership ownsFiles)
{
if (files == null || files.Count == 0)
{
throw new ArgumentException("At least one file must be provided");
}
if (files[files.Count - 1].NeedsParent)
{
throw new ArgumentException("Final image file needs a parent");
}
List<DiscUtils.Tuple<DiskImageFile, Ownership>> tempList = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>(files.Count);
for (int i = 0; i < files.Count - 1; ++i)
{
if (!files[i].NeedsParent)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "File at index {0} does not have a parent disk", i));
}
// Note: Can't do timestamp check, not a property on DiskImageFile.
if (files[i].Information.DynamicParentUniqueId != files[i + 1].UniqueId)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "File at index {0} is not the parent of file at index {1} - Unique Ids don't match", i + 1, i));
}
tempList.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(files[i], ownsFiles));
}
tempList.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(files[files.Count - 1], ownsFiles));
_files = tempList;
}
/// <summary>
/// Initializes a new instance of the Disk class. Differencing disks are supported.
/// </summary>
/// <param name="locator">The locator to access relative files.</param>
/// <param name="path">The path to the disk image.</param>
/// <param name="access">The access requested to the disk.</param>
internal Disk(FileLocator locator, string path, FileAccess access)
{
DiskImageFile file = new DiskImageFile(locator, path, access);
_files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>();
_files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, Ownership.Dispose));
ResolveFileChain();
}
/// <summary>
/// Initializes a new instance of the Disk class. Differencing disks are not supported.
/// </summary>
/// <param name="file">The file containing the disk.</param>
/// <param name="ownsFile">Indicates if the new instance should control the lifetime of the file.</param>
private Disk(DiskImageFile file, Ownership ownsFile)
{
_files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>();
_files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, ownsFile));
ResolveFileChain();
}
/// <summary>
/// Initializes a new instance of the Disk class. Differencing disks are supported.
/// </summary>
/// <param name="file">The file containing the disk.</param>
/// <param name="ownsFile">Indicates if the new instance should control the lifetime of the file.</param>
/// <param name="parentLocator">Object used to locate the parent disk.</param>
/// <param name="parentPath">Path to the parent disk (if required).</param>
private Disk(DiskImageFile file, Ownership ownsFile, FileLocator parentLocator, string parentPath)
{
_files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>();
_files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, ownsFile));
if (file.NeedsParent)
{
_files.Add(
new DiscUtils.Tuple<DiskImageFile, Ownership>(
new DiskImageFile(parentLocator, parentPath, FileAccess.Read),
Ownership.Dispose));
ResolveFileChain();
}
}
/// <summary>
/// Initializes a new instance of the Disk class. Differencing disks are supported.
/// </summary>
/// <param name="file">The file containing the disk.</param>
/// <param name="ownsFile">Indicates if the new instance should control the lifetime of the file.</param>
/// <param name="parentFile">The file containing the disk's parent.</param>
/// <param name="ownsParent">Indicates if the new instance should control the lifetime of the parentFile.</param>
private Disk(DiskImageFile file, Ownership ownsFile, DiskImageFile parentFile, Ownership ownsParent)
{
_files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>();
_files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, ownsFile));
if (file.NeedsParent)
{
_files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(parentFile, ownsParent));
ResolveFileChain();
}
else
{
if (parentFile != null && ownsParent == Ownership.Dispose)
{
parentFile.Dispose();
}
}
}
/// <summary>
/// Gets the geometry of the disk.
/// </summary>
public override Geometry Geometry
{
get { return _files[0].First.Geometry; }
}
/// <summary>
/// Gets the type of disk represented by this object.
/// </summary>
public override VirtualDiskClass DiskClass
{
get { return VirtualDiskClass.HardDisk; }
}
/// <summary>
/// Gets the capacity of the disk (in bytes).
/// </summary>
public override long Capacity
{
get { return _files[0].First.Capacity; }
}
/// <summary>
/// Gets or sets a value indicating whether the VHD footer is written every time a new block is allocated.
/// </summary>
/// <remarks>
/// This is enabled by default, disabling this can make write activity faster - however,
/// some software may be unable to access the VHD file if Dispose is not called on this class.
/// </remarks>
public bool AutoCommitFooter
{
get
{
DynamicStream dynContent = Content as DynamicStream;
if (dynContent == null)
{
return true;
}
return dynContent.AutoCommitFooter;
}
set
{
DynamicStream dynContent = Content as DynamicStream;
if (dynContent != null)
{
dynContent.AutoCommitFooter = value;
}
}
}
/// <summary>
/// Gets the content of the disk as a stream.
/// </summary>
/// <remarks>Note the returned stream is not guaranteed to be at any particular position. The actual position
/// will depend on the last partition table/file system activity, since all access to the disk contents pass
/// through a single stream instance. Set the stream position before accessing the stream.</remarks>
public override SparseStream Content
{
get
{
if (_content == null)
{
SparseStream stream = null;
for (int i = _files.Count - 1; i >= 0; --i)
{
stream = _files[i].First.OpenContent(stream, Ownership.Dispose);
}
_content = stream;
}
return _content;
}
}
/// <summary>
/// Gets the layers that make up the disk.
/// </summary>
public override IEnumerable<VirtualDiskLayer> Layers
{
get
{
foreach (var file in _files)
{
yield return file.First as VirtualDiskLayer;
}
}
}
/// <summary>
/// Gets information about the type of disk.
/// </summary>
/// <remarks>This property provides access to meta-data about the disk format, for example whether the
/// BIOS geometry is preserved in the disk file.</remarks>
public override VirtualDiskTypeInfo DiskTypeInfo
{
get { return DiskFactory.MakeDiskTypeInfo(_files[_files.Count - 1].First.IsSparse ? "dynamic" : "fixed"); }
}
/// <summary>
/// Initializes a stream as a fixed-sized VHD file.
/// </summary>
/// <param name="stream">The stream to initialize.</param>
/// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param>
/// <param name="capacity">The desired capacity of the new disk.</param>
/// <returns>An object that accesses the stream as a VHD file.</returns>
public static Disk InitializeFixed(Stream stream, Ownership ownsStream, long capacity)
{
return InitializeFixed(stream, ownsStream, capacity, null);
}
/// <summary>
/// Initializes a stream as a fixed-sized VHD file.
/// </summary>
/// <param name="stream">The stream to initialize.</param>
/// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param>
/// <param name="capacity">The desired capacity of the new disk.</param>
/// <param name="geometry">The desired geometry of the new disk, or <c>null</c> for default.</param>
/// <returns>An object that accesses the stream as a VHD file.</returns>
public static Disk InitializeFixed(Stream stream, Ownership ownsStream, long capacity, Geometry geometry)
{
return new Disk(DiskImageFile.InitializeFixed(stream, ownsStream, capacity, geometry), Ownership.Dispose);
}
/// <summary>
/// Initializes a stream as a dynamically-sized VHD file.
/// </summary>
/// <param name="stream">The stream to initialize.</param>
/// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param>
/// <param name="capacity">The desired capacity of the new disk.</param>
/// <returns>An object that accesses the stream as a VHD file.</returns>
public static Disk InitializeDynamic(Stream stream, Ownership ownsStream, long capacity)
{
return InitializeDynamic(stream, ownsStream, capacity, null);
}
/// <summary>
/// Initializes a stream as a dynamically-sized VHD file.
/// </summary>
/// <param name="stream">The stream to initialize.</param>
/// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param>
/// <param name="capacity">The desired capacity of the new disk.</param>
/// <param name="geometry">The desired geometry of the new disk, or <c>null</c> for default.</param>
/// <returns>An object that accesses the stream as a VHD file.</returns>
public static Disk InitializeDynamic(Stream stream, Ownership ownsStream, long capacity, Geometry geometry)
{
return new Disk(DiskImageFile.InitializeDynamic(stream, ownsStream, capacity, geometry), Ownership.Dispose);
}
/// <summary>
/// Initializes a stream as a dynamically-sized VHD file.
/// </summary>
/// <param name="stream">The stream to initialize.</param>
/// <param name="ownsStream">Indicates if the new instance controls the lifetime of the stream.</param>
/// <param name="capacity">The desired capacity of the new disk.</param>
/// <param name="blockSize">The size of each block (unit of allocation).</param>
/// <returns>An object that accesses the stream as a VHD file.</returns>
public static Disk InitializeDynamic(Stream stream, Ownership ownsStream, long capacity, long blockSize)
{
return new Disk(DiskImageFile.InitializeDynamic(stream, ownsStream, capacity, blockSize), Ownership.Dispose);
}
/// <summary>
/// Creates a new VHD differencing disk file.
/// </summary>
/// <param name="path">The path to the new disk file.</param>
/// <param name="parentPath">The path to the parent disk file.</param>
/// <returns>An object that accesses the new file as a Disk.</returns>
public static Disk InitializeDifferencing(string path, string parentPath)
{
LocalFileLocator parentLocator = new LocalFileLocator(Path.GetDirectoryName(parentPath));
string parentFileName = Path.GetFileName(parentPath);
DiskImageFile newFile;
using (DiskImageFile parent = new DiskImageFile(parentLocator, parentFileName, FileAccess.Read))
{
LocalFileLocator locator = new LocalFileLocator(Path.GetDirectoryName(path));
newFile = parent.CreateDifferencing(locator, Path.GetFileName(path));
}
return new Disk(newFile, Ownership.Dispose, parentLocator, parentFileName);
}
/// <summary>
/// Initializes a stream as a differencing disk VHD file.
/// </summary>
/// <param name="stream">The stream to initialize.</param>
/// <param name="ownsStream">Indicates if the new instance controls the lifetime of the <paramref name="stream"/>.</param>
/// <param name="parent">The disk this file is a different from.</param>
/// <param name="ownsParent">Indicates if the new instance controls the lifetime of the <paramref name="parent"/> file.</param>
/// <param name="parentAbsolutePath">The full path to the parent disk.</param>
/// <param name="parentRelativePath">The relative path from the new disk to the parent disk.</param>
/// <param name="parentModificationTime">The time the parent disk's file was last modified (from file system).</param>
/// <returns>An object that accesses the stream as a VHD file.</returns>
public static Disk InitializeDifferencing(
Stream stream,
Ownership ownsStream,
DiskImageFile parent,
Ownership ownsParent,
string parentAbsolutePath,
string parentRelativePath,
DateTime parentModificationTime)
{
DiskImageFile file = DiskImageFile.InitializeDifferencing(stream, ownsStream, parent, parentAbsolutePath, parentRelativePath, parentModificationTime);
return new Disk(file, Ownership.Dispose, parent, ownsParent);
}
/// <summary>
/// Create a new differencing disk, possibly within an existing disk.
/// </summary>
/// <param name="fileSystem">The file system to create the disk on.</param>
/// <param name="path">The path (or URI) for the disk to create.</param>
/// <returns>The newly created disk.</returns>
public override VirtualDisk CreateDifferencingDisk(DiscFileSystem fileSystem, string path)
{
FileLocator locator = new DiscFileLocator(fileSystem, Utilities.GetDirectoryFromPath(path));
DiskImageFile file = _files[0].First.CreateDifferencing(locator, Utilities.GetFileFromPath(path));
return new Disk(file, Ownership.Dispose);
}
/// <summary>
/// Create a new differencing disk.
/// </summary>
/// <param name="path">The path (or URI) for the disk to create.</param>
/// <returns>The newly created disk.</returns>
public override VirtualDisk CreateDifferencingDisk(string path)
{
FileLocator locator = new LocalFileLocator(Path.GetDirectoryName(path));
DiskImageFile file = _files[0].First.CreateDifferencing(locator, Path.GetFileName(path));
return new Disk(file, Ownership.Dispose);
}
internal static Disk InitializeFixed(FileLocator fileLocator, string path, long capacity, Geometry geometry)
{
return new Disk(DiskImageFile.InitializeFixed(fileLocator, path, capacity, geometry), Ownership.Dispose);
}
internal static Disk InitializeDynamic(FileLocator fileLocator, string path, long capacity, Geometry geometry, long blockSize)
{
return new Disk(DiskImageFile.InitializeDynamic(fileLocator, path, capacity, geometry, blockSize), Ownership.Dispose);
}
/// <summary>
/// Disposes of underlying resources.
/// </summary>
/// <param name="disposing">Set to <c>true</c> if called within Dispose(),
/// else <c>false</c>.</param>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_content != null)
{
_content.Dispose();
_content = null;
}
if (_files != null)
{
foreach (var record in _files)
{
if (record.Second == Ownership.Dispose)
{
record.First.Dispose();
}
}
_files = null;
}
}
}
finally
{
base.Dispose(disposing);
}
}
private void ResolveFileChain()
{
DiskImageFile file = _files[_files.Count - 1].First;
while (file.NeedsParent)
{
FileLocator fileLocator = file.RelativeFileLocator;
bool found = false;
foreach (string testPath in file.GetParentLocations())
{
if (fileLocator.Exists(testPath))
{
DiskImageFile newFile = new DiskImageFile(fileLocator, testPath, FileAccess.Read);
if (newFile.UniqueId != file.ParentUniqueId)
{
throw new IOException(string.Format(CultureInfo.InstalledUICulture, "Invalid disk chain found looking for parent with id {0}, found {1} with id {2}", file.ParentUniqueId, newFile.FullPath, newFile.UniqueId));
}
file = newFile;
_files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, Ownership.Dispose));
found = true;
break;
}
}
if (!found)
{
throw new IOException(string.Format(CultureInfo.InvariantCulture, "Failed to find parent for disk '{0}'", file.FullPath));
}
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using Moq;
using NUnit.Framework;
using Wonga.SLAMonitor.Asynchronous;
namespace Wonga.SLAMonitor.Tests.Asynchronous
{
[TestFixture]
public class SlaProcessorTests
{
class TestableSlaProcessor : SlaProcessor
{
public TestableSlaProcessor(SlaProvider provider) : this(provider, SlaProcessorBuilder.DefaultQuotaPerMessageType) { }
public TestableSlaProcessor(SlaProvider provider, int quotaPerMessageType)
: base(provider, quotaPerMessageType, SlaProcessorBuilder.DefaultLoggingConfiguration, p => new Mock<IDisposable>().Object) { }
public TestableSlaProcessor(SlaProvider provider, Func<ISlaProcessor, IDisposable> timeoutValidationSchedulerFactory)
: base(provider, SlaProcessorBuilder.DefaultQuotaPerMessageType, SlaProcessorBuilder.DefaultLoggingConfiguration, timeoutValidationSchedulerFactory) { }
public readonly ConcurrentQueue<Tuple<SlaDefinition, TimeSpan, Guid>> Results = new ConcurrentQueue<Tuple<SlaDefinition, TimeSpan, Guid>>();
public readonly ConcurrentQueue<Tuple<MessageDefinition, TimeSpan, Guid>> Timeouts = new ConcurrentQueue<Tuple<MessageDefinition, TimeSpan, Guid>>();
public readonly ConcurrentQueue<Tuple<MessageDefinition, Guid>> Rejections = new ConcurrentQueue<Tuple<MessageDefinition, Guid>>();
protected override void ProcessSla(SlaDefinition definition, TimeSpan elapsed, Guid correlationId)
{
Results.Enqueue(Tuple.Create(definition, elapsed, correlationId));
}
protected override void ProcessQuotaReached(MessageDefinition requestDefinition, Guid correlationId)
{
Rejections.Enqueue(Tuple.Create(requestDefinition, correlationId));
}
protected override void ProcessMessageTimeout(MessageDefinition requestDefinition, TimeSpan elapsed, Guid correlationId)
{
Timeouts.Enqueue(Tuple.Create(requestDefinition, elapsed, correlationId));
}
}
private SlaProvider _slaProvider;
private TestableSlaProcessor _slaProcessor;
private int WaitDeltaMs=20;
class Request { public Guid Id { get; set; } }
class Response { public Guid Id { get; set; } }
class ErrorResponse { public Guid Id { get; set; } }
class Request2 { public Guid Id { get; set; } }
class Response2 { public Guid Id { get; set; } }
class ErrorResponse2 { public Guid Id { get; set; } }
[SetUp]
public void SetUp()
{
_slaProvider = new SlaProvider();
_slaProcessor = new TestableSlaProcessor(_slaProvider);
}
[Test]
public void Processor_should_measure_sla()
{
ConfigureSla();
var id = Guid.NewGuid();
var delayInMs = 50;
_slaProcessor.ProcessOutgoingMessage(new Request { Id = id });
Thread.Sleep((int)(delayInMs * 1.5));
_slaProcessor.ProcessIncomingMessage(new Response { Id = id });
Assert.That(_slaProcessor.Results.Count, Is.EqualTo(1), "results");
var result = _slaProcessor.Results.Single();
Assert.That(result.Item2.TotalMilliseconds, Is.GreaterThan(delayInMs).And.LessThan(2 * delayInMs), "elapsed");
Assert.That(result.Item3, Is.EqualTo(id), "Correlation ID");
Assert.That(result.Item1.Response.Type, Is.EqualTo(typeof(Response)), "response message");
}
[Test]
public void Processor_should_measure_sla_once()
{
ConfigureSla();
var id = Guid.NewGuid();
_slaProcessor.ProcessOutgoingMessage(new Request { Id = id });
_slaProcessor.ProcessIncomingMessage(new Response { Id = id });
Assert.That(_slaProcessor.Results.Count, Is.EqualTo(1), "results");
_slaProcessor.ProcessIncomingMessage(new Response { Id = id });
_slaProcessor.ProcessIncomingMessage(new ErrorResponse { Id = id });
Assert.That(_slaProcessor.Results.Count, Is.EqualTo(1), "results should still contain 1 entry");
}
[Test]
public void Processor_should_be_able_to_process_multiple_messages_in_parallel()
{
_slaProcessor = new TestableSlaProcessor(_slaProvider, 50000);
ConfigureSla();
var ids = Enumerable.Range(0, 50000).Select(i => Guid.NewGuid()).ToArray();
ids.AsParallel().WithDegreeOfParallelism(64).ForAll(id =>
{
_slaProcessor.ProcessOutgoingMessage(new Request { Id = id });
_slaProcessor.ProcessOutgoingMessage(new Request2 { Id = id });
});
ids.AsParallel().WithDegreeOfParallelism(64).ForAll(id =>
{
_slaProcessor.ProcessIncomingMessage(new Response { Id = id });
_slaProcessor.ProcessIncomingMessage(new ErrorResponse2 { Id = id });
});
Assert.That(CountProcessedMessages<Request>(), Is.EqualTo(ids.Length), "Not all Request messages were processed");
Assert.That(CountProcessedMessages<Request2>(), Is.EqualTo(ids.Length), "Not all Request2 messages were processed");
Assert.That(CountRejectedMessages<Request>(), Is.EqualTo(0), "All Request messages should be successfully processed");
Assert.That(CountRejectedMessages<Request2>(), Is.EqualTo(0), "All Request2 messages should be successfully processed");
}
[Test]
public void Processor_should_limit_processed_messages()
{
var quota = 1000;
var degreeOfParallelism = 64;
_slaProcessor = new TestableSlaProcessor(_slaProvider, quota);
ConfigureSla();
var ids = Enumerable.Range(0, 50000).Select(i => Guid.NewGuid()).ToArray();
ids.AsParallel().WithDegreeOfParallelism(degreeOfParallelism).ForAll(id =>
{
_slaProcessor.ProcessOutgoingMessage(new Request { Id = id });
_slaProcessor.ProcessOutgoingMessage(new Request2 { Id = id });
});
ids.AsParallel().WithDegreeOfParallelism(degreeOfParallelism).ForAll(id =>
{
_slaProcessor.ProcessIncomingMessage(new Response { Id = id });
_slaProcessor.ProcessIncomingMessage(new ErrorResponse2 { Id = id });
});
Assert.That(CountProcessedMessages<Request>(), Is.EqualTo(quota).Within(degreeOfParallelism), "Processed Request messages should be limited by quota");
Assert.That(CountProcessedMessages<Request2>(), Is.EqualTo(quota).Within(degreeOfParallelism), "Processed Request2 messages should be limited by quota");
Assert.That(CountRejectedMessages<Request>(), Is.EqualTo(ids.Length - quota).Within(degreeOfParallelism), "The Request messages exceeding the quota should be rejected");
Assert.That(CountRejectedMessages<Request2>(), Is.EqualTo(ids.Length - quota).Within(degreeOfParallelism), "The Request2 messages exceeding the quota should be rejected");
}
[Test]
public void Dispose_should_dispose_timeout_scheduler_once()
{
var mockScheduler = new Mock<IDisposable>();
_slaProcessor = new TestableSlaProcessor(_slaProvider, p => mockScheduler.Object);
_slaProcessor.Dispose();
_slaProcessor.Dispose();
mockScheduler.Verify(s => s.Dispose(), Times.Once);
}
[Test]
public void ProcessSlaTimeouts_should_remove_all_timedout_requests()
{
var slaInMs = 50;
var slaMultiplier = 2;
SlaDefinitionBuilder.AddSla<Request, Response>(TimeSpan.FromMilliseconds(slaInMs), req => req.Id, rsp => rsp.Id, _slaProvider);
SlaDefinitionBuilder.AddSla<Request2, Response2>(TimeSpan.FromMinutes(2), req => req.Id, rsp => rsp.Id, _slaProvider);
_slaProcessor = new TestableSlaProcessor(_slaProvider);
_slaProcessor.ProcessOutgoingMessage(new Request { Id = Guid.NewGuid() });
_slaProcessor.ProcessOutgoingMessage(new Request { Id = Guid.NewGuid() });
_slaProcessor.ProcessOutgoingMessage(new Request2 { Id = Guid.NewGuid() });
_slaProcessor.ProcessOutgoingMessage(new Request2 { Id = Guid.NewGuid() });
_slaProcessor.ProcessSlaTimeouts();
Assert.That(_slaProcessor.Timeouts.Count, Is.EqualTo(0), "None of messages should time out yet");
Thread.Sleep(TimeSpan.FromMilliseconds(slaInMs * slaMultiplier + WaitDeltaMs));
_slaProcessor.ProcessSlaTimeouts();
Assert.That(_slaProcessor.Timeouts.Count, Is.EqualTo(2), "Two messages should timeout");
Assert.That(_slaProcessor.Timeouts.Count(m => m.Item1.Type == typeof(Request)), Is.EqualTo(2), "Messages of Request type should timeout");
}
[Test]
public void ProcessSlaTimeouts_should_remove_requests_only_if_the_longest_sla_timed_out()
{
var lowerSlaInMs = 20;
var higherSlaInMs = 50;
var slaMultiplier = 2;
var lowerTimeout = lowerSlaInMs * slaMultiplier + WaitDeltaMs;
var higherTimeout = higherSlaInMs * slaMultiplier + WaitDeltaMs;
SlaDefinitionBuilder
.For<Request>(req => req.Id)
.AddSla<Response>(TimeSpan.FromMilliseconds(lowerSlaInMs), rsp => rsp.Id)
.AddSla<Response2>(TimeSpan.FromMilliseconds(higherSlaInMs), rsp => rsp.Id)
.Configure(_slaProvider);
_slaProcessor = new TestableSlaProcessor(_slaProvider);
_slaProcessor.ProcessOutgoingMessage(new Request { Id = Guid.NewGuid() });
Thread.Sleep(lowerTimeout);
_slaProcessor.ProcessSlaTimeouts();
Assert.That(_slaProcessor.Timeouts.Count, Is.EqualTo(0), "None of messages should time out yet");
Thread.Sleep(higherTimeout - lowerSlaInMs);
_slaProcessor.ProcessSlaTimeouts();
Assert.That(_slaProcessor.Timeouts.Count, Is.EqualTo(1), "Message should time out now");
}
[Test]
public void ProcessSlaTimeouts_should_be_thread_safe()
{
var actionsCount = 50000;
var groupSize = 100;
var messagesInGroup = groupSize - 1;
SlaDefinitionBuilder.AddSla<Request, Response>(TimeSpan.FromTicks(1), r => r.Id, r => r.Id, _slaProvider);
_slaProcessor = new TestableSlaProcessor(_slaProvider, actionsCount);
Action purge = () => _slaProcessor.ProcessSlaTimeouts();
Action add = () => _slaProcessor.ProcessOutgoingMessage(new Request { Id = Guid.NewGuid() });
Enumerable.Range(0, actionsCount)
.Select(index => ((index % groupSize) >= messagesInGroup) ? purge : add)
.AsParallel()
.WithDegreeOfParallelism(64)
.ForAll(action => action.Invoke());
_slaProcessor.ProcessSlaTimeouts();
var expectedMessagesCount = messagesInGroup * actionsCount / groupSize;
Assert.That(_slaProcessor.Timeouts.Count, Is.EqualTo(expectedMessagesCount), "Processor should timeout all messages");
}
private int CountProcessedMessages<T>()
{
return _slaProcessor.Results.Where(r => r.Item1.Request.Type == typeof(T)).Select(r => r.Item3).Distinct().Count();
}
private int CountRejectedMessages<T>()
{
return _slaProcessor.Rejections.Where(r => r.Item1.Type == typeof(T)).Select(r => r.Item2).Distinct().Count();
}
private void ConfigureSla()
{
SlaDefinitionBuilder.For<Request>(r => r.Id)
.AddSla<Response>(TimeSpan.FromSeconds(1), r => r.Id)
.AddSla<ErrorResponse>(TimeSpan.FromSeconds(1), r => r.Id)
.Configure(_slaProvider);
SlaDefinitionBuilder.For<Request2>(r => r.Id)
.AddSla<Response2>(TimeSpan.FromSeconds(1), r => r.Id)
.AddSla<ErrorResponse2>(TimeSpan.FromSeconds(1), r => r.Id)
.Configure(_slaProvider);
}
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Xml.Schema;
using OpenADK.Library;
using NUnit.Framework;
using Library.Nunit.US;
using Library.Nunit.US.Library.Tools;
using Library.UnitTesting.Framework;
using Library.UnitTesting.Framework.Validation;
namespace OpenADK.Library.Nunit.US.Validation
{
[TestFixture, Explicit]
public class VersioningTests : AdkTest
{
private const bool VERBOSE = true;
/*
* Reads all supported SIF US 1.5r1 objects - Writes them IN SIF US 1.1 - Validates
* them with the SIF US 1.1 Schema - Parses them back into Adk Objects
*/
[Test]
public void ReadSIF15r1WriteSIF11()
{
RunVersioningTests(SifVersion.SIF15r1, SifVersion.SIF11, false);
}
/*
* Reads all supported SIF US 1.5r1 objects - Writes them IN SIF US 1.5r1 - Validates
* them with the SIF US 1.5r1 Schema - Parses them back into Adk Objects
*/
[Test]
public void ReadSIF15r1WriteSIF15r1()
{
RunVersioningTests(SifVersion.SIF15r1, SifVersion.SIF15r1, false);
}
/*
* Reads all supported SIF US 1.5r1 objects - Writes them IN SIF US 2.0 - Validates
* them with the SIF US 2.0 Schema - Parses them back into Adk Objects
*/
[Test]
public void ReadSIF15r1WriteSIF20()
{
RunVersioningTests(SifVersion.SIF15r1, SifVersion.SIF20, true);
}
/*
* Reads all supported SIF US 2.0r1 objects - Writes them IN SIF US 1.1 - Validates
* them with the SIF US 1.1 Schema - Parses them back into Adk Objects
*/
[Test]
public void ReadSIF20r1WriteSIF11()
{
RunVersioningTests(SifVersion.SIF20r1, SifVersion.SIF11, true);
}
[Test]
public void ReadSIF20r1WriteSIF15r1()
{
RunVersioningTests(SifVersion.SIF20r1, SifVersion.SIF15r1, true);
}
[Test]
public void ReadSIF20r1Write20r1()
{
RunVersioningTests(SifVersion.SIF20r1, SifVersion.SIF20r1, false);
}
[Test]
public void ReadSIF21Write21()
{
RunVersioningTests(SifVersion.SIF21, SifVersion.SIF21, false);
}
[Test]
public void ReadSIF21Write20r1()
{
RunVersioningTests(SifVersion.SIF21, SifVersion.SIF20r1, false);
}
[Test]
public void ReadSIF22Write22()
{
RunVersioningTests(SifVersion.SIF22, SifVersion.SIF22, false);
}
[Test]
public void ReadSIF22Write21()
{
RunVersioningTests(SifVersion.SIF22, SifVersion.SIF21, false);
}
[Test]
public void ReadSIF22Write20r1()
{
RunVersioningTests(SifVersion.SIF22, SifVersion.SIF20r1, false);
}
private void RunVersioningTests(SifVersion dataVersion, SifVersion schemaVersion, bool ignoreEnumerationErrors)
{
// Tests assume that the schema files are embedded in the test assembly
DirectoryInfo workingDirectory = new DirectoryInfo(Environment.CurrentDirectory);
SchemaValidator sv = USSchemaValidator.NewInstance( schemaVersion );
sv.IgnoreEnumerationErrors = ignoreEnumerationErrors;
String dataVersionStr = getShortenedVersion(dataVersion);
// Warning, slight hack. Move up two directories to the project root
// directory (assumes the project directory is still there)
// This assumption will need to be changed if the tests need to become more portable
workingDirectory = workingDirectory.Parent.Parent;
DirectoryInfo dataDir = new DirectoryInfo(workingDirectory.FullName + "\\data\\" + dataVersionStr);
int errorCount = RunDirectoryTest(dataVersion, schemaVersion, dataDir, Console.Out, sv);
Assert.AreEqual(0, errorCount, "Tests Failed. See System.out for details");
}
private void OnValidateRead( object sender, ValidationEventArgs e )
{
Console.WriteLine( e.Message );
}
private int RunDirectoryTest(SifVersion parseVersion, SifVersion writeVersion, DirectoryInfo dir, TextWriter output, SchemaValidator sv)
{
int errorCount = 0;
foreach (DirectoryInfo childDir in dir.GetDirectories())
{
errorCount += RunDirectoryTest(parseVersion, writeVersion, childDir, output, sv);
}
foreach (FileInfo fileInfo in dir.GetFiles("*.xml"))
{
if (!RunSingleTest(parseVersion, writeVersion, fileInfo.FullName, output, sv))
{
errorCount++;
}
}
output.Flush();
return errorCount;
}
private bool RunSingleTest(
SifVersion parseVersion,
SifVersion writeVersion,
string fileName,
TextWriter output,
SchemaValidator sv)
{
sv.Clear();
if (VERBOSE)
{
output.Write("Running test on " + fileName + "\r\n");
}
// 1) Read the object into memory
SifElement se = null;
try
{
se = AdkObjectParseHelper.ParseFile(fileName, parseVersion);
}
catch (AdkException adke)
{
// Parsing failed. However, since this unit test is a complete
// test of all available objects, just emit the problem and allow
// the test to continue (with a notification of false)
output
.WriteLine("Error parsing file " + fileName + "\r\n - "
+ adke);
output.WriteLine();
return false;
}
catch (Exception re)
{
output.WriteLine("Error parsing file " + fileName + "\r\n - " + re);
output.WriteLine();
return false;
}
// if (VERBOSE)
// {
// SifWriter writer = new SifWriter(output);
// writer.Write(se,parseVersion);
// output.Flush();
// }
// Before we can validate with the schema, we need to ensure that the
// data object is wrapped in a SIF_Message elements, because the SIF
// Schema makes that assumption
SifMessagePayload smp = SchemaValidator.MakeSIFMessagePayload(se);
String tmpFileName = fileName + "." + writeVersion.ToString() + ".adk";
// 2) Write the message out to a file
try
{
SchemaValidator.WriteObject( writeVersion, tmpFileName, smp );
}
catch( Exception ex )
{
Console.WriteLine( "Error running test on {0}. {1}", tmpFileName, ex );
return false;
}
// 3) Validate the file
bool validated = sv.Validate(tmpFileName);
// 4) If validation failed, write the object out for tracing purposes
if (!validated)
{
if (VERBOSE)
{
SifWriter outWriter = new SifWriter(output);
outWriter.Write(se, writeVersion );
outWriter.Flush();
}
output.WriteLine("Validation failed on " + tmpFileName );
sv.PrintProblems(output);
return false;
}
// 5) Read the object again into memory
try
{
se = AdkObjectParseHelper.ParseFile(fileName, parseVersion);
}
catch (AdkException adke)
{
// Parsing failed. However, since this unit test is a complete
// test of all available objects, just emit the problem and allow
// the test to continue (with a notification of false)
output.WriteLine("Error parsing file " + fileName + ": "
+ adke.Message );
return false;
}
catch (Exception re)
{
output.Write("Error parsing file " + fileName + ": "
+ re.Message + "\r\n");
return false;
}
return validated;
}
private String getShortenedVersion(SifVersion version)
{
StringBuilder builder = new StringBuilder();
builder.Append("SIF");
builder.Append(version.Major);
builder.Append(version.Minor);
if (version.Revision > 0)
{
builder.Append('r');
builder.Append(version.Revision);
}
return builder.ToString();
}
}
}
| |
using System; // partial
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using Rynchodon.AntennaRelay;
using Rynchodon.Autopilot;
using Rynchodon.Utility;
using Rynchodon.Utility.Network;
using Rynchodon.Weapons;
using Rynchodon.Weapons.SystemDisruption;
using Sandbox.ModAPI;
using VRage.Collections;
namespace Rynchodon.Update
{
/// <summary>
/// Saves/loads persistent data to/from a save file.
/// </summary>
/// TODO: client saving
public class Saver
{
[Serializable]
public class Builder_ArmsData
{
[XmlAttribute]
public long SaveTime;
public Version ArmsVersion;
public RelayStorage.Builder_NetworkStorage[] AntennaStorage;
public Disruption.Builder_Disruption[] SystemDisruption;
public ShipAutopilot.Builder_Autopilot[] Autopilot;
public ASync.SyncBuilder Sync;
#pragma warning disable CS0649
[XmlAttribute]
public int ModVersion;
public ProgrammableBlock.Builder_ProgrammableBlock[] ProgrammableBlock;
public TextPanel.Builder_TextPanel[] TextPanel;
public WeaponTargeting.Builder_WeaponTargeting[] Weapon;
public UpgradeEntityValue.Builder_EntityValues[] EntityValues;
#pragma warning restore CS0649
}
private const string SaveIdString = "ARMS save file id", SaveXml = "ARMS save XML data";
private static Saver Instance { get; set; }
[AfterArmsInit]
private static void OnLoad()
{
Instance = new Saver();
}
[OnWorldClose]
private static void Unload()
{
Instance = null;
}
/// <summary>LastSeen that were not added immediately upon world loading, Saver will keep trying to add them.</summary>
private CachingDictionary<long, CachingList<LastSeen.Builder_LastSeen>> m_failedLastSeen;
private FileMaster m_fileMaster;
private Saver()
{
DoLoad(GetData());
}
private Builder_ArmsData GetData()
{
m_fileMaster = new FileMaster("SaveDataMaster.txt", "SaveData - ", int.MaxValue);
Builder_ArmsData data = null;
string serialized;
if (MyAPIGateway.Utilities.GetVariable(SaveXml, out serialized))
{
data = MyAPIGateway.Utilities.SerializeFromXML<Builder_ArmsData>(serialized);
if (data != null)
{
Logger.DebugLog("ARMS data was imbeded in the save file proper", Rynchodon.Logger.severity.DEBUG);
return data;
}
}
string identifier = LegacyIdentifier(true);
if (identifier == null)
{
Logger.DebugLog("no identifier");
return data;
}
var reader = m_fileMaster.GetTextReader(identifier);
if (reader != null)
{
Logger.DebugLog("loading from file: " + identifier);
data = MyAPIGateway.Utilities.SerializeFromXML<Builder_ArmsData>(reader.ReadToEnd());
reader.Close();
}
else
Logger.AlwaysLog("Failed to open file reader for " + identifier);
return data;
}
/// <summary>
/// Load data from a file. Shall be called after mod is fully initialized.
/// </summary>
private void DoLoad(Builder_ArmsData data)
{
try
{
LoadSaveData(data);
}
catch (Exception ex)
{
Logger.AlwaysLog("Exception: " + ex, Rynchodon.Logger.severity.ERROR);
Rynchodon.Logger.Notify("ARMS: failed to load data", 60000, Rynchodon.Logger.severity.ERROR);
}
}
private void RetryLastSeen()
{
foreach (KeyValuePair<long, CachingList<LastSeen.Builder_LastSeen>> storageLastSeen in m_failedLastSeen)
{
RelayNode node;
if (Registrar.TryGetValue(storageLastSeen.Key, out node))
{
RelayStorage store = node.Storage;
foreach (LastSeen.Builder_LastSeen builder in storageLastSeen.Value)
{
if (MyAPIGateway.Entities.EntityExists(builder.EntityId))
{
LastSeen ls = new LastSeen(builder);
if (ls.IsValid)
{
Logger.DebugLog("Successfully created a LastSeen. Primary node: " + storageLastSeen.Key + ", entity: " + ls.Entity.nameWithId());
storageLastSeen.Value.Remove(builder);
}
else
Logger.AlwaysLog("Unknown failure with last seen", Rynchodon.Logger.severity.ERROR);
}
else
Logger.DebugLog("Not yet available: " + builder.EntityId);
}
storageLastSeen.Value.ApplyRemovals();
if (storageLastSeen.Value.Count == 0)
{
Logger.DebugLog("Finished with: " + storageLastSeen.Key, Rynchodon.Logger.severity.DEBUG);
m_failedLastSeen.Remove(storageLastSeen.Key);
}
else
Logger.DebugLog("For " + storageLastSeen.Key + ", " + storageLastSeen.Value.Count + " builders remain");
}
else
Logger.DebugLog("Failed to get node for " + storageLastSeen.Key, Rynchodon.Logger.severity.WARNING);
}
m_failedLastSeen.ApplyRemovals();
if (m_failedLastSeen.Count() == 0)
{
Logger.DebugLog("All LastSeen have been successfully added", Rynchodon.Logger.severity.INFO);
m_failedLastSeen = null;
UpdateManager.Unregister(100, RetryLastSeen);
}
else
{
Logger.DebugLog(m_failedLastSeen.Count() + " primary nodes still have last seen to be added");
if (Globals.UpdateCount >= 3600)
{
foreach (KeyValuePair<long, CachingList<LastSeen.Builder_LastSeen>> storageLastSeen in m_failedLastSeen)
foreach (LastSeen.Builder_LastSeen builder in storageLastSeen.Value)
Logger.AlwaysLog("Failed to add last seen to world. Primary node: " + storageLastSeen.Key + ", entity ID: " + builder.EntityId, Rynchodon.Logger.severity.WARNING);
m_failedLastSeen = null;
UpdateManager.Unregister(100, RetryLastSeen);
}
}
}
private string LegacyIdentifier(bool loading)
{
string path = MyAPIGateway.Session.CurrentPath;
string saveId_fromPath = path.Substring(path.LastIndexOfAny(new char[] { '/', '\\' }) + 1) + ".xml";
string saveId_fromWorld;
string saveId = null;
if (m_fileMaster.FileExists(saveId_fromPath))
saveId = saveId_fromPath;
// if file from path exists, it should match stored value
if (saveId != null)
{
if (!MyAPIGateway.Utilities.GetVariable(SaveIdString, out saveId_fromWorld))
{
Logger.AlwaysLog("Save exists for path but save id could not be retrieved from world. From path: " + saveId_fromPath, Rynchodon.Logger.severity.ERROR);
}
else if (saveId_fromPath != saveId_fromWorld)
{
Logger.AlwaysLog("Save id from path does not match save id from world. From path: " + saveId_fromPath + ", from world: " + saveId_fromWorld, Rynchodon.Logger.severity.ERROR);
// prefer from world
if (m_fileMaster.FileExists(saveId_fromWorld))
saveId = saveId_fromWorld;
else
Logger.AlwaysLog("Save id from world does not match a save. From world: " + saveId_fromWorld, Rynchodon.Logger.severity.ERROR);
}
}
else
{
if (MyAPIGateway.Utilities.GetVariable(SaveIdString, out saveId_fromWorld))
{
if (m_fileMaster.FileExists(saveId_fromWorld))
{
if (loading)
Logger.AlwaysLog("Save is a copy, loading from old world: " + saveId_fromWorld, Rynchodon.Logger.severity.DEBUG);
saveId = saveId_fromWorld;
}
else
{
if (loading)
Logger.AlwaysLog("Cannot load world, save id does not match any save: " + saveId_fromWorld, Rynchodon.Logger.severity.DEBUG);
return null;
}
}
else
{
if (loading)
Logger.AlwaysLog("Cannot load world, no save id found", Rynchodon.Logger.severity.DEBUG);
return null;
}
}
return saveId;
}
private void LoadSaveData(Builder_ArmsData data)
{
if (data == null)
{
Logger.DebugLog("No data to load");
return;
}
#pragma warning disable 612, 618
if (Comparer<Version>.Default.Compare(data.ArmsVersion, default(Version)) == 0)
{
Logger.DebugLog("Old version: " + data.ModVersion);
data.ArmsVersion = new Version(data.ModVersion);
}
#pragma warning restore 612, 618
Logger.AlwaysLog("Save version: " + data.ArmsVersion, Rynchodon.Logger.severity.INFO);
// relay
Dictionary<Message.Builder_Message, Message> messages = MyAPIGateway.Multiplayer.IsServer ? new Dictionary<Message.Builder_Message, Message>() : null;
SerializableGameTime.Adjust = new TimeSpan(data.SaveTime);
foreach (RelayStorage.Builder_NetworkStorage bns in data.AntennaStorage)
{
RelayNode node;
if (!Registrar.TryGetValue(bns.PrimaryNode, out node))
{
Logger.AlwaysLog("Failed to get node for: " + bns.PrimaryNode, Rynchodon.Logger.severity.WARNING);
continue;
}
RelayStorage store = node.Storage;
if (store == null) // probably always true
{
node.ForceCreateStorage();
store = node.Storage;
if (store == null)
{
Logger.AlwaysLog("failed to create storage for " + node.DebugName, Rynchodon.Logger.severity.ERROR);
continue;
}
}
foreach (LastSeen.Builder_LastSeen bls in bns.LastSeenList)
{
LastSeen ls = new LastSeen(bls);
if (ls.IsValid)
store.Receive(ls);
else
{
Logger.AlwaysLog("failed to create a valid last seen from builder for " + bls.EntityId, Rynchodon.Logger.severity.WARNING);
if (m_failedLastSeen == null)
{
m_failedLastSeen = new CachingDictionary<long, CachingList<LastSeen.Builder_LastSeen>>();
UpdateManager.Register(100, RetryLastSeen);
}
CachingList<LastSeen.Builder_LastSeen> list;
if (!m_failedLastSeen.TryGetValue(bns.PrimaryNode, out list))
{
list = new CachingList<LastSeen.Builder_LastSeen>();
m_failedLastSeen.Add(bns.PrimaryNode, list, true);
}
list.Add(bls);
list.ApplyAdditions();
}
}
Logger.DebugLog("added " + bns.LastSeenList.Length + " last seen to " + store.PrimaryNode.DebugName, Rynchodon.Logger.severity.DEBUG);
// messages in the save file belong on the server
if (messages == null)
continue;
foreach (Message.Builder_Message bm in bns.MessageList)
{
Message msg;
if (!messages.TryGetValue(bm, out msg))
{
msg = new Message(bm);
messages.Add(bm, msg);
}
else
{
Logger.DebugLog("found linked message", Rynchodon.Logger.severity.TRACE);
}
if (msg.IsValid)
store.Receive(msg);
else
Logger.AlwaysLog("failed to create a valid message from builder for " + bm.DestCubeBlock + "/" + bm.SourceCubeBlock, Rynchodon.Logger.severity.WARNING);
}
Logger.DebugLog("added " + bns.MessageList.Length + " message to " + store.PrimaryNode.DebugName, Rynchodon.Logger.severity.DEBUG);
}
// past this point, only synchronized data
if (!MyAPIGateway.Multiplayer.IsServer)
{
data = null;
return;
}
// system disruption
foreach (Disruption.Builder_Disruption bd in data.SystemDisruption)
{
Disruption disrupt;
switch (bd.Type)
{
case "AirVentDepressurize":
disrupt = new AirVentDepressurize();
break;
case "CryoChamberMurder":
disrupt = new CryoChamberMurder();
break;
case "DisableTurret":
disrupt = new DisableTurret();
break;
case "DoorLock":
disrupt = new DoorLock();
break;
case "EMP":
disrupt = new EMP();
break;
case "GravityReverse":
disrupt = new GravityReverse();
break;
case "JumpDriveDrain":
disrupt = new JumpDriveDrain();
break;
case "MedicalRoom":
disrupt = new MedicalRoom();
break;
case "TraitorTurret":
disrupt = new TraitorTurret();
break;
default:
Logger.AlwaysLog("Unknown disruption: " + bd.Type, Rynchodon.Logger.severity.WARNING);
continue;
}
disrupt.Start(bd);
}
// autopilot
if (data.Autopilot != null)
foreach (ShipAutopilot.Builder_Autopilot ba in data.Autopilot)
{
ShipAutopilot autopilot;
if (Registrar.TryGetValue(ba.AutopilotBlock, out autopilot))
autopilot.ResumeFromSave(ba);
else
Logger.AlwaysLog("failed to find autopilot block " + ba.AutopilotBlock, Rynchodon.Logger.severity.WARNING);
}
// programmable block
if (data.ProgrammableBlock != null)
foreach (ProgrammableBlock.Builder_ProgrammableBlock bpa in data.ProgrammableBlock)
{
ProgrammableBlock pb;
if (Registrar.TryGetValue(bpa.BlockId, out pb))
pb.ResumeFromSave(bpa);
else
Logger.AlwaysLog("failed to find programmable block " + bpa.BlockId, Rynchodon.Logger.severity.WARNING);
}
// text panel
if (data.TextPanel != null)
foreach (TextPanel.Builder_TextPanel btp in data.TextPanel)
{
TextPanel panel;
if (Registrar.TryGetValue(btp.BlockId, out panel))
panel.ResumeFromSave(btp);
else
Logger.AlwaysLog("failed to find text panel " + btp.BlockId, Rynchodon.Logger.severity.WARNING);
}
// weapon
if (data.Weapon != null)
foreach (WeaponTargeting.Builder_WeaponTargeting bwt in data.Weapon)
{
WeaponTargeting targeting;
if (WeaponTargeting.TryGetWeaponTargeting(bwt.WeaponId, out targeting))
targeting.ResumeFromSave(bwt);
else
Logger.AlwaysLog("failed to find weapon " + bwt.WeaponId, Rynchodon.Logger.severity.WARNING);
}
// entity values
if (data.EntityValues != null)
UpgradeEntityValue.Load(data.EntityValues);
// sync
if (data.Sync != null)
ASync.SetBuilder(data.Sync);
data = null;
}
/// <summary>
/// Saves data to a variable.
/// </summary>
[OnWorldSave(Order = int.MaxValue)] // has to be last, obviously
private static void SaveData()
{
if (!MyAPIGateway.Multiplayer.IsServer)
return;
try
{
// fetching data needs to happen on game thread as not every script has locks
Builder_ArmsData data = new Builder_ArmsData();
data.SaveTime = Globals.ElapsedTimeTicks;
data.ArmsVersion = Settings.ServerSettings.CurrentVersion;
// network data
Dictionary<long, RelayStorage.Builder_NetworkStorage> storages = new Dictionary<long, RelayStorage.Builder_NetworkStorage>();
Registrar.ForEach<RelayNode>(node => {
if (node.Block != null && node.Storage != null && !storages.ContainsKey(node.Storage.PrimaryNode.EntityId))
{
RelayStorage.Builder_NetworkStorage bns = node.Storage.GetBuilder();
if (bns != null)
storages.Add(bns.PrimaryNode, bns);
}
});
data.AntennaStorage = storages.Values.ToArray();
// disruption
List<Disruption.Builder_Disruption> systemDisrupt = new List<Disruption.Builder_Disruption>();
foreach (Disruption disrupt in Disruption.AllDisruptions)
systemDisrupt.Add(disrupt.GetBuilder());
data.SystemDisruption = systemDisrupt.ToArray();
// autopilot
List<ShipAutopilot.Builder_Autopilot> buildAuto = new List<ShipAutopilot.Builder_Autopilot>();
Registrar.ForEach<ShipAutopilot>(autopilot => {
ShipAutopilot.Builder_Autopilot builder = autopilot.GetBuilder();
if (builder != null)
buildAuto.Add(builder);
});
data.Autopilot = buildAuto.ToArray();
// Sync
data.Sync = ASync.GetBuilder();
MyAPIGateway.Utilities.SetVariable(SaveXml, MyAPIGateway.Utilities.SerializeToXML(data));
if (Instance.m_fileMaster != null)
{
string identifier = Instance.LegacyIdentifier(false);
if (identifier != null)
if (Instance.m_fileMaster.Delete(identifier))
Rynchodon.Logger.DebugLog("file deleted: " + identifier);
}
}
catch (Exception ex)
{
Rynchodon.Logger.AlwaysLog("Exception: " + ex, Rynchodon.Logger.severity.ERROR);
Rynchodon.Logger.Notify("ARMS: failed to save data", 60000, Rynchodon.Logger.severity.ERROR);
}
}
}
}
| |
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.Data.SQLite;
using Burrows.NewIds;
using Burrows.NHib.Tests.Framework;
using Burrows.Saga.Configuration;
namespace Burrows.NHib.Tests.Sagas
{
using System;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Magnum.Extensions;
using Burrows.Saga;
using Burrows.Tests.TextFixtures;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using NUnit.Framework;
using Saga;
using Burrows.Tests.Framework;
using log4net;
[TestFixture, Category("Integration")]
public abstract class ConcurrentSagaTestFixtureBase :
LoopbackTestFixture
{
private IDbConnection _openConnection;
protected ISessionFactory SessionFactory;
protected override void EstablishContext()
{
base.EstablishContext();
var provider = new SqlLiteSessionFactoryProvider(new Type[]
{
typeof(ConcurrentSagaMap), typeof(ConcurrentLegacySagaMap)
});
var sessionFactory = provider.GetSessionFactory();
_openConnection = new SQLiteConnection(provider.Configuration.Properties[NHibernate.Cfg.Environment.ConnectionString]);
_openConnection.Open();
sessionFactory.OpenSession(_openConnection);
SessionFactory = new SingleConnectionSessionFactory(sessionFactory, _openConnection);
BuildSchema(provider.Configuration, _openConnection);
}
protected override void TeardownContext()
{
base.TeardownContext();
if (_openConnection != null)
{
_openConnection.Close();
_openConnection.Dispose();
}
if (SessionFactory != null)
SessionFactory.Dispose();
}
static void BuildSchema(Configuration config, IDbConnection connection)
{
new SchemaExport(config).Execute(true, true, false, connection, null);
}
}
[TestFixture, Category("Integration")]
public class Sending_multiple_messages_to_the_same_saga_at_the_same_time :
ConcurrentSagaTestFixtureBase
{
ISagaRepository<ConcurrentSaga> _sagaRepository;
protected override void EstablishContext()
{
base.EstablishContext();
_sagaRepository = new NHibernateSagaRepository<ConcurrentSaga>(SessionFactory);
}
[Test]
public void Should_process_the_messages_in_order_and_not_at_the_same_time()
{
UnsubscribeAction unsubscribeAction = LocalBus.SubscribeSaga(_sagaRepository);
Guid transactionId = NewId.NextGuid();
Trace.WriteLine("Creating transaction for " + transactionId);
int startValue = 1;
var startConcurrentSaga = new StartConcurrentSaga
{CorrelationId = transactionId, Name = "Chris", Value = startValue};
LocalBus.Publish(startConcurrentSaga);
var saga = _sagaRepository.ShouldContainSaga(transactionId, 8.Seconds());
Assert.IsNotNull(saga);
int nextValue = 2;
var continueConcurrentSaga = new ContinueConcurrentSaga {CorrelationId = transactionId, Value = nextValue};
LocalBus.Publish(continueConcurrentSaga);
saga = _sagaRepository.ShouldContainSaga(x => x.CorrelationId == transactionId && x.Value == nextValue, 8.Seconds());
Assert.IsNotNull(saga);
unsubscribeAction();
Assert.AreEqual(nextValue, saga.Value);
}
}
[TestFixture, Category("Integration")]
public class Sending_multiple_messages_to_the_same_saga_legacy_at_the_same_time :
ConcurrentSagaTestFixtureBase
{
static readonly ILog _log =
LogManager.GetLogger(typeof (Sending_multiple_messages_to_the_same_saga_legacy_at_the_same_time));
ISagaRepository<ConcurrentLegacySaga> _sagaRepository;
protected override void EstablishContext()
{
base.EstablishContext();
_sagaRepository = new NHibernateSagaRepository<ConcurrentLegacySaga>(SessionFactory);
}
[Test]
public void Should_process_the_messages_in_order_and_not_at_the_same_time()
{
UnsubscribeAction unsubscribeAction = LocalBus.SubscribeSaga(_sagaRepository);
Guid transactionId = NewId.NextGuid();
_log.Info("Creating transaction for " + transactionId);
const int startValue = 1;
var startConcurrentSaga = new StartConcurrentSaga
{CorrelationId = transactionId, Name = "Chris", Value = startValue};
LocalBus.Publish(startConcurrentSaga);
_log.Info("Just published the start message");
Thread.Sleep(500);
const int nextValue = 2;
var continueConcurrentSaga = new ContinueConcurrentSaga {CorrelationId = transactionId, Value = nextValue};
LocalBus.Publish(continueConcurrentSaga);
_log.Info("Just published the continue message");
Thread.Sleep(8000);
unsubscribeAction();
foreach (ConcurrentLegacySaga saga in _sagaRepository.Where(x => true))
{
_log.Info("Found saga: " + saga.CorrelationId);
}
int currentValue = _sagaRepository.Where(x => x.CorrelationId == transactionId).First().Value;
Assert.AreEqual(nextValue, currentValue);
}
}
[TestFixture, Category("Integration")]
public class Sending_multiple_initiating_messages_should_not_fail_badly :
ConcurrentSagaTestFixtureBase
{
static readonly ILog _log =
LogManager.GetLogger(typeof (Sending_multiple_initiating_messages_should_not_fail_badly));
ISagaRepository<ConcurrentLegacySaga> _sagaRepository;
protected override void EstablishContext()
{
base.EstablishContext();
_sagaRepository = new NHibernateSagaRepository<ConcurrentLegacySaga>(SessionFactory);
}
[Test]
public void Should_process_the_messages_in_order_and_not_at_the_same_time()
{
Guid transactionId = NewId.NextGuid();
_log.Info("Creating transaction for " + transactionId);
const int startValue = 1;
var startConcurrentSaga = new StartConcurrentSaga
{CorrelationId = transactionId, Name = "Chris", Value = startValue};
LocalBus.Endpoint.Send(startConcurrentSaga);
LocalBus.Endpoint.Send(startConcurrentSaga);
_log.Info("Just published the start message");
UnsubscribeAction unsubscribeAction = LocalBus.SubscribeSaga(_sagaRepository);
Thread.Sleep(1500);
const int nextValue = 2;
var continueConcurrentSaga = new ContinueConcurrentSaga {CorrelationId = transactionId, Value = nextValue};
LocalBus.Publish(continueConcurrentSaga);
_log.Info("Just published the continue message");
Thread.Sleep(8000);
unsubscribeAction();
foreach (ConcurrentLegacySaga saga in _sagaRepository.Where(x => true))
{
_log.Info("Found saga: " + saga.CorrelationId);
}
int currentValue = _sagaRepository.Where(x => x.CorrelationId == transactionId).First().Value;
Assert.AreEqual(nextValue, currentValue);
}
}
}
| |
// 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 Microsoft.Xml.Schema
{
using System;
using System.Diagnostics;
using System.Text;
/// <summary>
/// This structure holds components of an Xsd Duration. It is used internally to support Xsd durations without loss
/// of fidelity. XsdDuration structures are immutable once they've been created.
/// </summary>
internal struct XsdDuration
{
private int _years;
private int _months;
private int _days;
private int _hours;
private int _minutes;
private int _seconds;
private uint _nanoseconds; // High bit is used to indicate whether duration is negative
private const uint NegativeBit = 0x80000000;
private enum Parts
{
HasNone = 0,
HasYears = 1,
HasMonths = 2,
HasDays = 4,
HasHours = 8,
HasMinutes = 16,
HasSeconds = 32,
}
public enum DurationType
{
Duration,
YearMonthDuration,
DayTimeDuration,
};
/// <summary>
/// Construct an XsdDuration from component parts.
/// </summary>
public XsdDuration(bool isNegative, int years, int months, int days, int hours, int minutes, int seconds, int nanoseconds)
{
if (years < 0) throw new ArgumentOutOfRangeException("years");
if (months < 0) throw new ArgumentOutOfRangeException("months");
if (days < 0) throw new ArgumentOutOfRangeException("days");
if (hours < 0) throw new ArgumentOutOfRangeException("hours");
if (minutes < 0) throw new ArgumentOutOfRangeException("minutes");
if (seconds < 0) throw new ArgumentOutOfRangeException("seconds");
if (nanoseconds < 0 || nanoseconds > 999999999) throw new ArgumentOutOfRangeException("nanoseconds");
_years = years;
_months = months;
_days = days;
_hours = hours;
_minutes = minutes;
_seconds = seconds;
_nanoseconds = (uint)nanoseconds;
if (isNegative)
_nanoseconds |= NegativeBit;
}
/// <summary>
/// Construct an XsdDuration from a TimeSpan value.
/// </summary>
public XsdDuration(TimeSpan timeSpan) : this(timeSpan, DurationType.Duration)
{
}
/// <summary>
/// Construct an XsdDuration from a TimeSpan value that represents an xsd:duration, an xdt:dayTimeDuration, or
/// an xdt:yearMonthDuration.
/// </summary>
public XsdDuration(TimeSpan timeSpan, DurationType durationType)
{
long ticks = timeSpan.Ticks;
ulong ticksPos;
bool isNegative;
if (ticks < 0)
{
// Note that (ulong) -Int64.MinValue = Int64.MaxValue + 1, which is what we want for that special case
isNegative = true;
ticksPos = (ulong)-ticks;
}
else
{
isNegative = false;
ticksPos = (ulong)ticks;
}
if (durationType == DurationType.YearMonthDuration)
{
int years = (int)(ticksPos / ((ulong)TimeSpan.TicksPerDay * 365));
int months = (int)((ticksPos % ((ulong)TimeSpan.TicksPerDay * 365)) / ((ulong)TimeSpan.TicksPerDay * 30));
if (months == 12)
{
// If remaining days >= 360 and < 365, then round off to year
years++;
months = 0;
}
this = new XsdDuration(isNegative, years, months, 0, 0, 0, 0, 0);
}
else
{
Debug.Assert(durationType == DurationType.Duration || durationType == DurationType.DayTimeDuration);
// Tick count is expressed in 100 nanosecond intervals
_nanoseconds = (uint)(ticksPos % 10000000) * 100;
if (isNegative)
_nanoseconds |= NegativeBit;
_years = 0;
_months = 0;
_days = (int)(ticksPos / (ulong)TimeSpan.TicksPerDay);
_hours = (int)((ticksPos / (ulong)TimeSpan.TicksPerHour) % 24);
_minutes = (int)((ticksPos / (ulong)TimeSpan.TicksPerMinute) % 60);
_seconds = (int)((ticksPos / (ulong)TimeSpan.TicksPerSecond) % 60);
}
}
/// <summary>
/// Constructs an XsdDuration from a string in the xsd:duration format. Components are stored with loss
/// of fidelity (except in the case of overflow).
/// </summary>
public XsdDuration(string s) : this(s, DurationType.Duration)
{
}
/// <summary>
/// Constructs an XsdDuration from a string in the xsd:duration format. Components are stored without loss
/// of fidelity (except in the case of overflow).
/// </summary>
public XsdDuration(string s, DurationType durationType)
{
XsdDuration result;
Exception exception = TryParse(s, durationType, out result);
if (exception != null)
{
throw exception;
}
_years = result.Years;
_months = result.Months;
_days = result.Days;
_hours = result.Hours;
_minutes = result.Minutes;
_seconds = result.Seconds;
_nanoseconds = (uint)result.Nanoseconds;
if (result.IsNegative)
{
_nanoseconds |= NegativeBit;
}
return;
}
/// <summary>
/// Return true if this duration is negative.
/// </summary>
public bool IsNegative
{
get { return (_nanoseconds & NegativeBit) != 0; }
}
/// <summary>
/// Return number of years in this duration (stored in 31 bits).
/// </summary>
public int Years
{
get { return _years; }
}
/// <summary>
/// Return number of months in this duration (stored in 31 bits).
/// </summary>
public int Months
{
get { return _months; }
}
/// <summary>
/// Return number of days in this duration (stored in 31 bits).
/// </summary>
public int Days
{
get { return _days; }
}
/// <summary>
/// Return number of hours in this duration (stored in 31 bits).
/// </summary>
public int Hours
{
get { return _hours; }
}
/// <summary>
/// Return number of minutes in this duration (stored in 31 bits).
/// </summary>
public int Minutes
{
get { return _minutes; }
}
/// <summary>
/// Return number of seconds in this duration (stored in 31 bits).
/// </summary>
public int Seconds
{
get { return _seconds; }
}
/// <summary>
/// Return number of nanoseconds in this duration.
/// </summary>
public int Nanoseconds
{
get { return (int)(_nanoseconds & ~NegativeBit); }
}
/// <summary>
/// Return number of microseconds in this duration.
/// </summary>
public int Microseconds
{
get { return Nanoseconds / 1000; }
}
/// <summary>
/// Return number of milliseconds in this duration.
/// </summary>
public int Milliseconds
{
get { return Nanoseconds / 1000000; }
}
/// <summary>
/// Normalize year-month part and day-time part so that month < 12, hour < 24, minute < 60, and second < 60.
/// </summary>
public XsdDuration Normalize()
{
int years = Years;
int months = Months;
int days = Days;
int hours = Hours;
int minutes = Minutes;
int seconds = Seconds;
try
{
checked
{
if (months >= 12)
{
years += months / 12;
months %= 12;
}
if (seconds >= 60)
{
minutes += seconds / 60;
seconds %= 60;
}
if (minutes >= 60)
{
hours += minutes / 60;
minutes %= 60;
}
if (hours >= 24)
{
days += hours / 24;
hours %= 24;
}
}
}
catch (OverflowException)
{
throw new OverflowException(string.Format(ResXml.XmlConvert_Overflow, ToString(), "Duration"));
}
return new XsdDuration(IsNegative, years, months, days, hours, minutes, seconds, Nanoseconds);
}
/// <summary>
/// Internal helper method that converts an Xsd duration to a TimeSpan value. This code uses the estimate
/// that there are 365 days in the year and 30 days in a month.
/// </summary>
public TimeSpan ToTimeSpan()
{
return ToTimeSpan(DurationType.Duration);
}
/// <summary>
/// Internal helper method that converts an Xsd duration to a TimeSpan value. This code uses the estimate
/// that there are 365 days in the year and 30 days in a month.
/// </summary>
public TimeSpan ToTimeSpan(DurationType durationType)
{
TimeSpan result;
Exception exception = TryToTimeSpan(durationType, out result);
if (exception != null)
{
throw exception;
}
return result;
}
internal Exception TryToTimeSpan(out TimeSpan result)
{
return TryToTimeSpan(DurationType.Duration, out result);
}
internal Exception TryToTimeSpan(DurationType durationType, out TimeSpan result)
{
Exception exception = null;
ulong ticks = 0;
// Throw error if result cannot fit into a long
try
{
checked
{
// Discard year and month parts if constructing TimeSpan for DayTimeDuration
if (durationType != DurationType.DayTimeDuration)
{
ticks += ((ulong)_years + (ulong)_months / 12) * 365;
ticks += ((ulong)_months % 12) * 30;
}
// Discard day and time parts if constructing TimeSpan for YearMonthDuration
if (durationType != DurationType.YearMonthDuration)
{
ticks += (ulong)_days;
ticks *= 24;
ticks += (ulong)_hours;
ticks *= 60;
ticks += (ulong)_minutes;
ticks *= 60;
ticks += (ulong)_seconds;
// Tick count interval is in 100 nanosecond intervals (7 digits)
ticks *= (ulong)TimeSpan.TicksPerSecond;
ticks += (ulong)Nanoseconds / 100;
}
else
{
// Multiply YearMonth duration by number of ticks per day
ticks *= (ulong)TimeSpan.TicksPerDay;
}
if (IsNegative)
{
// Handle special case of Int64.MaxValue + 1 before negation, since it would otherwise overflow
if (ticks == (ulong)Int64.MaxValue + 1)
{
result = new TimeSpan(Int64.MinValue);
}
else
{
result = new TimeSpan(-((long)ticks));
}
}
else
{
result = new TimeSpan((long)ticks);
}
return null;
}
}
catch (OverflowException)
{
result = TimeSpan.MinValue;
exception = new OverflowException(string.Format(ResXml.XmlConvert_Overflow, durationType, "TimeSpan"));
}
return exception;
}
/// <summary>
/// Return the string representation of this Xsd duration.
/// </summary>
public override string ToString()
{
return ToString(DurationType.Duration);
}
/// <summary>
/// Return the string representation according to xsd:duration rules, xdt:dayTimeDuration rules, or
/// xdt:yearMonthDuration rules.
/// </summary>
internal string ToString(DurationType durationType)
{
StringBuilder sb = new StringBuilder(20);
int nanoseconds, digit, zeroIdx, len;
if (IsNegative)
sb.Append('-');
sb.Append('P');
if (durationType != DurationType.DayTimeDuration)
{
if (_years != 0)
{
sb.Append(XmlConvert.ToString(_years));
sb.Append('Y');
}
if (_months != 0)
{
sb.Append(XmlConvert.ToString(_months));
sb.Append('M');
}
}
if (durationType != DurationType.YearMonthDuration)
{
if (_days != 0)
{
sb.Append(XmlConvert.ToString(_days));
sb.Append('D');
}
if (_hours != 0 || _minutes != 0 || _seconds != 0 || Nanoseconds != 0)
{
sb.Append('T');
if (_hours != 0)
{
sb.Append(XmlConvert.ToString(_hours));
sb.Append('H');
}
if (_minutes != 0)
{
sb.Append(XmlConvert.ToString(_minutes));
sb.Append('M');
}
nanoseconds = Nanoseconds;
if (_seconds != 0 || nanoseconds != 0)
{
sb.Append(XmlConvert.ToString(_seconds));
if (nanoseconds != 0)
{
sb.Append('.');
len = sb.Length;
sb.Length += 9;
zeroIdx = sb.Length - 1;
for (int idx = zeroIdx; idx >= len; idx--)
{
digit = nanoseconds % 10;
sb[idx] = (char)(digit + '0');
if (zeroIdx == idx && digit == 0)
zeroIdx--;
nanoseconds /= 10;
}
sb.Length = zeroIdx + 1;
}
sb.Append('S');
}
}
// Zero is represented as "PT0S"
if (sb[sb.Length - 1] == 'P')
sb.Append("T0S");
}
else
{
// Zero is represented as "T0M"
if (sb[sb.Length - 1] == 'P')
sb.Append("0M");
}
return sb.ToString();
}
internal static Exception TryParse(string s, out XsdDuration result)
{
return TryParse(s, DurationType.Duration, out result);
}
internal static Exception TryParse(string s, DurationType durationType, out XsdDuration result)
{
string errorCode;
int length;
int value, pos, numDigits;
Parts parts = Parts.HasNone;
result = new XsdDuration();
s = s.Trim();
length = s.Length;
pos = 0;
numDigits = 0;
if (pos >= length) goto InvalidFormat;
if (s[pos] == '-')
{
pos++;
result._nanoseconds = NegativeBit;
}
else
{
result._nanoseconds = 0;
}
if (pos >= length) goto InvalidFormat;
if (s[pos++] != 'P') goto InvalidFormat;
errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits);
if (errorCode != null) goto Error;
if (pos >= length) goto InvalidFormat;
if (s[pos] == 'Y')
{
if (numDigits == 0) goto InvalidFormat;
parts |= Parts.HasYears;
result._years = value;
if (++pos == length) goto Done;
errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits);
if (errorCode != null) goto Error;
if (pos >= length) goto InvalidFormat;
}
if (s[pos] == 'M')
{
if (numDigits == 0) goto InvalidFormat;
parts |= Parts.HasMonths;
result._months = value;
if (++pos == length) goto Done;
errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits);
if (errorCode != null) goto Error;
if (pos >= length) goto InvalidFormat;
}
if (s[pos] == 'D')
{
if (numDigits == 0) goto InvalidFormat;
parts |= Parts.HasDays;
result._days = value;
if (++pos == length) goto Done;
errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits);
if (errorCode != null) goto Error;
if (pos >= length) goto InvalidFormat;
}
if (s[pos] == 'T')
{
if (numDigits != 0) goto InvalidFormat;
pos++;
errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits);
if (errorCode != null) goto Error;
if (pos >= length) goto InvalidFormat;
if (s[pos] == 'H')
{
if (numDigits == 0) goto InvalidFormat;
parts |= Parts.HasHours;
result._hours = value;
if (++pos == length) goto Done;
errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits);
if (errorCode != null) goto Error;
if (pos >= length) goto InvalidFormat;
}
if (s[pos] == 'M')
{
if (numDigits == 0) goto InvalidFormat;
parts |= Parts.HasMinutes;
result._minutes = value;
if (++pos == length) goto Done;
errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits);
if (errorCode != null) goto Error;
if (pos >= length) goto InvalidFormat;
}
if (s[pos] == '.')
{
pos++;
parts |= Parts.HasSeconds;
result._seconds = value;
errorCode = TryParseDigits(s, ref pos, true, out value, out numDigits);
if (errorCode != null) goto Error;
if (numDigits == 0)
{ //If there are no digits after the decimal point, assume 0
value = 0;
}
// Normalize to nanosecond intervals
for (; numDigits > 9; numDigits--)
value /= 10;
for (; numDigits < 9; numDigits++)
value *= 10;
result._nanoseconds |= (uint)value;
if (pos >= length) goto InvalidFormat;
if (s[pos] != 'S') goto InvalidFormat;
if (++pos == length) goto Done;
}
else if (s[pos] == 'S')
{
if (numDigits == 0) goto InvalidFormat;
parts |= Parts.HasSeconds;
result._seconds = value;
if (++pos == length) goto Done;
}
}
// Duration cannot end with digits
if (numDigits != 0) goto InvalidFormat;
// No further characters are allowed
if (pos != length) goto InvalidFormat;
Done:
// At least one part must be defined
if (parts == Parts.HasNone) goto InvalidFormat;
if (durationType == DurationType.DayTimeDuration)
{
if ((parts & (Parts.HasYears | Parts.HasMonths)) != 0)
goto InvalidFormat;
}
else if (durationType == DurationType.YearMonthDuration)
{
if ((parts & ~(XsdDuration.Parts.HasYears | XsdDuration.Parts.HasMonths)) != 0)
goto InvalidFormat;
}
return null;
InvalidFormat:
return new FormatException(string.Format(ResXml.XmlConvert_BadFormat, s, durationType));
Error:
return new OverflowException(string.Format(ResXml.XmlConvert_Overflow, s, durationType));
}
/// Helper method that constructs an integer from leading digits starting at s[offset]. "offset" is
/// updated to contain an offset just beyond the last digit. The number of digits consumed is returned in
/// cntDigits. The integer is returned (0 if no digits). If the digits cannot fit into an Int32:
/// 1. If eatDigits is true, then additional digits will be silently discarded (don't count towards numDigits)
/// 2. If eatDigits is false, an overflow exception is thrown
private static string TryParseDigits(string s, ref int offset, bool eatDigits, out int result, out int numDigits)
{
int offsetStart = offset;
int offsetEnd = s.Length;
int digit;
result = 0;
numDigits = 0;
while (offset < offsetEnd && s[offset] >= '0' && s[offset] <= '9')
{
digit = s[offset] - '0';
if (result > (Int32.MaxValue - digit) / 10)
{
if (!eatDigits)
{
return ResXml.XmlConvert_Overflow;
}
// Skip past any remaining digits
numDigits = offset - offsetStart;
while (offset < offsetEnd && s[offset] >= '0' && s[offset] <= '9')
{
offset++;
}
return null;
}
result = result * 10 + digit;
offset++;
}
numDigits = offset - offsetStart;
return 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.Collections;
using System.Diagnostics;
using System.IO;
using System.Text;
using Xunit;
namespace System.Runtime.InteropServices.RuntimeInformationTests
{
public class DescriptionNameTests
{
[Fact]
public void DumpRuntimeInformationToConsole()
{
// Not really a test, but useful to dump a variety of information to the test log to help
// debug environmental issues, in particular in CI
string dvs = PlatformDetection.GetDistroVersionString();
string osd = RuntimeInformation.OSDescription.Trim();
string osv = Environment.OSVersion.ToString();
string osa = RuntimeInformation.OSArchitecture.ToString();
Console.WriteLine($"### OS: Distro={dvs} Description={osd} Version={osv} Arch={osa}");
string lcr = PlatformDetection.LibcRelease;
string lcv = PlatformDetection.LibcVersion;
Console.WriteLine($"### LIBC: Release={lcr} Version={lcv}");
Console.WriteLine($"### FRAMEWORK: Version={Environment.Version} Description={RuntimeInformation.FrameworkDescription.Trim()}");
if (!PlatformDetection.IsNetNative)
{
string binariesLocation = Path.GetDirectoryName(typeof(object).Assembly.Location);
string binariesLocationFormat = PlatformDetection.IsInAppContainer ? "Unknown" : new DriveInfo(binariesLocation).DriveFormat;
Console.WriteLine($"### BINARIES: {binariesLocation} (drive format {binariesLocationFormat})");
}
string tempPathLocation = Path.GetTempPath();
string tempPathLocationFormat = PlatformDetection.IsInAppContainer ? "Unknown" : new DriveInfo(tempPathLocation).DriveFormat;
Console.WriteLine($"### TEMP PATH: {tempPathLocation} (drive format {tempPathLocationFormat})");
Console.WriteLine($"### CURRENT DIRECTORY: {Environment.CurrentDirectory}");
string cgroupsLocation = Interop.cgroups.s_cgroupMemoryPath;
if (cgroupsLocation != null)
{
Console.WriteLine($"### CGROUPS MEMORY: {cgroupsLocation}");
}
Console.WriteLine($"### ENVIRONMENT VARIABLES");
foreach (DictionaryEntry envvar in Environment.GetEnvironmentVariables())
{
Console.WriteLine($"###\t{envvar.Key}: {envvar.Value}");
}
using (Process p = Process.GetCurrentProcess())
{
var sb = new StringBuilder();
sb.AppendLine("### PROCESS INFORMATION:");
sb.AppendFormat($"###\tArchitecture: {RuntimeInformation.ProcessArchitecture.ToString()}").AppendLine();
foreach (string prop in new string[]
{
#pragma warning disable 0618 // some of these Int32-returning properties are marked obsolete
nameof(p.BasePriority),
nameof(p.HandleCount),
nameof(p.Id),
nameof(p.MachineName),
nameof(p.MainModule),
nameof(p.MainWindowHandle),
nameof(p.MainWindowTitle),
nameof(p.MaxWorkingSet),
nameof(p.MinWorkingSet),
nameof(p.NonpagedSystemMemorySize),
nameof(p.NonpagedSystemMemorySize64),
nameof(p.PagedMemorySize),
nameof(p.PagedMemorySize64),
nameof(p.PagedSystemMemorySize),
nameof(p.PagedSystemMemorySize64),
nameof(p.PeakPagedMemorySize),
nameof(p.PeakPagedMemorySize64),
nameof(p.PeakVirtualMemorySize),
nameof(p.PeakVirtualMemorySize64),
nameof(p.PeakWorkingSet),
nameof(p.PeakWorkingSet64),
nameof(p.PriorityBoostEnabled),
nameof(p.PriorityClass),
nameof(p.PrivateMemorySize),
nameof(p.PrivateMemorySize64),
nameof(p.PrivilegedProcessorTime),
nameof(p.ProcessName),
nameof(p.ProcessorAffinity),
nameof(p.Responding),
nameof(p.SessionId),
nameof(p.StartTime),
nameof(p.TotalProcessorTime),
nameof(p.UserProcessorTime),
nameof(p.VirtualMemorySize),
nameof(p.VirtualMemorySize64),
nameof(p.WorkingSet),
nameof(p.WorkingSet64),
#pragma warning restore 0618
})
{
sb.Append($"###\t{prop}: ");
try
{
sb.Append(p.GetType().GetProperty(prop).GetValue(p));
}
catch (Exception e)
{
sb.Append($"(Exception: {e.Message})");
}
sb.AppendLine();
}
Console.WriteLine(sb.ToString());
}
if (osd.Contains("Linux"))
{
// Dump several procfs files
foreach (string path in new string[] { "/proc/self/mountinfo", "/proc/self/cgroup", "/proc/self/limits" })
{
Console.WriteLine($"### CONTENTS OF \"{path}\":");
try
{
using (Process cat = Process.Start("cat", path))
{
cat.WaitForExit();
}
}
catch (Exception e)
{
Console.WriteLine($"###\t(Exception: {e.Message})");
}
}
}
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.Netcoreapp)]
public void VerifyRuntimeNameOnNetCoreApp()
{
Assert.True(RuntimeInformation.FrameworkDescription.StartsWith(".NET Core"), RuntimeInformation.FrameworkDescription);
Assert.Same(RuntimeInformation.FrameworkDescription, RuntimeInformation.FrameworkDescription);
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.UapAot)]
public void VerifyRuntimeNameOnNetNative()
{
Assert.True(RuntimeInformation.FrameworkDescription.StartsWith(".NET Native"), RuntimeInformation.FrameworkDescription);
Assert.Same(RuntimeInformation.FrameworkDescription, RuntimeInformation.FrameworkDescription);
}
[Fact]
public void VerifyOSDescription()
{
Assert.NotNull(RuntimeInformation.OSDescription);
Assert.Same(RuntimeInformation.OSDescription, RuntimeInformation.OSDescription);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
[PlatformSpecific(TestPlatforms.Windows)]
public void VerifyWindowsDescriptionDoesNotContainTrailingWhitespace()
{
Assert.False(RuntimeInformation.OSDescription.EndsWith(" "));
}
[Fact, PlatformSpecific(TestPlatforms.Windows)] // Checks Windows name in RuntimeInformation
public void VerifyWindowsName()
{
Assert.Contains("windows", RuntimeInformation.OSDescription, StringComparison.OrdinalIgnoreCase);
}
[Fact, PlatformSpecific(TestPlatforms.Linux)] // Checks Linux name in RuntimeInformation
public void VerifyLinuxName()
{
Assert.Contains("linux", RuntimeInformation.OSDescription, StringComparison.OrdinalIgnoreCase);
}
[Fact, PlatformSpecific(TestPlatforms.NetBSD)] // Checks NetBSD name in RuntimeInformation
public void VerifyNetBSDName()
{
Assert.Contains("netbsd", RuntimeInformation.OSDescription, StringComparison.OrdinalIgnoreCase);
}
[Fact, PlatformSpecific(TestPlatforms.FreeBSD)] // Checks FreeBSD name in RuntimeInformation
public void VerifyFreeBSDName()
{
Assert.Contains("FreeBSD", RuntimeInformation.OSDescription, StringComparison.OrdinalIgnoreCase);
}
[Fact, PlatformSpecific(TestPlatforms.OSX)] // Checks OSX name in RuntimeInformation
public void VerifyOSXName()
{
Assert.Contains("darwin", RuntimeInformation.OSDescription, StringComparison.OrdinalIgnoreCase);
}
}
}
| |
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* 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 Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
namespace Alphaleonis.Win32
{
/// <summary>Base class for classes representing a block of unmanaged memory.</summary>
internal abstract class SafeNativeMemoryBufferHandle : SafeHandleZeroOrMinusOneIsInvalid
{
#region Private Fields
private int m_capacity;
#endregion
#region Constructors
protected SafeNativeMemoryBufferHandle(bool ownsHandle)
: base(ownsHandle)
{
}
/// <summary>Initializes a new instance of the <see cref="SafeNativeMemoryBufferHandle"/> specifying the allocated capacity of the memory block.</summary>
/// <param name="capacity">The capacity.</param>
protected SafeNativeMemoryBufferHandle(int capacity)
: this(true)
{
m_capacity = capacity;
}
protected SafeNativeMemoryBufferHandle(IntPtr memory, int capacity)
: this(capacity)
{
SetHandle(memory);
}
#endregion
#region Properties
/// <summary>Gets the capacity. Only valid if this instance was created using a constructor that specifies the size,
/// it is not correct if this handle was returned by a native method using p/invoke.
/// </summary>
public int Capacity
{
get { return m_capacity; }
}
#endregion
#region Public Methods
/// <summary>Copies data from a one-dimensional, managed 8-bit unsigned integer array to the unmanaged memory pointer referenced by this instance.</summary>
/// <param name="source">The one-dimensional array to copy from. </param>
/// <param name="startIndex">The zero-based index into the array where Copy should start.</param>
/// <param name="length">The number of array elements to copy.</param>
public void CopyFrom(byte[] source, int startIndex, int length)
{
Marshal.Copy(source, startIndex, handle, length);
}
public void CopyFrom(char[] source, int startIndex, int length)
{
Marshal.Copy(source, startIndex, handle, length);
}
public void CopyFrom(char[] source, int startIndex, int length, int offset)
{
Marshal.Copy(source, startIndex, new IntPtr(handle.ToInt64() + offset), length);
}
/// <summary>Copies data from an unmanaged memory pointer to a managed 8-bit unsigned integer array.</summary>
/// <param name="destination">The array to copy to.</param>
/// <param name="destinationOffset">The zero-based index in the destination array where copying should start.</param>
/// <param name="length">The number of array elements to copy.</param>
public void CopyTo(byte[] destination, int destinationOffset, int length)
{
if (destination == null)
throw new ArgumentNullException("destination");
if (destinationOffset < 0)
throw new ArgumentOutOfRangeException("destinationOffset", Resources.Negative_Destination_Offset);
if (length < 0)
throw new ArgumentOutOfRangeException("length", Resources.Negative_Length);
if (destinationOffset + length > destination.Length)
throw new ArgumentException(Resources.Destination_Buffer_Not_Large_Enough);
if (length > Capacity)
throw new ArgumentOutOfRangeException("length", Resources.Source_Offset_And_Length_Outside_Bounds);
Marshal.Copy(handle, destination, destinationOffset, length);
}
/// <summary>Copies data from this unmanaged memory pointer to a managed 8-bit unsigned integer array.</summary>
/// <param name="sourceOffset">The offset in the buffer to start copying from.</param>
/// <param name="destination">The array to copy to.</param>
/// <param name="destinationOffset">The zero-based index in the destination array where copying should start.</param>
/// <param name="length">The number of array elements to copy.</param>
public void CopyTo(int sourceOffset, byte[] destination, int destinationOffset, int length)
{
if (destination == null)
throw new ArgumentNullException("destination");
if (destinationOffset < 0)
throw new ArgumentOutOfRangeException("destinationOffset", Resources.Negative_Destination_Offset);
if (length < 0)
throw new ArgumentOutOfRangeException("length", Resources.Negative_Length);
if (destinationOffset + length > destination.Length)
throw new ArgumentException(Resources.Destination_Buffer_Not_Large_Enough);
if (length > Capacity)
throw new ArgumentOutOfRangeException("length", Resources.Source_Offset_And_Length_Outside_Bounds);
Marshal.Copy(new IntPtr(handle.ToInt64() + sourceOffset), destination, destinationOffset, length);
}
public byte[] ToByteArray(int startIndex, int length)
{
if (IsInvalid)
return null;
byte[] arr = new byte[length];
Marshal.Copy(handle, arr, startIndex, length);
return arr;
}
#region Write
public void WriteInt16(int offset, short value)
{
Marshal.WriteInt16(handle, offset, value);
}
public void WriteInt16(int offset, char value)
{
Marshal.WriteInt16(handle, offset, value);
}
public void WriteInt16(char value)
{
Marshal.WriteInt16(handle, value);
}
public void WriteInt16(short value)
{
Marshal.WriteInt16(handle, value);
}
public void WriteInt32(int offset, short value)
{
Marshal.WriteInt32(handle, offset, value);
}
public void WriteInt32(int value)
{
Marshal.WriteInt32(handle, value);
}
public void WriteInt64(int offset, long value)
{
Marshal.WriteInt64(handle, offset, value);
}
public void WriteInt64(long value)
{
Marshal.WriteInt64(handle, value);
}
public void WriteByte(int offset, byte value)
{
Marshal.WriteByte(handle, offset, value);
}
public void WriteByte(byte value)
{
Marshal.WriteByte(handle, value);
}
public void WriteIntPtr(int offset, IntPtr value)
{
Marshal.WriteIntPtr(handle, offset, value);
}
public void WriteIntPtr(IntPtr value)
{
Marshal.WriteIntPtr(handle, value);
}
#endregion // Write
#region Read
public byte ReadByte()
{
return Marshal.ReadByte(handle);
}
public byte ReadByte(int offset)
{
return Marshal.ReadByte(handle, offset);
}
public short ReadInt16()
{
return Marshal.ReadInt16(handle);
}
public short ReadInt16(int offset)
{
return Marshal.ReadInt16(handle, offset);
}
public int ReadInt32()
{
return Marshal.ReadInt32(handle);
}
public int ReadInt32(int offset)
{
return Marshal.ReadInt32(handle, offset);
}
public long ReadInt64()
{
return Marshal.ReadInt64(handle);
}
public long ReadInt64(int offset)
{
return Marshal.ReadInt64(handle, offset);
}
public IntPtr ReadIntPtr()
{
return Marshal.ReadIntPtr(handle);
}
public IntPtr ReadIntPtr(int offset)
{
return Marshal.ReadIntPtr(handle, offset);
}
#endregion // Read
/// <summary>Marshals data from a managed object to an unmanaged block of memory.</summary>
public void StructureToPtr(object structure, bool deleteOld)
{
Marshal.StructureToPtr(structure, handle, deleteOld);
}
/// <summary>Marshals data from an unmanaged block of memory to a newly allocated managed object of the specified type.</summary>
/// <returns>A managed object containing the data pointed to by the ptr parameter.</returns>
public T PtrToStructure<T>(int offset)
{
return (T) Marshal.PtrToStructure(new IntPtr(handle.ToInt64() + offset), typeof (T));
}
/// <summary>Allocates a managed System.String and copies a specified number of characters from an unmanaged Unicode string into it.</summary>
/// <returns>A managed string that holds a copy of the unmanaged string if the value of the ptr parameter is not null; otherwise, this method returns null.</returns>
public string PtrToStringUni(int offset, int length)
{
return Marshal.PtrToStringUni(new IntPtr(handle.ToInt64() + offset), length);
}
/// <summary>Allocates a managed System.String and copies all characters up to the first null character from an unmanaged Unicode string into it.</summary>
/// <returns>A managed string that holds a copy of the unmanaged string if the value of the ptr parameter is not null; otherwise, this method returns null.</returns>
public string PtrToStringUni()
{
return Marshal.PtrToStringUni(handle);
}
#endregion // Public Methods
}
}
| |
// ***********************************************************************
// Copyright (c) 2014-2015 Charlie Poole, Rob Prouse
//
// 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 NUnit.Framework.Interfaces;
namespace NUnitLite
{
/// <summary>
/// Helper class used to summarize the result of a test run
/// </summary>
public class ResultSummary
{
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ResultSummary"/> class.
/// </summary>
/// <param name="result">The result.</param>
public ResultSummary(ITestResult result)
{
InitializeCounters();
ResultState = result.ResultState;
StartTime = result.StartTime;
EndTime = result.EndTime;
Duration = result.Duration;
Summarize(result);
}
#endregion
#region Properties
/// <summary>
/// Gets the number of test cases for which results
/// have been summarized. Any tests excluded by use of
/// Category or Explicit attributes are not counted.
/// </summary>
public int TestCount { get; private set; }
/// <summary>
/// Returns the number of test cases actually run.
/// </summary>
public int RunCount
{
get { return PassCount + ErrorCount + FailureCount + InconclusiveCount; }
}
/// <summary>
/// Gets the number of tests not run for any reason.
/// </summary>
public int NotRunCount
{
get { return InvalidCount + SkipCount + IgnoreCount + ExplicitCount; }
}
/// <summary>
/// Returns the number of failed test cases (including errors and invalid tests)
/// </summary>
public int FailedCount
{
get { return FailureCount + InvalidCount + ErrorCount; }
}
/// <summary>
/// Returns the sum of skipped test cases, including ignored and explicit tests
/// </summary>
public int TotalSkipCount
{
get { return SkipCount + IgnoreCount + ExplicitCount; }
}
/// <summary>
/// Gets the count of passed tests
/// </summary>
public int PassCount { get; private set; }
/// <summary>
/// Gets count of failed tests, excluding errors and invalid tests
/// </summary>
public int FailureCount { get; private set; }
/// <summary>
/// Gets count of tests with warnings
/// </summary>
public int WarningCount { get; private set; }
/// <summary>
/// Gets the error count
/// </summary>
public int ErrorCount { get; private set; }
/// <summary>
/// Gets the count of inconclusive tests
/// </summary>
public int InconclusiveCount { get; private set; }
/// <summary>
/// Returns the number of test cases that were not runnable
/// due to errors in the signature of the class or method.
/// Such tests are also counted as Errors.
/// </summary>
public int InvalidCount { get; private set; }
/// <summary>
/// Gets the count of skipped tests, excluding ignored tests
/// </summary>
public int SkipCount { get; private set; }
/// <summary>
/// Gets the ignore count
/// </summary>
public int IgnoreCount { get; private set; }
/// <summary>
/// Gets the explicit count
/// </summary>
public int ExplicitCount { get; private set; }
/// <summary>
/// Invalid Test Fixtures
/// </summary>
public int InvalidTestFixtures { get; private set; }
/// <summary>
/// Gets the ResultState of the test result, which
/// indicates the success or failure of the test.
/// </summary>
public ResultState ResultState { get; }
/// <summary>
/// Gets or sets the time the test started running.
/// </summary>
public DateTime StartTime { get; }
/// <summary>
/// Gets or sets the time the test finished running.
/// </summary>
public DateTime EndTime { get; }
/// <summary>
/// Gets or sets the elapsed time for running the test in seconds
/// </summary>
public double Duration { get; }
#endregion
#region Helper Methods
private void InitializeCounters()
{
TestCount = 0;
PassCount = 0;
FailureCount = 0;
WarningCount = 0;
ErrorCount = 0;
InconclusiveCount = 0;
SkipCount = 0;
IgnoreCount = 0;
ExplicitCount = 0;
InvalidCount = 0;
}
private void Summarize(ITestResult result)
{
var label = result.ResultState.Label;
var status = result.ResultState.Status;
if (result.Test.IsSuite)
{
if (status == TestStatus.Failed && label == "Invalid")
InvalidTestFixtures++;
foreach (ITestResult r in result.Children)
Summarize(r);
}
else
{
TestCount++;
switch (status)
{
case TestStatus.Passed:
PassCount++;
break;
case TestStatus.Skipped:
if (label == "Ignored")
IgnoreCount++;
else if (label == "Explicit")
ExplicitCount++;
else
SkipCount++;
break;
case TestStatus.Warning:
WarningCount++; // This is not actually used by the nunit 2 format
break;
case TestStatus.Failed:
if (label == "Invalid")
InvalidCount++;
else if (label == "Error")
ErrorCount++;
else
FailureCount++;
break;
case TestStatus.Inconclusive:
InconclusiveCount++;
break;
}
return;
}
}
#endregion
}
}
| |
using UnityEngine;
using System;
namespace ST
{
public class MapLayer
{
// parent
private Map map;
public string name;
public Texture2D tileset;
public Size tileSize = new Size (32f, 16f);
public Size textureTileSize = new Size (32f, 16f);
public int cols = 24;
public int rows = 24;
public float tileHeightStep = 3.0f;
public int maxTileSteps = 8;
public bool showTileGround = false;
public float zOffset = 0;
// TODO: refactor to tile class and private with accessors
private GameObject[,] tiles;
private GameObject[,] tilesGround;
public MapLayer (Map map, string name, Texture2D tileset, Size tileSize, Size texTileSize, bool showGround)
{
this.name = name;
this.map = map;
this.tileset = tileset;
this.tileSize = tileSize;
this.textureTileSize = texTileSize;
int cols = map.cols;
int rows = map.rows;
tiles = new GameObject[cols, rows];
if (this.showTileGround)
tilesGround = new GameObject[cols, rows];
}
public GameObject createTile (GameObject parentNode, TileCoord coord, int tileIndex)
{
GameObject tile = new GameObject ();
var sr = tile.AddComponent<SpriteRenderer> ();
sr.sprite = spriteCreateForTileIndex (tileIndex);
// attach as child
tile.transform.parent = parentNode.transform;
var xy = map.posForTile (coord);
var z = zOrderForTile (coord);
var yoff = map.heightForTile (coord);
//Debug.Log ("refresh height yoff = " + yoff);
tile.transform.localPosition = new Vector3 (xy.x, xy.y + yoff, z);
tiles [coord.c, coord.r] = tile;
return tile;
}
public void changeTileColor (TileCoord coord, Color color)
{
if (! map.validTileCoord (coord))
return;
GameObject tile = tiles [coord.c, coord.r];
//Debug.Log (coord);
//Debug.Log (color);
if (tile) {
var sr = tile.GetComponent<SpriteRenderer> ();
sr.material.color = color;
}
}
// z order in Unity is + into the screen
public float zOrderForTile (TileCoord coord)
{
if (! map.validTileCoord (coord))
return 0;
// greater y = greater z (top center to lower left should decrease z)
// greater tile x = greater z (top center to lower right)
float h = map.heightForTile (coord);
float zHeightOffset = h / (float)maxTileSteps * 0.5f;
return zOffset - (coord.r + coord.c) - zHeightOffset;
//return zOffset - (coord.r + coord.c);
}
public void refreshTile (TileCoord coord)
{
if (! map.validTileCoord (coord))
return;
if (map.heightForTile (coord) >= 0) {
var tile = tiles [coord.c, coord.r];
if (null != tile) {
var xy = map.posForTile (coord);
var z = zOrderForTile (coord);
var yoff = map.heightForTile (coord);
//Debug.Log ("refresh height yoff = " + yoff);
tile.transform.localPosition = new Vector3 (xy.x, xy.y + yoff, z);
// TODO: need to figure out how to anchor the child to (0,1f)
// ground underneath
if (showTileGround) {
// find child
GameObject child = tilesGround [coord.c, coord.r];
if (! child) {
child = GameObject.CreatePrimitive (PrimitiveType.Quad);
child.renderer.material.color = new Color (0.35f, 0.35f, 0.25f);
child.transform.parent = tile.transform;
tilesGround [coord.c, coord.r] = child;
}
float groundHeight = map.heightForTile (coord);
child.transform.localPosition = new Vector3 (0, -groundHeight, 0);
child.transform.localScale = new Vector3 (tileSize.width * 0.95f, groundHeight * 2f + tileSize.height * 0.15f, 1);
}
}
}
}
public Sprite spriteCreateForTileIndex (int index)
{
Vector2 pivot = new Vector2 (0.5f, 0.0f);
Rect rect = rectForTileIndex (index);
return Sprite.Create (tileset, rect, pivot, 1f);
}
// map tile coord to rect in texture
// row - starts 0 at top increasing down (like in Tiled)
public Rect rectForTile (TileCoord coord)
{
return new Rect (coord.c * textureTileSize.width, tileset.height - (coord.r * textureTileSize.height), textureTileSize.width, textureTileSize.height);
}
public Rect rectForTileIndex (int index)
{
int colPerRow = (int)(tileset.width / textureTileSize.width);
int row = index / colPerRow;
int col = index - row * colPerRow;
return rectForTile (new TileCoord (col, row + 1));
}
public void changeTileIndex (GameObject parentNode, TileCoord coord, int tileIndex)
{
if (! map.validTileCoord (coord))
return;
GameObject tile = tiles [coord.c, coord.r];
if (null == tile && tileIndex >= 0) {
tile = createTile (parentNode, coord, tileIndex);
} else {
if (tileIndex >= 0) {
var sr = tile.GetComponent<SpriteRenderer> ();
//sr.sprite.textureRect = rectForTileIndex(tileIndex);
sr.sprite = spriteCreateForTileIndex (tileIndex);
} else {
GameObject.Destroy (tile);
tiles [coord.c, coord.r] = null;
}
}
}
// base position of tile (doesn't include height)
// 0,0 => halfcols, fullrows
public Vector3 posForTile (TileCoord coord)
{
var mh = rows;
var mw = cols;
var th = tileSize.height;
var tw = tileSize.width;
float x = tw / 2f * (mw + coord.c - coord.r);
float y = th / 2f * ((mh * 2f - coord.c - coord.r) - 1f);
return new Vector3 (x, y, 0);
}
// base position of tile (doesn't include height)
// 0,0 => halfcols, fullrows
public Vector3 posForTile (Vector2 coordFloat)
{
var mh = rows;
var mw = cols;
var th = tileSize.height;
var tw = tileSize.width;
// coord is in "row,col" format that maps to "x,y"
float x = tw / 2f * (mw + coordFloat.y - coordFloat.x);
float y = th / 2f * ((mh * 2f - coordFloat.y - coordFloat.x) - 1f);
return new Vector3 (x, y, 0);
}
// calculating the tile coordinates from world location
public TileCoord tileForPos (Vector2 pos)
{
var x = pos.x;
var y = pos.y;
var mh = rows;
var mw = cols;
var th = tileSize.height;
var tw = tileSize.width;
var isox = Mathf.FloorToInt (mh - y / th + x / tw - mw / 2);// - 1/2),
var isoy = Mathf.FloorToInt (mh - y / th - x / tw + mw / 2 + 1 / 2); // - 3/2)
return new TileCoord (isox, isoy, 0);
}
public bool tileExists (TileCoord coord)
{
return (tiles [coord.c, coord.r] != null);
}
}
}
| |
/*
* OEML - REST API
*
* This section will provide necessary information about the `CoinAPI OEML REST API` protocol. <br/> This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a> <br/><br/> Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)
*
* The version of the OpenAPI document: v1
* Contact: support@coinapi.io
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace CoinAPI.OMS.API.SDK.Client
{
/// <summary>
/// Utility functions providing some benefit to API client consumers.
/// </summary>
public static class ClientUtils
{
/// <summary>
/// Sanitize filename by removing the path
/// </summary>
/// <param name="filename">Filename</param>
/// <returns>Filename</returns>
public static string SanitizeFilename(string filename)
{
Match match = Regex.Match(filename, @".*[/\\](.*)$");
return match.Success ? match.Groups[1].Value : filename;
}
/// <summary>
/// Convert params to key/value pairs.
/// Use collectionFormat to properly format lists and collections.
/// </summary>
/// <param name="collectionFormat">The swagger-supported collection format, one of: csv, tsv, ssv, pipes, multi</param>
/// <param name="name">Key name.</param>
/// <param name="value">Value object.</param>
/// <returns>A multimap of keys with 1..n associated values.</returns>
public static Multimap<string, string> ParameterToMultiMap(string collectionFormat, string name, object value)
{
var parameters = new Multimap<string, string>();
if (value is ICollection collection && collectionFormat == "multi")
{
foreach (var item in collection)
{
parameters.Add(name, ParameterToString(item));
}
}
else if (value is IDictionary dictionary)
{
if(collectionFormat == "deepObject") {
foreach (DictionaryEntry entry in dictionary)
{
parameters.Add(name + "[" + entry.Key + "]", ParameterToString(entry.Value));
}
}
else {
foreach (DictionaryEntry entry in dictionary)
{
parameters.Add(entry.Key.ToString(), ParameterToString(entry.Value));
}
}
}
else
{
parameters.Add(name, ParameterToString(value));
}
return parameters;
}
/// <summary>
/// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime.
/// If parameter is a list, join the list with ",".
/// Otherwise just return the string.
/// </summary>
/// <param name="obj">The parameter (header, path, query, form).</param>
/// <param name="configuration">An optional configuration instance, providing formatting options used in processing.</param>
/// <returns>Formatted string.</returns>
public static string ParameterToString(object obj, IReadableConfiguration configuration = null)
{
if (obj is DateTime dateTime)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return dateTime.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat);
if (obj is DateTimeOffset dateTimeOffset)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return dateTimeOffset.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat);
if (obj is bool boolean)
return boolean ? "true" : "false";
if (obj is ICollection collection)
return string.Join(",", collection.Cast<object>());
return Convert.ToString(obj, CultureInfo.InvariantCulture);
}
/// <summary>
/// URL encode a string
/// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50
/// </summary>
/// <param name="input">string to be URL encoded</param>
/// <returns>Byte array</returns>
public static string UrlEncode(string input)
{
const int maxLength = 32766;
if (input == null)
{
throw new ArgumentNullException("input");
}
if (input.Length <= maxLength)
{
return Uri.EscapeDataString(input);
}
StringBuilder sb = new StringBuilder(input.Length * 2);
int index = 0;
while (index < input.Length)
{
int length = Math.Min(input.Length - index, maxLength);
string subString = input.Substring(index, length);
sb.Append(Uri.EscapeDataString(subString));
index += subString.Length;
}
return sb.ToString();
}
/// <summary>
/// Encode string in base64 format.
/// </summary>
/// <param name="text">string to be encoded.</param>
/// <returns>Encoded string.</returns>
public static string Base64Encode(string text)
{
return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text));
}
/// <summary>
/// Convert stream to byte array
/// </summary>
/// <param name="inputStream">Input stream to be converted</param>
/// <returns>Byte array</returns>
public static byte[] ReadAsBytes(Stream inputStream)
{
using (var ms = new MemoryStream())
{
inputStream.CopyTo(ms);
return ms.ToArray();
}
}
/// <summary>
/// Select the Content-Type header's value from the given content-type array:
/// if JSON type exists in the given array, use it;
/// otherwise use the first one defined in 'consumes'
/// </summary>
/// <param name="contentTypes">The Content-Type array to select from.</param>
/// <returns>The Content-Type header to use.</returns>
public static string SelectHeaderContentType(string[] contentTypes)
{
if (contentTypes.Length == 0)
return null;
foreach (var contentType in contentTypes)
{
if (IsJsonMime(contentType))
return contentType;
}
return contentTypes[0]; // use the first content type specified in 'consumes'
}
/// <summary>
/// Select the Accept header's value from the given accepts array:
/// if JSON exists in the given array, use it;
/// otherwise use all of them (joining into a string)
/// </summary>
/// <param name="accepts">The accepts array to select from.</param>
/// <returns>The Accept header to use.</returns>
public static string SelectHeaderAccept(string[] accepts)
{
if (accepts.Length == 0)
return null;
if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase))
return "application/json";
return string.Join(",", accepts);
}
/// <summary>
/// Provides a case-insensitive check that a provided content type is a known JSON-like content type.
/// </summary>
public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$");
/// <summary>
/// Check if the given MIME is a JSON MIME.
/// JSON MIME examples:
/// application/json
/// application/json; charset=UTF8
/// APPLICATION/JSON
/// application/vnd.company+json
/// </summary>
/// <param name="mime">MIME</param>
/// <returns>Returns True if MIME type is json.</returns>
public static bool IsJsonMime(string mime)
{
if (string.IsNullOrWhiteSpace(mime)) return false;
return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json");
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NonSilo.Tests.Utilities;
using NSubstitute;
using Orleans;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Runtime.MembershipService;
using TestExtensions;
using Xunit;
using Xunit.Abstractions;
namespace NonSilo.Tests.Membership
{
[TestCategory("BVT"), TestCategory("Membership")]
public class MembershipAgentTests
{
private readonly ITestOutputHelper output;
private readonly LoggerFactory loggerFactory;
private readonly ILocalSiloDetails localSiloDetails;
private readonly SiloAddress localSilo;
private readonly IFatalErrorHandler fatalErrorHandler;
private readonly IMembershipGossiper membershipGossiper;
private readonly SiloLifecycleSubject lifecycle;
private readonly List<DelegateAsyncTimer> timers;
private readonly ConcurrentDictionary<string, ConcurrentQueue<(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion)>> timerCalls;
private readonly DelegateAsyncTimerFactory timerFactory;
private readonly InMemoryMembershipTable membershipTable;
private readonly IOptions<ClusterMembershipOptions> clusterMembershipOptions;
private readonly MembershipTableManager manager;
private readonly ClusterHealthMonitor clusterHealthMonitor;
private readonly MembershipAgent agent;
public MembershipAgentTests(ITestOutputHelper output)
{
this.output = output;
this.loggerFactory = new LoggerFactory(new[] { new XunitLoggerProvider(this.output) });
this.localSiloDetails = Substitute.For<ILocalSiloDetails>();
this.localSilo = SiloAddress.FromParsableString("127.0.0.1:100@100");
this.localSiloDetails.SiloAddress.Returns(this.localSilo);
this.localSiloDetails.DnsHostName.Returns("MyServer11");
this.localSiloDetails.Name.Returns(Guid.NewGuid().ToString("N"));
this.fatalErrorHandler = Substitute.For<IFatalErrorHandler>();
this.fatalErrorHandler.IsUnexpected(default).ReturnsForAnyArgs(true);
this.membershipGossiper = Substitute.For<IMembershipGossiper>();
this.lifecycle = new SiloLifecycleSubject(this.loggerFactory.CreateLogger<SiloLifecycleSubject>());
this.timers = new List<DelegateAsyncTimer>();
this.timerCalls = new ConcurrentDictionary<string, ConcurrentQueue<(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion)>>();
this.timerFactory = new DelegateAsyncTimerFactory(
(period, name) =>
{
var t = new DelegateAsyncTimer(
overridePeriod =>
{
var queue = this.timerCalls.GetOrAdd(name, n => new ConcurrentQueue<(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion)>());
var task = new TaskCompletionSource<bool>();
queue.Enqueue((overridePeriod, task));
return task.Task;
});
this.timers.Add(t);
return t;
});
this.membershipTable = new InMemoryMembershipTable(new TableVersion(1, "1"));
this.clusterMembershipOptions = Options.Create(new ClusterMembershipOptions());
this.manager = new MembershipTableManager(
localSiloDetails: this.localSiloDetails,
clusterMembershipOptions: Options.Create(new ClusterMembershipOptions()),
membershipTable: membershipTable,
fatalErrorHandler: this.fatalErrorHandler,
gossiper: this.membershipGossiper,
log: this.loggerFactory.CreateLogger<MembershipTableManager>(),
timerFactory: new AsyncTimerFactory(this.loggerFactory),
this.lifecycle);
((ILifecycleParticipant<ISiloLifecycle>)this.manager).Participate(this.lifecycle);
this.clusterHealthMonitor = new ClusterHealthMonitor(
this.localSiloDetails,
this.manager,
this.loggerFactory.CreateLogger<ClusterHealthMonitor>(),
this.clusterMembershipOptions,
this.fatalErrorHandler,
null,
this.timerFactory);
this.agent = new MembershipAgent(
this.manager,
this.clusterHealthMonitor,
this.localSiloDetails,
this.fatalErrorHandler,
this.clusterMembershipOptions,
this.loggerFactory.CreateLogger<MembershipAgent>(),
this.timerFactory);
((ILifecycleParticipant<ISiloLifecycle>)this.agent).Participate(this.lifecycle);
}
[Fact]
public async Task MembershipAgent_LifecycleStages_GracefulShutdown()
{
var levels = new ConcurrentDictionary<int, SiloStatus>();
Func<CancellationToken, Task> Callback(int level) => ct =>
{
levels[level] = this.manager.CurrentStatus;
return Task.CompletedTask;
};
Func<CancellationToken, Task> NoOp = ct => Task.CompletedTask;
foreach (var l in new[] {
ServiceLifecycleStage.RuntimeInitialize,
ServiceLifecycleStage.AfterRuntimeGrainServices,
ServiceLifecycleStage.BecomeActive})
{
// After start
this.lifecycle.Subscribe(
"x",
l + 1,
Callback(l + 1),
NoOp);
// After stop
this.lifecycle.Subscribe(
"x",
l - 1,
NoOp,
Callback(l - 1));
}
await this.lifecycle.OnStart();
Assert.Equal(SiloStatus.Created, levels[ServiceLifecycleStage.RuntimeInitialize + 1]);
Assert.Equal(SiloStatus.Joining, levels[ServiceLifecycleStage.AfterRuntimeGrainServices + 1]);
Assert.Equal(SiloStatus.Active, levels[ServiceLifecycleStage.BecomeActive + 1]);
await StopLifecycle();
Assert.Equal(SiloStatus.ShuttingDown, levels[ServiceLifecycleStage.BecomeActive - 1]);
Assert.Equal(SiloStatus.ShuttingDown, levels[ServiceLifecycleStage.AfterRuntimeGrainServices - 1]);
Assert.Equal(SiloStatus.Dead, levels[ServiceLifecycleStage.RuntimeInitialize - 1]);
}
[Fact]
public async Task MembershipAgent_LifecycleStages_UngracefulShutdown()
{
var levels = new ConcurrentDictionary<int, SiloStatus>();
Func<CancellationToken, Task> Callback(int level) => ct =>
{
levels[level] = this.manager.CurrentStatus;
return Task.CompletedTask;
};
Func<CancellationToken, Task> NoOp = ct => Task.CompletedTask;
foreach (var l in new[] {
ServiceLifecycleStage.RuntimeInitialize,
ServiceLifecycleStage.AfterRuntimeGrainServices,
ServiceLifecycleStage.BecomeActive})
{
// After start
this.lifecycle.Subscribe(
"x",
l + 1,
Callback(l + 1),
NoOp);
// After stop
this.lifecycle.Subscribe(
"x",
l - 1,
NoOp,
Callback(l - 1));
}
await this.lifecycle.OnStart();
Assert.Equal(SiloStatus.Created, levels[ServiceLifecycleStage.RuntimeInitialize + 1]);
Assert.Equal(SiloStatus.Joining, levels[ServiceLifecycleStage.AfterRuntimeGrainServices + 1]);
Assert.Equal(SiloStatus.Active, levels[ServiceLifecycleStage.BecomeActive + 1]);
var cancellation = new CancellationTokenSource();
cancellation.Cancel();
await StopLifecycle(cancellation.Token);
Assert.Equal(SiloStatus.Stopping, levels[ServiceLifecycleStage.BecomeActive - 1]);
Assert.Equal(SiloStatus.Stopping, levels[ServiceLifecycleStage.AfterRuntimeGrainServices - 1]);
Assert.Equal(SiloStatus.Dead, levels[ServiceLifecycleStage.RuntimeInitialize - 1]);
}
[Fact]
public async Task MembershipAgent_UpdateIAmAlive()
{
await this.lifecycle.OnStart();
await Until(() => this.timerCalls.ContainsKey("UpdateIAmAlive"));
var updateCounter = 0;
var testAccessor = (MembershipAgent.ITestAccessor)this.agent;
testAccessor.OnUpdateIAmAlive = () => ++updateCounter;
(TimeSpan? DelayOverride, TaskCompletionSource<bool> Completion) timer = (default, default);
while (!this.timerCalls["UpdateIAmAlive"].TryDequeue(out timer)) await Task.Delay(1);
timer.Completion.TrySetResult(true);
await Until(() => updateCounter == 1);
testAccessor.OnUpdateIAmAlive = () => { ++updateCounter; throw new Exception("no"); };
while (!this.timerCalls["UpdateIAmAlive"].TryDequeue(out timer)) await Task.Delay(1);
timer.Completion.TrySetResult(true);
Assert.False(timer.DelayOverride.HasValue);
await Until(() => updateCounter == 2);
testAccessor.OnUpdateIAmAlive = () => ++updateCounter;
while (!this.timerCalls["UpdateIAmAlive"].TryDequeue(out timer)) await Task.Delay(1);
Assert.True(timer.DelayOverride.HasValue);
timer.Completion.TrySetResult(true);
await Until(() => updateCounter == 3);
Assert.Equal(3, updateCounter);
// When something goes horribly awry (eg, the timer throws an exception), the silo should fault.
this.fatalErrorHandler.DidNotReceiveWithAnyArgs().OnFatalException(default, default, default);
while (!this.timerCalls["UpdateIAmAlive"].TryDequeue(out timer)) await Task.Delay(1);
timer.Completion.TrySetException(new Exception("no"));
Assert.False(timer.DelayOverride.HasValue);
await Until(() => this.fatalErrorHandler.ReceivedCalls().Any());
this.fatalErrorHandler.ReceivedWithAnyArgs().OnFatalException(default, default, default);
// Stop & cancel all timers.
await StopLifecycle();
}
[Fact]
public async Task MembershipAgent_LifecycleStages_ValidateInitialConnectivity_Success()
{
MessagingStatisticsGroup.Init(true);
var otherSilos = new[]
{
Entry(Silo("127.0.0.200:100@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:200@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:300@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:400@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:500@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:600@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:700@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:800@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:900@100"), SiloStatus.Active)
};
// Add the new silos
foreach (var entry in otherSilos)
{
var table = await this.membershipTable.ReadAll();
Assert.True(await this.membershipTable.InsertRow(entry, table.Version.Next()));
}
var prober = Substitute.For<IRemoteSiloProber>();
prober.Probe(default, default).ReturnsForAnyArgs(Task.CompletedTask);
var clusterHealthMonitorTestAccessor = (ClusterHealthMonitor.ITestAccessor)this.clusterHealthMonitor;
clusterHealthMonitorTestAccessor.CreateMonitor = silo => new SiloHealthMonitor(silo, this.loggerFactory, prober);
var started = this.lifecycle.OnStart();
await Until(() => prober.ReceivedCalls().Count() < otherSilos.Length);
await Until(() => started.IsCompleted);
await started;
await StopLifecycle();
}
[Fact]
public async Task MembershipAgent_LifecycleStages_ValidateInitialConnectivity_Failure()
{
MessagingStatisticsGroup.Init(true);
this.timerFactory.CreateDelegate = (period, name) => new DelegateAsyncTimer(_ => Task.FromResult(false));
var otherSilos = new[]
{
Entry(Silo("127.0.0.200:100@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:200@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:300@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:400@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:500@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:600@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:700@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:800@100"), SiloStatus.Active),
Entry(Silo("127.0.0.200:900@100"), SiloStatus.Active)
};
// Add the new silos
foreach (var entry in otherSilos)
{
var table = await this.membershipTable.ReadAll();
Assert.True(await this.membershipTable.InsertRow(entry, table.Version.Next()));
}
var prober = Substitute.For<IRemoteSiloProber>();
prober.Probe(default, default).ReturnsForAnyArgs(Task.FromException(new Exception("no")));
var dateTimeIndex = 0;
var dateTimes = new DateTime[] { DateTime.UtcNow, DateTime.UtcNow.AddMinutes(8) };
var membershipAgentTestAccessor = ((MembershipAgent.ITestAccessor)this.agent).GetDateTime = () => dateTimes[dateTimeIndex++];
var clusterHealthMonitorTestAccessor = (ClusterHealthMonitor.ITestAccessor)this.clusterHealthMonitor;
clusterHealthMonitorTestAccessor.CreateMonitor = silo => new SiloHealthMonitor(silo, this.loggerFactory, prober);
var started = this.lifecycle.OnStart();
await Until(() => prober.ReceivedCalls().Count() < otherSilos.Length);
await Until(() => started.IsCompleted);
// Startup should have faulted.
Assert.True(started.IsFaulted);
await StopLifecycle();
}
private static SiloAddress Silo(string value) => SiloAddress.FromParsableString(value);
private static MembershipEntry Entry(SiloAddress address, SiloStatus status) => new MembershipEntry { SiloAddress = address, Status = status, StartTime = DateTime.UtcNow, IAmAliveTime = DateTime.UtcNow };
private static async Task Until(Func<bool> condition)
{
var maxTimeout = 40_000;
while (!condition() && (maxTimeout -= 10) > 0) await Task.Delay(10);
Assert.True(maxTimeout > 0);
}
private async Task StopLifecycle(CancellationToken cancellation = default)
{
var stopped = this.lifecycle.OnStop(cancellation);
while (!stopped.IsCompleted)
{
foreach (var pair in this.timerCalls) while (pair.Value.TryDequeue(out var call)) call.Completion.TrySetResult(false);
await Task.Delay(15);
}
await stopped;
}
}
}
| |
using System;
using Csla;
using SelfLoad.DataAccess;
using SelfLoad.DataAccess.ERLevel;
namespace SelfLoad.Business.ERLevel
{
/// <summary>
/// C02_Continent (editable root object).<br/>
/// This is a generated base class of <see cref="C02_Continent"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="C03_SubContinentObjects"/> of type <see cref="C03_SubContinentColl"/> (1:M relation to <see cref="C04_SubContinent"/>)
/// </remarks>
[Serializable]
public partial class C02_Continent : BusinessBase<C02_Continent>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continents ID");
/// <summary>
/// Gets the Continents ID.
/// </summary>
/// <value>The Continents ID.</value>
public int Continent_ID
{
get { return GetProperty(Continent_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Continent_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continents Name");
/// <summary>
/// Gets or sets the Continents Name.
/// </summary>
/// <value>The Continents Name.</value>
public string Continent_Name
{
get { return GetProperty(Continent_NameProperty); }
set { SetProperty(Continent_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C03_Continent_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<C03_Continent_Child> C03_Continent_SingleObjectProperty = RegisterProperty<C03_Continent_Child>(p => p.C03_Continent_SingleObject, "C03 Continent Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the C03 Continent Single Object ("self load" child property).
/// </summary>
/// <value>The C03 Continent Single Object.</value>
public C03_Continent_Child C03_Continent_SingleObject
{
get { return GetProperty(C03_Continent_SingleObjectProperty); }
private set { LoadProperty(C03_Continent_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C03_Continent_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<C03_Continent_ReChild> C03_Continent_ASingleObjectProperty = RegisterProperty<C03_Continent_ReChild>(p => p.C03_Continent_ASingleObject, "C03 Continent ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the C03 Continent ASingle Object ("self load" child property).
/// </summary>
/// <value>The C03 Continent ASingle Object.</value>
public C03_Continent_ReChild C03_Continent_ASingleObject
{
get { return GetProperty(C03_Continent_ASingleObjectProperty); }
private set { LoadProperty(C03_Continent_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C03_SubContinentObjects"/> property.
/// </summary>
public static readonly PropertyInfo<C03_SubContinentColl> C03_SubContinentObjectsProperty = RegisterProperty<C03_SubContinentColl>(p => p.C03_SubContinentObjects, "C03 SubContinent Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the C03 Sub Continent Objects ("self load" child property).
/// </summary>
/// <value>The C03 Sub Continent Objects.</value>
public C03_SubContinentColl C03_SubContinentObjects
{
get { return GetProperty(C03_SubContinentObjectsProperty); }
private set { LoadProperty(C03_SubContinentObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="C02_Continent"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="C02_Continent"/> object.</returns>
public static C02_Continent NewC02_Continent()
{
return DataPortal.Create<C02_Continent>();
}
/// <summary>
/// Factory method. Loads a <see cref="C02_Continent"/> object, based on given parameters.
/// </summary>
/// <param name="continent_ID">The Continent_ID parameter of the C02_Continent to fetch.</param>
/// <returns>A reference to the fetched <see cref="C02_Continent"/> object.</returns>
public static C02_Continent GetC02_Continent(int continent_ID)
{
return DataPortal.Fetch<C02_Continent>(continent_ID);
}
/// <summary>
/// Factory method. Deletes a <see cref="C02_Continent"/> object, based on given parameters.
/// </summary>
/// <param name="continent_ID">The Continent_ID of the C02_Continent to delete.</param>
public static void DeleteC02_Continent(int continent_ID)
{
DataPortal.Delete<C02_Continent>(continent_ID);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="C02_Continent"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public C02_Continent()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="C02_Continent"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(Continent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(C03_Continent_SingleObjectProperty, DataPortal.CreateChild<C03_Continent_Child>());
LoadProperty(C03_Continent_ASingleObjectProperty, DataPortal.CreateChild<C03_Continent_ReChild>());
LoadProperty(C03_SubContinentObjectsProperty, DataPortal.CreateChild<C03_SubContinentColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="C02_Continent"/> object from the database, based on given criteria.
/// </summary>
/// <param name="continent_ID">The Continent ID.</param>
protected void DataPortal_Fetch(int continent_ID)
{
var args = new DataPortalHookArgs(continent_ID);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var dal = dalManager.GetProvider<IC02_ContinentDal>();
var data = dal.Fetch(continent_ID);
Fetch(data);
}
OnFetchPost(args);
FetchChildren();
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Loads a <see cref="C02_Continent"/> object from the given <see cref="C02_ContinentDto"/>.
/// </summary>
/// <param name="data">The C02_ContinentDto to use.</param>
private void Fetch(C02_ContinentDto data)
{
// Value properties
LoadProperty(Continent_IDProperty, data.Continent_ID);
LoadProperty(Continent_NameProperty, data.Continent_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
private void FetchChildren()
{
LoadProperty(C03_Continent_SingleObjectProperty, C03_Continent_Child.GetC03_Continent_Child(Continent_ID));
LoadProperty(C03_Continent_ASingleObjectProperty, C03_Continent_ReChild.GetC03_Continent_ReChild(Continent_ID));
LoadProperty(C03_SubContinentObjectsProperty, C03_SubContinentColl.GetC03_SubContinentColl(Continent_ID));
}
/// <summary>
/// Inserts a new <see cref="C02_Continent"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
var dto = new C02_ContinentDto();
dto.Continent_Name = Continent_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IC02_ContinentDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
LoadProperty(Continent_IDProperty, resultDto.Continent_ID);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="C02_Continent"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
var dto = new C02_ContinentDto();
dto.Continent_ID = Continent_ID;
dto.Continent_Name = Continent_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IC02_ContinentDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="C02_Continent"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(Continent_ID);
}
/// <summary>
/// Deletes the <see cref="C02_Continent"/> object from database.
/// </summary>
/// <param name="continent_ID">The delete criteria.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(int continent_ID)
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
// flushes all pending data operations
FieldManager.UpdateChildren(this);
OnDeletePre(args);
var dal = dalManager.GetProvider<IC02_ContinentDal>();
using (BypassPropertyChecks)
{
dal.Delete(continent_ID);
}
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
}
}
| |
#region CopyrightHeader
//
// Copyright by Contributors
//
// 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.txt
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using gov.va.medora.mdws.dto;
using System.ServiceModel;
/// <summary>
/// Summary description for MhvService
/// </summary>
namespace gov.va.medora.mdws
{
/// <summary>
/// Summary description for PhrSvc
/// </summary>
[WebService(Namespace = "http://mdws.medora.va.gov/PhrSvc")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ServiceContract(Namespace = "http://mdws.medora.va.gov/PhrSvc")]
public partial class PhrSvc : BaseService
{
/// <summary>
/// This facade is for Patient Health Record. It is assumed the user is the patient.
/// </summary>
public PhrSvc() { }
[OperationContract]
[WebMethod(EnableSession = true, Description = "Authenticate a user with his/her MHV or DS Logon credentials")]
public UserTO patientLogin(byte[] cert, string username, string password, string credentialType)
{
return new UserTO() { fault = new FaultTO("Not currently implemented") };
}
[OperationContract]
[WebMethod(EnableSession = true, Description = "Get patient medical record")]
public PatientMedicalRecordTO getMedicalRecord(byte[] cert, string patientId)
{
return new PatientMedicalRecordTO() { fault = new FaultTO("Not currently implemented") };
}
[OperationContract]
[WebMethod(EnableSession = true, Description = "Write a new Secure Message to the SM database")]
public TextTO writeSecureMessage(string patientId, string message)
{
return new TextTO() { fault = new FaultTO("Not currently implemented") };
}
[OperationContract]
[WebMethod(EnableSession = true, Description = "Get all of a patient's secure messages from the SM database")]
public TextTO getSecureMessages(string patientId, string message)
{
return new TextTO() { fault = new FaultTO("Not currently implemented") };
}
/// <summary>
/// This method connects to a site.
/// </summary>
/// <param name="pwd">Application's security phrase</param>
/// <param name="sitecode">Station # of the VistA site</param>
/// <param name="mpiPid">National patient identifier (ICN)</param>
/// <returns>SiteTO: name, hostname, port, etc. of connected site</returns>
[WebMethod(EnableSession = true, Description = "Connect to a site.")]
public SiteTO connect(string pwd, string sitecode, string mpiPid)
{
return (SiteTO)MySession.execute("AccountLib", "patientVisit", new object[] { pwd, sitecode, mpiPid });
}
/// <summary>
/// This method closes all VistA connections.
/// </summary>
/// <returns>"OK" if successful</returns>
[WebMethod(EnableSession = true, Description = "Disconnect from all Vista systems.")]
public TaggedTextArray disconnect()
{
return (TaggedTextArray)MySession.execute("ConnectionLib", "disconnectAll", new object[] { });
}
/// <summary>
/// This method connects to all the patient's VistA systems. Subsequent queries will be made
/// against all these sources.
/// </summary>
/// <param name="appPwd">The application's security phrase</param>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Setup patient's remote sites for querying.")]
public SiteArray setupMultiSiteQuery(string appPwd)
{
return (SiteArray)MySession.execute("AccountLib", "setupMultiSourcePatientQuery", new object[] { appPwd, "" });
}
/// <summary>
/// This method gets all the patient's vital signs from VistA sources.
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get patient's vital signs from all connected VistAs.")]
public TaggedVitalSignSetArrays getVitalSigns()
{
return (TaggedVitalSignSetArrays)MySession.execute("VitalsLib", "getVitalSigns", new object[] { });
}
/// <summary>
/// This method gets all the patient's allergies from VistA sources.
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get allergies from all connected VistAs")]
public TaggedAllergyArrays getAllergies()
{
return (TaggedAllergyArrays)MySession.execute("ClinicalLib", "getAllergies", new object[] { });
}
/// <summary>
/// This method gets the patient's radiology reports from VistA sources for a given time frame.
/// </summary>
/// <param name="fromDate">yyyyMMdd</param>
/// <param name="toDate">yyyyMMdd</param>
/// <param name="nrpts">Max reports from each site. Defaults to 50.</param>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get radiology reports from all connected VistAs")]
public TaggedRadiologyReportArrays getRadiologyReports(string fromDate, string toDate, int nrpts)
{
return (TaggedRadiologyReportArrays)MySession.execute("ClinicalLib", "getRadiologyReports", new object[] { fromDate, toDate, nrpts });
}
/// <summary>
/// This method gets all the patient's surgery reports from VistA sources.
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get surgery reports from all connected VistAs")]
public TaggedSurgeryReportArrays getSurgeryReports()
{
return (TaggedSurgeryReportArrays)MySession.execute("ClinicalLib", "getSurgeryReports", new object[] { true });
}
/// <summary>
/// This method gets all the patient's problem lists of a given type from VistA sources.
/// </summary>
/// <param name="type">ACTIVE, INACTIVE, ALL</param>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get problem list from all connected VistAs")]
public TaggedProblemArrays getProblemList(string type)
{
return (TaggedProblemArrays)MySession.execute("ClinicalLib", "getProblemList", new object[] { type });
}
/// <summary>
/// This method gets all the patient's outpatient meds from VistA sources.
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get outpatient medications from all connected VistAs")]
public TaggedMedicationArrays getOutpatientMeds()
{
return (TaggedMedicationArrays)MySession.execute("MedsLib", "getOutpatientMeds", new object[] { });
}
/// <summary>
/// This method gets all the patient's IV meds from VistA sources.
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get IV medications from all connected VistAs")]
public TaggedMedicationArrays getIvMeds()
{
return (TaggedMedicationArrays)MySession.execute("MedsLib", "getIvMeds", new object[] { });
}
/// <summary>
/// This method gets all the patient's unit dose meds from VistA sources.
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get unit dose medications from all connected VistAs")]
public TaggedMedicationArrays getUnitDoseMeds()
{
return (TaggedMedicationArrays)MySession.execute("MedsLib", "getUnitDoseMeds", new object[] { });
}
/// <summary>
/// This method gets all the patient's non-VA meds from VistA sources.
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get non-VA medications from all connected VistAs")]
public TaggedMedicationArrays getOtherMeds()
{
return (TaggedMedicationArrays)MySession.execute("MedsLib", "getOtherMeds", new object[] { });
}
/// <summary>
/// This method get all the patient's outpatient, inpatient and non-VA meds from VistA sources.
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get all medications from all connected VistAs")]
public TaggedMedicationArrays getAllMeds()
{
return (TaggedMedicationArrays)MySession.execute("MedsLib", "getAllMeds", new object[] { });
}
/// <summary>
/// This method gets all the patient's appointments from VistA sources.
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get patient's appointments.")]
public TaggedAppointmentArrays getAppointments()
{
return (TaggedAppointmentArrays)MySession.execute("EncounterLib", "getAppointments", new object[] { });
}
/// <summary>
/// This method gets all the detailed MHV health summaries from VistA sources.
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get patient's detailed MHV health summaries from all connected VistAs.")]
public TaggedTextArray getDetailedHealthSummary()
{
return (TaggedTextArray)MySession.execute("ClinicalLib", "getAdHocHealthSummaryByDisplayName", new object[] { "MHV REMINDERS DETAIL DISPLAY [MHVD]" });
}
/// <summary>
/// This method gets all the MHV health summaries from VistA sources.
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get patient's MHV health summaries from all connected VistAs.")]
public TaggedTextArray getHealthSummary()
{
return (TaggedTextArray)MySession.execute("ClinicalLib", "getAdHocHealthSummaryByDisplayName", new object[] { "MHV REMINDERS SUMMARY DISPLAY [MHVS]" });
}
/// <summary>
/// This method gets all the patient's immunizations from VistA sources.
/// </summary>
/// <param name="fromDate">yyyyMMdd</param>
/// <param name="toDate">yyyyMMdd</param>
/// <param name="nrpts">Max reports from each site. Defaults to 50.</param>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get patient's immunizations.")]
public TaggedTextArray getImmunizations(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("MedsLib", "getImmunizations", new object[] { fromDate, toDate, nrpts });
}
/// <summary>
/// This method gets all the patient's outpatient meds profiles from VistA sources.
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get patient's outpatient prescription profile.")]
public TaggedTextArray getOutpatientRxProfile()
{
return (TaggedTextArray)MySession.execute("MedsLib", "getOutpatientRxProfile", new object[] { });
}
/// <summary>
/// This method gets all the patient's chem/hem lab results from VistA sources.
/// </summary>
/// <param name="fromDate">yyyyMMdd</param>
/// <param name="toDate">yyyyMMdd</param>
/// <param name="nrpts">Max reports from each site. Defaults to 50.</param>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get patient's chem/hem lab results.")]
public TaggedChemHemRptArrays getChemHemReports(string fromDate, string toDate, int nrpts)
{
return (TaggedChemHemRptArrays)MySession.execute("LabsLib", "getChemHemReports", new object[] { fromDate, toDate, nrpts });
}
/// <summary>
/// This method gets all the patient's cytology reports from VistA sources.
/// </summary>
/// <param name="fromDate">yyyyMMdd</param>
/// <param name="toDate">yyyyMMdd</param>
/// <param name="nrpts">Max reports from each site. Defaults to 50.</param>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get patient's Cytology lab results.")]
public TaggedCytologyRptArrays getCytologyReports(string fromDate, string toDate, int nrpts)
{
return (TaggedCytologyRptArrays)MySession.execute("LabsLib", "getCytologyReports", new object[] { fromDate, toDate, nrpts });
}
/// <summary>
/// This method gets all the patient's microbiology reports from VistA sources.
/// </summary>
/// <param name="fromDate">yyyyMMdd</param>
/// <param name="toDate">yyyyMMdd</param>
/// <param name="nrpts">Max reports from each site. Defaults to 50.</param>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get patient's microbiology lab results.")]
public TaggedMicrobiologyRptArrays getMicrobiologyReports(string fromDate, string toDate, int nrpts)
{
return (TaggedMicrobiologyRptArrays)MySession.execute("LabsLib", "getMicrobiologyReports", new object[] { fromDate, toDate, nrpts });
}
/// <summary>
///
/// </summary>
/// <param name="fromDate">yyyyMMdd</param>
/// <param name="toDate">yyyyMMdd</param>
/// <param name="nrpts">Max reports from each site. Defaults to 50.</param>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get patient's surgical pathology lab results.")]
public TaggedSurgicalPathologyRptArrays getSurgicalPathologyReports(string fromDate, string toDate, int nrpts)
{
return (TaggedSurgicalPathologyRptArrays)MySession.execute("LabsLib", "getSurgicalPathologyReports", new object[] { fromDate, toDate, nrpts });
}
/// <summary>
/// This method gets all the patient's electron microscopy reports from VistA sources.
/// </summary>
/// <param name="fromDate">yyyyMMdd</param>
/// <param name="toDate">yyyyMMdd</param>
/// <param name="nrpts">Max reports from each site. Defaults to 50.</param>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get patient's electron microscopy reports.")]
public TaggedTextArray getElectronMicroscopyReports(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("LabsLib", "getElectronMicroscopyReports", new object[] { fromDate, toDate, nrpts });
}
/// <summary>
/// This method gets all the patient's cytopathology reports from VistA sources.
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get patient's cytopathology reports.")]
public TaggedTextArray getCytopathologyReports()
{
return (TaggedTextArray)MySession.execute("LabsLib", "getCytopathologyReports", new object[] { });
}
/// <summary>
/// This method gets all the patient's admissions from VistA sources.
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get selected patient's admissions")]
public TaggedInpatientStayArray getAdmissions()
{
return (TaggedInpatientStayArray)MySession.execute("EncounterLib", "getAdmissions", new object[] { });
}
/// <summary>
/// This method gets all the patient's visits from VistA sources.
/// </summary>
/// <param name="fromDate">yyyyMMdd</param>
/// <param name="toDate">yyyyMMdd</param>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get selected patient's visits")]
public TaggedVisitArray getVisits(string fromDate, string toDate)
{
return (TaggedVisitArray)MySession.execute("EncounterLib", "getVisits", new object[] { fromDate, toDate });
}
/// <summary>
/// This method gets all the patient's demographics from VistA sources.
/// </summary>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get a patient's demographics")]
public PatientTO getDemographics()
{
PatientLib lib = new PatientLib(MySession);
return lib.getDemographics();
}
/// <summary>
/// This method gets all the patient's advance directives from VistA sources.
/// </summary>
/// <param name="fromDate">yyyyMMdd</param>
/// <param name="toDate">yyyyMMdd</param>
/// <param name="nrpts">Max reports from each site. Defaults to 50.</param>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get patient's advance directives.")]
public TaggedTextArray getAdvanceDirectives(string fromDate, string toDate, int nrpts)
{
return (TaggedTextArray)MySession.execute("NoteLib", "getAdvanceDirectives", new object[] { fromDate, toDate, nrpts });
}
/// <summary>
/// This method gets a synopsis of the patient's data from VistA sources.
/// </summary>
/// <param name="fromDate">yyyyMMdd</param>
/// <param name="toDate">yyyyMMdd</param>
/// <returns></returns>
[WebMethod(EnableSession = true, Description = "Get a synopsis from VistA sources")]
public Synopsis getSynopsis(string fromDate, string toDate)
{
Synopsis result = new Synopsis();
result.advanceDirectives = getAdvanceDirectives(fromDate, toDate, 50);
result.allergies = getAllergies();
result.chemHemReports = getChemHemReports(fromDate, toDate, 50);
result.detailedHealthSummaries = getDetailedHealthSummary();
result.healthSummaries = getHealthSummary();
result.immunizations = getImmunizations(fromDate, toDate, 50);
result.medications = getOutpatientMeds();
result.microbiologyReports = getMicrobiologyReports(fromDate, toDate, 50);
result.supplements = getOtherMeds();
result.problemLists = getProblemList("ACTIVE");
result.radiologyReports = getRadiologyReports(fromDate, toDate, 50);
result.surgeryReports = getSurgeryReports();
result.vitalSigns = getVitalSigns();
SitesLib sitesLib = new SitesLib(MySession);
result.treatingFacilities = sitesLib.getConnectedSites();
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.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Threading;
namespace System.Collections.Generic
{
/// <summary>
/// Used internally to control behavior of insertion into a <see cref="Dictionary{TKey, TValue}"/>.
/// </summary>
internal enum InsertionBehavior : byte
{
/// <summary>
/// The default insertion behavior.
/// </summary>
None = 0,
/// <summary>
/// Specifies that an existing entry with the same key should be overwritten if encountered.
/// </summary>
OverwriteExisting = 1,
/// <summary>
/// Specifies that if an existing entry with the same key is encountered, an exception should be thrown.
/// </summary>
ThrowOnExisting = 2
}
[DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback
{
private struct Entry
{
public int hashCode; // Lower 31 bits of hash code, -1 if unused
public int next; // Index of next entry, -1 if last
public TKey key; // Key of entry
public TValue value; // Value of entry
}
private int[] _buckets;
private Entry[] _entries;
private int _count;
private int _freeList;
private int _freeCount;
private int _version;
private IEqualityComparer<TKey> _comparer;
private KeyCollection _keys;
private ValueCollection _values;
// constants for serialization
private const string VersionName = "Version"; // Do not rename (binary serialization)
private const string HashSizeName = "HashSize"; // Do not rename (binary serialization). Must save buckets.Length
private const string KeyValuePairsName = "KeyValuePairs"; // Do not rename (binary serialization)
private const string ComparerName = "Comparer"; // Do not rename (binary serialization)
public Dictionary() : this(0, null) { }
public Dictionary(int capacity) : this(capacity, null) { }
public Dictionary(IEqualityComparer<TKey> comparer) : this(0, comparer) { }
public Dictionary(int capacity, IEqualityComparer<TKey> comparer)
{
if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
if (capacity > 0) Initialize(capacity);
if (comparer != EqualityComparer<TKey>.Default)
{
_comparer = comparer;
}
if (typeof(TKey) == typeof(string) && _comparer == null)
{
// To start, move off default comparer for string which is randomised
_comparer = (IEqualityComparer<TKey>)NonRandomizedStringEqualityComparer.Default;
}
}
public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { }
public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) :
this(dictionary != null ? dictionary.Count : 0, comparer)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
// It is likely that the passed-in dictionary is Dictionary<TKey,TValue>. When this is the case,
// avoid the enumerator allocation and overhead by looping through the entries array directly.
// We only do this when dictionary is Dictionary<TKey,TValue> and not a subclass, to maintain
// back-compat with subclasses that may have overridden the enumerator behavior.
if (dictionary.GetType() == typeof(Dictionary<TKey, TValue>))
{
Dictionary<TKey, TValue> d = (Dictionary<TKey, TValue>)dictionary;
int count = d._count;
Entry[] entries = d._entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
Add(entries[i].key, entries[i].value);
}
}
return;
}
foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
Add(pair.Key, pair.Value);
}
}
public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection) : this(collection, null) { }
public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer) :
this((collection as ICollection<KeyValuePair<TKey, TValue>>)?.Count ?? 0, comparer)
{
if (collection == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
foreach (KeyValuePair<TKey, TValue> pair in collection)
{
Add(pair.Key, pair.Value);
}
}
protected Dictionary(SerializationInfo info, StreamingContext context)
{
// We can't do anything with the keys and values until the entire graph has been deserialized
// and we have a resonable estimate that GetHashCode is not going to fail. For the time being,
// we'll just cache this. The graph is not valid until OnDeserialization has been called.
HashHelpers.SerializationInfoTable.Add(this, info);
}
public IEqualityComparer<TKey> Comparer
{
get
{
return (_comparer == null || _comparer is NonRandomizedStringEqualityComparer) ? EqualityComparer<TKey>.Default : _comparer;
}
}
public int Count
{
get { return _count - _freeCount; }
}
public KeyCollection Keys
{
get
{
if (_keys == null) _keys = new KeyCollection(this);
return _keys;
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get
{
if (_keys == null) _keys = new KeyCollection(this);
return _keys;
}
}
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
{
get
{
if (_keys == null) _keys = new KeyCollection(this);
return _keys;
}
}
public ValueCollection Values
{
get
{
if (_values == null) _values = new ValueCollection(this);
return _values;
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get
{
if (_values == null) _values = new ValueCollection(this);
return _values;
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
{
get
{
if (_values == null) _values = new ValueCollection(this);
return _values;
}
}
public TValue this[TKey key]
{
get
{
int i = FindEntry(key);
if (i >= 0) return _entries[i].value;
ThrowHelper.ThrowKeyNotFoundException(key);
return default;
}
set
{
bool modified = TryInsert(key, value, InsertionBehavior.OverwriteExisting);
Debug.Assert(modified);
}
}
public void Add(TKey key, TValue value)
{
bool modified = TryInsert(key, value, InsertionBehavior.ThrowOnExisting);
Debug.Assert(modified); // If there was an existing key and the Add failed, an exception will already have been thrown.
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
=> Add(keyValuePair.Key, keyValuePair.Value);
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair)
{
int i = FindEntry(keyValuePair.Key);
if (i >= 0 && EqualityComparer<TValue>.Default.Equals(_entries[i].value, keyValuePair.Value))
{
return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
{
int i = FindEntry(keyValuePair.Key);
if (i >= 0 && EqualityComparer<TValue>.Default.Equals(_entries[i].value, keyValuePair.Value))
{
Remove(keyValuePair.Key);
return true;
}
return false;
}
public void Clear()
{
int count = _count;
if (count > 0)
{
Array.Clear(_buckets, 0, _buckets.Length);
_count = 0;
_freeList = -1;
_freeCount = 0;
Array.Clear(_entries, 0, count);
}
}
public bool ContainsKey(TKey key)
=> FindEntry(key) >= 0;
public bool ContainsValue(TValue value)
{
Entry[] entries = _entries;
if (value == null)
{
for (int i = 0; i < _count; i++)
{
if (entries[i].hashCode >= 0 && entries[i].value == null) return true;
}
}
else
{
if (default(TValue) != null)
{
// ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic
for (int i = 0; i < _count; i++)
{
if (entries[i].hashCode >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, value)) return true;
}
}
else
{
// Object type: Shared Generic, EqualityComparer<TValue>.Default won't devirtualize
// https://github.com/dotnet/coreclr/issues/17273
// So cache in a local rather than get EqualityComparer per loop iteration
EqualityComparer<TValue> defaultComparer = EqualityComparer<TValue>.Default;
for (int i = 0; i < _count; i++)
{
if (entries[i].hashCode >= 0 && defaultComparer.Equals(entries[i].value, value)) return true;
}
}
}
return false;
}
private void CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if ((uint)index > (uint)array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = _count;
Entry[] entries = _entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
array[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value);
}
}
}
public Enumerator GetEnumerator()
=> new Enumerator(this, Enumerator.KeyValuePair);
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
=> new Enumerator(this, Enumerator.KeyValuePair);
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info);
}
info.AddValue(VersionName, _version);
info.AddValue(ComparerName, _comparer ?? EqualityComparer<TKey>.Default, typeof(IEqualityComparer<TKey>));
info.AddValue(HashSizeName, _buckets == null ? 0 : _buckets.Length); // This is the length of the bucket array
if (_buckets != null)
{
var array = new KeyValuePair<TKey, TValue>[Count];
CopyTo(array, 0);
info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[]));
}
}
private int FindEntry(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
int i = -1;
int[] buckets = _buckets;
Entry[] entries = _entries;
int collisionCount = 0;
if (buckets != null)
{
IEqualityComparer<TKey> comparer = _comparer;
if (comparer == null)
{
int hashCode = key.GetHashCode() & 0x7FFFFFFF;
// Value in _buckets is 1-based
i = buckets[hashCode % buckets.Length] - 1;
if (default(TKey) != null)
{
// ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic
do
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test in if to drop range check for following array access
if ((uint)i >= (uint)entries.Length || (entries[i].hashCode == hashCode && EqualityComparer<TKey>.Default.Equals(entries[i].key, key)))
{
break;
}
i = entries[i].next;
if (collisionCount >= entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
collisionCount++;
} while (true);
}
else
{
// Object type: Shared Generic, EqualityComparer<TValue>.Default won't devirtualize
// https://github.com/dotnet/coreclr/issues/17273
// So cache in a local rather than get EqualityComparer per loop iteration
EqualityComparer<TKey> defaultComparer = EqualityComparer<TKey>.Default;
do
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test in if to drop range check for following array access
if ((uint)i >= (uint)entries.Length || (entries[i].hashCode == hashCode && defaultComparer.Equals(entries[i].key, key)))
{
break;
}
i = entries[i].next;
if (collisionCount >= entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
collisionCount++;
} while (true);
}
}
else
{
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
// Value in _buckets is 1-based
i = buckets[hashCode % buckets.Length] - 1;
do
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test in if to drop range check for following array access
if ((uint)i >= (uint)entries.Length ||
(entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)))
{
break;
}
i = entries[i].next;
if (collisionCount >= entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
collisionCount++;
} while (true);
}
}
return i;
}
private int Initialize(int capacity)
{
int size = HashHelpers.GetPrime(capacity);
_freeList = -1;
_buckets = new int[size];
_entries = new Entry[size];
return size;
}
private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
if (_buckets == null)
{
Initialize(0);
}
Entry[] entries = _entries;
IEqualityComparer<TKey> comparer = _comparer;
int hashCode = ((comparer == null) ? key.GetHashCode() : comparer.GetHashCode(key)) & 0x7FFFFFFF;
int collisionCount = 0;
ref int bucket = ref _buckets[hashCode % _buckets.Length];
// Value in _buckets is 1-based
int i = bucket - 1;
if (comparer == null)
{
if (default(TKey) != null)
{
// ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic
do
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test uint in if rather than loop condition to drop range check for following array access
if ((uint)i >= (uint)entries.Length)
{
break;
}
if (entries[i].hashCode == hashCode && EqualityComparer<TKey>.Default.Equals(entries[i].key, key))
{
if (behavior == InsertionBehavior.OverwriteExisting)
{
entries[i].value = value;
_version++;
return true;
}
if (behavior == InsertionBehavior.ThrowOnExisting)
{
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
}
return false;
}
i = entries[i].next;
if (collisionCount >= entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
collisionCount++;
} while (true);
}
else
{
// Object type: Shared Generic, EqualityComparer<TValue>.Default won't devirtualize
// https://github.com/dotnet/coreclr/issues/17273
// So cache in a local rather than get EqualityComparer per loop iteration
EqualityComparer<TKey> defaultComparer = EqualityComparer<TKey>.Default;
do
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test uint in if rather than loop condition to drop range check for following array access
if ((uint)i >= (uint)entries.Length)
{
break;
}
if (entries[i].hashCode == hashCode && defaultComparer.Equals(entries[i].key, key))
{
if (behavior == InsertionBehavior.OverwriteExisting)
{
entries[i].value = value;
_version++;
return true;
}
if (behavior == InsertionBehavior.ThrowOnExisting)
{
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
}
return false;
}
i = entries[i].next;
if (collisionCount >= entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
collisionCount++;
} while (true);
}
}
else
{
do
{
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
// Test uint in if rather than loop condition to drop range check for following array access
if ((uint)i >= (uint)entries.Length)
{
break;
}
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
{
if (behavior == InsertionBehavior.OverwriteExisting)
{
entries[i].value = value;
_version++;
return true;
}
if (behavior == InsertionBehavior.ThrowOnExisting)
{
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
}
return false;
}
i = entries[i].next;
if (collisionCount >= entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
collisionCount++;
} while (true);
}
bool updateFreeList = false;
int index;
if (_freeCount > 0)
{
index = _freeList;
updateFreeList = true;
_freeCount--;
}
else
{
int count = _count;
if (count == entries.Length)
{
Resize();
bucket = ref _buckets[hashCode % _buckets.Length];
}
index = count;
_count = count + 1;
entries = _entries;
}
ref Entry entry = ref entries[index];
if (updateFreeList)
{
_freeList = entry.next;
}
entry.hashCode = hashCode;
// Value in _buckets is 1-based
entry.next = bucket - 1;
entry.key = key;
entry.value = value;
// Value in _buckets is 1-based
bucket = index + 1;
_version++;
// Value types never rehash
if (default(TKey) == null && collisionCount > HashHelpers.HashCollisionThreshold && comparer is NonRandomizedStringEqualityComparer)
{
// If we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing
// i.e. EqualityComparer<string>.Default.
_comparer = null;
Resize(entries.Length, true);
}
return true;
}
public virtual void OnDeserialization(object sender)
{
HashHelpers.SerializationInfoTable.TryGetValue(this, out SerializationInfo siInfo);
if (siInfo == null)
{
// We can return immediately if this function is called twice.
// Note we remove the serialization info from the table at the end of this method.
return;
}
int realVersion = siInfo.GetInt32(VersionName);
int hashsize = siInfo.GetInt32(HashSizeName);
_comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>));
if (hashsize != 0)
{
Initialize(hashsize);
KeyValuePair<TKey, TValue>[] array = (KeyValuePair<TKey, TValue>[])
siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[]));
if (array == null)
{
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys);
}
for (int i = 0; i < array.Length; i++)
{
if (array[i].Key == null)
{
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey);
}
Add(array[i].Key, array[i].Value);
}
}
else
{
_buckets = null;
}
_version = realVersion;
HashHelpers.SerializationInfoTable.Remove(this);
}
private void Resize()
=> Resize(HashHelpers.ExpandPrime(_count), false);
private void Resize(int newSize, bool forceNewHashCodes)
{
// Value types never rehash
Debug.Assert(!forceNewHashCodes || default(TKey) == null);
Debug.Assert(newSize >= _entries.Length);
int[] buckets = new int[newSize];
Entry[] entries = new Entry[newSize];
int count = _count;
Array.Copy(_entries, 0, entries, 0, count);
if (default(TKey) == null && forceNewHashCodes)
{
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
Debug.Assert(_comparer == null);
entries[i].hashCode = (entries[i].key.GetHashCode() & 0x7FFFFFFF);
}
}
}
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
int bucket = entries[i].hashCode % newSize;
// Value in _buckets is 1-based
entries[i].next = buckets[bucket] - 1;
// Value in _buckets is 1-based
buckets[bucket] = i + 1;
}
}
_buckets = buckets;
_entries = entries;
}
// The overload Remove(TKey key, out TValue value) is a copy of this method with one additional
// statement to copy the value for entry being removed into the output parameter.
// Code has been intentionally duplicated for performance reasons.
public bool Remove(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
int[] buckets = _buckets;
Entry[] entries = _entries;
int collisionCount = 0;
if (buckets != null)
{
int hashCode = (_comparer?.GetHashCode(key) ?? key.GetHashCode()) & 0x7FFFFFFF;
int bucket = hashCode % buckets.Length;
int last = -1;
// Value in buckets is 1-based
int i = buckets[bucket] - 1;
while (i >= 0)
{
ref Entry entry = ref entries[i];
if (entry.hashCode == hashCode && (_comparer?.Equals(entry.key, key) ?? EqualityComparer<TKey>.Default.Equals(entry.key, key)))
{
if (last < 0)
{
// Value in buckets is 1-based
buckets[bucket] = entry.next + 1;
}
else
{
entries[last].next = entry.next;
}
entry.hashCode = -1;
entry.next = _freeList;
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
entry.key = default;
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
entry.value = default;
}
_freeList = i;
_freeCount++;
return true;
}
last = i;
i = entry.next;
if (collisionCount >= entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
collisionCount++;
}
}
return false;
}
// This overload is a copy of the overload Remove(TKey key) with one additional
// statement to copy the value for entry being removed into the output parameter.
// Code has been intentionally duplicated for performance reasons.
public bool Remove(TKey key, out TValue value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
int[] buckets = _buckets;
Entry[] entries = _entries;
int collisionCount = 0;
if (buckets != null)
{
int hashCode = (_comparer?.GetHashCode(key) ?? key.GetHashCode()) & 0x7FFFFFFF;
int bucket = hashCode % buckets.Length;
int last = -1;
// Value in buckets is 1-based
int i = buckets[bucket] - 1;
while (i >= 0)
{
ref Entry entry = ref entries[i];
if (entry.hashCode == hashCode && (_comparer?.Equals(entry.key, key) ?? EqualityComparer<TKey>.Default.Equals(entry.key, key)))
{
if (last < 0)
{
// Value in buckets is 1-based
buckets[bucket] = entry.next + 1;
}
else
{
entries[last].next = entry.next;
}
value = entry.value;
entry.hashCode = -1;
entry.next = _freeList;
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
entry.key = default;
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
entry.value = default;
}
_freeList = i;
_freeCount++;
return true;
}
last = i;
i = entry.next;
if (collisionCount >= entries.Length)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported();
}
collisionCount++;
}
}
value = default;
return false;
}
public bool TryGetValue(TKey key, out TValue value)
{
int i = FindEntry(key);
if (i >= 0)
{
value = _entries[i].value;
return true;
}
value = default;
return false;
}
public bool TryAdd(TKey key, TValue value)
=> TryInsert(key, value, InsertionBehavior.None);
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => false;
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
=> CopyTo(array, index);
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (array.Rank != 1)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
if (array.GetLowerBound(0) != 0)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
if ((uint)index > (uint)array.Length)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (array.Length - index < Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
if (array is KeyValuePair<TKey, TValue>[] pairs)
{
CopyTo(pairs, index);
}
else if (array is DictionaryEntry[] dictEntryArray)
{
Entry[] entries = _entries;
for (int i = 0; i < _count; i++)
{
if (entries[i].hashCode >= 0)
{
dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value);
}
}
}
else
{
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
try
{
int count = _count;
Entry[] entries = _entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
objects[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value);
}
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
IEnumerator IEnumerable.GetEnumerator()
=> new Enumerator(this, Enumerator.KeyValuePair);
/// <summary>
/// Ensures that the dictionary can hold up to 'capacity' entries without any further expansion of its backing storage
/// </summary>
public int EnsureCapacity(int capacity)
{
if (capacity < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
int currentCapacity = _entries == null ? 0 : _entries.Length;
if (currentCapacity >= capacity)
return currentCapacity;
_version++;
if (_buckets == null)
return Initialize(capacity);
int newSize = HashHelpers.GetPrime(capacity);
Resize(newSize, forceNewHashCodes: false);
return newSize;
}
/// <summary>
/// Sets the capacity of this dictionary to what it would be if it had been originally initialized with all its entries
///
/// This method can be used to minimize the memory overhead
/// once it is known that no new elements will be added.
///
/// To allocate minimum size storage array, execute the following statements:
///
/// dictionary.Clear();
/// dictionary.TrimExcess();
/// </summary>
public void TrimExcess()
=> TrimExcess(Count);
/// <summary>
/// Sets the capacity of this dictionary to hold up 'capacity' entries without any further expansion of its backing storage
///
/// This method can be used to minimize the memory overhead
/// once it is known that no new elements will be added.
/// </summary>
public void TrimExcess(int capacity)
{
if (capacity < Count)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
int newSize = HashHelpers.GetPrime(capacity);
Entry[] oldEntries = _entries;
int currentCapacity = oldEntries == null ? 0 : oldEntries.Length;
if (newSize >= currentCapacity)
return;
int oldCount = _count;
_version++;
Initialize(newSize);
Entry[] entries = _entries;
int[] buckets = _buckets;
int count = 0;
for (int i = 0; i < oldCount; i++)
{
int hashCode = oldEntries[i].hashCode;
if (hashCode >= 0)
{
ref Entry entry = ref entries[count];
entry = oldEntries[i];
int bucket = hashCode % newSize;
// Value in _buckets is 1-based
entry.next = buckets[bucket] - 1;
// Value in _buckets is 1-based
buckets[bucket] = count + 1;
count++;
}
}
_count = count;
_freeCount = 0;
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => this;
bool IDictionary.IsFixedSize => false;
bool IDictionary.IsReadOnly => false;
ICollection IDictionary.Keys => (ICollection)Keys;
ICollection IDictionary.Values => (ICollection)Values;
object IDictionary.this[object key]
{
get
{
if (IsCompatibleKey(key))
{
int i = FindEntry((TKey)key);
if (i >= 0)
{
return _entries[i].value;
}
}
return null;
}
set
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try
{
TKey tempKey = (TKey)key;
try
{
this[tempKey] = (TValue)value;
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
}
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
return (key is TKey);
}
void IDictionary.Add(object key, object value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
try
{
TKey tempKey = (TKey)key;
try
{
Add(tempKey, (TValue)value);
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
bool IDictionary.Contains(object key)
{
if (IsCompatibleKey(key))
{
return ContainsKey((TKey)key);
}
return false;
}
IDictionaryEnumerator IDictionary.GetEnumerator()
=> new Enumerator(this, Enumerator.DictEntry);
void IDictionary.Remove(object key)
{
if (IsCompatibleKey(key))
{
Remove((TKey)key);
}
}
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>,
IDictionaryEnumerator
{
private readonly Dictionary<TKey, TValue> _dictionary;
private readonly int _version;
private int _index;
private KeyValuePair<TKey, TValue> _current;
private readonly int _getEnumeratorRetType; // What should Enumerator.Current return?
internal const int DictEntry = 1;
internal const int KeyValuePair = 2;
internal Enumerator(Dictionary<TKey, TValue> dictionary, int getEnumeratorRetType)
{
_dictionary = dictionary;
_version = dictionary._version;
_index = 0;
_getEnumeratorRetType = getEnumeratorRetType;
_current = new KeyValuePair<TKey, TValue>();
}
public bool MoveNext()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
// Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
// dictionary.count+1 could be negative if dictionary.count is int.MaxValue
while ((uint)_index < (uint)_dictionary._count)
{
ref Entry entry = ref _dictionary._entries[_index++];
if (entry.hashCode >= 0)
{
_current = new KeyValuePair<TKey, TValue>(entry.key, entry.value);
return true;
}
}
_index = _dictionary._count + 1;
_current = new KeyValuePair<TKey, TValue>();
return false;
}
public KeyValuePair<TKey, TValue> Current => _current;
public void Dispose()
{
}
object IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
if (_getEnumeratorRetType == DictEntry)
{
return new DictionaryEntry(_current.Key, _current.Value);
}
else
{
return new KeyValuePair<TKey, TValue>(_current.Key, _current.Value);
}
}
}
void IEnumerator.Reset()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
_index = 0;
_current = new KeyValuePair<TKey, TValue>();
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return new DictionaryEntry(_current.Key, _current.Value);
}
}
object IDictionaryEnumerator.Key
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _current.Key;
}
}
object IDictionaryEnumerator.Value
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _current.Value;
}
}
}
[DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
private Dictionary<TKey, TValue> _dictionary;
public KeyCollection(Dictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
_dictionary = dictionary;
}
public Enumerator GetEnumerator()
=> new Enumerator(_dictionary);
public void CopyTo(TKey[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < _dictionary.Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = _dictionary._count;
Entry[] entries = _dictionary._entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) array[index++] = entries[i].key;
}
}
public int Count => _dictionary.Count;
bool ICollection<TKey>.IsReadOnly => true;
void ICollection<TKey>.Add(TKey item)
=> ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
void ICollection<TKey>.Clear()
=> ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
bool ICollection<TKey>.Contains(TKey item)
=> _dictionary.ContainsKey(item);
bool ICollection<TKey>.Remove(TKey item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
return false;
}
IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator()
=> new Enumerator(_dictionary);
IEnumerator IEnumerable.GetEnumerator()
=> new Enumerator(_dictionary);
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (array.Rank != 1)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
if (array.GetLowerBound(0) != 0)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
if ((uint)index > (uint)array.Length)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (array.Length - index < _dictionary.Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
if (array is TKey[] keys)
{
CopyTo(keys, index);
}
else
{
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = _dictionary._count;
Entry[] entries = _dictionary._entries;
try
{
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) objects[index++] = entries[i].key;
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot;
public struct Enumerator : IEnumerator<TKey>, IEnumerator
{
private readonly Dictionary<TKey, TValue> _dictionary;
private int _index;
private readonly int _version;
private TKey _currentKey;
internal Enumerator(Dictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
_version = dictionary._version;
_index = 0;
_currentKey = default;
}
public void Dispose()
{
}
public bool MoveNext()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
while ((uint)_index < (uint)_dictionary._count)
{
ref Entry entry = ref _dictionary._entries[_index++];
if (entry.hashCode >= 0)
{
_currentKey = entry.key;
return true;
}
}
_index = _dictionary._count + 1;
_currentKey = default;
return false;
}
public TKey Current => _currentKey;
object IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _currentKey;
}
}
void IEnumerator.Reset()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
_index = 0;
_currentKey = default;
}
}
}
[DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
private Dictionary<TKey, TValue> _dictionary;
public ValueCollection(Dictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
_dictionary = dictionary;
}
public Enumerator GetEnumerator()
=> new Enumerator(_dictionary);
public void CopyTo(TValue[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0 || index > array.Length)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < _dictionary.Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = _dictionary._count;
Entry[] entries = _dictionary._entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) array[index++] = entries[i].value;
}
}
public int Count => _dictionary.Count;
bool ICollection<TValue>.IsReadOnly => true;
void ICollection<TValue>.Add(TValue item)
=> ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
bool ICollection<TValue>.Remove(TValue item)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
return false;
}
void ICollection<TValue>.Clear()
=> ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
bool ICollection<TValue>.Contains(TValue item)
=> _dictionary.ContainsValue(item);
IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator()
=> new Enumerator(_dictionary);
IEnumerator IEnumerable.GetEnumerator()
=> new Enumerator(_dictionary);
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (array.Rank != 1)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
if (array.GetLowerBound(0) != 0)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
if ((uint)index > (uint)array.Length)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (array.Length - index < _dictionary.Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
if (array is TValue[] values)
{
CopyTo(values, index);
}
else
{
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = _dictionary._count;
Entry[] entries = _dictionary._entries;
try
{
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0) objects[index++] = entries[i].value;
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot;
public struct Enumerator : IEnumerator<TValue>, IEnumerator
{
private readonly Dictionary<TKey, TValue> _dictionary;
private int _index;
private readonly int _version;
private TValue _currentValue;
internal Enumerator(Dictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
_version = dictionary._version;
_index = 0;
_currentValue = default;
}
public void Dispose()
{
}
public bool MoveNext()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
while ((uint)_index < (uint)_dictionary._count)
{
ref Entry entry = ref _dictionary._entries[_index++];
if (entry.hashCode >= 0)
{
_currentValue = entry.value;
return true;
}
}
_index = _dictionary._count + 1;
_currentValue = default;
return false;
}
public TValue Current => _currentValue;
object IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _dictionary._count + 1))
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return _currentValue;
}
}
void IEnumerator.Reset()
{
if (_version != _dictionary._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
_index = 0;
_currentValue = default;
}
}
}
}
}
| |
using System;
using System.Globalization;
/// <summary>
/// Convert.ToString(System.DateTime,System.IFormatProvider)
/// </summary>
public class ConvertToString8
{
public static int Main()
{
ConvertToString8 testObj = new ConvertToString8();
TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToString(System.DateTime,System.IFormatProvider)");
if (testObj.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;
//ur-PK doesn't exist in telesto
// retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
string c_TEST_DESC = "PosTest1: Verify the DateTime is now and IFormatProvider is en-US CultureInfo... ";
string c_TEST_ID = "P001";
DateTime dt = DateTime.Now;
IFormatProvider provider = new CultureInfo("en-US");
String actualValue = dt.ToString(provider);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
String resValue = Convert.ToString(dt,provider);
if (actualValue != resValue)
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc = "\n IFormatProvider is en-US CultureInfo.";
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string c_TEST_DESC = "PosTest2: Verify the DateTime is now and IFormatProvider is fr-FR CultureInfo... ";
string c_TEST_ID = "P002";
DateTime dt = DateTime.Now;
IFormatProvider provider = new CultureInfo("fr-FR");
String actualValue = dt.ToString(provider);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
String resValue = Convert.ToString(dt,provider);
if (actualValue != resValue)
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc = "\n IFormatProvider is fr-FR CultureInfo.";
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string c_TEST_DESC = "PosTest3: Verify DateTime instance is created by ctor(int year,int month,int day) and IFormatProvider is ur-PK... ";
string c_TEST_ID = "P003";
Random rand = new Random(-55);
int year = rand.Next(1900, 2050);
int month = rand.Next(1, 12);
int day = rand.Next(1, 28);
DateTime dt = new DateTime(year, month, day);
IFormatProvider provider = new CultureInfo("ur-PK");
String actualValue = dt.ToString(provider);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
String resValue = Convert.ToString(dt,provider);
if (actualValue != resValue)
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc = "\n IFormatProvider is ur-PK CultureInfo.";
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string c_TEST_DESC = "PosTest4: Verify DateTime instance is created by ctor(int year,int month,int day,int hour,int minute,int second) and IFormatProvider is ru-RU CultureInfo...... ";
string c_TEST_ID = "P004";
Random rand = new Random(-55);
int year = rand.Next(1900, 2050);
int month = rand.Next(1, 12);
int day = rand.Next(1, 28);
int hour = rand.Next(0, 23);
int minute = rand.Next(0, 59);
int second = rand.Next(0, 59);
DateTime dt = new DateTime(year, month, day);
IFormatProvider provider = new CultureInfo("ru-RU");
String actualValue = dt.ToString(provider);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
String resValue = Convert.ToString(dt,provider);
if (actualValue != resValue)
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc = "\n IFormatProvider is ur-PK CultureInfo.";
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
string c_TEST_DESC = "PosTest5: Verify DateTime instance is created by ctor(int year,int month,int day,int hour,int minute,int second) and IFormatProvider is a null reference... ";
string c_TEST_ID = "P005";
Random rand = new Random(-55);
int year = rand.Next(1900, 2050);
int month = rand.Next(1, 12);
int day = rand.Next(1, 28);
int hour = rand.Next(0, 23);
int minute = rand.Next(0, 59);
int second = rand.Next(0, 59);
DateTime dt = new DateTime(year, month, day);
IFormatProvider provider = null;
String actualValue = dt.ToString(provider);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
String resValue = Convert.ToString(dt, provider);
if (actualValue != resValue)
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc = "\n IFormatProvider is a null reference.";
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
#endregion
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
using System.Runtime.InteropServices;
namespace System.Security
{
// DynamicSecurityMethodAttribute:
// Indicates that calling the target method requires space for a security
// object to be allocated on the callers stack. This attribute is only ever
// set on certain security methods defined within mscorlib.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false )]
sealed internal class DynamicSecurityMethodAttribute : System.Attribute
{
}
// SuppressUnmanagedCodeSecurityAttribute:
// Indicates that the target P/Invoke method(s) should skip the per-call
// security checked for unmanaged code permission.
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false )]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class SuppressUnmanagedCodeSecurityAttribute : System.Attribute
{
}
// UnverifiableCodeAttribute:
// Indicates that the target module contains unverifiable code.
[AttributeUsage(AttributeTargets.Module, AllowMultiple = true, Inherited = false )]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class UnverifiableCodeAttribute : System.Attribute
{
}
// AllowPartiallyTrustedCallersAttribute:
// Indicates that the Assembly is secure and can be used by untrusted
// and semitrusted clients
// For v.1, this is valid only on Assemblies, but could be expanded to
// include Module, Method, class
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false )]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class AllowPartiallyTrustedCallersAttribute : System.Attribute
{
private PartialTrustVisibilityLevel _visibilityLevel;
public AllowPartiallyTrustedCallersAttribute () { }
public PartialTrustVisibilityLevel PartialTrustVisibilityLevel
{
get { return _visibilityLevel; }
set { _visibilityLevel = value; }
}
}
public enum PartialTrustVisibilityLevel
{
VisibleToAllHosts = 0,
NotVisibleByDefault = 1
}
#if !FEATURE_CORECLR
[Obsolete("SecurityCriticalScope is only used for .NET 2.0 transparency compatibility.")]
public enum SecurityCriticalScope
{
Explicit = 0,
Everything = 0x1
}
#endif // FEATURE_CORECLR
// SecurityCriticalAttribute
// Indicates that the decorated code or assembly performs security critical operations (e.g. Assert, "unsafe", LinkDemand, etc.)
// The attribute can be placed on most targets, except on arguments/return values.
[AttributeUsage(AttributeTargets.Assembly |
AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Field |
AttributeTargets.Interface |
AttributeTargets.Delegate,
AllowMultiple = false,
Inherited = false )]
sealed public class SecurityCriticalAttribute : System.Attribute
{
#pragma warning disable 618 // We still use SecurityCriticalScope for v2 compat
#if !FEATURE_CORECLR
private SecurityCriticalScope _val;
#endif // FEATURE_CORECLR
public SecurityCriticalAttribute () {}
#if !FEATURE_CORECLR
public SecurityCriticalAttribute(SecurityCriticalScope scope)
{
_val = scope;
}
[Obsolete("SecurityCriticalScope is only used for .NET 2.0 transparency compatibility.")]
public SecurityCriticalScope Scope {
get {
return _val;
}
}
#endif // FEATURE_CORECLR
#pragma warning restore 618
}
// SecurityTreatAsSafeAttribute:
// Indicates that the code may contain violations to the security critical rules (e.g. transitions from
// critical to non-public transparent, transparent to non-public critical, etc.), has been audited for
// security concerns and is considered security clean.
// At assembly-scope, all rule checks will be suppressed within the assembly and for calls made against the assembly.
// At type-scope, all rule checks will be suppressed for members within the type and for calls made against the type.
// At member level (e.g. field and method) the code will be treated as public - i.e. no rule checks for the members.
[AttributeUsage(AttributeTargets.Assembly |
AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Field |
AttributeTargets.Interface |
AttributeTargets.Delegate,
AllowMultiple = false,
Inherited = false )]
[Obsolete("SecurityTreatAsSafe is only used for .NET 2.0 transparency compatibility. Please use the SecuritySafeCriticalAttribute instead.")]
sealed public class SecurityTreatAsSafeAttribute : System.Attribute
{
public SecurityTreatAsSafeAttribute () { }
}
// SecuritySafeCriticalAttribute:
// Indicates that the code may contain violations to the security critical rules (e.g. transitions from
// critical to non-public transparent, transparent to non-public critical, etc.), has been audited for
// security concerns and is considered security clean. Also indicates that the code is considered SecurityCritical.
// The effect of this attribute is as if the code was marked [SecurityCritical][SecurityTreatAsSafe].
// At assembly-scope, all rule checks will be suppressed within the assembly and for calls made against the assembly.
// At type-scope, all rule checks will be suppressed for members within the type and for calls made against the type.
// At member level (e.g. field and method) the code will be treated as public - i.e. no rule checks for the members.
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Field |
AttributeTargets.Interface |
AttributeTargets.Delegate,
AllowMultiple = false,
Inherited = false )]
sealed public class SecuritySafeCriticalAttribute : System.Attribute
{
public SecuritySafeCriticalAttribute () { }
}
// SecurityTransparentAttribute:
// Indicates the assembly contains only transparent code.
// Security critical actions will be restricted or converted into less critical actions. For example,
// Assert will be restricted, SuppressUnmanagedCode, LinkDemand, unsafe, and unverifiable code will be converted
// into Full-Demands.
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false )]
sealed public class SecurityTransparentAttribute : System.Attribute
{
public SecurityTransparentAttribute () {}
}
#if !FEATURE_CORECLR
public enum SecurityRuleSet : byte
{
None = 0,
Level1 = 1, // v2.0 transparency model
Level2 = 2, // v4.0 transparency model
}
// SecurityRulesAttribute
//
// Indicates which set of security rules an assembly was authored against, and therefore which set of
// rules the runtime should enforce on the assembly. For instance, an assembly marked with
// [SecurityRules(SecurityRuleSet.Level1)] will follow the v2.0 transparency rules, where transparent code
// can call a LinkDemand by converting it to a full demand, public critical methods are implicitly
// treat as safe, and the remainder of the v2.0 rules apply.
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class SecurityRulesAttribute : Attribute
{
private SecurityRuleSet m_ruleSet;
private bool m_skipVerificationInFullTrust = false;
public SecurityRulesAttribute(SecurityRuleSet ruleSet)
{
m_ruleSet = ruleSet;
}
// Should fully trusted transparent code skip IL verification
public bool SkipVerificationInFullTrust
{
get { return m_skipVerificationInFullTrust; }
set { m_skipVerificationInFullTrust = value; }
}
public SecurityRuleSet RuleSet
{
get { return m_ruleSet; }
}
}
#endif // !FEATURE_CORECLR
}
| |
namespace Microsoft.Protocols.TestSuites.MS_ASNOTE
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestSuites.Common.DataStructures;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Request = Microsoft.Protocols.TestSuites.Common.Request;
using Response = Microsoft.Protocols.TestSuites.Common.Response;
/// <summary>
/// This scenario is designed to synchronize notes on the server.
/// </summary>
[TestClass]
public class S01_SyncCommand : TestSuiteBase
{
#region Class initialize and clean up
/// <summary>
/// Initialize the class.
/// </summary>
/// <param name="testContext">VSTS test context.</param>
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
/// <summary>
/// Clear the class.
/// </summary>
[ClassCleanup]
public static void ClassCleanUp()
{
TestClassBase.Cleanup();
}
#endregion
#region MSASNOTE_S01_TC01_Sync_AddNote
/// <summary>
/// This test case is designed to test adding a note using the Sync command.
/// </summary>
[TestCategory("MSASNOTE"), TestMethod()]
public void MSASNOTE_S01_TC01_Sync_AddNote()
{
#region Call method Sync to add a note to the server
Dictionary<Request.ItemsChoiceType8, object> addElements = this.CreateNoteElements();
this.SyncAdd(addElements, 1);
#endregion
#region Call method Sync to synchronize the note item with the server.
SyncStore result = this.SyncChanges(1);
Note note = result.AddElements[0].Note;
Site.Assert.IsNotNull(
note.Categories,
@"The Categories element in note class in response should not be null.");
Site.Assert.IsNotNull(
note.Categories.Category,
@"The Category element in note class in response should not be null.");
Site.Assert.AreEqual<int>(
1,
note.Categories.Category.Length,
"The length of category should be 1 in response");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R211");
// Verify MS-ASNOTE requirement: MS-ASNOTE_R211
// If the value of the single category element is the same in request and response, then MS-ASNOTE_R211 can be captured.
Site.CaptureRequirementIfAreEqual<string>(
((Request.Categories3)addElements[Request.ItemsChoiceType8.Categories2]).Category[0],
note.Categories.Category[0],
211,
@"[In Category] [The Category element] specifies a user-selected label that has been applied to the note.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R123");
Site.Assert.IsNotNull(
note.Body,
@"The Body element in note class in response should not be null.");
// Verify MS-ASNOTE requirement: MS-ASNOTE_R123
// If Body element is present in response, and the Data element is not null, then MS-ASNOTE_R123 can be captured.
Site.CaptureRequirementIfIsNotNull(
note.Body.Data,
123,
@"[In Body] When the airsyncbase:Body element is used in a Sync command response ([MS-ASCMD] section 2.2.2.19), the airsyncbase:Data element ([MS-ASAIRS] section 2.2.2.10.1) is a required child element of the airsyncbase:Body element.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R58");
// Verify MS-ASNOTE requirement: MS-ASNOTE_R58
// If the value of the subject element is the same in request and response, then MS-ASNOTE_R58 can be captured.
Site.CaptureRequirementIfAreEqual<string>(
addElements[Request.ItemsChoiceType8.Subject1].ToString(),
note.Subject,
58,
@"[In Subject] The Subject element specifies the subject of the note.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R51");
// Verify MS-ASNOTE requirement: MS-ASNOTE_R51
// If the value of the LastModifiedDate element is specified, then MS-ASNOTE_R51 can be captured.
Site.CaptureRequirementIfIsTrue(
note.IsLastModifiedDateSpecified,
51,
@"[In LastModifiedDate] The LastModifiedDate element specifies when the note was last changed.");
#endregion
}
#endregion
#region MSASNOTE_S01_TC02_Sync_ChangeNote_WithoutBodyInRequest
/// <summary>
/// This test case is designed to test changing a note's Subject and MessageClass elements without including the note's body in the Sync command.
/// </summary>
[TestCategory("MSASNOTE"), TestMethod()]
public void MSASNOTE_S01_TC02_Sync_ChangeNote_WithoutBodyInRequest()
{
#region Call method Sync to add a note to the server
Dictionary<Request.ItemsChoiceType8, object> addElements = this.CreateNoteElements();
addElements[Request.ItemsChoiceType8.Categories2] = new Request.Categories3();
SyncStore addResult = this.SyncAdd(addElements, 1);
Response.SyncCollectionsCollectionResponsesAdd item = addResult.AddResponses[0];
#endregion
#region Call method Sync to change the note's Subject and MessageClass elements.
// changeElements:Change the note's subject by replacing its subject with a new subject.
Dictionary<Request.ItemsChoiceType7, object> changeElements = new Dictionary<Request.ItemsChoiceType7, object>();
string changedSubject = Common.GenerateResourceName(Site, "subject");
changeElements.Add(Request.ItemsChoiceType7.Subject1, changedSubject);
// changeElements:Change the note's MessageClass by replacing its MessageClass with a new MessageClass.
changeElements.Add(Request.ItemsChoiceType7.MessageClass, "IPM.StickyNote.MSASNOTE");
changeElements = TestSuiteHelper.CombineChangeAndAddNoteElements(addElements, changeElements);
// changeElements:Remove the note's Body in change command
changeElements.Remove(Request.ItemsChoiceType7.Body);
SyncStore changeResult = this.SyncChange(addResult.SyncKey, item.ServerId, changeElements);
Site.Assert.AreEqual<byte>(
1,
changeResult.CollectionStatus,
"The server should return a Status 1 in the Sync command response indicate sync command succeed.");
// The subject of the note is updated.
this.ExistingNoteSubjects.Remove(addElements[Request.ItemsChoiceType8.Subject1].ToString());
this.ExistingNoteSubjects.Add(changeElements[Request.ItemsChoiceType7.Subject1].ToString());
#endregion
#region Call method Sync to synchronize the note item with the server.
// Synchronize the changes with server
SyncStore result = this.SyncChanges(addResult.SyncKey, 1);
bool isNoteFound = TestSuiteHelper.CheckSyncChangeCommands(result, changeElements[Request.ItemsChoiceType7.Subject1].ToString(), this.Site);
Site.Assert.IsTrue(isNoteFound, "The note with subject:{0} should be returned in Sync command response.", changeElements[Request.ItemsChoiceType7.Subject1].ToString());
Note note = result.ChangeElements[0].Note;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R113");
// Verify MS-ASNOTE requirement: MS-ASNOTE_R113
Site.CaptureRequirementIfIsNotNull(
note.Body,
113,
@"[In Sync Command Response] The absence of an airsyncbase:Body element (section 2.2.2.1) within an airsync:Change element is not to be interpreted as an implicit delete.");
Site.Assert.AreEqual<string>(
changeElements[Request.ItemsChoiceType7.Subject1].ToString(),
note.Subject,
"The subject element in Change Command response should be the same with the changed value of subject in Change Command request.");
Site.Assert.AreEqual<string>(
changeElements[Request.ItemsChoiceType7.MessageClass].ToString(),
note.MessageClass,
"The MessageClass element in Change Command response should be the same with the changed value of MessageClass in Change Command request.");
#endregion
}
#endregion
#region MSASNOTE_S01_TC03_Sync_LastModifiedDateIgnored
/// <summary>
/// This test case is designed to test the server ignores the element LastModifiedDate if includes it in the request.
/// </summary>
[TestCategory("MSASNOTE"), TestMethod()]
public void MSASNOTE_S01_TC03_Sync_LastModifiedDateIgnored()
{
#region Call method Sync to add a note to the server
Dictionary<Request.ItemsChoiceType8, object> addElements = this.CreateNoteElements();
string lastModifiedDate = DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture);
addElements.Add(Request.ItemsChoiceType8.LastModifiedDate, lastModifiedDate);
System.Threading.Thread.Sleep(1000);
SyncStore addResult = this.SyncAdd(addElements, 1);
Response.SyncCollectionsCollectionResponsesAdd item = addResult.AddResponses[0];
#endregion
#region Call method Sync to synchronize the note item with the server.
SyncStore result = this.SyncChanges(1);
Note note=null;
for (int i = 0; i < result.AddElements.Count; i++)
{
if (addResult.AddElements != null && addResult.AddElements.Count > 0)
{
if (result.AddElements[i].ServerId.Equals(addResult.AddElements[0].ServerId))
{
note = result.AddElements[i].Note;
break;
}
}
else if(addResult.AddResponses!=null && addResult.AddResponses.Count > 0)
{
if (result.AddElements[i].ServerId.Equals(addResult.AddResponses[0].ServerId))
{
note = result.AddElements[i].Note;
break;
}
}
}
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R84");
// Verify MS-ASNOTE requirement: MS-ASNOTE_R84
Site.CaptureRequirementIfAreNotEqual<string>(
lastModifiedDate,
note.LastModifiedDate.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture),
84,
@"[In LastModifiedDate Element] If it is included in a Sync command request, the server will ignore it.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R209");
// Verify MS-ASNOTE requirement: MS-ASNOTE_R209
// this requirement can be captured directly after MS-ASNOTE_R84.
Site.CaptureRequirement(
209,
@"[In LastModifiedDate Element] If a Sync command request includes the LastModifiedDate element, the server ignores the element and returns the actual time that the note was last modified.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R126");
bool isVerifiedR126 = note.Body != null && note.Subject != null && note.MessageClass != null && note.IsLastModifiedDateSpecified && note.Categories != null && note.Categories.Category != null;
// Verify MS-ASNOTE requirement: MS-ASNOTE_R126
Site.CaptureRequirementIfIsTrue(
isVerifiedR126,
126,
@"[In Sync Command Response] Any of the elements for the Notes class[airsyncbase:Body, Subject, MessageClass, LastModifiedDate, Categories or Category], as specified in section 2.2.2, can be included in a Sync command response as child elements of the airsync:ApplicationData element ([MS-ASCMD] section 2.2.3.11) within [either] an airsync:Add element ([MS-ASCMD] section 2.2.3.7.2) [or an airsync:Change element ([MS-ASCMD] section 2.2.3.24)].");
#endregion
#region Call method Sync to only change the note's LastModifiedDate element, the server will ignore the change, and the note item should be unchanged.
// changeElements: Change the note's LastModifiedDate by replacing its LastModifiedDate with a new LastModifiedDate.
Dictionary<Request.ItemsChoiceType7, object> changeElements = new Dictionary<Request.ItemsChoiceType7, object>();
lastModifiedDate = DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture);
changeElements.Add(Request.ItemsChoiceType7.LastModifiedDate, lastModifiedDate);
this.SyncChange(result.SyncKey, item.ServerId, changeElements);
#endregion
#region Call method Sync to synchronize the changes with the server.
SyncStore result2 = this.SyncChanges(result.SyncKey, 1);
bool isNoteFound;
if (result2.ChangeElements != null)
{
isNoteFound = TestSuiteHelper.CheckSyncChangeCommands(result, addElements[Request.ItemsChoiceType8.Subject1].ToString(), this.Site);
Site.Assert.IsFalse(isNoteFound, "The note with subject:{0} should not be returned in Sync command response.", addElements[Request.ItemsChoiceType8.Subject1].ToString());
}
else
{
Site.Log.Add(LogEntryKind.Debug, @"The Change elements are null.");
}
#endregion
#region Call method Sync to change the note's LastModifiedDate and subject.
// changeElements: Change the note's LastModifiedDate by replacing its LastModifiedDate with a new LastModifiedDate.
// changeElements: Change the note's subject by replacing its subject with a new subject.
changeElements = new Dictionary<Request.ItemsChoiceType7, object>();
lastModifiedDate = DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture);
changeElements.Add(Request.ItemsChoiceType7.LastModifiedDate, lastModifiedDate);
string changedSubject = Common.GenerateResourceName(Site, "subject");
changeElements.Add(Request.ItemsChoiceType7.Subject1, changedSubject);
changeElements = TestSuiteHelper.CombineChangeAndAddNoteElements(addElements, changeElements);
this.SyncChange(result.SyncKey, item.ServerId, changeElements);
#endregion
#region Call method Sync to synchronize the note item with the server.
result = this.SyncChanges(result.SyncKey, 1);
isNoteFound = TestSuiteHelper.CheckSyncChangeCommands(result, changeElements[Request.ItemsChoiceType7.Subject1].ToString(), this.Site);
Site.Assert.IsTrue(isNoteFound, "The note with subject:{0} should be returned in Sync command response.", changeElements[Request.ItemsChoiceType7.Subject1].ToString());
// The subject of the note is updated.
this.ExistingNoteSubjects.Remove(addElements[Request.ItemsChoiceType8.Subject1].ToString());
this.ExistingNoteSubjects.Add(changeElements[Request.ItemsChoiceType7.Subject1].ToString());
note = result.ChangeElements[0].Note;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R210");
bool isVerifiedR210 = note.Body != null && note.Subject != null && note.MessageClass != null && note.IsLastModifiedDateSpecified && note.Categories != null && note.Categories.Category != null;
// Verify MS-ASNOTE requirement: MS-ASNOTE_R210
Site.CaptureRequirementIfIsTrue(
isVerifiedR210,
210,
@"[In Sync Command Response] Any of the elements for the Notes class[airsyncbase:Body, Subject, MessageClass, LastModifiedDate, Categories or Category], as specified in section 2.2.2, can be included in a Sync command response as child elements of the airsync:ApplicationData element ([MS-ASCMD] section 2.2.3.11) within [either an airsync:Add element ([MS-ASCMD] section 2.2.3.7.2) or] an airsync:Change element ([MS-ASCMD] section 2.2.3.24).");
Site.Assert.AreEqual<string>(
changeElements[Request.ItemsChoiceType7.Subject1].ToString(),
note.Subject,
"The subject element in Change Command response should be the same with the changed value of subject in Change Command request.");
#endregion
}
#endregion
#region MSASNOTE_S01_TC04_Sync_SupportedError
/// <summary>
/// This test case is designed to test when the client includes an airsync:Supported element in a Sync command request, the server returns a status error 4.
/// </summary>
[TestCategory("MSASNOTE"), TestMethod()]
public void MSASNOTE_S01_TC04_Sync_SupportedError()
{
#region Call an initial method Sync including the Supported option.
Request.SyncCollection syncCollection = new Request.SyncCollection
{
CollectionId = this.UserInformation.NotesCollectionId,
SyncKey = "0",
Supported = new Request.Supported()
};
SyncRequest syncRequest = Common.CreateSyncRequest(new Request.SyncCollection[] { syncCollection });
SyncStore syncResult = this.NOTEAdapter.Sync(syncRequest, false);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R114");
// Verify MS-ASNOTE requirement: MS-ASNOTE_R114
Site.CaptureRequirementIfAreEqual<int>(
4,
syncResult.Status,
114,
@"[In Sync Command Response] If the airsync:Supported element ([MS-ASCMD] section 2.2.3.164) is included in a Sync command request for Notes class data, the server returns a Status element with a value of 4, as specified in [MS-ASCMD] section 2.2.3.162.16.");
#endregion
}
#endregion
#region MSASNOTE_S01_TC05_Sync_InvalidMessageClass
/// <summary>
/// This test case is designed to test when the MessageClass content does not use the standard format in a Sync request, the server responds with a status error 6.
/// </summary>
[TestCategory("MSASNOTE"), TestMethod()]
public void MSASNOTE_S01_TC05_Sync_InvalidMessageClass()
{
#region Call method Sync to add a note to the server
Dictionary<Request.ItemsChoiceType8, object> addElements = this.CreateNoteElements();
addElements[Request.ItemsChoiceType8.MessageClass] = "IPM.invalidClass";
SyncRequest syncRequest = TestSuiteHelper.CreateInitialSyncRequest(this.UserInformation.NotesCollectionId);
SyncStore syncResult = this.NOTEAdapter.Sync(syncRequest, false);
Site.Assert.AreEqual<byte>(
1,
syncResult.CollectionStatus,
"The server should return a status code 1 in the Sync command response indicate sync command success.");
List<object> addData = new List<object>();
Request.SyncCollectionAdd add = new Request.SyncCollectionAdd
{
ClientId = System.Guid.NewGuid().ToString(),
ApplicationData = new Request.SyncCollectionAddApplicationData
{
ItemsElementName = new Request.ItemsChoiceType8[addElements.Count],
Items = new object[addElements.Count]
}
};
addElements.Keys.CopyTo(add.ApplicationData.ItemsElementName, 0);
addElements.Values.CopyTo(add.ApplicationData.Items, 0);
addData.Add(add);
syncRequest = TestSuiteHelper.CreateSyncRequest(syncResult.SyncKey, this.UserInformation.NotesCollectionId, addData);
SyncStore addResult = this.NOTEAdapter.Sync(syncRequest, false);
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R119");
// Verify MS-ASNOTE requirement: MS-ASNOTE_R119
Site.CaptureRequirementIfAreEqual<int>(
6,
int.Parse(addResult.AddResponses[0].Status),
119,
@"[In MessageClass Element] If a client submits a Sync command request ([MS-ASCMD] section 2.2.2.19) that contains a MessageClass element value that does not conform to the requirements specified in section 2.2.2.5, the server MUST respond with a Status element with a value of 6, as specified in [MS-ASCMD] section 2.2.3.162.16.");
#endregion
}
#endregion
#region MSASNOTE_S01_TC06_Sync_AddNote_WithBodyTypes
/// <summary>
/// This test case is designed to test that the type element of the body in note item has 3 different values:1, 2, 3.
/// </summary>
[TestCategory("MSASNOTE"), TestMethod()]
public void MSASNOTE_S01_TC06_Sync_AddNote_WithBodyTypes()
{
#region Call method Sync to add a note to the server
Dictionary<Request.ItemsChoiceType8, object> addElements = this.CreateNoteElements();
this.SyncAdd(addElements, 1);
#endregion
#region Call method Sync to synchronize the note item with the server and expect to get the body of Type 1.
SyncStore result = this.SyncChanges(1);
Note note = result.AddElements[0].Note;
Site.Assert.AreEqual<string>(
((Request.Body)addElements[Request.ItemsChoiceType8.Body]).Data,
note.Body.Data,
@"The content of body in response should be equal to that in request.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R38");
// Verify MS-ASNOTE requirement: MS-ASNOTE_R38
// If the content of the body is the same in request and response and the type is 1, then MS-ASNOTE_R38 can be captured.
Site.CaptureRequirementIfAreEqual<int>(
1,
note.Body.Type,
38,
@"[In Body] The value 1 means Plain text.");
#endregion
#region Call method Sync to synchronize the note item with the server and expect to get the body of Type 2.
result = this.SyncChanges(2);
note = result.AddElements[0].Note;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R39");
bool isHTML = TestSuiteHelper.IsHTML(note.Body.Data);
Site.Assert.IsTrue(
isHTML,
@"The content of body element in response should be in HTML format. Actual: {0}",
isHTML);
// Verify MS-ASNOTE requirement: MS-ASNOTE_R39
// If the content of the body is in HTML format and the type is 2, then MS-ASNOTE_R39 can be captured.
Site.CaptureRequirementIfAreEqual<int>(
2,
note.Body.Type,
39,
@"[In Body] The value 2 means HTML.");
#endregion
#region Call method Sync to synchronize the note item with the server and expect to get the body of Type 3.
result = this.SyncChanges(3);
note = result.AddElements[0].Note;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R40");
try
{
byte[] contentBytes = Convert.FromBase64String(note.Body.Data);
System.Text.Encoding.UTF8.GetString(contentBytes);
}
catch (FormatException formatException)
{
throw new FormatException("The content of body should be Base64 encoded", formatException);
}
// Verify MS-ASNOTE requirement: MS-ASNOTE_R40
// If the content of the body is in Base64 format and the type is 3, then MS-ASNOTE_R40 can be captured.
Site.CaptureRequirementIfAreEqual<int>(
3,
note.Body.Type,
40,
@"[In Body] The value 3 means Rich Text Format (RTF).");
#endregion
}
#endregion
#region MSASNOTE_S01_TC07_Sync_ChangeNote_Categories
/// <summary>
/// This test case is designed to test changing a note's Categories element and its child elements.
/// </summary>
[TestCategory("MSASNOTE"), TestMethod()]
public void MSASNOTE_S01_TC07_Sync_ChangeNote_Categories()
{
#region Call method Sync to add a note with two child elements in a Categories element to the server
Dictionary<Request.ItemsChoiceType8, object> addElements = this.CreateNoteElements();
Request.Categories3 categories = new Request.Categories3 { Category = new string[2] };
Collection<string> category = new Collection<string> { "blue category", "red category" };
category.CopyTo(categories.Category, 0);
addElements[Request.ItemsChoiceType8.Categories2] = categories;
this.SyncAdd(addElements, 1);
#endregion
#region Call method Sync to synchronize the note item with the server and expect to get two child elements in response.
// Synchronize the changes with server
SyncStore result = this.SyncChanges(1);
Note noteAdded = result.AddElements[0].Note;
Site.Assert.IsNotNull(noteAdded.Categories, "The Categories element in response should not be null.");
Site.Assert.IsNotNull(noteAdded.Categories.Category, "The category array in response should not be null.");
Site.Assert.AreEqual(2, noteAdded.Categories.Category.Length, "The length of category array in response should be equal to 2.");
#endregion
#region Call method Sync to change the note with MessageClass elements and one child element of Categories element is missing.
Dictionary<Request.ItemsChoiceType7, object> changeElements = new Dictionary<Request.ItemsChoiceType7, object>
{
{
Request.ItemsChoiceType7.MessageClass, "IPM.StickyNote.MSASNOTE1"
}
};
categories.Category = new string[1];
category.Remove("red category");
category.CopyTo(categories.Category, 0);
changeElements.Add(Request.ItemsChoiceType7.Categories3, categories);
SyncStore changeResult = this.SyncChange(result.SyncKey, result.AddElements[0].ServerId, changeElements);
Site.Assert.AreEqual<byte>(
1,
changeResult.CollectionStatus,
"The server should return a Status 1 in the Sync command response indicate sync command succeed.");
#endregion
#region Call method Sync to synchronize the note item with the server, and check if one child element is missing in response.
// Synchronize the changes with server
result = this.SyncChanges(result.SyncKey, 1);
bool isNoteFound = TestSuiteHelper.CheckSyncChangeCommands(result, addElements[Request.ItemsChoiceType8.Subject1].ToString(), this.Site);
Site.Assert.IsTrue(isNoteFound, "The note with subject:{0} should be returned in Sync command response.", addElements[Request.ItemsChoiceType8.Subject1].ToString());
Note note = result.ChangeElements[0].Note;
Site.Assert.IsNotNull(note.Categories, "The Categories element in response should not be null.");
Site.Assert.IsNotNull(note.Categories.Category, "The category array in response should not be null.");
Site.Assert.IsNotNull(note.Subject, "The Subject element in response should not be null.");
Site.Assert.AreEqual(1, note.Categories.Category.Length, "The length of category array in response should be equal to 1.");
bool hasRedCategory = false;
if (note.Categories.Category[0].Equals("red category", StringComparison.Ordinal))
{
hasRedCategory = true;
}
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R10002");
// Verify MS-ASNOTE requirement: MS-ASNOTE_R10002
Site.CaptureRequirementIfIsFalse(
hasRedCategory,
10002,
@"[In Sync Command Response] If a child of the Categories element (section 2.2.2.3) that was previously set is missing, the server will delete that property from the note.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R10003");
// Verify MS-ASNOTE requirement: MS-ASNOTE_R10003
Site.CaptureRequirementIfAreEqual<string>(
noteAdded.Subject,
note.Subject,
10003,
@"[In Sync Command Response] The absence of a Subject element (section 2.2.2.6) within an airsync:Change element is not to be interpreted as an implicit delete.");
#endregion
#region Call method Sync to change the note with MessageClass elements and without Categories element.
changeElements = new Dictionary<Request.ItemsChoiceType7, object>
{
{
Request.ItemsChoiceType7.MessageClass, "IPM.StickyNote.MSASNOTE2"
}
};
changeResult = this.SyncChange(result.SyncKey, result.ChangeElements[0].ServerId, changeElements);
Site.Assert.AreEqual<byte>(
1,
changeResult.CollectionStatus,
"The server should return a Status 1 in the Sync command response indicate sync command succeed.");
#endregion
#region Call method Sync to synchronize the note item with the server, and check if the Categories element is missing in response.
// Synchronize the changes with server
result = this.SyncChanges(result.SyncKey, 1);
isNoteFound = TestSuiteHelper.CheckSyncChangeCommands(result, addElements[Request.ItemsChoiceType8.Subject1].ToString(), this.Site);
Site.Assert.IsTrue(isNoteFound, "The note with subject:{0} should be returned in Sync command response.", addElements[Request.ItemsChoiceType8.Subject1].ToString());
note = result.ChangeElements[0].Note;
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASNOTE_R112");
// Verify MS-ASNOTE requirement: MS-ASNOTE_R112
Site.CaptureRequirementIfIsNull(
note.Categories,
112,
@"[In Sync Command Response] If the Categories element (section 2.2.2.2) that was previously set is missing[in an airsync:Change element in a Sync command request], the server will delete that property from the note.");
#endregion
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A pool in the Azure Batch service.
/// </summary>
public partial class CloudPool : ITransportObjectProvider<Models.PoolAddParameter>, IInheritedBehaviors, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<Common.AllocationState?> AllocationStateProperty;
public readonly PropertyAccessor<DateTime?> AllocationStateTransitionTimeProperty;
public readonly PropertyAccessor<IList<string>> ApplicationLicensesProperty;
public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty;
public readonly PropertyAccessor<bool?> AutoScaleEnabledProperty;
public readonly PropertyAccessor<TimeSpan?> AutoScaleEvaluationIntervalProperty;
public readonly PropertyAccessor<string> AutoScaleFormulaProperty;
public readonly PropertyAccessor<AutoScaleRun> AutoScaleRunProperty;
public readonly PropertyAccessor<IList<CertificateReference>> CertificateReferencesProperty;
public readonly PropertyAccessor<CloudServiceConfiguration> CloudServiceConfigurationProperty;
public readonly PropertyAccessor<DateTime?> CreationTimeProperty;
public readonly PropertyAccessor<int?> CurrentDedicatedComputeNodesProperty;
public readonly PropertyAccessor<int?> CurrentLowPriorityComputeNodesProperty;
public readonly PropertyAccessor<string> DisplayNameProperty;
public readonly PropertyAccessor<string> ETagProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<BatchPoolIdentity> IdentityProperty;
public readonly PropertyAccessor<bool?> InterComputeNodeCommunicationEnabledProperty;
public readonly PropertyAccessor<DateTime?> LastModifiedProperty;
public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty;
public readonly PropertyAccessor<IList<MountConfiguration>> MountConfigurationProperty;
public readonly PropertyAccessor<NetworkConfiguration> NetworkConfigurationProperty;
public readonly PropertyAccessor<IReadOnlyList<ResizeError>> ResizeErrorsProperty;
public readonly PropertyAccessor<TimeSpan?> ResizeTimeoutProperty;
public readonly PropertyAccessor<StartTask> StartTaskProperty;
public readonly PropertyAccessor<Common.PoolState?> StateProperty;
public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty;
public readonly PropertyAccessor<PoolStatistics> StatisticsProperty;
public readonly PropertyAccessor<int?> TargetDedicatedComputeNodesProperty;
public readonly PropertyAccessor<int?> TargetLowPriorityComputeNodesProperty;
public readonly PropertyAccessor<TaskSchedulingPolicy> TaskSchedulingPolicyProperty;
public readonly PropertyAccessor<int?> TaskSlotsPerNodeProperty;
public readonly PropertyAccessor<string> UrlProperty;
public readonly PropertyAccessor<IList<UserAccount>> UserAccountsProperty;
public readonly PropertyAccessor<VirtualMachineConfiguration> VirtualMachineConfigurationProperty;
public readonly PropertyAccessor<string> VirtualMachineSizeProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.AllocationStateProperty = this.CreatePropertyAccessor<Common.AllocationState?>(nameof(AllocationState), BindingAccess.None);
this.AllocationStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(AllocationStateTransitionTime), BindingAccess.None);
this.ApplicationLicensesProperty = this.CreatePropertyAccessor<IList<string>>(nameof(ApplicationLicenses), BindingAccess.Read | BindingAccess.Write);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>(nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(AutoScaleEnabled), BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(AutoScaleEvaluationInterval), BindingAccess.Read | BindingAccess.Write);
this.AutoScaleFormulaProperty = this.CreatePropertyAccessor<string>(nameof(AutoScaleFormula), BindingAccess.Read | BindingAccess.Write);
this.AutoScaleRunProperty = this.CreatePropertyAccessor<AutoScaleRun>(nameof(AutoScaleRun), BindingAccess.None);
this.CertificateReferencesProperty = this.CreatePropertyAccessor<IList<CertificateReference>>(nameof(CertificateReferences), BindingAccess.Read | BindingAccess.Write);
this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor<CloudServiceConfiguration>(nameof(CloudServiceConfiguration), BindingAccess.Read | BindingAccess.Write);
this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(CreationTime), BindingAccess.None);
this.CurrentDedicatedComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(CurrentDedicatedComputeNodes), BindingAccess.None);
this.CurrentLowPriorityComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(CurrentLowPriorityComputeNodes), BindingAccess.None);
this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write);
this.ETagProperty = this.CreatePropertyAccessor<string>(nameof(ETag), BindingAccess.None);
this.IdProperty = this.CreatePropertyAccessor<string>(nameof(Id), BindingAccess.Read | BindingAccess.Write);
this.IdentityProperty = this.CreatePropertyAccessor<BatchPoolIdentity>(nameof(Identity), BindingAccess.Read | BindingAccess.Write);
this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(InterComputeNodeCommunicationEnabled), BindingAccess.Read | BindingAccess.Write);
this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>(nameof(LastModified), BindingAccess.None);
this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>(nameof(Metadata), BindingAccess.Read | BindingAccess.Write);
this.MountConfigurationProperty = this.CreatePropertyAccessor<IList<MountConfiguration>>(nameof(MountConfiguration), BindingAccess.Read | BindingAccess.Write);
this.NetworkConfigurationProperty = this.CreatePropertyAccessor<NetworkConfiguration>(nameof(NetworkConfiguration), BindingAccess.Read | BindingAccess.Write);
this.ResizeErrorsProperty = this.CreatePropertyAccessor<IReadOnlyList<ResizeError>>(nameof(ResizeErrors), BindingAccess.None);
this.ResizeTimeoutProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(ResizeTimeout), BindingAccess.Read | BindingAccess.Write);
this.StartTaskProperty = this.CreatePropertyAccessor<StartTask>(nameof(StartTask), BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor<Common.PoolState?>(nameof(State), BindingAccess.None);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(StateTransitionTime), BindingAccess.None);
this.StatisticsProperty = this.CreatePropertyAccessor<PoolStatistics>(nameof(Statistics), BindingAccess.None);
this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetDedicatedComputeNodes), BindingAccess.Read | BindingAccess.Write);
this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetLowPriorityComputeNodes), BindingAccess.Read | BindingAccess.Write);
this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor<TaskSchedulingPolicy>(nameof(TaskSchedulingPolicy), BindingAccess.Read | BindingAccess.Write);
this.TaskSlotsPerNodeProperty = this.CreatePropertyAccessor<int?>(nameof(TaskSlotsPerNode), BindingAccess.Read | BindingAccess.Write);
this.UrlProperty = this.CreatePropertyAccessor<string>(nameof(Url), BindingAccess.None);
this.UserAccountsProperty = this.CreatePropertyAccessor<IList<UserAccount>>(nameof(UserAccounts), BindingAccess.Read | BindingAccess.Write);
this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor<VirtualMachineConfiguration>(nameof(VirtualMachineConfiguration), BindingAccess.Read | BindingAccess.Write);
this.VirtualMachineSizeProperty = this.CreatePropertyAccessor<string>(nameof(VirtualMachineSize), BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.CloudPool protocolObject) : base(BindingState.Bound)
{
this.AllocationStateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.AllocationState, Common.AllocationState>(protocolObject.AllocationState),
nameof(AllocationState),
BindingAccess.Read);
this.AllocationStateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.AllocationStateTransitionTime,
nameof(AllocationStateTransitionTime),
BindingAccess.Read);
this.ApplicationLicensesProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CollectionToThreadSafeCollection(protocolObject.ApplicationLicenses, o => o),
nameof(ApplicationLicenses),
BindingAccess.Read);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor(
ApplicationPackageReference.ConvertFromProtocolCollection(protocolObject.ApplicationPackageReferences),
nameof(ApplicationPackageReferences),
BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEnabledProperty = this.CreatePropertyAccessor(
protocolObject.EnableAutoScale,
nameof(AutoScaleEnabled),
BindingAccess.Read);
this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor(
protocolObject.AutoScaleEvaluationInterval,
nameof(AutoScaleEvaluationInterval),
BindingAccess.Read);
this.AutoScaleFormulaProperty = this.CreatePropertyAccessor(
protocolObject.AutoScaleFormula,
nameof(AutoScaleFormula),
BindingAccess.Read);
this.AutoScaleRunProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AutoScaleRun, o => new AutoScaleRun(o).Freeze()),
nameof(AutoScaleRun),
BindingAccess.Read);
this.CertificateReferencesProperty = this.CreatePropertyAccessor(
CertificateReference.ConvertFromProtocolCollection(protocolObject.CertificateReferences),
nameof(CertificateReferences),
BindingAccess.Read | BindingAccess.Write);
this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.CloudServiceConfiguration, o => new CloudServiceConfiguration(o).Freeze()),
nameof(CloudServiceConfiguration),
BindingAccess.Read);
this.CreationTimeProperty = this.CreatePropertyAccessor(
protocolObject.CreationTime,
nameof(CreationTime),
BindingAccess.Read);
this.CurrentDedicatedComputeNodesProperty = this.CreatePropertyAccessor(
protocolObject.CurrentDedicatedNodes,
nameof(CurrentDedicatedComputeNodes),
BindingAccess.Read);
this.CurrentLowPriorityComputeNodesProperty = this.CreatePropertyAccessor(
protocolObject.CurrentLowPriorityNodes,
nameof(CurrentLowPriorityComputeNodes),
BindingAccess.Read);
this.DisplayNameProperty = this.CreatePropertyAccessor(
protocolObject.DisplayName,
nameof(DisplayName),
BindingAccess.Read);
this.ETagProperty = this.CreatePropertyAccessor(
protocolObject.ETag,
nameof(ETag),
BindingAccess.Read);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
nameof(Id),
BindingAccess.Read);
this.IdentityProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Identity, o => new BatchPoolIdentity(o)),
nameof(Identity),
BindingAccess.Read | BindingAccess.Write);
this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor(
protocolObject.EnableInterNodeCommunication,
nameof(InterComputeNodeCommunicationEnabled),
BindingAccess.Read);
this.LastModifiedProperty = this.CreatePropertyAccessor(
protocolObject.LastModified,
nameof(LastModified),
BindingAccess.Read);
this.MetadataProperty = this.CreatePropertyAccessor(
MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata),
nameof(Metadata),
BindingAccess.Read | BindingAccess.Write);
this.MountConfigurationProperty = this.CreatePropertyAccessor(
Batch.MountConfiguration.ConvertFromProtocolCollectionAndFreeze(protocolObject.MountConfiguration),
nameof(MountConfiguration),
BindingAccess.Read);
this.NetworkConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NetworkConfiguration, o => new NetworkConfiguration(o).Freeze()),
nameof(NetworkConfiguration),
BindingAccess.Read);
this.ResizeErrorsProperty = this.CreatePropertyAccessor(
ResizeError.ConvertFromProtocolCollectionReadOnly(protocolObject.ResizeErrors),
nameof(ResizeErrors),
BindingAccess.Read);
this.ResizeTimeoutProperty = this.CreatePropertyAccessor(
protocolObject.ResizeTimeout,
nameof(ResizeTimeout),
BindingAccess.Read);
this.StartTaskProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.StartTask, o => new StartTask(o)),
nameof(StartTask),
BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.PoolState, Common.PoolState>(protocolObject.State),
nameof(State),
BindingAccess.Read);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.StateTransitionTime,
nameof(StateTransitionTime),
BindingAccess.Read);
this.StatisticsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new PoolStatistics(o).Freeze()),
nameof(Statistics),
BindingAccess.Read);
this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor(
protocolObject.TargetDedicatedNodes,
nameof(TargetDedicatedComputeNodes),
BindingAccess.Read);
this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor(
protocolObject.TargetLowPriorityNodes,
nameof(TargetLowPriorityComputeNodes),
BindingAccess.Read);
this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.TaskSchedulingPolicy, o => new TaskSchedulingPolicy(o).Freeze()),
nameof(TaskSchedulingPolicy),
BindingAccess.Read);
this.TaskSlotsPerNodeProperty = this.CreatePropertyAccessor(
protocolObject.TaskSlotsPerNode,
nameof(TaskSlotsPerNode),
BindingAccess.Read);
this.UrlProperty = this.CreatePropertyAccessor(
protocolObject.Url,
nameof(Url),
BindingAccess.Read);
this.UserAccountsProperty = this.CreatePropertyAccessor(
UserAccount.ConvertFromProtocolCollectionAndFreeze(protocolObject.UserAccounts),
nameof(UserAccounts),
BindingAccess.Read);
this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.VirtualMachineConfiguration, o => new VirtualMachineConfiguration(o).Freeze()),
nameof(VirtualMachineConfiguration),
BindingAccess.Read);
this.VirtualMachineSizeProperty = this.CreatePropertyAccessor(
protocolObject.VmSize,
nameof(VirtualMachineSize),
BindingAccess.Read);
}
}
private PropertyContainer propertyContainer;
private readonly BatchClient parentBatchClient;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CloudPool"/> class.
/// </summary>
/// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param>
/// <param name='baseBehaviors'>The base behaviors to use.</param>
internal CloudPool(
BatchClient parentBatchClient,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.propertyContainer = new PropertyContainer();
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
}
internal CloudPool(
BatchClient parentBatchClient,
Models.CloudPool protocolObject,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region IInheritedBehaviors
/// <summary>
/// Gets or sets a list of behaviors that modify or customize requests to the Batch service
/// made via this <see cref="CloudPool"/>.
/// </summary>
/// <remarks>
/// <para>These behaviors are inherited by child objects.</para>
/// <para>Modifications are applied in the order of the collection. The last write wins.</para>
/// </remarks>
public IList<BatchClientBehavior> CustomBehaviors { get; set; }
#endregion IInheritedBehaviors
#region CloudPool
/// <summary>
/// Gets an <see cref="Common.AllocationState"/> which indicates what node allocation activity is occurring on the
/// pool.
/// </summary>
public Common.AllocationState? AllocationState
{
get { return this.propertyContainer.AllocationStateProperty.Value; }
}
/// <summary>
/// Gets the time at which the pool entered its current <see cref="AllocationState"/>.
/// </summary>
public DateTime? AllocationStateTransitionTime
{
get { return this.propertyContainer.AllocationStateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets or sets the list of application licenses the Batch service will make available on each compute node in the
/// pool.
/// </summary>
/// <remarks>
/// <para>The list of application licenses must be a subset of available Batch service application licenses.</para><para>The
/// permitted licenses available on the pool are 'maya', 'vray', '3dsmax', 'arnold'. An additional charge applies
/// for each application license added to the pool.</para>
/// </remarks>
public IList<string> ApplicationLicenses
{
get { return this.propertyContainer.ApplicationLicensesProperty.Value; }
set
{
this.propertyContainer.ApplicationLicensesProperty.Value = ConcurrentChangeTrackedList<string>.TransformEnumerableToConcurrentList(value);
}
}
/// <summary>
/// Gets or sets a list of application packages to be installed on each compute node in the pool.
/// </summary>
/// <remarks>
/// Changes to application package references affect all new compute nodes joining the pool, but do not affect compute
/// nodes that are already in the pool until they are rebooted or reimaged. There is a maximum of 10 application
/// package references on any given pool.
/// </remarks>
public IList<ApplicationPackageReference> ApplicationPackageReferences
{
get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; }
set
{
this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets whether the pool size should automatically adjust according to the <see cref="AutoScaleFormula"/>.
/// </summary>
/// <remarks>
/// <para>If true, the <see cref="AutoScaleFormula"/> property is required, the pool automatically resizes according
/// to the formula, and <see cref="TargetDedicatedComputeNodes"/> and <see cref="TargetLowPriorityComputeNodes"/>
/// must be null.</para> <para>If false, one of the <see cref="TargetDedicatedComputeNodes"/> or <see cref="TargetLowPriorityComputeNodes"/>
/// properties is required.</para><para>The default value is false.</para>
/// </remarks>
public bool? AutoScaleEnabled
{
get { return this.propertyContainer.AutoScaleEnabledProperty.Value; }
set { this.propertyContainer.AutoScaleEnabledProperty.Value = value; }
}
/// <summary>
/// Gets or sets a time interval at which to automatically adjust the pool size according to the <see cref="AutoScaleFormula"/>.
/// </summary>
/// <remarks>
/// The default value is 15 minutes. The minimum allowed value is 5 minutes.
/// </remarks>
public TimeSpan? AutoScaleEvaluationInterval
{
get { return this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value; }
set { this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value = value; }
}
/// <summary>
/// Gets or sets a formula for the desired number of compute nodes in the pool.
/// </summary>
/// <remarks>
/// <para>For how to write autoscale formulas, see https://azure.microsoft.com/documentation/articles/batch-automatic-scaling/.
/// This property is required if <see cref="AutoScaleEnabled"/> is set to true. It must be null if AutoScaleEnabled
/// is false.</para><para>The formula is checked for validity before the pool is created. If the formula is not valid,
/// an exception is thrown when you try to commit the <see cref="CloudPool"/>.</para>
/// </remarks>
public string AutoScaleFormula
{
get { return this.propertyContainer.AutoScaleFormulaProperty.Value; }
set { this.propertyContainer.AutoScaleFormulaProperty.Value = value; }
}
/// <summary>
/// Gets the results and errors from the last execution of the <see cref="AutoScaleFormula"/>.
/// </summary>
public AutoScaleRun AutoScaleRun
{
get { return this.propertyContainer.AutoScaleRunProperty.Value; }
}
/// <summary>
/// Gets or sets a list of certificates to be installed on each compute node in the pool.
/// </summary>
public IList<CertificateReference> CertificateReferences
{
get { return this.propertyContainer.CertificateReferencesProperty.Value; }
set
{
this.propertyContainer.CertificateReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<CertificateReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the <see cref="CloudServiceConfiguration"/> for the pool.
/// </summary>
public CloudServiceConfiguration CloudServiceConfiguration
{
get { return this.propertyContainer.CloudServiceConfigurationProperty.Value; }
set { this.propertyContainer.CloudServiceConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets the creation time for the pool.
/// </summary>
public DateTime? CreationTime
{
get { return this.propertyContainer.CreationTimeProperty.Value; }
}
/// <summary>
/// Gets the number of dedicated compute nodes currently in the pool.
/// </summary>
public int? CurrentDedicatedComputeNodes
{
get { return this.propertyContainer.CurrentDedicatedComputeNodesProperty.Value; }
}
/// <summary>
/// Gets the number of low-priority compute nodes currently in the pool.
/// </summary>
/// <remarks>
/// Low-priority compute nodes which have been preempted are included in this count.
/// </remarks>
public int? CurrentLowPriorityComputeNodes
{
get { return this.propertyContainer.CurrentLowPriorityComputeNodesProperty.Value; }
}
/// <summary>
/// Gets or sets the display name of the pool.
/// </summary>
public string DisplayName
{
get { return this.propertyContainer.DisplayNameProperty.Value; }
set { this.propertyContainer.DisplayNameProperty.Value = value; }
}
/// <summary>
/// Gets the ETag for the pool.
/// </summary>
public string ETag
{
get { return this.propertyContainer.ETagProperty.Value; }
}
/// <summary>
/// Gets or sets the id of the pool.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
set { this.propertyContainer.IdProperty.Value = value; }
}
/// <summary>
/// Gets or sets the identity of the Batch pool, if configured.
/// </summary>
/// <remarks>
/// The list of user identities associated with the Batch pool. The user identity dictionary key references will
/// be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
/// </remarks>
public BatchPoolIdentity Identity
{
get { return this.propertyContainer.IdentityProperty.Value; }
set { this.propertyContainer.IdentityProperty.Value = value; }
}
/// <summary>
/// Gets or sets whether the pool permits direct communication between its compute nodes.
/// </summary>
/// <remarks>
/// Enabling inter-node communication limits the maximum size of the pool due to deployment restrictions on the nodes
/// of the pool. This may result in the pool not reaching its desired size.
/// </remarks>
public bool? InterComputeNodeCommunicationEnabled
{
get { return this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value; }
set { this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value = value; }
}
/// <summary>
/// Gets the last modified time of the pool.
/// </summary>
public DateTime? LastModified
{
get { return this.propertyContainer.LastModifiedProperty.Value; }
}
/// <summary>
/// Gets or sets a list of name-value pairs associated with the pool as metadata.
/// </summary>
public IList<MetadataItem> Metadata
{
get { return this.propertyContainer.MetadataProperty.Value; }
set
{
this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets a list of file systems to mount on each node in the pool.
/// </summary>
/// <remarks>
/// This supports Azure Files, NFS, CIFS/SMB, and Blobfuse.
/// </remarks>
public IList<MountConfiguration> MountConfiguration
{
get { return this.propertyContainer.MountConfigurationProperty.Value; }
set
{
this.propertyContainer.MountConfigurationProperty.Value = ConcurrentChangeTrackedModifiableList<MountConfiguration>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the network configuration of the pool.
/// </summary>
public NetworkConfiguration NetworkConfiguration
{
get { return this.propertyContainer.NetworkConfigurationProperty.Value; }
set { this.propertyContainer.NetworkConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets a list of errors encountered while performing the last resize on the <see cref="CloudPool"/>. Errors are
/// returned only when the Batch service encountered an error while resizing the pool, and when the pool's <see cref="CloudPool.AllocationState"/>
/// is <see cref="Common.AllocationState.Steady">Steady</see>.
/// </summary>
public IReadOnlyList<ResizeError> ResizeErrors
{
get { return this.propertyContainer.ResizeErrorsProperty.Value; }
}
/// <summary>
/// Gets or sets the timeout for allocation of compute nodes to the pool.
/// </summary>
public TimeSpan? ResizeTimeout
{
get { return this.propertyContainer.ResizeTimeoutProperty.Value; }
set { this.propertyContainer.ResizeTimeoutProperty.Value = value; }
}
/// <summary>
/// Gets or sets a task to run on each compute node as it joins the pool. The task runs when the node is added to
/// the pool or when the node is restarted.
/// </summary>
public StartTask StartTask
{
get { return this.propertyContainer.StartTaskProperty.Value; }
set { this.propertyContainer.StartTaskProperty.Value = value; }
}
/// <summary>
/// Gets the current state of the pool.
/// </summary>
public Common.PoolState? State
{
get { return this.propertyContainer.StateProperty.Value; }
}
/// <summary>
/// Gets the time at which the pool entered its current state.
/// </summary>
public DateTime? StateTransitionTime
{
get { return this.propertyContainer.StateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets the resource usage statistics for the pool.
/// </summary>
/// <remarks>
/// This property is populated only if the <see cref="CloudPool"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/>
/// including the 'stats' attribute; otherwise it is null. The statistics may not be immediately available. The Batch
/// service performs periodic roll-up of statistics. The typical delay is about 30 minutes.
/// </remarks>
public PoolStatistics Statistics
{
get { return this.propertyContainer.StatisticsProperty.Value; }
}
/// <summary>
/// Gets or sets the desired number of dedicated compute nodes in the pool.
/// </summary>
/// <remarks>
/// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of this property
/// and <see cref="TargetLowPriorityComputeNodes"/> must be specified if <see cref="AutoScaleEnabled"/> is false.
/// If not specified, the default is 0.
/// </remarks>
public int? TargetDedicatedComputeNodes
{
get { return this.propertyContainer.TargetDedicatedComputeNodesProperty.Value; }
set { this.propertyContainer.TargetDedicatedComputeNodesProperty.Value = value; }
}
/// <summary>
/// Gets or sets the desired number of low-priority compute nodes in the pool.
/// </summary>
/// <remarks>
/// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of <see cref="TargetDedicatedComputeNodes"/>
/// and this property must be specified if <see cref="AutoScaleEnabled"/> is false. If not specified, the default
/// is 0.
/// </remarks>
public int? TargetLowPriorityComputeNodes
{
get { return this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value; }
set { this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value = value; }
}
/// <summary>
/// Gets or sets how tasks are distributed among compute nodes in the pool.
/// </summary>
public TaskSchedulingPolicy TaskSchedulingPolicy
{
get { return this.propertyContainer.TaskSchedulingPolicyProperty.Value; }
set { this.propertyContainer.TaskSchedulingPolicyProperty.Value = value; }
}
/// <summary>
/// Gets or sets the maximum number of tasks that can run concurrently on a single compute node in the pool.
/// </summary>
/// <remarks>
/// The default value is 1. The maximum value is the smaller of 4 times the number of cores of the <see cref="VirtualMachineSize"/>
/// of the pool or 256.
/// </remarks>
public int? TaskSlotsPerNode
{
get { return this.propertyContainer.TaskSlotsPerNodeProperty.Value; }
set { this.propertyContainer.TaskSlotsPerNodeProperty.Value = value; }
}
/// <summary>
/// Gets the URL of the pool.
/// </summary>
public string Url
{
get { return this.propertyContainer.UrlProperty.Value; }
}
/// <summary>
/// Gets or sets the list of user accounts to be created on each node in the pool.
/// </summary>
public IList<UserAccount> UserAccounts
{
get { return this.propertyContainer.UserAccountsProperty.Value; }
set
{
this.propertyContainer.UserAccountsProperty.Value = ConcurrentChangeTrackedModifiableList<UserAccount>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the <see cref="VirtualMachineConfiguration"/> of the pool.
/// </summary>
public VirtualMachineConfiguration VirtualMachineConfiguration
{
get { return this.propertyContainer.VirtualMachineConfigurationProperty.Value; }
set { this.propertyContainer.VirtualMachineConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets or sets the size of the virtual machines in the pool. All virtual machines in a pool are the same size.
/// </summary>
/// <remarks>
/// <para>For information about available sizes of virtual machines in pools, see Choose a VM size for compute nodes
/// in an Azure Batch pool (https://docs.microsoft.com/azure/batch/batch-pool-vm-sizes).</para>
/// </remarks>
public string VirtualMachineSize
{
get { return this.propertyContainer.VirtualMachineSizeProperty.Value; }
set { this.propertyContainer.VirtualMachineSizeProperty.Value = value; }
}
#endregion // CloudPool
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.PoolAddParameter ITransportObjectProvider<Models.PoolAddParameter>.GetTransportObject()
{
Models.PoolAddParameter result = new Models.PoolAddParameter()
{
ApplicationLicenses = this.ApplicationLicenses,
ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences),
EnableAutoScale = this.AutoScaleEnabled,
AutoScaleEvaluationInterval = this.AutoScaleEvaluationInterval,
AutoScaleFormula = this.AutoScaleFormula,
CertificateReferences = UtilitiesInternal.ConvertToProtocolCollection(this.CertificateReferences),
CloudServiceConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.CloudServiceConfiguration, (o) => o.GetTransportObject()),
DisplayName = this.DisplayName,
Id = this.Id,
EnableInterNodeCommunication = this.InterComputeNodeCommunicationEnabled,
Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata),
MountConfiguration = UtilitiesInternal.ConvertToProtocolCollection(this.MountConfiguration),
NetworkConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.NetworkConfiguration, (o) => o.GetTransportObject()),
ResizeTimeout = this.ResizeTimeout,
StartTask = UtilitiesInternal.CreateObjectWithNullCheck(this.StartTask, (o) => o.GetTransportObject()),
TargetDedicatedNodes = this.TargetDedicatedComputeNodes,
TargetLowPriorityNodes = this.TargetLowPriorityComputeNodes,
TaskSchedulingPolicy = UtilitiesInternal.CreateObjectWithNullCheck(this.TaskSchedulingPolicy, (o) => o.GetTransportObject()),
TaskSlotsPerNode = this.TaskSlotsPerNode,
UserAccounts = UtilitiesInternal.ConvertToProtocolCollection(this.UserAccounts),
VirtualMachineConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.VirtualMachineConfiguration, (o) => o.GetTransportObject()),
VmSize = this.VirtualMachineSize,
};
return result;
}
#endregion // Internal/private methods
}
}
| |
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class timelineMultiSelect : manipObject {
Material[] mats;
public timelineComponentInterface _interface;
BoxCollider coll;
Vector2 cornerA, cornerB;
Vector2 xRange, yRange;
public override void Awake() {
base.Awake();
createFrame();
mats = GetComponent<Renderer>().materials;
mats[0].SetColor("_TintColor", Color.white);
}
public void Activate() {
recalcRange();
if (selectedEvents.Count == 0) Close();
mats[0].SetColor("_TintColor", Color.blue);
coll = GetComponent<BoxCollider>();
coll.enabled = true;
}
public void Close() {
for (int i = 0; i < selectedEvents.Count; i++) {
if (selectedEvents[i] != null) {
selectedEvents[i].OnMultiselect(false);
}
}
Destroy(gameObject);
}
void recalcRange() {
cornerA = _interface.worldPosToGridPos(transform.TransformPoint(-.5f, -.5f, 0));
cornerB = _interface.worldPosToGridPos(transform.TransformPoint(.5f, .5f, 0));
xRange = new Vector2(_interface._gridParams.XtoUnit(cornerA.x), _interface._gridParams.XtoUnit(cornerB.x));
yRange = new Vector2(_interface._gridParams.YtoUnit(cornerA.y), _interface._gridParams.YtoUnit(cornerB.y));
if (xRange.x > xRange.y) xRange = new Vector2(xRange.y, xRange.x);
if (yRange.x > yRange.y) yRange = new Vector2(yRange.y, yRange.x);
}
List<timelineEvent> selectedEvents = new List<timelineEvent>();
public void SelectCheck() {
recalcRange();
selectedEvents.Clear();
for (int i = 0; i < _interface._tlEvents.Count; i++) {
if (_interface._tlEvents[i] != null) {
if (_interface._tlEvents[i].inMultiSelectRange(xRange, yRange)) {
selectedEvents.Add(_interface._tlEvents[i]);
_interface._tlEvents[i].OnMultiselect(true);
} else {
_interface._tlEvents[i].OnMultiselect(false);
}
}
}
}
Mesh mesh;
Vector3[] framepoints;
int[] framelines;
int[] frameQuad;
Renderer rend;
void createFrame() {
rend = GetComponent<Renderer>();
float w = 1;
float h = 1;
mesh = new Mesh();
mesh.subMeshCount = 2;
framepoints = new Vector3[]
{
new Vector3(-w/2f,-h/2,0),
new Vector3(-w/2f,h/2,0),
new Vector3(w/2f,h/2,0),
new Vector3(w/2f,-h/2,0)
};
framelines = new int[] { 0, 1, 1, 2, 2, 3, 3, 0 };
mesh.vertices = framepoints;
mesh.SetIndices(framelines, MeshTopology.Lines, 0);
frameQuad = new int[] { 0, 1, 2, 3 };
mesh.SetIndices(frameQuad, MeshTopology.Quads, 1);
GetComponent<MeshFilter>().mesh = mesh;
}
public void updateViz() {
float w = 1;
float h = 1;
float x1 = -w / 2f;
float x2 = w / 2f;
float y1 = -h / 2f;
float y2 = h / 2f;
Vector3 A = _interface.transform.InverseTransformPoint(transform.TransformPoint(-.5f, -.5f, 0));
Vector3 B = _interface.transform.InverseTransformPoint(transform.TransformPoint(.5f, .5f, 0));
bool a1 = false;
bool b1 = false;
a1 = A.y < 0;
b1 = B.y < 0;
if (a1 & b1) {
rend.enabled = false;
coll.enabled = false;
return;
} else if (a1) y1 = transform.InverseTransformPoint(_interface.transform.TransformPoint(Vector3.zero)).y;
else if (b1) y2 = transform.InverseTransformPoint(_interface.transform.TransformPoint(Vector3.zero)).y;
a1 = A.y > _interface._gridParams.getGridHeight();
b1 = B.y > _interface._gridParams.getGridHeight();
if (a1 & b1) {
rend.enabled = false;
coll.enabled = false;
return;
} else if (a1) y1 = transform.InverseTransformPoint(_interface.transform.TransformPoint(new Vector3(0, _interface._gridParams.getGridHeight(), 0))).y;
else if (b1) y2 = transform.InverseTransformPoint(_interface.transform.TransformPoint(new Vector3(0, _interface._gridParams.getGridHeight(), 0))).y;
a1 = A.x > 0;
b1 = B.x > 0;
if (a1 & b1) {
rend.enabled = false;
coll.enabled = false;
return;
} else if (a1) x1 = transform.InverseTransformPoint(_interface.transform.TransformPoint(Vector3.zero)).x;
else if (b1) x2 = transform.InverseTransformPoint(_interface.transform.TransformPoint(Vector3.zero)).x;
a1 = A.x < -_interface._gridParams.width;
b1 = B.x < -_interface._gridParams.width;
if (a1 & b1) {
rend.enabled = false;
coll.enabled = false;
return;
} else if (a1) x1 = transform.InverseTransformPoint(_interface.transform.TransformPoint(new Vector3(-_interface._gridParams.width, 0, 0))).x;
else if (b1) x2 = transform.InverseTransformPoint(_interface.transform.TransformPoint(new Vector3(-_interface._gridParams.width, 0, 0))).x;
framepoints[0] = new Vector3(x1, y1, 0);
framepoints[1] = new Vector3(x1, y2, 0);
framepoints[2] = new Vector3(x2, y2, 0);
framepoints[3] = new Vector3(x2, y1, 0);
rend.enabled = true;
coll.enabled = true;
mesh.vertices = framepoints;
}
public override void grabUpdate(Transform t) {
Vector2 a = _interface.worldPosToGridPos(t.position, false, false);
Vector2 dif = a - manipOffset;
dif.x *= -1;
if (_interface.notelock) dif.y = 0;
transform.localPosition = startPosition + dif;
Vector2 candidate;
dif.x /= _interface._gridParams.unitSize;
dif.y /= _interface._gridParams.trackHeight;
for (int i = 0; i < selectedEvents.Count; i++) {
if (selectedEvents[i] != null) {
// in_out
candidate = new Vector2(selectedEvents[i].multiselect_io.x + dif.x, selectedEvents[i].multiselect_io.y + dif.x);
if (_interface.snapping) {
float dist = candidate.y - candidate.x;
selectedEvents[i].in_out.x = _interface._gridParams.UnittoSnap(candidate.x, false);
selectedEvents[i].in_out.y = selectedEvents[i].in_out.x + dist;
} else selectedEvents[i].in_out = candidate;
// track
if (!_interface.notelock) {
int _t = Mathf.RoundToInt(selectedEvents[i].multiselect_track + dif.y);
if (_t < 0) _t = 0;
if (_t >= _interface._gridParams.tracks) _t = (int)_interface._gridParams.tracks - 1;
selectedEvents[i].track = _t;
selectedEvents[i].body.setHue(selectedEvents[i].track);
}
selectedEvents[i].gridUpdate();
}
}
updateViz();
}
Vector2 manipOffset;
Vector2 startPosition;
public override void setState(manipState state) {
if (curState == manipState.grabbed && state != manipState.grabbed) {
for (int i = 0; i < selectedEvents.Count; i++) {
if (selectedEvents[i] != null) {
selectedEvents[i].overlapCheck();
}
}
updateViz();
if (!rend.enabled) Close();
}
curState = state;
if (curState == manipState.none) {
mats[0].SetColor("_TintColor", Color.blue);
} else if (curState == manipState.selected) {
mats[0].SetColor("_TintColor", Color.white);
} else if (curState == manipState.grabbed) {
mats[0].SetColor("_TintColor", Color.red);
manipOffset = _interface.worldPosToGridPos(manipulatorObj.position, false, false);
startPosition = transform.localPosition;
for (int i = 0; i < selectedEvents.Count; i++) {
if (selectedEvents[i] != null) {
selectedEvents[i].multiselect_io = selectedEvents[i].in_out;
selectedEvents[i].multiselect_track = selectedEvents[i].track;
}
}
}
}
}
| |
/*
* Copyright (c) 2006-2014, openmetaverse.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.
* - Neither the name of the openmetaverse.org 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;
using System.Collections.Generic;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.Packets;
namespace OpenMetaverse.Utilities
{
/// <summary>
///
/// </summary>
public enum WaterType
{
/// <summary></summary>
Unknown,
/// <summary></summary>
Dry,
/// <summary></summary>
Waterfront,
/// <summary></summary>
Underwater
}
public static class Realism
{
/// <summary>
/// Aims at the specified position, enters mouselook, presses and
/// releases the left mouse button, and leaves mouselook
/// </summary>
/// <param name="client"></param>
/// <param name="target">Target to shoot at</param>
/// <returns></returns>
public static bool Shoot(GridClient client, Vector3 target)
{
if (client.Self.Movement.TurnToward(target))
return Shoot(client);
else
return false;
}
/// <summary>
/// Enters mouselook, presses and releases the left mouse button, and leaves mouselook
/// </summary>
/// <returns></returns>
public static bool Shoot(GridClient client)
{
if (client.Settings.SEND_AGENT_UPDATES)
{
client.Self.Movement.Mouselook = true;
client.Self.Movement.MLButtonDown = true;
client.Self.Movement.SendUpdate();
client.Self.Movement.MLButtonUp = true;
client.Self.Movement.MLButtonDown = false;
client.Self.Movement.FinishAnim = true;
client.Self.Movement.SendUpdate();
client.Self.Movement.Mouselook = false;
client.Self.Movement.MLButtonUp = false;
client.Self.Movement.FinishAnim = false;
client.Self.Movement.SendUpdate();
return true;
}
else
{
Logger.Log("Attempted Shoot but agent updates are disabled", Helpers.LogLevel.Warning, client);
return false;
}
}
/// <summary>
/// A psuedo-realistic chat function that uses the typing sound and
/// animation, types at three characters per second, and randomly
/// pauses. This function will block until the message has been sent
/// </summary>
/// <param name="client">A reference to the client that will chat</param>
/// <param name="message">The chat message to send</param>
public static void Chat(GridClient client, string message)
{
Chat(client, message, ChatType.Normal, 3);
}
/// <summary>
/// A psuedo-realistic chat function that uses the typing sound and
/// animation, types at a given rate, and randomly pauses. This
/// function will block until the message has been sent
/// </summary>
/// <param name="client">A reference to the client that will chat</param>
/// <param name="message">The chat message to send</param>
/// <param name="type">The chat type (usually Normal, Whisper or Shout)</param>
/// <param name="cps">Characters per second rate for chatting</param>
public static void Chat(GridClient client, string message, ChatType type, int cps)
{
Random rand = new Random();
int characters = 0;
bool typing = true;
// Start typing
client.Self.Chat(String.Empty, 0, ChatType.StartTyping);
client.Self.AnimationStart(Animations.TYPE, false);
while (characters < message.Length)
{
if (!typing)
{
// Start typing again
client.Self.Chat(String.Empty, 0, ChatType.StartTyping);
client.Self.AnimationStart(Animations.TYPE, false);
typing = true;
}
else
{
// Randomly pause typing
if (rand.Next(10) >= 9)
{
client.Self.Chat(String.Empty, 0, ChatType.StopTyping);
client.Self.AnimationStop(Animations.TYPE, false);
typing = false;
}
}
// Sleep for a second and increase the amount of characters we've typed
System.Threading.Thread.Sleep(1000);
characters += cps;
}
// Send the message
client.Self.Chat(message, 0, type);
// Stop typing
client.Self.Chat(String.Empty, 0, ChatType.StopTyping);
client.Self.AnimationStop(Animations.TYPE, false);
}
}
public class ConnectionManager
{
private GridClient Client;
private ulong SimHandle;
private Vector3 Position = Vector3.Zero;
private System.Timers.Timer CheckTimer;
public ConnectionManager(GridClient client, int timerFrequency)
{
Client = client;
CheckTimer = new System.Timers.Timer(timerFrequency);
CheckTimer.Elapsed += new System.Timers.ElapsedEventHandler(CheckTimer_Elapsed);
}
public static bool PersistentLogin(GridClient client, string firstName, string lastName, string password,
string userAgent, string start, string author)
{
int unknownLogins = 0;
Start:
if (client.Network.Login(firstName, lastName, password, userAgent, start, author))
{
Logger.Log("Logged in to " + client.Network.CurrentSim, Helpers.LogLevel.Info, client);
return true;
}
else
{
if (client.Network.LoginErrorKey == "god")
{
Logger.Log("Grid is down, waiting 10 minutes", Helpers.LogLevel.Warning, client);
LoginWait(10);
goto Start;
}
else if (client.Network.LoginErrorKey == "key")
{
Logger.Log("Bad username or password, giving up on login", Helpers.LogLevel.Error, client);
return false;
}
else if (client.Network.LoginErrorKey == "presence")
{
Logger.Log("Server is still logging us out, waiting 1 minute", Helpers.LogLevel.Warning, client);
LoginWait(1);
goto Start;
}
else if (client.Network.LoginErrorKey == "disabled")
{
Logger.Log("This account has been banned! Giving up on login", Helpers.LogLevel.Error, client);
return false;
}
else if (client.Network.LoginErrorKey == "timed out" ||client.Network.LoginErrorKey == "no connection" )
{
Logger.Log("Login request timed out, waiting 1 minute", Helpers.LogLevel.Warning, client);
LoginWait(1);
goto Start;
} else if (client.Network.LoginErrorKey == "bad response") {
Logger.Log("Login server returned unparsable result", Helpers.LogLevel.Warning, client);
LoginWait(1);
goto Start;
} else
{
++unknownLogins;
if (unknownLogins < 5)
{
Logger.Log("Unknown login error, waiting 2 minutes: " + client.Network.LoginErrorKey,
Helpers.LogLevel.Warning, client);
LoginWait(2);
goto Start;
}
else
{
Logger.Log("Too many unknown login error codes, giving up", Helpers.LogLevel.Error, client);
return false;
}
}
}
}
public void StayInSim(ulong handle, Vector3 desiredPosition)
{
SimHandle = handle;
Position = desiredPosition;
CheckTimer.Start();
}
private static void LoginWait(int minutes)
{
Thread.Sleep(1000 * 60 * minutes);
}
private void CheckTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (SimHandle != 0)
{
if (Client.Network.CurrentSim.Handle != 0 &&
Client.Network.CurrentSim.Handle != SimHandle)
{
// Attempt to move to our target sim
Client.Self.Teleport(SimHandle, Position);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using ZocMonLib;
namespace ZocMonLib
{
/// <summary>
/// Manages flushing out the newly collected record data.
/// This will end up flushing/saving the lowest reduce resolution.
/// </summary>
public class RecordFlush : IRecordFlush
{
private readonly ISystemLogger _logger;
private readonly ISetupBuckets _setupBuckets;
private readonly IDataCache _cache;
private readonly IStorageCommands _storageCommands;
private readonly IRecordFlushUpdate _flushUpdate;
private readonly IStorageFactory _dbFactory;
private readonly ISettings _settings;
public RecordFlush(ISetupBuckets setupBuckets, IDataCache cache, IStorageCommands storageCommands, IRecordFlushUpdate flushUpdate, IStorageFactory dbFactory, ISettings settings)
{
_logger = settings.LoggerProvider.CreateLogger(typeof(RecordFlush));
_setupBuckets = setupBuckets;
_cache = cache;
_storageCommands = storageCommands;
_flushUpdate = flushUpdate;
_dbFactory = dbFactory;
_settings = settings;
}
/// <summary>
/// Flush all data accumulated thus far.
/// </summary>
public void FlushAll()
{
try
{
_logger.Info("Flushing - All - Starting to flush all");
using (var conn = _dbFactory.CreateConnection())
{
conn.Open();
foreach (var configName in _cache.Containers.Keys)
Flush(configName, conn);
}
_logger.Info("Flushing - All - Finished flushing all");
}
catch (Exception e)
{
_logger.Fatal("Flushing - All - Exception occured and swallowed", e);
if (_settings.Debug)
throw;
}
}
/// <summary>
/// Flush data for the lowest reduce resolution for the given configuration.
/// (The rest is only written on Reduce.)
/// </summary>
/// <param name="configName"></param>
/// <param name="conn"></param>
public void Flush(string configName, IDbConnection conn = null)
{
try
{
configName = Support.ValidateBucketName(configName);
_logger.Info("Flushing - '{0}' - Starting to flush config", configName);
Container container;
if (!_cache.Containers.TryGetValue(configName, out container))
throw new ArgumentException(String.Format("Flushing - '{0}' - No updates for monitor", configName));
var tablesPreviouslyCreated = container.BucketCreated;
//If the info/config hasn't been created yet lets go off and create it
if (!tablesPreviouslyCreated)
{
_logger.Info("Flushing - '{0}' - Config record not previously created, now creating", configName);
if (_setupBuckets.CreateDefaultReduceLevels(container.Bucket, container.Bucket.ReduceLevels, conn))
container.BucketCreated = true;
}
_logger.Info("Flushing - '{0}' - Cloning records for flushing", configName);
var reduceLevel = GetFirstReduceLevel(configName);
var updateListClone = CloneRecordList(container.Records);
//Go through and link up reduceLevelId's
if (!tablesPreviouslyCreated)
{
//Attach records together
foreach (var monitorRecord in updateListClone)
monitorRecord.ReduceLevelId = reduceLevel.ReduceLevelId;
}
_logger.Info("Flushing - '{0}' - Total records that we need to flush '{1}'", configName, updateListClone.Count);
//If we have records to work with
if (updateListClone.Count > 0)
{
var sortedUpdateListClone = ConvertRecordToSortedDictionary(updateListClone);
var shouldClose = false;
if (conn == null)
{
conn = _dbFactory.CreateConnection();
conn.Open();
shouldClose = true;
}
try
{
// Get the isolation level (is there a better way?)
var transaction = conn.BeginTransaction();
var initialIsolationLevel = transaction.IsolationLevel;
transaction.Rollback();
// Now open the real transaction
transaction = conn.BeginTransaction(IsolationLevel.Serializable);
try
{
_logger.Info("Flushing - '{0}' - Updateing existing records", configName);
_flushUpdate.UpdateExisting(configName, sortedUpdateListClone, conn, transaction);
_logger.Info("Flushing - '{0}' - Insert new records", configName);
_storageCommands.InsertRecords(sortedUpdateListClone.Values, conn, transaction);
transaction.Commit();
}
catch (Exception e)
{
transaction.Rollback();
var msg = String.Format("Flushing - '{0}' - Failed to flush data for reduceLevel '{1}'", configName, reduceLevel.ReduceLevelId);
_logger.Fatal(msg, e);
throw new Exception(msg, e);
}
//reset the isolation level
transaction = conn.BeginTransaction(initialIsolationLevel);
transaction.Rollback();
}
catch (Exception e)
{
var msg = String.Format("Flushing - '{0}' - Failed to flush with '{1}'", configName, updateListClone.FormatAsString());
_logger.Fatal(msg, e);
if (_settings.Debug)
throw new DataException(msg, e);
}
finally
{
if (shouldClose)
conn.Close();
}
}
_logger.Info("Flushing - '{0}' - Finished flushing config", configName);
}
catch (Exception e)
{
_logger.Fatal(String.Format("Flushing - '{0}' - Exception occured and swallowed", configName), e);
if (_settings.Debug)
throw;
}
}
/// <summary>
/// The first reduce level is the table for the primary data.
/// </summary>
/// <param name="configName"></param>
/// <returns></returns>
private ReduceLevel GetFirstReduceLevel(string configName)
{
Bucket bucket;
if (!_cache.Buckets.TryGetValue(configName, out bucket))
throw new ArgumentException(string.Format("Flushing - '{0}' - Unknown monitor configuration", configName));
return bucket.ReduceLevels.First();
}
/// <summary>
/// Clone the update list before writting it to the DB, but leave the last element
/// (since it may be an incomplete accumulation).
/// </summary>
/// <param name="updateList"></param>
/// <returns></returns>
private IList<Record<double>> CloneRecordList(IList<Record<double>> updateList)
{
IList<Record<double>> updateListClone;
lock (updateList)
{
if (updateList.Count > 0)
{
//UpdateList is necessarily sorted, since the values are inserted in time order by the Record method
updateListClone = new List<Record<double>>(updateList);
updateList.Clear();
}
else
{
updateListClone = new List<Record<double>>();
}
}
return updateListClone;
}
private SortedDictionary<long, Record<double>> ConvertRecordToSortedDictionary(IEnumerable<Record<double>> updateList)
{
var sortedUpdateListClone = new SortedDictionary<long, Record<double>>();
foreach (var update in updateList)
sortedUpdateListClone.Add(update.TimeStamp.Ticks, update);
return sortedUpdateListClone;
}
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Diagnostics;
namespace TrueSync.Physics2D
{
public enum JointType
{
Unknown,
Revolute,
Prismatic,
Distance,
Pulley,
//Mouse, <- We have fixed mouse
Gear,
Wheel,
Weld,
Friction,
Rope,
Motor,
//FPE note: From here on and down, it is only FPE joints
Angle,
FixedMouse,
FixedRevolute,
FixedDistance,
FixedLine,
FixedPrismatic,
FixedAngle,
FixedFriction,
}
public enum LimitState
{
Inactive,
AtLower,
AtUpper,
Equal,
}
/// <summary>
/// A joint edge is used to connect bodies and joints together
/// in a joint graph where each body is a node and each joint
/// is an edge. A joint edge belongs to a doubly linked list
/// maintained in each attached body. Each joint has two joint
/// nodes, one for each attached body.
/// </summary>
public sealed class JointEdge
{
/// <summary>
/// The joint.
/// </summary>
public Joint2D Joint;
/// <summary>
/// The next joint edge in the body's joint list.
/// </summary>
public JointEdge Next;
/// <summary>
/// Provides quick access to the other body attached.
/// </summary>
public Body Other;
/// <summary>
/// The previous joint edge in the body's joint list.
/// </summary>
public JointEdge Prev;
}
public abstract class Joint2D
{
private FP _breakpoint;
private FP _breakpointSquared;
/// <summary>
/// Indicate if this join is enabled or not. Disabling a joint
/// means it is still in the simulation, but inactive.
/// </summary>
public bool Enabled = true;
internal JointEdge EdgeA = new JointEdge();
internal JointEdge EdgeB = new JointEdge();
internal bool IslandFlag;
protected Joint2D()
{
Breakpoint = FP.MaxValue;
//Connected bodies should not collide by default
CollideConnected = false;
}
protected Joint2D(Body bodyA, Body bodyB) : this()
{
//Can't connect a joint to the same body twice.
Debug.Assert(bodyA != bodyB);
BodyA = bodyA;
BodyB = bodyB;
}
/// <summary>
/// Constructor for fixed joint
/// </summary>
protected Joint2D(Body body) : this()
{
BodyA = body;
}
/// <summary>
/// Gets or sets the type of the joint.
/// </summary>
/// <value>The type of the joint.</value>
public JointType JointType { get; protected set; }
/// <summary>
/// Get the first body attached to this joint.
/// </summary>
public Body BodyA { get; internal set; }
/// <summary>
/// Get the second body attached to this joint.
/// </summary>
public Body BodyB { get; internal set; }
/// <summary>
/// Get the anchor point on bodyA in world coordinates.
/// On some joints, this value indicate the anchor point within the world.
/// </summary>
public abstract TSVector2 WorldAnchorA { get; set; }
/// <summary>
/// Get the anchor point on bodyB in world coordinates.
/// On some joints, this value indicate the anchor point within the world.
/// </summary>
public abstract TSVector2 WorldAnchorB { get; set; }
/// <summary>
/// Set the user data pointer.
/// </summary>
/// <value>The data.</value>
public object UserData { get; set; }
/// <summary>
/// Set this flag to true if the attached bodies should collide.
/// </summary>
public bool CollideConnected { get; set; }
/// <summary>
/// The Breakpoint simply indicates the maximum Value the JointError can be before it breaks.
/// The default value is FP.MaxValue, which means it never breaks.
/// </summary>
public FP Breakpoint
{
get { return _breakpoint; }
set
{
_breakpoint = value;
_breakpointSquared = _breakpoint * _breakpoint;
}
}
/// <summary>
/// Fires when the joint is broken.
/// </summary>
public event Action<Joint2D, FP> Broke;
/// <summary>
/// Get the reaction force on body at the joint anchor in Newtons.
/// </summary>
/// <param name="invDt">The inverse delta time.</param>
public abstract TSVector2 GetReactionForce(FP invDt);
/// <summary>
/// Get the reaction torque on the body at the joint anchor in N*m.
/// </summary>
/// <param name="invDt">The inverse delta time.</param>
public abstract FP GetReactionTorque(FP invDt);
protected void WakeBodies()
{
if (BodyA != null)
BodyA.Awake = true;
if (BodyB != null)
BodyB.Awake = true;
}
/// <summary>
/// Return true if the joint is a fixed type.
/// </summary>
public bool IsFixedType()
{
return JointType == JointType.FixedRevolute ||
JointType == JointType.FixedDistance ||
JointType == JointType.FixedPrismatic ||
JointType == JointType.FixedLine ||
JointType == JointType.FixedMouse ||
JointType == JointType.FixedAngle ||
JointType == JointType.FixedFriction;
}
internal abstract void InitVelocityConstraints(ref SolverData data);
internal void Validate(FP invDt)
{
if (!Enabled)
return;
FP jointErrorSquared = GetReactionForce(invDt).LengthSquared();
if (FP.Abs(jointErrorSquared) <= _breakpointSquared)
return;
Enabled = false;
if (Broke != null)
Broke(this, FP.Sqrt(jointErrorSquared));
}
internal abstract void SolveVelocityConstraints(ref SolverData data);
/// <summary>
/// Solves the position constraints.
/// </summary>
/// <param name="data"></param>
/// <returns>returns true if the position errors are within tolerance.</returns>
internal abstract bool SolvePositionConstraints(ref SolverData data);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Bridge.Test.NUnit;
namespace Bridge.ClientTest.Collections.Generic.Dictionary
{
public class Dictionary_Tests
{
[Test]
public void CopyConstructorExceptions()
{
Assert.Throws<ArgumentNullException>(() => new Dictionary<int, int>((IDictionary<int, int>)null));
Assert.Throws<ArgumentNullException>(() => new Dictionary<int, int>((IDictionary<int, int>)null, null));
Assert.Throws<ArgumentNullException>(() => new Dictionary<int, int>((IDictionary<int, int>)null, EqualityComparer<int>.Default));
Assert.Throws<ArgumentOutOfRangeException>(() => new Dictionary<int, int>(new NegativeCountDictionary<int, int>()));
Assert.Throws<ArgumentOutOfRangeException>(() => new Dictionary<int, int>(new NegativeCountDictionary<int, int>(), null));
Assert.Throws<ArgumentOutOfRangeException>(() => new Dictionary<int, int>(new NegativeCountDictionary<int, int>(), EqualityComparer<int>.Default));
}
[Test]
public void ICollection_NonGeneric_CopyTo_NonContiguousDictionary()
{
int[] data = new int[] { 0, 1, 101};
foreach (var count in data)
{
ICollection collection = (ICollection)CreateDictionary(count, k => k.ToString());
KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[count];
collection.CopyTo(array, 0);
int i = 0;
foreach (object obj in collection)
Assert.AreEqual(array[i++], obj);
}
}
[Test]
public void ICollection_Generic_CopyTo_NonContiguousDictionary()
{
int[] data = new int[] { 0, 1, 101 };
foreach (var count in data)
{
ICollection<KeyValuePair<string, string>> collection = CreateDictionary(count, k => k.ToString());
KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[count];
collection.CopyTo(array, 0);
int i = 0;
foreach (KeyValuePair<string, string> obj in collection)
Assert.AreEqual(array[i++], obj);
}
}
[Test]
public void IDictionary_Generic_CopyTo_NonContiguousDictionary()
{
int[] data = new int[] { 0, 1, 101 };
foreach (var count in data)
{
IDictionary<string, string> collection = CreateDictionary(count, k => k.ToString());
KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[count];
collection.CopyTo(array, 0);
int i = 0;
foreach (KeyValuePair<string, string> obj in collection)
Assert.AreEqual(array[i++], obj);
}
}
[Test]
public void CopyTo_NonContiguousDictionary()
{
int[] data = new int[] { 0, 1, 101 };
foreach (var count in data)
{
Dictionary<string, string> collection = (Dictionary<string, string>)CreateDictionary(count, k => k.ToString());
string[] array = new string[count];
collection.Keys.CopyTo(array, 0);
int i = 0;
foreach (KeyValuePair<string, string> obj in collection)
Assert.AreEqual(array[i++], obj.Key);
collection.Values.CopyTo(array, 0);
i = 0;
foreach (KeyValuePair<string, string> obj in collection)
Assert.AreEqual(array[i++], obj.Key);
}
}
[Test]
public void Remove_NonExistentEntries_DoesNotPreventEnumeration()
{
const string SubKey = "-sub-key";
var dictionary = new Dictionary<string, string>();
dictionary.Add("a", "b");
dictionary.Add("c", "d");
foreach (string key in dictionary.Keys)
{
if (dictionary.Remove(key + SubKey))
break;
}
dictionary.Add("c" + SubKey, "d");
foreach (string key in dictionary.Keys)
{
if (dictionary.Remove(key + SubKey))
break;
}
}
[Test]
public void TryAdd_ItemAlreadyExists_DoesNotInvalidateEnumerator()
{
var dictionary = new Dictionary<string, string>();
dictionary.Add("a", "b");
IEnumerator valuesEnum = dictionary.GetEnumerator();
Assert.False(dictionary.TryAdd("a", "c"));
Assert.True(valuesEnum.MoveNext());
}
[Test]
public void CopyConstructorInt32()
{
foreach (var item in CopyConstructorInt32Data)
{
int size = (int)item[0];
Func<int, int> keyValueSelector = (Func<int, int>)item[1];
Func<IDictionary<int, int>, IDictionary<int, int>> dictionarySelector = (Func<IDictionary<int, int>, IDictionary<int, int>>)item[2];
TestCopyConstructor(size, keyValueSelector, dictionarySelector);
}
}
public static IEnumerable<object[]> CopyConstructorInt32Data
{
get { return GetCopyConstructorData(i => i); }
}
[Test]
public void CopyConstructorString()
{
foreach (var item in CopyConstructorStringData)
{
int size = (int)item[0];
Func<int, string> keyValueSelector = (Func<int, string>)item[1];
Func<IDictionary<string, string>, IDictionary<string, string>> dictionarySelector = (Func<IDictionary<string, string>, IDictionary<string, string>>)item[2];
TestCopyConstructor(size, keyValueSelector, dictionarySelector);
}
}
public static IEnumerable<object[]> CopyConstructorStringData
{
get { return GetCopyConstructorData(i => i.ToString()); }
}
private static void TestCopyConstructor<T>(int size, Func<int, T> keyValueSelector, Func<IDictionary<T, T>, IDictionary<T, T>> dictionarySelector)
{
IDictionary<T, T> expected = CreateDictionary(size, keyValueSelector);
IDictionary<T, T> input = dictionarySelector(CreateDictionary(size, keyValueSelector));
Assert.AreEqual(expected, new Dictionary<T, T>(input));
}
[Test]
public void CopyConstructorInt32Comparer()
{
foreach (var item in CopyConstructorInt32ComparerData)
{
int size = (int)item[0];
Func<int, int> keyValueSelector = (Func<int, int>)item[1];
Func<IDictionary<int, int>, IDictionary<int, int>> dictionarySelector = (Func<IDictionary<int, int>, IDictionary<int, int>>)item[2];
IEqualityComparer<int> comparer = (IEqualityComparer<int>)item[3];
TestCopyConstructor(size, keyValueSelector, dictionarySelector, comparer);
}
}
public static IEnumerable<object[]> CopyConstructorInt32ComparerData
{
get
{
var comparers = new IEqualityComparer<int>[]
{
null,
EqualityComparer<int>.Default
};
return GetCopyConstructorData(i => i, comparers);
}
}
[Test]
public void CopyConstructorStringComparer()
{
foreach (var item in CopyConstructorStringComparerData)
{
int size = (int)item[0];
Func<int, string> keyValueSelector = (Func<int, string>)item[1];
Func<IDictionary<string, string>, IDictionary<string, string>> dictionarySelector = (Func<IDictionary<string, string>, IDictionary<string, string>>)item[2];
IEqualityComparer<string> comparer = (IEqualityComparer<string>)item[3];
TestCopyConstructor(size, keyValueSelector, dictionarySelector, comparer);
}
}
[Test]
public void CantAcceptDuplicateKeysFromSourceDictionary()
{
Dictionary<string, int> source = new Dictionary<string, int> { { "a", 1 }, { "A", 1 } };
Assert.Throws<ArgumentException>(() => new Dictionary<string, int>(source, StringComparer.OrdinalIgnoreCase));
}
public static IEnumerable<object[]> CopyConstructorStringComparerData
{
get
{
var comparers = new IEqualityComparer<string>[]
{
null,
EqualityComparer<string>.Default,
StringComparer.Ordinal,
StringComparer.OrdinalIgnoreCase
};
return GetCopyConstructorData(i => i.ToString(), comparers);
}
}
private static void TestCopyConstructor<T>(int size, Func<int, T> keyValueSelector, Func<IDictionary<T, T>, IDictionary<T, T>> dictionarySelector, IEqualityComparer<T> comparer)
{
IDictionary<T, T> expected = CreateDictionary(size, keyValueSelector, comparer);
IDictionary<T, T> input = dictionarySelector(CreateDictionary(size, keyValueSelector, comparer));
Assert.AreEqual(expected, new Dictionary<T, T>(input, comparer));
}
private static IEnumerable<object[]> GetCopyConstructorData<T>(Func<int, T> keyValueSelector, IEqualityComparer<T>[] comparers = null)
{
var dictionarySelectors = new Func<IDictionary<T, T>, IDictionary<T, T>>[]
{
d => d,
d => new DictionarySubclass<T, T>(d),
d => new ReadOnlyDictionary<T, T>(d)
};
var sizes = new int[] { 0, 1, 2, 3 };
foreach (Func<IDictionary<T, T>, IDictionary<T, T>> dictionarySelector in dictionarySelectors)
{
foreach (int size in sizes)
{
if (comparers != null)
{
foreach (IEqualityComparer<T> comparer in comparers)
{
yield return new object[] { size, keyValueSelector, dictionarySelector, comparer };
}
}
else
{
yield return new object[] { size, keyValueSelector, dictionarySelector };
}
}
}
}
private static IDictionary<T, T> CreateDictionary<T>(int size, Func<int, T> keyValueSelector, IEqualityComparer<T> comparer = null)
{
Dictionary<T, T> dict = Enumerable.Range(0, size + 1).ToDictionary(keyValueSelector, keyValueSelector, comparer);
// Remove first item to reduce Count to size and alter the contiguity of the dictionary
dict.Remove(keyValueSelector(0));
return dict;
}
private sealed class DictionarySubclass<TKey, TValue> : Dictionary<TKey, TValue>
{
public DictionarySubclass(IDictionary<TKey, TValue> dictionary)
{
foreach (var pair in dictionary)
{
Add(pair.Key, pair.Value);
}
}
}
/// <summary>
/// An incorrectly implemented dictionary that returns -1 from Count.
/// </summary>
private sealed class NegativeCountDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
public int Count { get { return -1; } }
public TValue this[TKey key] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } }
public bool IsReadOnly { get { throw new NotImplementedException(); } }
public ICollection<TKey> Keys { get { throw new NotImplementedException(); } }
public ICollection<TValue> Values { get { throw new NotImplementedException(); } }
public void Add(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); }
public void Add(TKey key, TValue value) { throw new NotImplementedException(); }
public void Clear() { throw new NotImplementedException(); }
public bool Contains(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); }
public bool ContainsKey(TKey key) { throw new NotImplementedException(); }
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { throw new NotImplementedException(); }
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { throw new NotImplementedException(); }
public bool Remove(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); }
public bool Remove(TKey key) { throw new NotImplementedException(); }
public bool TryGetValue(TKey key, out TValue value) { throw new NotImplementedException(); }
IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); }
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableSortedDictionaryBuilderTest : ImmutableDictionaryBuilderTestBase
{
[Fact]
public void CreateBuilder()
{
var builder = ImmutableSortedDictionary.CreateBuilder<string, string>();
Assert.NotNull(builder);
builder = ImmutableSortedDictionary.CreateBuilder<string, string>(StringComparer.Ordinal);
Assert.Same(StringComparer.Ordinal, builder.KeyComparer);
Assert.Same(EqualityComparer<string>.Default, builder.ValueComparer);
builder = ImmutableSortedDictionary.CreateBuilder<string, string>(StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.Ordinal, builder.KeyComparer);
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.ValueComparer);
}
[Fact]
public void ToBuilder()
{
var builder = ImmutableSortedDictionary<int, string>.Empty.ToBuilder();
builder.Add(3, "3");
builder.Add(5, "5");
Assert.Equal(2, builder.Count);
Assert.True(builder.ContainsKey(3));
Assert.True(builder.ContainsKey(5));
Assert.False(builder.ContainsKey(7));
var set = builder.ToImmutable();
Assert.Equal(builder.Count, set.Count);
builder.Add(8, "8");
Assert.Equal(3, builder.Count);
Assert.Equal(2, set.Count);
Assert.True(builder.ContainsKey(8));
Assert.False(set.ContainsKey(8));
}
[Fact]
public void BuilderFromMap()
{
var set = ImmutableSortedDictionary<int, string>.Empty.Add(1, "1");
var builder = set.ToBuilder();
Assert.True(builder.ContainsKey(1));
builder.Add(3, "3");
builder.Add(5, "5");
Assert.Equal(3, builder.Count);
Assert.True(builder.ContainsKey(3));
Assert.True(builder.ContainsKey(5));
Assert.False(builder.ContainsKey(7));
var set2 = builder.ToImmutable();
Assert.Equal(builder.Count, set2.Count);
Assert.True(set2.ContainsKey(1));
builder.Add(8, "8");
Assert.Equal(4, builder.Count);
Assert.Equal(3, set2.Count);
Assert.True(builder.ContainsKey(8));
Assert.False(set.ContainsKey(8));
Assert.False(set2.ContainsKey(8));
}
[Fact]
public void SeveralChanges()
{
var mutable = ImmutableSortedDictionary<int, string>.Empty.ToBuilder();
var immutable1 = mutable.ToImmutable();
Assert.Same(immutable1, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences.");
mutable.Add(1, "a");
var immutable2 = mutable.ToImmutable();
Assert.NotSame(immutable1, immutable2); //, "Mutating the collection did not reset the Immutable property.");
Assert.Same(immutable2, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences.");
Assert.Equal(1, immutable2.Count);
}
[Fact]
public void AddRange()
{
var builder = ImmutableSortedDictionary.Create<string, int>().ToBuilder();
builder.AddRange(new Dictionary<string, int> { { "a", 1 }, { "b", 2 } });
Assert.Equal(2, builder.Count);
Assert.Equal(1, builder["a"]);
Assert.Equal(2, builder["b"]);
}
[Fact]
public void RemoveRange()
{
var builder =
ImmutableSortedDictionary.Create<string, int>()
.AddRange(new Dictionary<string, int> { { "a", 1 }, { "b", 2 }, { "c", 3 } })
.ToBuilder();
Assert.Equal(3, builder.Count);
builder.RemoveRange(new[] { "a", "b" });
Assert.Equal(1, builder.Count);
Assert.Equal(3, builder["c"]);
}
[Fact]
public void EnumerateBuilderWhileMutating()
{
var builder = ImmutableSortedDictionary<int, string>.Empty
.AddRange(Enumerable.Range(1, 10).Select(n => new KeyValuePair<int, string>(n, null)))
.ToBuilder();
Assert.Equal(
Enumerable.Range(1, 10).Select(n => new KeyValuePair<int, string>(n, null)),
builder);
var enumerator = builder.GetEnumerator();
Assert.True(enumerator.MoveNext());
builder.Add(11, null);
// Verify that a new enumerator will succeed.
Assert.Equal(
Enumerable.Range(1, 11).Select(n => new KeyValuePair<int, string>(n, null)),
builder);
// Try enumerating further with the previous enumerable now that we've changed the collection.
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
enumerator.Reset();
enumerator.MoveNext(); // resetting should fix the problem.
// Verify that by obtaining a new enumerator, we can enumerate all the contents.
Assert.Equal(
Enumerable.Range(1, 11).Select(n => new KeyValuePair<int, string>(n, null)),
builder);
}
[Fact]
public void BuilderReusesUnchangedImmutableInstances()
{
var collection = ImmutableSortedDictionary<int, string>.Empty.Add(1, null);
var builder = collection.ToBuilder();
Assert.Same(collection, builder.ToImmutable()); // no changes at all.
builder.Add(2, null);
var newImmutable = builder.ToImmutable();
Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance.
Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance.
collection = collection.Clear(); // now start with an empty collection
builder = collection.ToBuilder();
Assert.Same(collection, builder.ToImmutable()); // again, no changes at all.
builder.ValueComparer = StringComparer.OrdinalIgnoreCase; // now, force the builder to clear its cache
newImmutable = builder.ToImmutable();
Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance.
Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance.
}
[Fact]
public void ContainsValue()
{
var map = ImmutableSortedDictionary.Create<string, int>().Add("five", 5);
var builder = map.ToBuilder();
Assert.True(builder.ContainsValue(5));
Assert.False(builder.ContainsValue(4));
}
[Fact]
public void Clear()
{
var builder = ImmutableSortedDictionary.Create<string, int>().ToBuilder();
builder.Add("five", 5);
Assert.Equal(1, builder.Count);
builder.Clear();
Assert.Equal(0, builder.Count);
}
[Fact]
public void KeyComparer()
{
var builder = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("B", "1").ToBuilder();
Assert.Same(Comparer<string>.Default, builder.KeyComparer);
Assert.True(builder.ContainsKey("a"));
Assert.False(builder.ContainsKey("A"));
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
Assert.Equal(2, builder.Count);
Assert.True(builder.ContainsKey("a"));
Assert.True(builder.ContainsKey("A"));
Assert.True(builder.ContainsKey("b"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
Assert.True(set.ContainsKey("a"));
Assert.True(set.ContainsKey("A"));
Assert.True(set.ContainsKey("b"));
}
[Fact]
public void KeyComparerCollisions()
{
// First check where collisions have matching values.
var builder = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "1").ToBuilder();
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Equal(1, builder.Count);
Assert.True(builder.ContainsKey("a"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
Assert.Equal(1, set.Count);
Assert.True(set.ContainsKey("a"));
// Now check where collisions have conflicting values.
builder = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "2").Add("b", "3").ToBuilder();
Assert.Throws<ArgumentException>(() => builder.KeyComparer = StringComparer.OrdinalIgnoreCase);
// Force all values to be considered equal.
builder.ValueComparer = EverythingEqual<string>.Default;
Assert.Same(EverythingEqual<string>.Default, builder.ValueComparer);
builder.KeyComparer = StringComparer.OrdinalIgnoreCase; // should not throw because values will be seen as equal.
Assert.Equal(2, builder.Count);
Assert.True(builder.ContainsKey("a"));
Assert.True(builder.ContainsKey("b"));
}
[Fact]
public void KeyComparerEmptyCollection()
{
var builder = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("B", "1").ToBuilder();
Assert.Same(Comparer<string>.Default, builder.KeyComparer);
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
}
[Fact]
public void GetValueOrDefaultOfConcreteType()
{
var empty = ImmutableSortedDictionary.Create<string, int>().ToBuilder();
var populated = ImmutableSortedDictionary.Create<string, int>().Add("a", 5).ToBuilder();
Assert.Equal(0, empty.GetValueOrDefault("a"));
Assert.Equal(1, empty.GetValueOrDefault("a", 1));
Assert.Equal(5, populated.GetValueOrDefault("a"));
Assert.Equal(5, populated.GetValueOrDefault("a", 1));
}
protected override IImmutableDictionary<TKey, TValue> GetEmptyImmutableDictionary<TKey, TValue>()
{
return ImmutableSortedDictionary.Create<TKey, TValue>();
}
protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer)
{
return ImmutableSortedDictionary.Create<string, TValue>(comparer);
}
protected override bool TryGetKeyHelper<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey equalKey, out TKey actualKey)
{
return ((ImmutableSortedDictionary<TKey, TValue>.Builder)dictionary).TryGetKey(equalKey, out actualKey);
}
protected override IDictionary<TKey, TValue> GetBuilder<TKey, TValue>(IImmutableDictionary<TKey, TValue> basis)
{
return ((ImmutableSortedDictionary<TKey, TValue>)(basis ?? GetEmptyImmutableDictionary<TKey, TValue>())).ToBuilder();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Xml;
using Umbraco.Core.IO;
namespace umbraco.editorControls.tinymce
{
public class tinyMCEConfiguration
{
private static bool _init = false;
private static Hashtable _commands = new Hashtable(StringComparer.InvariantCultureIgnoreCase);
private static string _validElements;
private static Hashtable _configOptions = new Hashtable(StringComparer.InvariantCultureIgnoreCase);
public static Hashtable ConfigOptions
{
get
{
if (!_init)
init();
return _configOptions;
}
set
{
_configOptions = value;
}
}
public static string ValidElements
{
get
{
if (!_init)
init();
return _validElements;
}
set { _validElements = value; }
}
public static string PluginPath = IOHelper.ResolveUrl( SystemDirectories.Umbraco ) + "/plugins/tinymce3";
public static string JavascriptPath = IOHelper.ResolveUrl( SystemDirectories.UmbracoClient ) + "/tinymce3";
private static string _invalidElements;
public static string InvalidElements
{
get
{
if (!_init)
init();
return _invalidElements;
}
set { _invalidElements = value; }
}
private static Hashtable _plugins = new Hashtable(StringComparer.InvariantCultureIgnoreCase);
public static Hashtable Plugins
{
get
{
if (!_init)
init();
return _plugins;
}
set { _plugins = value; }
}
public static Hashtable Commands
{
get
{
if (!_init)
init();
return _commands;
}
}
public static SortedList SortedCommands
{
get
{
if (!_init)
init();
SortedList sc = new SortedList();
IDictionaryEnumerator ide = _commands.GetEnumerator();
while (ide.MoveNext())
sc.Add(((tinyMCECommand)ide.Value).Priority, (tinyMCECommand)ide.Value);
return sc;
}
}
private static void init()
{
// Load config
XmlDocument xd = new XmlDocument();
xd.Load(IOHelper.MapPath( SystemFiles.TinyMceConfig ));
foreach (XmlNode n in xd.DocumentElement.SelectNodes("//command"))
{
if (!_commands.ContainsKey(n.SelectSingleNode("./umbracoAlias").FirstChild.Value))
{
bool isStyle = false;
if (n.Attributes.GetNamedItem("isStyle") != null)
isStyle = bool.Parse(n.Attributes.GetNamedItem("isStyle").Value);
_commands.Add(
n.SelectSingleNode("./umbracoAlias").FirstChild.Value.ToLower(),
new tinyMCECommand(
isStyle,
n.SelectSingleNode("./icon").FirstChild.Value,
n.SelectSingleNode("./tinyMceCommand").FirstChild.Value,
n.SelectSingleNode("./umbracoAlias").FirstChild.Value.ToLower(),
n.SelectSingleNode("./tinyMceCommand").Attributes.GetNamedItem("userInterface").Value,
n.SelectSingleNode("./tinyMceCommand").Attributes.GetNamedItem("frontendCommand").Value,
n.SelectSingleNode("./tinyMceCommand").Attributes.GetNamedItem("value").Value,
int.Parse(n.SelectSingleNode("./priority").FirstChild.Value)
));
}
}
foreach (XmlNode n in xd.DocumentElement.SelectNodes("//plugin"))
{
if (!_plugins.ContainsKey(n.FirstChild.Value))
{
bool useOnFrontend = false;
if (n.Attributes.GetNamedItem("loadOnFrontend") != null)
useOnFrontend = bool.Parse(n.Attributes.GetNamedItem("loadOnFrontend").Value);
_plugins.Add(
n.FirstChild.Value.ToLower(),
new tinyMCEPlugin(
n.FirstChild.Value,
useOnFrontend));
}
}
foreach (XmlNode n in xd.DocumentElement.SelectNodes("//config"))
{
if (!_configOptions.ContainsKey(n.Attributes["key"].FirstChild.Value))
{
var value = "";
if (n.FirstChild != null)
value = n.FirstChild.Value;
_configOptions.Add(
n.Attributes["key"].FirstChild.Value.ToLower(),
value);
}
}
if (xd.DocumentElement.SelectSingleNode("./invalidElements") != null)
_invalidElements = xd.DocumentElement.SelectSingleNode("./invalidElements").FirstChild.Value;
if (xd.DocumentElement.SelectSingleNode("./validElements") != null)
{
string _val = xd.DocumentElement.SelectSingleNode("./validElements").FirstChild.Value.Replace("\r", "");
foreach (string s in _val.Split("\n".ToCharArray()))
_validElements += "'" + s + "' + \n";
_validElements = _validElements.Substring(0, _validElements.Length - 4);
}
_init = true;
}
}
public class tinyMCEPlugin
{
public tinyMCEPlugin(string Name, bool UseOnFrontEnd)
{
_name = Name;
_useOnFrontend = UseOnFrontEnd;
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private bool _useOnFrontend;
public bool UseOnFrontend
{
get { return _useOnFrontend; }
set { _useOnFrontend = value; }
}
}
public class tinyMCECommand
{
public tinyMCECommand(bool isStylePicker, string Icon, string Command, string Alias, string UserInterface, string FrontEndCommand, string Value, int Priority)
{
_isStylePicker = isStylePicker;
_icon = Icon;
_command = Command;
_alias = Alias;
_userInterface = UserInterface;
_frontEndCommand = FrontEndCommand;
_value = Value;
_priority = Priority;
}
private bool _isStylePicker;
public bool IsStylePicker
{
get { return _isStylePicker; }
set { _isStylePicker = value; }
}
private string _icon;
public string Icon
{
get { return IOHelper.ResolveUrl( SystemDirectories.Umbraco ) + "/" + _icon; }
set { _icon = value; }
}
private string _command;
public string Command
{
get { return _command; }
set { _command = value; }
}
private string _alias;
public string Alias
{
get { return _alias; }
set { _alias = value; }
}
private string _userInterface;
public string UserInterface
{
get { return _userInterface; }
set { _userInterface = value; }
}
private string _frontEndCommand;
public string FrontEndCommand
{
get { return _frontEndCommand; }
set { _frontEndCommand = value; }
}
private string _value;
public string Value
{
get { return _value; }
set { _value = value; }
}
private int _priority;
public int Priority
{
get { return _priority; }
set { _priority = value; }
}
}
}
| |
using System;
using System.Net;
using System.Net.Mail;
using System.Security.Principal;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using AnglicanGeek.MarkdownMailer;
using Elmah;
using Microsoft.WindowsAzure.ServiceRuntime;
using Ninject;
using Ninject.Modules;
using NuGetGallery.Configuration;
using NuGetGallery.Infrastructure;
namespace NuGetGallery
{
public class ContainerBindings : NinjectModule
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:CyclomaticComplexity", Justification = "This code is more maintainable in the same function.")]
public override void Load()
{
var configuration = new ConfigurationService();
Bind<ConfigurationService>()
.ToMethod(context => configuration);
Bind<IAppConfiguration>()
.ToMethod(context => configuration.Current);
Bind<PoliteCaptcha.IConfigurationSource>()
.ToMethod(context => configuration);
Bind<Lucene.Net.Store.Directory>()
.ToMethod(_ => LuceneCommon.GetDirectory(configuration.Current.LuceneIndexLocation))
.InSingletonScope();
Bind<ISearchService>()
.To<LuceneSearchService>()
.InRequestScope();
if (!String.IsNullOrEmpty(configuration.Current.AzureStorageConnectionString))
{
Bind<ErrorLog>()
.ToMethod(_ => new TableErrorLog(configuration.Current.AzureStorageConnectionString))
.InSingletonScope();
}
else
{
Bind<ErrorLog>()
.ToMethod(_ => new SqlErrorLog(configuration.Current.SqlConnectionString))
.InSingletonScope();
}
Bind<ICacheService>()
.To<HttpContextCacheService>()
.InRequestScope();
Bind<IContentService>()
.To<ContentService>()
.InSingletonScope();
Bind<IEntitiesContext>()
.ToMethod(context => new EntitiesContext(configuration.Current.SqlConnectionString, readOnly: configuration.Current.ReadOnlyMode))
.InRequestScope();
Bind<IEntityRepository<User>>()
.To<EntityRepository<User>>()
.InRequestScope();
Bind<IEntityRepository<CuratedFeed>>()
.To<EntityRepository<CuratedFeed>>()
.InRequestScope();
Bind<IEntityRepository<CuratedPackage>>()
.To<EntityRepository<CuratedPackage>>()
.InRequestScope();
Bind<IEntityRepository<PackageRegistration>>()
.To<EntityRepository<PackageRegistration>>()
.InRequestScope();
Bind<IEntityRepository<Package>>()
.To<EntityRepository<Package>>()
.InRequestScope();
Bind<IEntityRepository<PackageDependency>>()
.To<EntityRepository<PackageDependency>>()
.InRequestScope();
Bind<IEntityRepository<PackageStatistics>>()
.To<EntityRepository<PackageStatistics>>()
.InRequestScope();
Bind<ICuratedFeedService>()
.To<CuratedFeedService>()
.InRequestScope();
Bind<IUserService>()
.To<UserService>()
.InRequestScope();
Bind<IPackageService>()
.To<PackageService>()
.InRequestScope();
Bind<EditPackageService>().ToSelf();
Bind<IFormsAuthenticationService>()
.To<FormsAuthenticationService>()
.InSingletonScope();
Bind<IControllerFactory>()
.To<NuGetControllerFactory>()
.InRequestScope();
Bind<IIndexingService>()
.To<LuceneIndexingService>()
.InRequestScope();
Bind<INuGetExeDownloaderService>()
.To<NuGetExeDownloaderService>()
.InRequestScope();
var mailSenderThunk = new Lazy<IMailSender>(
() =>
{
var settings = Kernel.Get<ConfigurationService>();
if (settings.Current.SmtpUri != null)
{
var smtpUri = new SmtpUri(settings.Current.SmtpUri);
var mailSenderConfiguration = new MailSenderConfiguration
{
DeliveryMethod = SmtpDeliveryMethod.Network,
Host = smtpUri.Host,
Port = smtpUri.Port,
EnableSsl = smtpUri.Secure
};
if (!String.IsNullOrWhiteSpace(smtpUri.UserName))
{
mailSenderConfiguration.UseDefaultCredentials = false;
mailSenderConfiguration.Credentials = new NetworkCredential(
smtpUri.UserName,
smtpUri.Password);
}
return new MailSender(mailSenderConfiguration);
}
else
{
var mailSenderConfiguration = new MailSenderConfiguration
{
DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory,
PickupDirectoryLocation = HostingEnvironment.MapPath("~/App_Data/Mail")
};
return new MailSender(mailSenderConfiguration);
}
});
Bind<IMailSender>()
.ToMethod(context => mailSenderThunk.Value);
Bind<IMessageService>()
.To<MessageService>();
Bind<IPrincipal>().ToMethod(context => HttpContext.Current.User);
switch (configuration.Current.StorageType)
{
case StorageType.FileSystem:
case StorageType.NotSpecified:
ConfigureForLocalFileSystem();
break;
case StorageType.AzureStorage:
ConfigureForAzureStorage(configuration);
break;
}
Bind<IFileSystemService>()
.To<FileSystemService>()
.InSingletonScope();
Bind<IPackageFileService>()
.To<PackageFileService>();
Bind<IEntityRepository<PackageOwnerRequest>>()
.To<EntityRepository<PackageOwnerRequest>>()
.InRequestScope();
Bind<IUploadFileService>()
.To<UploadFileService>();
// todo: bind all package curators by convention
Bind<IAutomaticPackageCurator>()
.To<WebMatrixPackageCurator>();
Bind<IAutomaticPackageCurator>()
.To<Windows8PackageCurator>();
// todo: bind all commands by convention
Bind<IAutomaticallyCuratePackageCommand>()
.To<AutomaticallyCuratePackageCommand>()
.InRequestScope();
Bind<IAggregateStatsService>()
.To<AggregateStatsService>()
.InRequestScope();
Bind<IPackageIdsQuery>()
.To<PackageIdsQuery>()
.InRequestScope();
Bind<IPackageVersionsQuery>()
.To<PackageVersionsQuery>()
.InRequestScope();
}
private void ConfigureForLocalFileSystem()
{
Bind<IFileStorageService>()
.To<FileSystemFileStorageService>()
.InSingletonScope();
}
private void ConfigureForAzureStorage(ConfigurationService configuration)
{
Bind<ICloudBlobClient>()
.ToMethod(
_ => new CloudBlobClientWrapper(configuration.Current.AzureStorageConnectionString))
.InSingletonScope();
Bind<IFileStorageService>()
.To<CloudBlobFileStorageService>()
.InSingletonScope();
// when running on Windows Azure, pull the statistics from the warehouse via storage
Bind<IReportService>()
.ToMethod(context => new CloudReportService(configuration.Current.AzureStorageConnectionString))
.InSingletonScope();
Bind<IStatisticsService>()
.To<JsonStatisticsService>()
.InSingletonScope();
}
}
}
| |
using System;
using System.ComponentModel;
using System.Windows.Forms;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Xinq
{
internal partial class XinqEditor : UserControl
{
private XinqPackage _package;
private XinqEditorPane _editorPane;
private uint _updateLevel;
public XinqDocument Document
{
get;
set;
}
public XinqEditor()
{
InitializeComponent();
tsRemoveQuery.Enabled = false;
txtQuery.Enabled = false;
}
public XinqEditor(XinqPackage package, XinqEditorPane editorPane) : this()
{
_package = package;
_editorPane = editorPane;
}
public void LoadDocument()
{
_updateLevel++;
dgQueries.Rows.Clear();
foreach (var query in Document.Queries)
{
var row = new DataGridViewQueryRow(dgQueries, query);
dgQueries.Rows.Add(row);
}
_updateLevel--;
}
public void ClearUndoStack()
{
txtQuery.ClearUndo();
}
public bool CanSelectAll()
{
var activeControl = SplitContainer.ActiveControl;
if (activeControl is TextBoxBase)
return true;
return false;
}
public bool CanCut()
{
var activeControl = SplitContainer.ActiveControl;
if (activeControl is DataGridView)
{
var currentGridView = (DataGridView)activeControl;
var currentCell = currentGridView.CurrentCell;
var currentColumn = currentCell.OwningColumn;
if (!string.IsNullOrEmpty((string)currentCell.Value))
if (currentColumn == dgcComment)
return true;
}
if (activeControl is TextBoxBase)
if (((TextBoxBase)activeControl).SelectionLength > 0)
return true;
return false;
}
public bool CanCopy()
{
var activeControl = SplitContainer.ActiveControl;
if (activeControl is DataGridView)
{
var currentGridView = (DataGridView)activeControl;
var currentCell = currentGridView.CurrentCell;
if (!string.IsNullOrEmpty((string)currentCell.Value))
return true;
}
if (activeControl is TextBoxBase)
if (((TextBoxBase)activeControl).SelectionLength > 0)
return true;
return false;
}
public bool CanPaste()
{
var activeControl = SplitContainer.ActiveControl;
if (activeControl is DataGridView)
return true;
if (activeControl is TextBoxBase)
if (Clipboard.ContainsText())
return true;
return false;
}
public void OnSelectAll()
{
var activeControl = SplitContainer.ActiveControl;
if (activeControl is TextBoxBase)
{
((TextBoxBase)activeControl).SelectAll();
return;
}
throw new NotImplementedException();
}
public void OnCut()
{
var activeControl = SplitContainer.ActiveControl;
if (activeControl is DataGridView)
{
var currentGridView = (DataGridView)activeControl;
var currentCell = currentGridView.CurrentCell;
Clipboard.SetText((string)currentCell.Value);
currentCell.Value = null;
return;
}
if (activeControl is TextBoxBase)
{
((TextBoxBase)activeControl).Cut();
return;
}
throw new NotImplementedException();
}
public void OnCopy()
{
var activeControl = SplitContainer.ActiveControl;
if (activeControl is DataGridView)
{
var currentGridView = (DataGridView)activeControl;
var currentCell = currentGridView.CurrentCell;
Clipboard.SetText((string)currentCell.Value);
return;
}
if (activeControl is TextBoxBase)
{
((TextBoxBase)activeControl).Copy();
return;
}
throw new NotImplementedException();
}
public void OnPaste()
{
var activeControl = SplitContainer.ActiveControl;
if (activeControl is DataGridView)
{
var currentGridView = (DataGridView)activeControl;
var currentCell = currentGridView.CurrentCell;
var currentColumn = currentCell.OwningColumn;
var text = Clipboard.GetText();
if (currentColumn == dgcName)
{
if (Document.Queries[text] != null)
{
MessageBox.Show(_package.GetResourceString(121), _package.GetResourceString(110), MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
currentCell.Value = text;
dgQueries_CellEndEdit(null, new DataGridViewCellEventArgs(currentCell.ColumnIndex, currentCell.RowIndex));
return;
}
if (activeControl is TextBoxBase)
{
((TextBoxBase)activeControl).Paste();
return;
}
throw new NotImplementedException();
}
public void CommitPendingEdit()
{
var activeControl = SplitContainer.ActiveControl;
if (activeControl is IDataGridViewEditingControl)
{
var currentGridView = ((IDataGridViewEditingControl)activeControl).EditingControlDataGridView;
var currentCell = currentGridView.CurrentCell;
var currentColumn = currentCell.OwningColumn;
var currentRow = (DataGridViewQueryRow)currentCell.OwningRow;
if (currentCell.IsInEditMode)
{
if (currentColumn == dgcName)
{
var name = (activeControl).Text;
if (name.Trim().Length == 0)
{
currentGridView.CancelEdit();
}
else
{
var existingQuery = Document.Queries[name];
if (existingQuery != null && existingQuery != currentRow.Query)
currentGridView.CancelEdit();
}
}
else
{
currentGridView.EndEdit();
}
}
}
}
private void tsAddQuery_Click(object sender, EventArgs e)
{
if (!_editorPane.CanEdit())
return;
var newQuery = new Query(Document);
var nameSuffix = 1;
while (true)
{
var name = string.Format("MyQuery{0}", nameSuffix++);
if (Document.Queries[name] == null)
{
newQuery.Name = name;
break;
}
}
Document.Queries.Add(newQuery);
var newRow = new DataGridViewQueryRow(dgQueries, newQuery);
dgQueries.Rows.Add(newRow);
newRow.Selected = true;
dgQueries.CurrentCell = newRow.Cells[0];
dgQueries.BeginEdit(true);
}
private void tsRemoveQuery_Click(object sender, EventArgs e)
{
if (_updateLevel > 0)
return;
if (MessageBox.Show(_package.GetResourceString(122), _package.GetResourceString(110), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
return;
if (!_editorPane.CanEdit())
return;
dgQueries.Rows.Remove(dgQueries.CurrentRow);
}
private void dgQueries_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if (!_editorPane.CanEdit())
e.Cancel = true;
}
private void dgQueries_SelectionChanged(object sender, EventArgs e)
{
_updateLevel++;
if (dgQueries.SelectedRows.Count > 0)
{
var row = (DataGridViewQueryRow)dgQueries.SelectedRows[0];
txtQuery.Text = row.Query.Text;
txtQuery.Enabled = true;
}
else
{
txtQuery.Clear();
txtQuery.Enabled = false;
}
_updateLevel--;
}
private void dgQueries_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
var row = (DataGridViewQueryRow)dgQueries.Rows[e.RowIndex];
var column = dgQueries.Columns[e.ColumnIndex];
var cell = row.Cells[e.ColumnIndex];
if (row.IsNewRow)
return;
if (!cell.IsInEditMode)
return;
if (column == dgcName)
{
var name = (string)e.FormattedValue;
if (name.Trim().Length == 0)
{
MessageBox.Show(_package.GetResourceString(120), _package.GetResourceString(110), MessageBoxButtons.OK, MessageBoxIcon.Error);
e.Cancel = true;
}
else
{
var existingQuery = Document.Queries[name];
if (existingQuery != null && existingQuery != row.Query)
{
MessageBox.Show(_package.GetResourceString(121), _package.GetResourceString(110), MessageBoxButtons.OK, MessageBoxIcon.Error);
e.Cancel = true;
}
}
}
}
private void dgQueries_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (_updateLevel > 0)
return;
var row = (DataGridViewQueryRow)dgQueries.Rows[e.RowIndex];
var column = dgQueries.Columns[e.ColumnIndex];
var cell = row.Cells[e.ColumnIndex];
var text = ((string)cell.Value).Trim();
cell.Value = text;
if (column == dgcName)
{
row.Query.Name = text;
return;
}
if (column == dgcComment)
{
row.Query.Comment = text;
return;
}
}
private void dgQueries_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
if (MessageBox.Show(_package.GetResourceString(122), _package.GetResourceString(110), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
return;
}
if (!_editorPane.CanEdit())
{
e.Cancel = true;
return;
}
}
private void dgQueries_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
tsRemoveQuery.Enabled = dgQueries.Rows.Count > 0;
}
private void dgQueries_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
if (_updateLevel > 0)
return;
Document.Queries.RemoveAt(e.RowIndex);
tsRemoveQuery.Enabled = dgQueries.Rows.Count > 0;
}
private void txtQuery_TextChanging(object sender, CancelEventArgs e)
{
e.Cancel = (!_editorPane.CanEdit());
}
private void txtQuery_TextChanged(object sender, EventArgs e)
{
if (_updateLevel > 0)
return;
var row = (DataGridViewQueryRow)dgQueries.CurrentRow;
row.Query.Text = txtQuery.Text;
}
}
internal class DataGridViewQueryRow : DataGridViewRow
{
private Query _query;
public Query Query
{
get
{
return _query;
}
}
public DataGridViewQueryRow(DataGridView dataGridView, Query query)
{
CreateCells(dataGridView, query.Name, query.Comment);
_query = query;
}
}
}
| |
/*
Copyright (c) 2012, Dan Clarke
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 Dan Clarke nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Net;
#if !MONOMAC
using MonoTouch.Foundation;
using MonoTouch.SystemConfiguration;
using MonoTouch.CoreFoundation;
#else
using MonoMac.Foundation;
using MonoMac.CoreFoundation;
#endif
namespace Reachability
{
/// <summary>
/// Class for checking network reachability via WiFi / WWAN (Cellular)
/// </summary>
public class Reachability : IDisposable
{
// iOS apps are most likely to have a WWAN interface, MonoMac apps, probably not
#if !MONOMAC
protected const bool DefaultHasWWAN = true;
#else
protected const bool DefaultHasWWAN = false;
#endif
/// <summary>
/// Hardcoded copy of IN_LINKLOCALNETNUM in <netinet/in.h>
/// </summary>
protected static readonly byte[] LocalNetNum = { 169, 254, 0, 0};
/// <summary>
/// The NetworkReachability instance to work on
/// </summary>
/// <value>
/// The network reachability.
/// </value>
protected NetworkReachability NetworkReachability { get; set; }
/// <summary>
/// Whether the platform has WWAN
/// </summary>
protected bool HasWWAN { get; set; }
/// <summary>
/// The reachability status has changed
/// </summary>
public event EventHandler<ReachabilityEventArgs> ReachabilityUpdated;
/// <summary>
/// Set whether WWAN counts as 'connected'. Default is True.
/// </summary>
public bool AllowWWAN { get; set; }
private bool _disposed;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Reachability.Reachability"/> class.
/// </summary>
/// <param name='reachability'>
/// NetworkReachability instance to use
/// </param>
/// <param name='hasWWAN'>
/// Platform has a WWAN interface
/// </param>
protected Reachability(NetworkReachability reachability, bool hasWWAN)
{
NetworkReachability = reachability;
HasWWAN = hasWWAN;
AllowWWAN = true;
NetworkReachability.SetCallback(OnReachabilityNotification);
NetworkReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);
}
/// <summary>
/// Initializes a new instance of the <see cref="Reachability.Reachability"/> class.
/// </summary>
/// <param name='hostname'>
/// Target hostname
/// </param>
/// <param name='hasWWAN'>
/// Set whether the platform has a WWAN interface
/// </param>
public Reachability(string hostname, bool hasWWAN = DefaultHasWWAN)
: this(new NetworkReachability(hostname), hasWWAN) {}
/// <summary>
/// Initializes a new instance of the <see cref="Reachability.Reachability"/> class.
/// </summary>
/// <param name='address'>
/// Target IP address
/// </param>
/// <param name='hasWWAN'>
/// Set whether the platform has a WWAN interface
/// </param>
public Reachability(IPAddress address, bool hasWWAN = DefaultHasWWAN)
: this(new NetworkReachability(address), hasWWAN) {}
/// <summary>
/// Get a new <see cref="Reachability.Reachability"/> instance that checks for general Internet access
/// </summary>
/// <returns>
/// <see cref="Reachability.Reachability"/> instance
/// </returns>
/// <param name='hasWWAN'>
/// Set whether the platform has a WWAN interface
/// </param>
public static Reachability ReachabilityForInternet(bool hasWWAN = DefaultHasWWAN)
{
return new Reachability(new IPAddress(0), hasWWAN);
}
/// <summary>
/// Get a new <see cref="Reachability.Reachability"/> instance that checks for local network access via WiFi
/// </summary>
/// <returns>
/// <see cref="Reachability.Reachability"/> instance
/// </returns>
/// <param name='hasWWAN'>
/// Set whether the platform has a WWAN interface
/// </param>
public static Reachability ReachabilityForLocalWiFi(bool hasWWAN = DefaultHasWWAN)
{
return new Reachability(new IPAddress(LocalNetNum), hasWWAN);
}
#endregion
#region Flag util
/// <summary>
/// Get whether the requested resource is reachable with the specified flags
/// </summary>
/// <returns>
/// <c>true</c> if the requested resource is reachable with the specified flags; otherwise, <c>false</c>.
/// </returns>
/// <param name='flags'>
/// Reachability flags.
/// </param>
/// <remarks>
/// This is for the case where you flick the airplane mode you end up getting something like this:
/// Reachability: WR ct-----
/// Reachability: -- -------
/// Reachability: WR ct-----
/// Reachability: -- -------
/// We treat this as 4 UNREACHABLE triggers - really Apple should do better than this
/// </remarks>
private bool IsReachableWithFlags(NetworkReachabilityFlags flags)
{
if (!flags.HasFlag(NetworkReachabilityFlags.Reachable))
return false;
var testCase = NetworkReachabilityFlags.ConnectionRequired | NetworkReachabilityFlags.TransientConnection;
if ((flags & testCase) == testCase)
return false;
if (HasWWAN)
{
// If we're connecting via WWAN, and WWAN doesn't count as connected, return false
if (flags.HasFlag(NetworkReachabilityFlags.IsWWAN) && !AllowWWAN)
return false;
}
return true;
}
private bool ReachableViaWWAN(NetworkReachabilityFlags flags)
{
if (!HasWWAN)
return false;
return (flags.HasFlag(NetworkReachabilityFlags.Reachable) && flags.HasFlag(NetworkReachabilityFlags.IsWWAN));
}
private bool ReachableViaWiFi(NetworkReachabilityFlags flags)
{
if (!flags.HasFlag(NetworkReachabilityFlags.Reachable))
return false;
// If we don't have WWAN, reachable = WiFi (close enough)
if (!HasWWAN)
return true;
// We have WWAN, if we're connecting through WWAN, we're not connecting through WiFi
if (flags.HasFlag(NetworkReachabilityFlags.IsWWAN))
return false;
else
return true; // Connecting through WiFi, not WWAN
}
/// <summary>
/// Utility method that gets the flags as a string
/// </summary>
/// <returns>
/// The flags as string
/// </returns>
/// <param name='flags'>
/// Flags
/// </param>
protected string GetFlagsAsString(NetworkReachabilityFlags flags)
{
return string.Concat(
!HasWWAN ? "X" : flags.HasFlag(NetworkReachabilityFlags.IsWWAN) ? "W" : "-",
flags.HasFlag(NetworkReachabilityFlags.Reachable) ? "R" : "-",
" ",
flags.HasFlag(NetworkReachabilityFlags.ConnectionRequired) ? "c" : "-",
flags.HasFlag(NetworkReachabilityFlags.TransientConnection) ? "t" : "-",
flags.HasFlag(NetworkReachabilityFlags.InterventionRequired) ? "i" : "-",
flags.HasFlag(NetworkReachabilityFlags.ConnectionOnTraffic) ? "C" : "-",
flags.HasFlag(NetworkReachabilityFlags.ConnectionOnDemand) ? "D" : "-",
flags.HasFlag(NetworkReachabilityFlags.IsLocalAddress) ? "l" : "-",
flags.HasFlag(NetworkReachabilityFlags.IsDirect) ? "d" : "-"
);
}
#endregion
/// <summary>
/// Get the current status as an English string
/// </summary>
/// <returns>
/// The status string
/// </returns>
public virtual string GetReachabilityString()
{
switch (CurrentStatus)
{
case ReachabilityStatus.ViaWWAN:
return "Cellular";
case ReachabilityStatus.ViaWiFi:
return "WiFi";
default:
return "No Connection";
}
}
#region Notifications
protected virtual void OnReachabilityNotification(NetworkReachabilityFlags flags)
{
if (ReachabilityUpdated == null)
return;
ReachabilityStatus status = ReachabilityStatus.NotReachable;
if (!IsReachableWithFlags(flags))
status = ReachabilityStatus.NotReachable;
else if (ReachableViaWWAN(flags))
status = ReachabilityStatus.ViaWWAN;
else if (ReachableViaWiFi(flags))
status = ReachabilityStatus.ViaWiFi;
if (ReachabilityUpdated != null)
ReachabilityUpdated(this, new ReachabilityEventArgs(status));
}
#endregion
#region Status properties
/// <summary>
/// Requested resource is reachable
/// </summary>
public virtual bool IsReachable
{
get
{
NetworkReachabilityFlags flags;
if (!NetworkReachability.TryGetFlags(out flags))
return false;
return IsReachableWithFlags(flags);
}
}
/// <summary>
/// Requested resource is reachable via WWAN
/// </summary>
public virtual bool IsReachableViaWWAN
{
get
{
if (!HasWWAN)
return false;
NetworkReachabilityFlags flags;
if (!NetworkReachability.TryGetFlags(out flags))
return false;
return ReachableViaWWAN(flags);
}
}
/// <summary>
/// Requested resource is reachable via WiFi
/// </summary>
public virtual bool IsReachableViaWiFi
{
get
{
NetworkReachabilityFlags flags;
if (!NetworkReachability.TryGetFlags(out flags))
return false;
if (!flags.HasFlag(NetworkReachabilityFlags.Reachable))
return false;
return ReachableViaWiFi(flags);
}
}
/// <summary>
/// WWAN is not active until a connection is required
/// </summary>
public virtual bool IsConnectionRequired
{
get
{
NetworkReachabilityFlags flags;
if (!NetworkReachability.TryGetFlags(out flags))
return false;
return flags.HasFlag(NetworkReachabilityFlags.ConnectionRequired);
}
}
/// <summary>
/// Connection will be automatically made, but only on demand. The link is otherwise inactive.
/// </summary>
public virtual bool IsConnectionOnDemand
{
get
{
NetworkReachabilityFlags flags;
if (!NetworkReachability.TryGetFlags(out flags))
return false;
return (flags.HasFlag(NetworkReachabilityFlags.ConnectionRequired) &&
flags.HasFlag(NetworkReachabilityFlags.ConnectionOnTraffic) &&
flags.HasFlag(NetworkReachabilityFlags.ConnectionOnDemand));
}
}
/// <summary>
/// The requested resource is reachable, but it'll require user interaction
/// </summary>
public virtual bool IsInterventionRequired
{
get
{
NetworkReachabilityFlags flags;
if (!NetworkReachability.TryGetFlags(out flags))
return false;
return (flags.HasFlag(NetworkReachabilityFlags.ConnectionRequired) &&
flags.HasFlag(NetworkReachabilityFlags.InterventionRequired));
}
}
/// <summary>
/// Gets the current reachability status
/// </summary>
/// <value>
/// The current status
/// </value>
public virtual ReachabilityStatus CurrentStatus
{
get
{
if (!IsReachable)
return ReachabilityStatus.NotReachable;
if (IsReachableViaWiFi)
return ReachabilityStatus.ViaWiFi;
if (IsReachableViaWWAN)
return ReachabilityStatus.ViaWWAN;
return ReachabilityStatus.NotReachable;
}
}
#endregion
#region IDisposable implementation
~Reachability()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
NetworkReachability.SetCallback(null);
NetworkReachability.Dispose();
NetworkReachability = null;
_disposed = true;
}
#endregion
}
/// <summary>
/// Reachability status.
/// </summary>
public enum ReachabilityStatus
{
/// <summary>
/// Resource is not reachable.
/// </summary>
NotReachable = 0,
/// <summary>
/// Resource is reachable via WiFi.
/// </summary>
ViaWiFi,
/// <summary>
/// Resource is reachable via WWAN
/// </summary>
ViaWWAN
}
/// <summary>
/// Event arguments that represent reachability
/// </summary>
public class ReachabilityEventArgs : EventArgs
{
private readonly ReachabilityStatus _status;
/// <summary>
/// Gets the reachability status.
/// </summary>
/// <value>
/// The status
/// </value>
public ReachabilityStatus Status { get { return _status; } }
public ReachabilityEventArgs(ReachabilityStatus status)
{
_status = status;
}
}
}
| |
//
// SourceManager.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2005-2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Addins;
using Hyena;
using Banshee.ServiceStack;
using Banshee.Library;
namespace Banshee.Sources
{
public delegate void SourceEventHandler(SourceEventArgs args);
public delegate void SourceAddedHandler(SourceAddedArgs args);
public class SourceEventArgs : EventArgs
{
public Source Source;
}
public class SourceAddedArgs : SourceEventArgs
{
public int Position;
}
public class SourceManager : /*ISourceManager,*/ IInitializeService, IRequiredService, IDBusExportable, IDisposable
{
private List<Source> sources = new List<Source>();
private Dictionary<string, Source> extension_sources = new Dictionary<string, Source> ();
private Source active_source;
private Source default_source;
private MusicLibrarySource music_library;
private VideoLibrarySource video_library;
public event SourceEventHandler SourceUpdated;
public event SourceAddedHandler SourceAdded;
public event SourceEventHandler SourceRemoved;
public event SourceEventHandler ActiveSourceChanged;
public class GroupSource : Source
{
public GroupSource (string name, int order) : base (name, name, order)
{
TypeUniqueId = order.ToString ();
}
}
public void Initialize ()
{
// TODO should add library sources here, but requires changing quite a few
// things that depend on being loaded before the music library is added.
//AddSource (music_library = new MusicLibrarySource (), true);
//AddSource (video_library = new VideoLibrarySource (), false);
AddSource (new GroupSource ("Library", 39));
AddSource (new GroupSource ("Online Media", 60));
//AddSource (new GroupSource ("Devices", 400));
}
internal void LoadExtensionSources ()
{
lock (this) {
AddinManager.AddExtensionNodeHandler ("/Banshee/SourceManager/Source", OnExtensionChanged);
}
}
public void Dispose ()
{
lock (this) {
try {
AddinManager.RemoveExtensionNodeHandler ("/Banshee/SourceManager/Source", OnExtensionChanged);
} catch {}
active_source = null;
default_source = null;
music_library = null;
video_library = null;
// Do dispose extension sources
foreach (Source source in extension_sources.Values) {
RemoveSource (source, true);
}
// But do not dispose non-extension sources
while (sources.Count > 0) {
RemoveSource (sources[0], false);
}
sources.Clear ();
extension_sources.Clear ();
}
}
private void OnExtensionChanged (object o, ExtensionNodeEventArgs args)
{
lock (this) {
TypeExtensionNode node = (TypeExtensionNode)args.ExtensionNode;
if (args.Change == ExtensionChange.Add && !extension_sources.ContainsKey (node.Id)) {
Source source = (Source)node.CreateInstance ();
extension_sources.Add (node.Id, source);
bool add_source = true;
if (source.Properties.Contains ("AutoAddSource")) {
add_source = source.Properties.GetBoolean ("AutoAddSource");
}
if (add_source) {
AddSource (source);
}
Log.DebugFormat ("Extension source loaded: {0}", source.Name);
} else if (args.Change == ExtensionChange.Remove && extension_sources.ContainsKey (node.Id)) {
Source source = extension_sources[node.Id];
extension_sources.Remove (node.Id);
RemoveSource (source, true);
Log.DebugFormat ("Extension source unloaded: {0}", source.Name);
}
}
}
public void AddSource(Source source)
{
AddSource(source, false);
}
public void AddSource(Source source, bool isDefault)
{
ThreadAssist.AssertInMainThread ();
if(source == null || ContainsSource (source)) {
return;
}
int position = FindSourceInsertPosition(source);
sources.Insert(position, source);
if(isDefault) {
default_source = source;
}
source.Updated += OnSourceUpdated;
source.ChildSourceAdded += OnChildSourceAdded;
source.ChildSourceRemoved += OnChildSourceRemoved;
if (source is MusicLibrarySource) {
music_library = source as MusicLibrarySource;
} else if (source is VideoLibrarySource) {
video_library = source as VideoLibrarySource;
}
SourceAdded.SafeInvoke (new SourceAddedArgs () {
Position = position,
Source = source
});
IDBusExportable exportable = source as IDBusExportable;
if (exportable != null) {
ServiceManager.DBusServiceManager.RegisterObject (exportable);
}
List<Source> children = new List<Source> (source.Children);
foreach(Source child_source in children) {
AddSource (child_source, false);
}
if(isDefault && ActiveSource == null) {
SetActiveSource(source);
}
}
public void RemoveSource (Source source)
{
RemoveSource (source, false);
}
public void RemoveSource (Source source, bool recursivelyDispose)
{
if(source == null || !ContainsSource (source)) {
return;
}
if(source == default_source) {
default_source = null;
}
source.Updated -= OnSourceUpdated;
source.ChildSourceAdded -= OnChildSourceAdded;
source.ChildSourceRemoved -= OnChildSourceRemoved;
sources.Remove(source);
foreach(Source child_source in source.Children) {
RemoveSource (child_source, recursivelyDispose);
}
IDBusExportable exportable = source as IDBusExportable;
if (exportable != null) {
ServiceManager.DBusServiceManager.UnregisterObject (exportable);
}
if (recursivelyDispose) {
IDisposable disposable = source as IDisposable;
if (disposable != null) {
disposable.Dispose ();
}
}
ThreadAssist.ProxyToMain (delegate {
if(source == active_source) {
SetActiveSource(default_source);
}
SourceEventHandler handler = SourceRemoved;
if(handler != null) {
SourceEventArgs args = new SourceEventArgs();
args.Source = source;
handler(args);
}
});
}
public void RemoveSource(Type type)
{
Queue<Source> remove_queue = new Queue<Source>();
foreach(Source source in Sources) {
if(source.GetType() == type) {
remove_queue.Enqueue(source);
}
}
while(remove_queue.Count > 0) {
RemoveSource(remove_queue.Dequeue());
}
}
public bool ContainsSource(Source source)
{
return sources.Contains(source);
}
private void OnSourceUpdated(object o, EventArgs args)
{
ThreadAssist.ProxyToMain (delegate {
SourceEventHandler handler = SourceUpdated;
if(handler != null) {
SourceEventArgs evargs = new SourceEventArgs();
evargs.Source = o as Source;
handler(evargs);
}
});
}
private void OnChildSourceAdded(SourceEventArgs args)
{
AddSource (args.Source);
}
private void OnChildSourceRemoved(SourceEventArgs args)
{
RemoveSource (args.Source);
}
private int FindSourceInsertPosition(Source source)
{
for(int i = sources.Count - 1; i >= 0; i--) {
if((sources[i] as Source).Order == source.Order) {
return i;
}
}
for(int i = 0; i < sources.Count; i++) {
if((sources[i] as Source).Order >= source.Order) {
return i;
}
}
return sources.Count;
}
public Source DefaultSource {
get { return default_source; }
set { default_source = value; }
}
public MusicLibrarySource MusicLibrary {
get { return music_library; }
}
public VideoLibrarySource VideoLibrary {
get { return video_library; }
}
public Source ActiveSource {
get { return active_source; }
}
/*ISource ISourceManager.DefaultSource {
get { return DefaultSource; }
}
ISource ISourceManager.ActiveSource {
get { return ActiveSource; }
set { value.Activate (); }
}*/
public void SetActiveSource(Source source)
{
SetActiveSource(source, true);
}
public void SetActiveSource(Source source, bool notify)
{
ThreadAssist.AssertInMainThread ();
if(source == null || !source.CanActivate || active_source == source) {
return;
}
if(active_source != null) {
active_source.Deactivate();
}
active_source = source;
if (source.Parent != null) {
source.Parent.Expanded = true;
}
if(!notify) {
source.Activate();
return;
}
SourceEventHandler handler = ActiveSourceChanged;
if(handler != null) {
SourceEventArgs args = new SourceEventArgs();
args.Source = active_source;
handler(args);
}
source.Activate();
}
public IEnumerable<T> FindSources<T> () where T : Source
{
foreach (Source source in Sources) {
T t_source = source as T;
if (t_source != null) {
yield return t_source;
}
}
}
public ICollection<Source> Sources {
get { return sources; }
}
/*string [] ISourceManager.Sources {
get { return DBusServiceManager.MakeObjectPathArray<Source>(sources); }
}*/
IDBusExportable IDBusExportable.Parent {
get { return null; }
}
string Banshee.ServiceStack.IService.ServiceName {
get { return "SourceManager"; }
}
}
}
| |
//#define UNITY3D
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace LitJson
{
internal struct PropertyMetadata
{
public MemberInfo Info;
public bool IsField;
public Type Type;
}
internal struct ArrayMetadata
{
private Type element_type;
private bool is_array;
private bool is_list;
public Type ElementType {
get {
if (element_type == null)
return typeof(JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsArray {
get { return is_array; }
set { is_array = value; }
}
public bool IsList {
get { return is_list; }
set { is_list = value; }
}
}
internal struct ObjectMetadata
{
private Type element_type;
private bool is_dictionary;
private IDictionary<string, PropertyMetadata> properties;
public Type ElementType {
get {
if (element_type == null)
return typeof(JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsDictionary {
get { return is_dictionary; }
set { is_dictionary = value; }
}
public IDictionary<string, PropertyMetadata> Properties {
get { return properties; }
set { properties = value; }
}
}
internal delegate void ExporterFunc (object obj, JsonWriter writer);
public delegate void ExporterFunc<T> (T obj, JsonWriter writer);
internal delegate object ImporterFunc (object input);
public delegate TValue ImporterFunc<TJson, TValue> (TJson input);
public delegate IJsonWrapper WrapperFactory ();
/// <summary>
/// JSON to .Net object and object to JSON conversions.
/// </summary>
public class JsonMapper
{
#region Fields
private static int max_nesting_depth;
private static IFormatProvider datetime_format;
private static IDictionary<Type, ExporterFunc> base_exporters_table;
private static IDictionary<Type, ExporterFunc> custom_exporters_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>>
base_importers_table;
private static IDictionary<Type,
IDictionary<Type, ImporterFunc>>
custom_importers_table;
private static IDictionary<Type, ArrayMetadata> array_metadata;
private static readonly object array_metadata_lock = new Object ();
private static IDictionary<Type,
IDictionary<Type, MethodInfo>>
conv_ops;
private static readonly object conv_ops_lock = new Object ();
private static IDictionary<Type, ObjectMetadata> object_metadata;
private static readonly object object_metadata_lock = new Object ();
private static IDictionary<Type,
IList<PropertyMetadata>>
type_properties;
private static readonly object type_properties_lock = new Object ();
private static JsonWriter static_writer;
private static readonly object static_writer_lock = new Object ();
#endregion
#region Constructors
static JsonMapper ()
{
max_nesting_depth = 100;
array_metadata = new Dictionary<Type, ArrayMetadata> ();
conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> ();
object_metadata = new Dictionary<Type, ObjectMetadata> ();
type_properties = new Dictionary<Type,
IList<PropertyMetadata>> ();
static_writer = new JsonWriter ();
datetime_format = DateTimeFormatInfo.InvariantInfo;
base_exporters_table = new Dictionary<Type, ExporterFunc> ();
custom_exporters_table = new Dictionary<Type, ExporterFunc> ();
base_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
custom_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
RegisterBaseExporters ();
RegisterBaseImporters ();
}
#endregion
#region Private Methods
private static void AddArrayMetadata (Type type)
{
if (array_metadata.ContainsKey (type))
return;
ArrayMetadata data = new ArrayMetadata ();
data.IsArray = type.IsArray;
if (type.GetInterface ("System.Collections.IList") != null)
data.IsList = true;
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name != "Item")
continue;
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters [0].ParameterType == typeof(int))
data.ElementType = p_info.PropertyType;
}
lock (array_metadata_lock) {
try {
array_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddObjectMetadata (Type type)
{
if (object_metadata.ContainsKey (type))
return;
ObjectMetadata data = new ObjectMetadata ();
if (type.GetInterface ("System.Collections.IDictionary") != null)
data.IsDictionary = true;
data.Properties = new Dictionary<string, PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item") {
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters [0].ParameterType == typeof(string))
data.ElementType = p_info.PropertyType;
continue;
}
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.Type = p_info.PropertyType;
data.Properties.Add (p_info.Name, p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
p_data.Type = f_info.FieldType;
data.Properties.Add (f_info.Name, p_data);
}
lock (object_metadata_lock) {
try {
object_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddTypeProperties (Type type)
{
if (type_properties.ContainsKey (type))
return;
IList<PropertyMetadata> props = new List<PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item")
continue;
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.IsField = false;
props.Add (p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
props.Add (p_data);
}
lock (type_properties_lock) {
try {
type_properties.Add (type, props);
} catch (ArgumentException) {
return;
}
}
}
private static MethodInfo GetConvOp (Type t1, Type t2)
{
lock (conv_ops_lock) {
if (!conv_ops.ContainsKey (t1))
conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ());
}
if (conv_ops [t1].ContainsKey (t2))
return conv_ops [t1] [t2];
MethodInfo op = t1.GetMethod (
"op_Implicit", new Type[] { t2 });
lock (conv_ops_lock) {
try {
conv_ops [t1].Add (t2, op);
} catch (ArgumentException) {
return conv_ops [t1] [t2];
}
}
return op;
}
private static object ReadValue (Type inst_type, JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd)
return null;
Type underlying_type = Nullable.GetUnderlyingType (inst_type);
Type value_type = underlying_type ?? inst_type;
if (reader.Token == JsonToken.Null) {
if (inst_type.IsClass || underlying_type != null) {
return null;
}
throw new JsonException (String.Format (
"Can't assign null to an instance of type {0}",
inst_type));
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean) {
Type json_type = reader.Value.GetType ();
if (value_type.IsAssignableFrom (json_type))
return reader.Value;
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey (json_type) &&
custom_importers_table [json_type].ContainsKey (
value_type)) {
ImporterFunc importer =
custom_importers_table [json_type] [value_type];
return importer (reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey (json_type) &&
base_importers_table [json_type].ContainsKey (
value_type)) {
ImporterFunc importer =
base_importers_table [json_type] [value_type];
return importer (reader.Value);
}
// Maybe it's an enum
if (value_type.IsEnum)
return Enum.ToObject (value_type, reader.Value);
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp (value_type, json_type);
if (conv_op != null)
return conv_op.Invoke (null,
new object[] { reader.Value });
// No luck
throw new JsonException (String.Format (
"Can't assign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart) {
AddArrayMetadata (inst_type);
ArrayMetadata t_data = array_metadata [inst_type];
if (!t_data.IsArray && !t_data.IsList)
throw new JsonException (String.Format (
"Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (!t_data.IsArray) {
list = (IList)Activator.CreateInstance (inst_type);
elem_type = t_data.ElementType;
} else {
list = new ArrayList ();
elem_type = inst_type.GetElementType ();
}
while (true) {
object item = ReadValue (elem_type, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
list.Add (item);
}
if (t_data.IsArray) {
int n = list.Count;
instance = Array.CreateInstance (elem_type, n);
for (int i = 0; i < n; i++)
((Array)instance).SetValue (list [i], i);
} else
instance = list;
} else if (reader.Token == JsonToken.ObjectStart) {
AddObjectMetadata (value_type);
ObjectMetadata t_data = object_metadata [value_type];
instance = Activator.CreateInstance (value_type);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string)reader.Value;
if (t_data.Properties.ContainsKey (property)) {
PropertyMetadata prop_data =
t_data.Properties [property];
if (prop_data.IsField) {
((FieldInfo)prop_data.Info).SetValue (
instance, ReadValue (prop_data.Type, reader));
} else {
PropertyInfo p_info =
(PropertyInfo)prop_data.Info;
if (p_info.CanWrite)
p_info.SetValue (
instance,
ReadValue (prop_data.Type, reader),
null);
else
ReadValue (prop_data.Type, reader);
}
} else {
if (!t_data.IsDictionary) {
if (!reader.SkipNonMembers) {
throw new JsonException (String.Format (
"The type {0} doesn't have the " +
"property '{1}'",
inst_type, property));
} else {
ReadSkip (reader);
continue;
}
}
((IDictionary)instance).Add (
property, ReadValue (
t_data.ElementType, reader));
}
}
}
return instance;
}
private static IJsonWrapper ReadValue (WrapperFactory factory,
JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd ||
reader.Token == JsonToken.Null)
return null;
IJsonWrapper instance = factory ();
if (reader.Token == JsonToken.String) {
instance.SetString ((string)reader.Value);
return instance;
}
if (reader.Token == JsonToken.Double) {
instance.SetDouble ((double)reader.Value);
return instance;
}
if (reader.Token == JsonToken.Int) {
instance.SetInt ((int)reader.Value);
return instance;
}
if (reader.Token == JsonToken.Long) {
instance.SetLong ((long)reader.Value);
return instance;
}
if (reader.Token == JsonToken.Boolean) {
instance.SetBoolean ((bool)reader.Value);
return instance;
}
if (reader.Token == JsonToken.ArrayStart) {
instance.SetJsonType (JsonType.Array);
while (true) {
IJsonWrapper item = ReadValue (factory, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
((IList)instance).Add (item);
}
} else if (reader.Token == JsonToken.ObjectStart) {
instance.SetJsonType (JsonType.Object);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string)reader.Value;
((IDictionary)instance) [property] = ReadValue (
factory, reader);
}
}
return instance;
}
private static void ReadSkip (JsonReader reader)
{
ToWrapper (
delegate {
return new JsonMockWrapper ();
}, reader);
}
private static void RegisterBaseExporters ()
{
base_exporters_table [typeof(byte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((byte)obj));
};
base_exporters_table [typeof(char)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((char)obj));
};
base_exporters_table [typeof(DateTime)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((DateTime)obj,
datetime_format));
};
base_exporters_table [typeof(decimal)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((decimal)obj);
};
base_exporters_table [typeof(sbyte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((sbyte)obj));
};
base_exporters_table [typeof(short)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((short)obj));
};
base_exporters_table [typeof(ushort)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((ushort)obj));
};
base_exporters_table [typeof(uint)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToUInt64 ((uint)obj));
};
base_exporters_table [typeof(ulong)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((ulong)obj);
};
base_exporters_table [typeof(float)] =
delegate(object obj, JsonWriter writer) {
writer.Write (Convert.ToDouble ((float)obj));
};
base_exporters_table [typeof(Int64)] =
delegate(object obj, JsonWriter writer) {
writer.Write ((Int64)obj);
};
}
private static void RegisterBaseImporters ()
{
ImporterFunc importer;
importer = delegate (object input) {
return Convert.ToByte ((int)input);
};
RegisterImporter (base_importers_table, typeof(int),
typeof(byte), importer);
importer = delegate (object input) {
return Convert.ToUInt64 ((int)input);
};
RegisterImporter (base_importers_table, typeof(int),
typeof(ulong), importer);
importer = delegate (object input) {
return Convert.ToSByte ((int)input);
};
RegisterImporter (base_importers_table, typeof(int),
typeof(sbyte), importer);
importer = delegate (object input) {
return Convert.ToInt16 ((int)input);
};
RegisterImporter (base_importers_table, typeof(int),
typeof(short), importer);
importer = delegate (object input) {
return Convert.ToUInt16 ((int)input);
};
RegisterImporter (base_importers_table, typeof(int),
typeof(ushort), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((int)input);
};
RegisterImporter (base_importers_table, typeof(int),
typeof(uint), importer);
importer = delegate (object input) {
return Convert.ToSingle ((int)input);
};
RegisterImporter (base_importers_table, typeof(int),
typeof(float), importer);
importer = delegate (object input) {
return Convert.ToDouble ((int)input);
};
RegisterImporter (base_importers_table, typeof(int),
typeof(double), importer);
importer = delegate (object input) {
return Convert.ToDecimal ((double)input);
};
RegisterImporter (base_importers_table, typeof(double),
typeof(decimal), importer);
importer = delegate(object input) {
return Convert.ToSingle ((float)(double)input);
};
RegisterImporter (base_importers_table, typeof(double),
typeof(float), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((long)input);
};
RegisterImporter (base_importers_table, typeof(long),
typeof(uint), importer);
importer = delegate (object input) {
return Convert.ToChar ((string)input);
};
RegisterImporter (base_importers_table, typeof(string),
typeof(char), importer);
importer = delegate (object input) {
return Convert.ToDateTime ((string)input, datetime_format);
};
RegisterImporter (base_importers_table, typeof(string),
typeof(DateTime), importer);
importer = delegate(object input) {
return Convert.ToInt64 ((Int32)input);
};
RegisterImporter (base_importers_table, typeof(Int32),
typeof(Int64), importer);
}
private static void RegisterImporter (
IDictionary<Type, IDictionary<Type, ImporterFunc>> table,
Type json_type, Type value_type, ImporterFunc importer)
{
if (!table.ContainsKey (json_type))
table.Add (json_type, new Dictionary<Type, ImporterFunc> ());
table [json_type] [value_type] = importer;
}
private static void WriteValue (object obj, JsonWriter writer,
bool writer_is_private,
int depth)
{
if (depth > max_nesting_depth)
throw new JsonException (
String.Format ("Max allowed object depth reached while " +
"trying to export from type {0}",
obj.GetType ()));
if (obj == null) {
writer.Write (null);
return;
}
if (obj is IJsonWrapper) {
if (writer_is_private)
writer.TextWriter.Write (((IJsonWrapper)obj).ToJson ());
else
((IJsonWrapper)obj).ToJson (writer);
return;
}
#region UnityEngine specific
if (obj is UnityEngine.Vector2) {
writer.Write ((UnityEngine.Vector2)obj);
return;
}
if (obj is UnityEngine.Vector3) {
writer.Write ((UnityEngine.Vector3)obj);
return;
}
if (obj is UnityEngine.Vector4) {
writer.Write ((UnityEngine.Vector4)obj);
return;
}
if (obj is UnityEngine.Quaternion) {
writer.Write ((UnityEngine.Quaternion)obj);
return;
}
if (obj is UnityEngine.Matrix4x4) {
writer.Write ((UnityEngine.Matrix4x4)obj);
return;
}
if (obj is UnityEngine.Ray) {
writer.Write ((UnityEngine.Ray)obj);
return;
}
if (obj is UnityEngine.RaycastHit) {
writer.Write ((UnityEngine.RaycastHit)obj);
return;
}
if (obj is UnityEngine.Color) {
writer.Write ((UnityEngine.Color)obj);
return;
}
#endregion
if (obj is String) {
writer.Write ((string)obj);
return;
}
if (obj is Double) {
writer.Write ((double)obj);
return;
}
if (obj is Int32) {
writer.Write ((int)obj);
return;
}
if (obj is Boolean) {
writer.Write ((bool)obj);
return;
}
if (obj is Int64) {
writer.Write ((long)obj);
return;
}
if (obj is Array) {
writer.WriteArrayStart ();
foreach (object elem in (Array) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd(((Array)obj).Length > 0);
return;
}
if (obj is IList) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd (((IList)obj).Count > 0);
return;
}
if (obj is IDictionary) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in (IDictionary) obj) {
writer.WritePropertyName ((string)entry.Key);
WriteValue (entry.Value, writer, writer_is_private,
depth + 1);
}
writer.WriteObjectEnd ();
return;
}
Type obj_type = obj.GetType ();
// See if there's a custom exporter for the object
if (custom_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = custom_exporters_table [obj_type];
exporter (obj, writer);
return;
}
// If not, maybe there's a base exporter
if (base_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = base_exporters_table [obj_type];
exporter (obj, writer);
return;
}
// Last option, let's see if it's an enum
if (obj is Enum) {
Type e_type = Enum.GetUnderlyingType (obj_type);
if (e_type == typeof(long)
|| e_type == typeof(uint)
|| e_type == typeof(ulong))
writer.Write ((ulong)obj);
else
writer.Write ((int)obj);
return;
}
// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties (obj_type);
IList<PropertyMetadata> props = type_properties [obj_type];
writer.WriteObjectStart ();
foreach (PropertyMetadata p_data in props) {
if (p_data.IsField) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (((FieldInfo)p_data.Info).GetValue (obj),
writer, writer_is_private, depth + 1);
} else {
PropertyInfo p_info = (PropertyInfo)p_data.Info;
if (p_info.CanRead) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (p_info.GetValue (obj, null),
writer, writer_is_private, depth + 1);
}
}
}
writer.WriteObjectEnd ();
}
#endregion
public static string ToJson (object obj)
{
lock (static_writer_lock) {
static_writer.Reset ();
WriteValue (obj, static_writer, true, 0);
return static_writer.ToString ();
}
}
public static void ToJson (object obj, JsonWriter writer)
{
WriteValue (obj, writer, false, 0);
}
public static JsonData ToObject (JsonReader reader)
{
return (JsonData)ToWrapper (
delegate {
return new JsonData ();
}, reader);
}
public static JsonData ToObject (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (JsonData)ToWrapper (
delegate {
return new JsonData ();
}, json_reader);
}
public static JsonData ToObject (string json)
{
return (JsonData)ToWrapper (
delegate {
return new JsonData ();
}, json);
}
public static T ToObject<T> (JsonReader reader)
{
return (T)ReadValue (typeof(T), reader);
}
public static T ToObject<T> (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (T)ReadValue (typeof(T), json_reader);
}
public static T ToObject<T> (string json)
{
JsonReader reader = new JsonReader (json);
return (T)ReadValue (typeof(T), reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
JsonReader reader)
{
return ReadValue (factory, reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
string json)
{
JsonReader reader = new JsonReader (json);
return ReadValue (factory, reader);
}
public static void RegisterExporter<T> (ExporterFunc<T> exporter)
{
ExporterFunc exporter_wrapper =
delegate (object obj, JsonWriter writer) {
exporter ((T)obj, writer);
};
custom_exporters_table [typeof(T)] = exporter_wrapper;
}
public static void RegisterImporter<TJson, TValue> (
ImporterFunc<TJson, TValue> importer)
{
ImporterFunc importer_wrapper =
delegate (object input) {
return importer ((TJson)input);
};
RegisterImporter (custom_importers_table, typeof(TJson),
typeof(TValue), importer_wrapper);
}
public static void UnregisterExporters ()
{
custom_exporters_table.Clear ();
}
public static void UnregisterImporters ()
{
custom_importers_table.Clear ();
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.SS.Formula.Functions
{
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NUnit.Framework;
/**
* Test cases for SUMPRODUCT()
*
* @author Josh Micich
*/
[TestFixture]
public class TestSumif
{
private static NumberEval _30 = new NumberEval(30);
private static NumberEval _40 = new NumberEval(40);
private static NumberEval _50 = new NumberEval(50);
private static NumberEval _60 = new NumberEval(60);
private static ValueEval invokeSumif(int rowIx, int colIx, params ValueEval[] args)
{
return new Sumif().Evaluate(args, rowIx, colIx);
}
private static void ConfirmDouble(double expected, ValueEval actualEval)
{
if (!(actualEval is NumericValueEval))
{
throw new AssertionException("Expected numeric result");
}
NumericValueEval nve = (NumericValueEval)actualEval;
Assert.AreEqual(expected, nve.NumberValue, 0);
}
[Test]
public void TestBasic()
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
ValueEval[] arg0values = new ValueEval[] { _30, _30, _40, _40, _50, _50 };
ValueEval[] arg2values = new ValueEval[] { _30, _40, _50, _60, _60, _60 };
AreaEval arg0;
AreaEval arg2;
arg0 = EvalFactory.CreateAreaEval("A3:B5", arg0values);
arg2 = EvalFactory.CreateAreaEval("D1:E3", arg2values);
Confirm(60.0, arg0, new NumberEval(30.0));
Confirm(70.0, arg0, new NumberEval(30.0), arg2);
Confirm(100.0, arg0, new StringEval(">45"));
Confirm(100.0, arg0, new StringEval(">=45"));
Confirm(100.0, arg0, new StringEval(">=50.0"));
Confirm(140.0, arg0, new StringEval("<45"));
Confirm(140.0, arg0, new StringEval("<=45"));
Confirm(140.0, arg0, new StringEval("<=40.0"));
Confirm(160.0, arg0, new StringEval("<>40.0"));
Confirm(80.0, arg0, new StringEval("=40.0"));
}
private static void Confirm(double expectedResult, params ValueEval[] args)
{
ConfirmDouble(expectedResult, invokeSumif(-1, -1, args));
}
/**
* Test for bug observed near svn r882931
*/
[Test]
public void TestCriteriaArgRange()
{
ValueEval[] arg0values = new ValueEval[] { _50, _60, _50, _50, _50, _30, };
ValueEval[] arg1values = new ValueEval[] { _30, _40, _50, _60, };
AreaEval arg0;
AreaEval arg1;
ValueEval ve;
arg0 = EvalFactory.CreateAreaEval("A3:B5", arg0values);
arg1 = EvalFactory.CreateAreaEval("A2:D2", arg1values); // single row range
ve = invokeSumif(0, 2, arg0, arg1); // invoking from cell C1
if (ve is NumberEval)
{
NumberEval ne = (NumberEval)ve;
if (ne.NumberValue == 30.0)
{
throw new AssertionException("identified error in SUMIF - criteria arg not Evaluated properly");
}
}
ConfirmDouble(200, ve);
arg0 = EvalFactory.CreateAreaEval("C1:D3", arg0values);
arg1 = EvalFactory.CreateAreaEval("B1:B4", arg1values); // single column range
ve = invokeSumif(3, 0, arg0, arg1); // invoking from cell A4
ConfirmDouble(60, ve);
}
[Test]
public void TestEvaluateException()
{
Assert.AreEqual(ErrorEval.VALUE_INVALID, invokeSumif(-1, -1, BlankEval.instance, new NumberEval(30.0)));
Assert.AreEqual(ErrorEval.VALUE_INVALID, invokeSumif(-1, -1, BlankEval.instance, new NumberEval(30.0), new NumberEval(30.0)));
Assert.AreEqual(ErrorEval.VALUE_INVALID, invokeSumif(-1, -1, new NumberEval(30.0), BlankEval.instance, new NumberEval(30.0)));
Assert.AreEqual(ErrorEval.VALUE_INVALID, invokeSumif(-1, -1, new NumberEval(30.0), new NumberEval(30.0), BlankEval.instance));
}
[Test]
public void TestMicrosoftExample1()
{
IWorkbook wb = initWorkbook1();
IFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
ICell cell = wb.GetSheetAt(0).GetRow(0).CreateCell(100);
Util.Utils.AssertDouble(fe, cell, "SUMIF(A2:A5,\">160000\",B2:B5)", 63000);
Util.Utils.AssertDouble(fe, cell, "SUMIF(A2:A5,\">160000\")", 900000);
Util.Utils.AssertDouble(fe, cell, "SUMIF(A2:A5,300000,B2:B5)", 21000);
Util.Utils.AssertDouble(fe, cell, "SUMIF(A2:A5,\">\" & C2,B2:B5)", 49000);
}
[Test]
public void TestMicrosoftExample1WithNA()
{
IWorkbook wb = initWorkbook1WithNA();
IFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
ICell cell = wb.GetSheetAt(0).GetRow(0).CreateCell(100);
Util.Utils.AssertError(fe, cell, "SUMIF(A2:A6,\">160000\",B2:B6)", FormulaError.NA);
}
[Test]
public void TestMicrosoftExample1WithBooleanAndString()
{
IWorkbook wb = initWorkbook1WithBooleanAndString();
IFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
ICell cell = wb.GetSheetAt(0).GetRow(0).CreateCell(100);
Util.Utils.AssertDouble(fe, cell, "SUMIF(A2:A7,\">160000\",B2:B7)", 63000);
}
[Test]
public void TestMicrosoftExample2()
{
IWorkbook wb = initWorkbook2();
IFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
ICell cell = wb.GetSheetAt(0).GetRow(0).CreateCell(100);
Util.Utils.AssertDouble(fe, cell, "SUMIF(A2:A7,\"Fruits\",C2:C7)", 2000);
Util.Utils.AssertDouble(fe, cell, "SUMIF(A2:A7,\"Vegetables\",C2:C7)", 12000);
Util.Utils.AssertDouble(fe, cell, "SUMIF(B2:B7,\"*es\",C2:C7)", 4300);
Util.Utils.AssertDouble(fe, cell, "SUMIF(A2:A7,\"\",C2:C7)", 400);
}
//see https://support.microsoft.com/en-us/office/sumif-function-169b8c99-c05c-4483-a712-1697a653039b
private IWorkbook initWorkbook1()
{
IWorkbook wb = new HSSFWorkbook();
ISheet sheet = wb.CreateSheet();
Util.Utils.AddRow(sheet, 0, "Property Value", "Commission", "Data");
Util.Utils.AddRow(sheet, 1, 100000, 7000, 250000);
Util.Utils.AddRow(sheet, 2, 200000, 14000);
Util.Utils.AddRow(sheet, 3, 300000, 21000);
Util.Utils.AddRow(sheet, 4, 400000, 28000);
return wb;
}
private IWorkbook initWorkbook1WithNA()
{
IWorkbook wb = initWorkbook1();
ISheet sheet = wb.GetSheetAt(0);
Util.Utils.AddRow(sheet, 5, 500000, FormulaError.NA);
return wb;
}
private IWorkbook initWorkbook1WithBooleanAndString()
{
IWorkbook wb = initWorkbook1();
ISheet sheet = wb.GetSheetAt(0);
Util.Utils.AddRow(sheet, 5, 500000, true);
Util.Utils.AddRow(sheet, 6, 600000, "abc");
return wb;
}
private IWorkbook initWorkbook2()
{
IWorkbook wb = new HSSFWorkbook();
ISheet sheet = wb.CreateSheet();
Util.Utils.AddRow(sheet, 0, "Category", "Food", "Sales");
Util.Utils.AddRow(sheet, 1, "Vegetables", "Tomatoes", 2300);
Util.Utils.AddRow(sheet, 2, "Vegetables", "Celery", 5500);
Util.Utils.AddRow(sheet, 3, "Fruits", "Oranges", 800);
Util.Utils.AddRow(sheet, 4, null, "Butter", 400);
Util.Utils.AddRow(sheet, 5, "Vegetables", "Carrots", 4200);
Util.Utils.AddRow(sheet, 6, "Fruits", "Apples", 1200);
return wb;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using TsAngular2.Areas.HelpPage.ModelDescriptions;
using TsAngular2.Areas.HelpPage.Models;
namespace TsAngular2.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.IO;
using libsecondlife;
using libsecondlife.StructuredData;
namespace libsecondlife.TestClient
{
public class ImportCommand : Command
{
private enum ImporterState
{
RezzingParent,
RezzingChildren,
Linking,
Idle
}
private class Linkset
{
public Primitive RootPrim;
public List<Primitive> Children = new List<Primitive>();
public Linkset()
{
RootPrim = new Primitive();
}
public Linkset(Primitive rootPrim)
{
RootPrim = rootPrim;
}
}
Primitive currentPrim;
LLVector3 currentPosition;
AutoResetEvent primDone = new AutoResetEvent(false);
List<Primitive> primsCreated;
List<uint> linkQueue;
uint rootLocalID;
ImporterState state = ImporterState.Idle;
public ImportCommand(TestClient testClient)
{
Name = "import";
Description = "Import prims from an exported xml file. Usage: import inputfile.xml [usegroup]";
testClient.Objects.OnNewPrim += new ObjectManager.NewPrimCallback(Objects_OnNewPrim);
}
public override string Execute(string[] args, LLUUID fromAgentID)
{
if (args.Length < 1)
return "Usage: import inputfile.xml [usegroup]";
string filename = args[0];
LLUUID GroupID = (args.Length > 1) ? Client.GroupID : LLUUID.Zero;
string xml;
List<Primitive> prims;
try { xml = File.ReadAllText(filename); }
catch (Exception e) { return e.Message; }
try { prims = Helpers.LLSDToPrimList(LLSDParser.DeserializeXml(xml)); }
catch (Exception e) { return "Failed to deserialize " + filename + ": " + e.Message; }
// Build an organized structure from the imported prims
Dictionary<uint, Linkset> linksets = new Dictionary<uint, Linkset>();
for (int i = 0; i < prims.Count; i++)
{
Primitive prim = prims[i];
if (prim.ParentID == 0)
{
if (linksets.ContainsKey(prim.LocalID))
linksets[prim.LocalID].RootPrim = prim;
else
linksets[prim.LocalID] = new Linkset(prim);
}
else
{
if (!linksets.ContainsKey(prim.ParentID))
linksets[prim.ParentID] = new Linkset();
linksets[prim.ParentID].Children.Add(prim);
}
}
primsCreated = new List<Primitive>();
Console.WriteLine("Importing " + linksets.Count + " structures.");
foreach (Linkset linkset in linksets.Values)
{
if (linkset.RootPrim.LocalID != 0)
{
state = ImporterState.RezzingParent;
currentPrim = linkset.RootPrim;
// HACK: Import the structure just above our head
// We need a more elaborate solution for importing with relative or absolute offsets
linkset.RootPrim.Position = Client.Self.SimPosition;
linkset.RootPrim.Position.Z += 3.0f;
currentPosition = linkset.RootPrim.Position;
// Rez the root prim with no rotation
LLQuaternion rootRotation = linkset.RootPrim.Rotation;
linkset.RootPrim.Rotation = LLQuaternion.Identity;
Client.Objects.AddPrim(Client.Network.CurrentSim, linkset.RootPrim.Data, GroupID,
linkset.RootPrim.Position, linkset.RootPrim.Scale, linkset.RootPrim.Rotation);
if (!primDone.WaitOne(10000, false))
return "Rez failed, timed out while creating the root prim.";
Client.Objects.SetPosition(Client.Network.CurrentSim, primsCreated[primsCreated.Count - 1].LocalID, linkset.RootPrim.Position);
state = ImporterState.RezzingChildren;
// Rez the child prims
foreach (Primitive prim in linkset.Children)
{
currentPrim = prim;
currentPosition = prim.Position + linkset.RootPrim.Position;
Client.Objects.AddPrim(Client.Network.CurrentSim, prim.Data, GroupID, currentPosition,
prim.Scale, prim.Rotation);
if (!primDone.WaitOne(10000, false))
return "Rez failed, timed out while creating child prim.";
Client.Objects.SetPosition(Client.Network.CurrentSim, primsCreated[primsCreated.Count - 1].LocalID, currentPosition);
}
// Create a list of the local IDs of the newly created prims
List<uint> primIDs = new List<uint>(primsCreated.Count);
primIDs.Add(rootLocalID); // Root prim is first in list.
if (linkset.Children.Count != 0)
{
// Add the rest of the prims to the list of local IDs
foreach (Primitive prim in primsCreated)
{
if (prim.LocalID != rootLocalID)
primIDs.Add(prim.LocalID);
}
linkQueue = new List<uint>(primIDs.Count);
linkQueue.AddRange(primIDs);
// Link and set the permissions + rotation
state = ImporterState.Linking;
Client.Objects.LinkPrims(Client.Network.CurrentSim, linkQueue);
if (primDone.WaitOne(1000 * linkset.Children.Count, false))
Client.Objects.SetRotation(Client.Network.CurrentSim, rootLocalID, rootRotation);
else
Console.WriteLine("Warning: Failed to link {0} prims", linkQueue.Count);
}
else
{
Client.Objects.SetRotation(Client.Network.CurrentSim, rootLocalID, rootRotation);
}
// Set permissions on newly created prims
Client.Objects.SetPermissions(Client.Network.CurrentSim, primIDs,
PermissionWho.Everyone | PermissionWho.Group | PermissionWho.NextOwner,
PermissionMask.All, true);
state = ImporterState.Idle;
}
else
{
// Skip linksets with a missing root prim
Console.WriteLine("WARNING: Skipping a linkset with a missing root prim");
}
// Reset everything for the next linkset
primsCreated.Clear();
}
return "Import complete.";
}
void Objects_OnNewPrim(Simulator simulator, Primitive prim, ulong regionHandle, ushort timeDilation)
{
if ((prim.Flags & LLObject.ObjectFlags.CreateSelected) == 0)
return; // We received an update for an object we didn't create
switch (state)
{
case ImporterState.RezzingParent:
rootLocalID = prim.LocalID;
goto case ImporterState.RezzingChildren;
case ImporterState.RezzingChildren:
if (!primsCreated.Contains(prim))
{
Console.WriteLine("Setting properties for " + prim.LocalID);
// TODO: Is there a way to set all of this at once, and update more ObjectProperties stuff?
Client.Objects.SetPosition(simulator, prim.LocalID, currentPosition);
Client.Objects.SetTextures(simulator, prim.LocalID, currentPrim.Textures);
if (currentPrim.Light.Intensity > 0) {
Client.Objects.SetLight(simulator, prim.LocalID, currentPrim.Light);
}
Client.Objects.SetFlexible(simulator, prim.LocalID, currentPrim.Flexible);
if (currentPrim.Sculpt.SculptTexture != LLUUID.Zero) {
Client.Objects.SetSculpt(simulator, prim.LocalID, currentPrim.Sculpt);
}
if (!String.IsNullOrEmpty(currentPrim.Properties.Name))
Client.Objects.SetName(simulator, prim.LocalID, currentPrim.Properties.Name);
if (!String.IsNullOrEmpty(currentPrim.Properties.Description))
Client.Objects.SetDescription(simulator, prim.LocalID, currentPrim.Properties.Description);
primsCreated.Add(prim);
primDone.Set();
}
break;
case ImporterState.Linking:
lock (linkQueue)
{
int index = linkQueue.IndexOf(prim.LocalID);
if (index != -1)
{
linkQueue.RemoveAt(index);
if (linkQueue.Count == 0)
primDone.Set();
}
}
break;
}
}
}
}
| |
namespace PeregrineDb.Tests.Databases
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using FluentAssertions;
using PeregrineDb.Dialects;
using PeregrineDb.Schema;
using PeregrineDb.Tests.ExampleEntities;
using PeregrineDb.Tests.Utils;
using Xunit;
[SuppressMessage("ReSharper", "StringLiteralAsInterpolationArgument")]
[SuppressMessage("ReSharper", "AccessToDisposedClosure")]
public abstract partial class DefaultDatabaseConnectionCrudAsyncTests
{
public class InsertAsync
: DefaultDatabaseConnectionCrudAsyncTests
{
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_entity_with_int32_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entity = new KeyInt32 { Name = "Some Name" };
// Act
await database.InsertAsync(entity);
// Assert
database.Count<KeyInt32>().Should().Be(1);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_entity_with_int64_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entity = new KeyInt64 { Name = "Some Name" };
// Act
await database.InsertAsync(entity);
// Assert
database.Count<KeyInt64>().Should().Be(1);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_entities_with_composite_keys(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entity = new CompositeKeys { Key1 = 2, Key2 = 3, Name = "Some Name" };
// Act
await database.InsertAsync(entity);
// Assert
database.Count<CompositeKeys>().Should().Be(1);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public void Does_not_allow_part_of_composite_key_to_be_null(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entity = new CompositeKeys { Key1 = null, Key2 = 5, Name = "Some Name" };
// Act
Func<Task> act = async () => await database.InsertAsync(entity);
// Assert
act.Should().Throw<Exception>();
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_entities_with_string_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entity = new KeyString { Name = "Some Name", Age = 10 };
// Act
await database.InsertAsync(entity);
// Assert
database.Count<KeyString>().Should().Be(1);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public void Does_not_allow_string_key_to_be_null(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entity = new KeyString { Name = null, Age = 10 };
// Act
Func<Task> act = async () => await database.InsertAsync(entity);
// Assert
act.Should().Throw<Exception>();
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_entities_with_guid_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entity = new KeyGuid { Id = Guid.NewGuid(), Name = "Some Name" };
// Act
await database.InsertAsync(entity);
// Assert
database.Count<KeyGuid>().Should().Be(1);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Uses_key_attribute_to_determine_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entity = new KeyAlias { Name = "Some Name" };
// Act
await database.InsertAsync(entity);
// Assert
database.Count<KeyAlias>().Should().Be(1);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_into_other_schemas(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entity = new SchemaOther { Name = "Some name" };
// Act
await database.InsertAsync(entity);
// Assert
database.Count<SchemaOther>().Should().Be(1);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Ignores_columns_which_are_not_mapped(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entity = new PropertyNotMapped { FirstName = "Bobby", LastName = "DropTables", Age = 10 };
// Act
await database.InsertAsync(entity);
// Assert
database.Count<PropertyNotMapped>().Should().Be(1);
}
}
}
public class InsertAndReturnKeyAsync
: DefaultDatabaseConnectionCrudAsyncTests
{
[Theory]
[MemberData(nameof(TestDialects))]
public void Throws_exception_when_entity_has_no_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Act
Func<Task> act = async () => await database.InsertAsync<int>(new NoKey());
// Assert
act.Should().Throw<InvalidPrimaryKeyException>();
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public void Throws_exception_when_entity_has_composite_keys(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Act
Func<Task> act = async () => await database.InsertAsync<int>(new CompositeKeys());
// Assert
act.Should().Throw<InvalidPrimaryKeyException>();
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public void Throws_exception_for_string_keys(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entity = new KeyString { Name = "Some Name", Age = 10 };
// Act
Func<Task> act = async () => await database.InsertAsync<string>(entity);
// Assert
act.Should().Throw<InvalidPrimaryKeyException>();
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public void Throws_exception_for_guid_keys(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entity = new KeyGuid { Id = Guid.NewGuid(), Name = "Some Name" };
// Act
Func<Task> act = async () => await database.InsertAsync<Guid>(entity);
// Assert
act.Should().Throw<InvalidPrimaryKeyException>();
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_entity_with_int32_primary_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Act
var id = await database.InsertAsync<int>(new KeyInt32 { Name = "Some Name" });
// Assert
id.Should().BeGreaterThan(0);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_entity_with_int64_primary_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Act
var id = await database.InsertAsync<int>(new KeyInt64 { Name = "Some Name" });
// Assert
id.Should().BeGreaterThan(0);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Uses_key_attribute_to_determine_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Act
var id = await database.InsertAsync<int>(new KeyAlias { Name = "Some Name" });
// Assert
id.Should().BeGreaterThan(0);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_into_other_schemas(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Act
var id = await database.InsertAsync<int>(new SchemaOther { Name = "Some name" });
// Assert
id.Should().BeGreaterThan(0);
}
}
}
public class InsertRangeAsync
: DefaultDatabaseConnectionCrudAsyncTests
{
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_entity_with_int32_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entities = new[]
{
new KeyInt32 { Name = "Some Name" },
new KeyInt32 { Name = "Some Name2" }
};
// Act
await database.InsertRangeAsync(entities);
// Assert
database.Count<KeyInt32>().Should().Be(2);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_entity_with_int64_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entities = new[]
{
new KeyInt64 { Name = "Some Name" },
new KeyInt64 { Name = "Some Name2" }
};
// Act
await database.InsertRangeAsync(entities);
// Assert
database.Count<KeyInt64>().Should().Be(2);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_entities_with_composite_keys(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entities = new[]
{
new CompositeKeys { Key1 = 2, Key2 = 3, Name = "Some Name1" },
new CompositeKeys { Key1 = 3, Key2 = 3, Name = "Some Name2" }
};
// Act
await database.InsertRangeAsync(entities);
// Assert
database.Count<CompositeKeys>().Should().Be(2);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_entities_with_string_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entities = new[]
{
new KeyString { Name = "Some Name", Age = 10 },
new KeyString { Name = "Some Name2", Age = 11 }
};
// Act
await database.InsertRangeAsync(entities);
// Assert
database.Count<KeyString>().Should().Be(2);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_entities_with_guid_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entities = new[]
{
new KeyGuid { Id = Guid.NewGuid(), Name = "Some Name" },
new KeyGuid { Id = Guid.NewGuid(), Name = "Some Name2" }
};
// Act
await database.InsertRangeAsync(entities);
// Assert
database.Count<KeyGuid>().Should().Be(2);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Uses_key_attribute_to_determine_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entities = new[]
{
new KeyAlias { Name = "Some Name" },
new KeyAlias { Name = "Some Name2" }
};
// Act
await database.InsertRangeAsync(entities);
// Assert
database.Count<KeyAlias>().Should().Be(2);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_into_other_schemas(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entities = new[]
{
new SchemaOther { Name = "Some Name" },
new SchemaOther { Name = "Some Name2" }
};
// Act
await database.InsertRangeAsync(entities);
// Assert
database.Count<SchemaOther>().Should().Be(2);
}
}
}
public class InsertRangeAndSetKeyAsync
: DefaultDatabaseConnectionCrudAsyncTests
{
[Theory]
[MemberData(nameof(TestDialects))]
public void Throws_exception_when_entity_has_no_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entities = new[]
{
new NoKey()
};
// Act
Func<Task> act = async () => await database.InsertRangeAsync<NoKey, int>(entities, (e, k) => { });
// Assert
act.Should().Throw<InvalidPrimaryKeyException>();
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public void Throws_exception_when_entity_has_composite_keys(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entities = new[]
{
new CompositeKeys()
};
// Act
Func<Task> act = async () => await database.InsertRangeAsync<CompositeKeys, int>(entities, (e, k) => { });
// Assert
act.Should().Throw<InvalidPrimaryKeyException>();
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public void Throws_exception_for_string_keys(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entities = new[]
{
new KeyString { Name = "Some Name", Age = 10 }
};
// Act
Func<Task> act = async () => await database.InsertRangeAsync<KeyString, string>(entities, (e, k) => { });
// Assert
act.Should().Throw<InvalidPrimaryKeyException>();
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public void Throws_exception_for_guid_keys(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entities = new[]
{
new KeyGuid { Id = Guid.NewGuid(), Name = "Some Name" }
};
// Act
Func<Task> act = async () => await database.InsertRangeAsync<KeyGuid, Guid>(entities, (e, k) => { });
// Assert
act.Should().Throw<InvalidPrimaryKeyException>();
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_entity_with_int32_primary_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entities = new[]
{
new KeyInt32 { Name = "Some Name" },
new KeyInt32 { Name = "Some Name2" },
new KeyInt32 { Name = "Some Name3" }
};
// Act
await database.InsertRangeAsync<KeyInt32, int>(entities, (e, k) => { e.Id = k; });
// Assert
entities[0].Id.Should().BeGreaterThan(0);
entities[1].Id.Should().BeGreaterThan(entities[0].Id);
entities[2].Id.Should().BeGreaterThan(entities[1].Id);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_entity_with_int64_primary_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entities = new[]
{
new KeyInt64 { Name = "Some Name" },
new KeyInt64 { Name = "Some Name2" },
new KeyInt64 { Name = "Some Name3" }
};
// Act
await database.InsertRangeAsync<KeyInt64, long>(entities, (e, k) => { e.Id = k; });
// Assert
entities[0].Id.Should().BeGreaterThan(0);
entities[1].Id.Should().BeGreaterThan(entities[0].Id);
entities[2].Id.Should().BeGreaterThan(entities[1].Id);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Uses_key_attribute_to_determine_key(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entities = new[]
{
new KeyExplicit { Name = "Some Name" }
};
// Act
await database.InsertRangeAsync<KeyExplicit, int>(entities, (e, k) => { e.Key = k; });
// Assert
entities[0].Key.Should().BeGreaterThan(0);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Inserts_into_other_schemas(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
var entities = new[]
{
new SchemaOther { Name = "Some Name" },
new SchemaOther { Name = "Some Name2" },
new SchemaOther { Name = "Some Name3" }
};
// Act
await database.InsertRangeAsync<SchemaOther, int>(entities, (e, k) => { e.Id = k; });
// Assert
entities[0].Id.Should().BeGreaterThan(0);
entities[1].Id.Should().BeGreaterThan(entities[0].Id);
entities[2].Id.Should().BeGreaterThan(entities[1].Id);
}
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
namespace Lucene.Net.Test.Index
{
/// <summary>
/// Summary description for FieldEnumeratorTest
/// </summary>
[TestFixture]
public class FieldEnumeratorTest
{
public FieldEnumeratorTest()
{
//
// TODO: Add constructor logic here
//
}
private static IndexReader reader;
#region setup/teardown methods
[TestFixtureSetUp]
public static void MyClassInitialize()
{
RAMDirectory rd = new RAMDirectory();
IndexWriter writer = new IndexWriter(rd, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
for (int i = 0; i < 1000; i++)
{
Document doc = new Document();
doc.Add(new Field("string", i.ToString(), Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new NumericField("int", Field.Store.YES, true).SetIntValue(i));
doc.Add(new NumericField("long", Field.Store.YES, true).SetLongValue(i));
doc.Add(new NumericField("double", Field.Store.YES, true).SetDoubleValue(i));
doc.Add(new NumericField("float", Field.Store.YES, true).SetFloatValue(i));
writer.AddDocument(doc);
}
writer.Close();
reader = IndexReader.Open(rd, true);
}
[TestFixtureTearDown]
public static void MyClassCleanup()
{
if (reader != null)
{
reader.Close();
reader = null;
}
}
#endregion
[Test]
public void StringEnumTest()
{
using (StringFieldEnumerator sfe = new StringFieldEnumerator(reader, "string", false))
{
int value = 0;
foreach (string s in sfe.Terms)
{
value++;
}
Assert.AreEqual(1000, value);
}
// now with the documents
using (StringFieldEnumerator sfe = new StringFieldEnumerator(reader, "string"))
{
int value = 0;
foreach (string s in sfe.Terms)
{
foreach (int doc in sfe.Docs)
{
string expected = reader.Document(doc).Get("string");
Assert.AreEqual(expected, s);
}
value++;
}
Assert.AreEqual(1000, value);
}
}
[Test]
public void IntEnumTest()
{
using (IntFieldEnumerator ife = new IntFieldEnumerator(reader, "string", FieldParser.String))
{
int value = 0;
foreach (int i in ife.Terms)
{
foreach (int doc in ife.Docs)
{
int expected = Int32.Parse(reader.Document(doc).Get("string"));
Assert.AreEqual(expected, i);
}
value++;
}
Assert.AreEqual(1000, value);
}
using (IntFieldEnumerator ife = new IntFieldEnumerator(reader, "int", FieldParser.Numeric))
{
int value = 0;
foreach (int i in ife.Terms)
{
foreach (int doc in ife.Docs)
{
int expected = Int32.Parse(reader.Document(doc).Get("int"));
Assert.AreEqual(expected, i);
}
value++;
}
Assert.AreEqual(1000, value);
}
}
[Test]
public void LongEnumTest()
{
using (LongFieldEnumerator lfe = new LongFieldEnumerator(reader, "string", FieldParser.String))
{
int value = 0;
foreach (long i in lfe.Terms)
{
foreach (int doc in lfe.Docs)
{
long expected = Int64.Parse(reader.Document(doc).Get("string"));
Assert.AreEqual(expected, i);
}
value++;
}
Assert.AreEqual(1000, value);
}
using (LongFieldEnumerator lfe = new LongFieldEnumerator(reader, "long", FieldParser.Numeric))
{
int value = 0;
foreach (int i in lfe.Terms)
{
foreach (int doc in lfe.Docs)
{
long expected = Int64.Parse(reader.Document(doc).Get("long"));
Assert.AreEqual(expected, i);
}
value++;
}
Assert.AreEqual(1000, value);
}
}
[Test]
public void FloatEnumTest()
{
using (FloatFieldEnumerator ffe = new FloatFieldEnumerator(reader, "string", FieldParser.String))
{
int value = 0;
foreach (int i in ffe.Terms)
{
foreach (int doc in ffe.Docs)
{
float expected = Single.Parse(reader.Document(doc).Get("string"));
Assert.AreEqual(expected, i);
}
value++;
}
Assert.AreEqual(1000, value);
}
using (FloatFieldEnumerator ffe = new FloatFieldEnumerator(reader, "float", FieldParser.Numeric))
{
int value = 0;
foreach (int i in ffe.Terms)
{
foreach (int doc in ffe.Docs)
{
float expected = Single.Parse(reader.Document(doc).Get("float"));
Assert.AreEqual(expected, i);
}
value++;
}
Assert.AreEqual(1000, value);
}
}
[Test]
public void DoubleEnumTest()
{
using (DoubleFieldEnumerator dfe = new DoubleFieldEnumerator(reader, "string", FieldParser.String))
{
int value = 0;
foreach (int i in dfe.Terms)
{
foreach (int doc in dfe.Docs)
{
double expected = Double.Parse(reader.Document(doc).Get("string"));
Assert.AreEqual(expected, i);
}
value++;
}
Assert.AreEqual(1000, value);
}
using (DoubleFieldEnumerator dfe = new DoubleFieldEnumerator(reader, "double", FieldParser.Numeric))
{
int value = 0;
foreach (int i in dfe.Terms)
{
foreach (int doc in dfe.Docs)
{
double expected = Double.Parse(reader.Document(doc).Get("double"));
Assert.AreEqual(expected, i);
}
value++;
}
Assert.AreEqual(1000, value);
}
}
[Test]
public void TermDocEnumeratorOnlyTestSingleTerm()
{
Term t = new Term("string", "500");
using (TermDocEnumerator tde = new TermDocEnumerator(reader.TermDocs()))
{
tde.Seek(t);
int count = 0;
foreach (int doc in tde)
{
Assert.AreEqual(500, doc);
count++;
}
Assert.AreEqual(1, count);
}
}
[Test]
public void TermDocEnumeratorOnlyTestMultipleTerms()
{
HashSet<Term> terms = new HashSet<Term>();
terms.Add(new Term("string", "500"));
terms.Add(new Term("string", "600"));
terms.Add(new Term("string", "400"));
HashSet<int> docs = new HashSet<int>();
using (TermDocEnumerator tde = new TermDocEnumerator(reader.TermDocs()))
{
foreach (Term t in terms)
{
tde.Seek(t);
foreach (int doc in tde)
{
docs.Add(doc);
}
}
}
Assert.AreEqual(3, docs.Count);
Assert.IsTrue(docs.Contains(400));
Assert.IsTrue(docs.Contains(500));
Assert.IsTrue(docs.Contains(600));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition.Primitives;
using Xunit;
namespace System.ComponentModel.Composition
{
public interface IGetString
{
string GetString();
}
public class PublicComponentWithPublicExports
{
public const string PublicFieldExpectedValue = "PublicField";
[Export("PublicField")]
public string PublicField = PublicFieldExpectedValue;
public const string PublicPropertyExpectedValue = "PublicProperty";
[Export("PublicProperty")]
public string PublicProperty { get { return PublicPropertyExpectedValue; } }
public const string PublicMethodExpectedValue = "PublicMethod";
[Export("PublicDelegate")]
public string PublicMethod() { return PublicMethodExpectedValue; }
public const string PublicNestedClassExpectedValue = "PublicNestedClass";
[Export("PublicIGetString")]
public class PublicNestedClass : IGetString
{
public string GetString() { return PublicNestedClassExpectedValue; }
}
}
[Export]
public class PublicImportsExpectingPublicExports
{
[Import("PublicField")]
public string PublicImportPublicField { get; set; }
[Import("PublicProperty")]
public string PublicImportPublicProperty { get; set; }
[Import("PublicDelegate")]
public Func<string> PublicImportPublicMethod { get; set; }
[Import("PublicIGetString")]
public IGetString PublicImportPublicNestedClass { get; set; }
public void VerifyIsBound()
{
Assert.Equal(PublicComponentWithPublicExports.PublicFieldExpectedValue, PublicImportPublicField);
Assert.Equal(PublicComponentWithPublicExports.PublicPropertyExpectedValue, PublicImportPublicProperty);
Assert.Equal(PublicComponentWithPublicExports.PublicMethodExpectedValue, PublicImportPublicMethod());
Assert.Equal(PublicComponentWithPublicExports.PublicNestedClassExpectedValue, PublicImportPublicNestedClass.GetString());
}
}
[Export]
internal class InternalImportsExpectingPublicExports
{
[Import("PublicField")]
internal string InternalImportPublicField { get; set; }
[Import("PublicProperty")]
internal string InternalImportPublicProperty { get; set; }
[Import("PublicDelegate")]
internal Func<string> InternalImportPublicMethod { get; set; }
[Import("PublicIGetString")]
internal IGetString InternalImportPublicNestedClass { get; set; }
public void VerifyIsBound()
{
Assert.Equal(PublicComponentWithPublicExports.PublicFieldExpectedValue, InternalImportPublicField);
Assert.Equal(PublicComponentWithPublicExports.PublicPropertyExpectedValue, InternalImportPublicProperty);
Assert.Equal(PublicComponentWithPublicExports.PublicMethodExpectedValue, InternalImportPublicMethod());
Assert.Equal(PublicComponentWithPublicExports.PublicNestedClassExpectedValue, InternalImportPublicNestedClass.GetString());
}
}
public class PublicComponentWithInternalExports
{
public const string InternalFieldExpectedValue = "InternalField";
[Export("InternalField")]
internal string InternalField = InternalFieldExpectedValue;
public const string InternalPropertyExpectedValue = "InternalProperty";
[Export("InternalProperty")]
internal string InternalProperty { get { return InternalPropertyExpectedValue; } }
public const string InternalMethodExpectedValue = "InternalMethod";
[Export("InternalDelegate")]
internal string InternalMethod() { return InternalMethodExpectedValue; }
public const string InternalNestedClassExpectedValue = "InternalNestedClass";
[Export("InternalIGetString")]
internal class InternalNestedClass : IGetString
{
public string GetString() { return InternalNestedClassExpectedValue; }
}
}
[Export]
public class PublicImportsExpectingInternalExports
{
[Import("InternalField")]
public string PublicImportInternalField { get; set; }
[Import("InternalProperty")]
public string PublicImportInternalProperty { get; set; }
[Import("InternalDelegate")]
public Func<string> PublicImportInternalMethod { get; set; }
[Import("InternalIGetString")]
public IGetString PublicImportInternalNestedClass { get; set; }
public void VerifyIsBound()
{
Assert.Equal(PublicComponentWithInternalExports.InternalFieldExpectedValue, PublicImportInternalField);
Assert.Equal(PublicComponentWithInternalExports.InternalPropertyExpectedValue, PublicImportInternalProperty);
Assert.Equal(PublicComponentWithInternalExports.InternalMethodExpectedValue, PublicImportInternalMethod());
Assert.Equal(PublicComponentWithInternalExports.InternalNestedClassExpectedValue, PublicImportInternalNestedClass.GetString());
}
}
[Export]
internal class InternalImportsExpectingInternalExports
{
[Import("InternalField")]
internal string InternalImportInternalField { get; set; }
[Import("InternalProperty")]
internal string InternalImportInternalProperty { get; set; }
[Import("InternalDelegate")]
internal Func<string> InternalImportInternalMethod { get; set; }
[Import("InternalIGetString")]
internal IGetString InternalImportInternalNestedClass { get; set; }
public void VerifyIsBound()
{
Assert.Equal(PublicComponentWithInternalExports.InternalFieldExpectedValue, InternalImportInternalField);
Assert.Equal(PublicComponentWithInternalExports.InternalPropertyExpectedValue, InternalImportInternalProperty);
Assert.Equal(PublicComponentWithInternalExports.InternalMethodExpectedValue, InternalImportInternalMethod());
Assert.Equal(PublicComponentWithInternalExports.InternalNestedClassExpectedValue, InternalImportInternalNestedClass.GetString());
}
}
public class PublicComponentWithProtectedExports
{
public const string ProtectedFieldExpectedValue = "ProtectedField";
[Export("ProtectedField")]
protected string ProtectedField = ProtectedFieldExpectedValue;
public const string ProtectedPropertyExpectedValue = "ProtectedProperty";
[Export("ProtectedProperty")]
protected string ProtectedProperty { get { return ProtectedPropertyExpectedValue; } }
public const string ProtectedMethodExpectedValue = "ProtectedMethod";
[Export("ProtectedDelegate")]
protected string ProtectedMethod() { return ProtectedMethodExpectedValue; }
public const string ProtectedNestedClassExpectedValue = "ProtectedNestedClass";
[Export("ProtectedIGetString")]
protected class ProtectedNestedClass : IGetString
{
public string GetString() { return ProtectedNestedClassExpectedValue; }
}
}
[Export]
public class PublicImportsExpectingProtectedExports
{
[Import("ProtectedField")]
public string PublicImportProtectedField { get; set; }
[Import("ProtectedProperty")]
public string PublicImportProtectedProperty { get; set; }
[Import("ProtectedDelegate")]
public Func<string> PublicImportProtectedMethod { get; set; }
[Import("ProtectedIGetString")]
public IGetString PublicImportProtectedNestedClass { get; set; }
public void VerifyIsBound()
{
Assert.Equal(PublicComponentWithProtectedExports.ProtectedFieldExpectedValue, PublicImportProtectedField);
Assert.Equal(PublicComponentWithProtectedExports.ProtectedPropertyExpectedValue, PublicImportProtectedProperty);
Assert.Equal(PublicComponentWithProtectedExports.ProtectedMethodExpectedValue, PublicImportProtectedMethod());
Assert.Equal(PublicComponentWithProtectedExports.ProtectedNestedClassExpectedValue, PublicImportProtectedNestedClass.GetString());
}
}
[Export]
internal class InternalImportsExpectingProtectedExports
{
[Import("ProtectedField")]
internal string InternalImportProtectedField { get; set; }
[Import("ProtectedProperty")]
internal string InternalImportProtectedProperty { get; set; }
[Import("ProtectedDelegate")]
internal Func<string> InternalImportProtectedMethod { get; set; }
[Import("ProtectedIGetString")]
internal IGetString InternalImportProtectedNestedClass { get; set; }
public void VerifyIsBound()
{
Assert.Equal(PublicComponentWithProtectedExports.ProtectedFieldExpectedValue, InternalImportProtectedField);
Assert.Equal(PublicComponentWithProtectedExports.ProtectedPropertyExpectedValue, InternalImportProtectedProperty);
Assert.Equal(PublicComponentWithProtectedExports.ProtectedMethodExpectedValue, InternalImportProtectedMethod());
Assert.Equal(PublicComponentWithProtectedExports.ProtectedNestedClassExpectedValue, InternalImportProtectedNestedClass.GetString());
}
}
public class PublicComponentWithProtectedInternalExports
{
public const string ProtectedInternalFieldExpectedValue = "ProtectedInternalField";
[Export("ProtectedInternalField")]
protected internal string ProtectedInternalField = ProtectedInternalFieldExpectedValue;
public const string ProtectedInternalPropertyExpectedValue = "ProtectedInternalProperty";
[Export("ProtectedInternalProperty")]
protected internal string ProtectedInternalProperty { get { return ProtectedInternalPropertyExpectedValue; } }
public const string ProtectedInternalMethodExpectedValue = "ProtectedInternalMethod";
[Export("ProtectedInternalDelegate")]
protected internal string ProtectedInternalMethod() { return ProtectedInternalMethodExpectedValue; }
public const string ProtectedInternalNestedClassExpectedValue = "ProtectedInternalNestedClass";
[Export("ProtectedInternalIGetString")]
protected internal class ProtectedInternalNestedClass : IGetString
{
public string GetString() { return ProtectedInternalNestedClassExpectedValue; }
}
}
[Export]
public class PublicImportsExpectingProtectedInternalExports
{
[Import("ProtectedInternalField")]
public string PublicImportProtectedInternalField { get; set; }
[Import("ProtectedInternalProperty")]
public string PublicImportProtectedInternalProperty { get; set; }
[Import("ProtectedInternalDelegate")]
public Func<string> PublicImportProtectedInternalMethod { get; set; }
[Import("ProtectedInternalIGetString")]
public IGetString PublicImportProtectedInternalNestedClass { get; set; }
public void VerifyIsBound()
{
Assert.Equal(PublicComponentWithProtectedInternalExports.ProtectedInternalFieldExpectedValue, PublicImportProtectedInternalField);
Assert.Equal(PublicComponentWithProtectedInternalExports.ProtectedInternalPropertyExpectedValue, PublicImportProtectedInternalProperty);
Assert.Equal(PublicComponentWithProtectedInternalExports.ProtectedInternalMethodExpectedValue, PublicImportProtectedInternalMethod());
Assert.Equal(PublicComponentWithProtectedInternalExports.ProtectedInternalNestedClassExpectedValue, PublicImportProtectedInternalNestedClass.GetString());
}
}
[Export]
internal class InternalImportsExpectingProtectedInternalExports
{
[Import("ProtectedInternalField")]
internal string InternalImportProtectedInternalField { get; set; }
[Import("ProtectedInternalProperty")]
internal string InternalImportProtectedInternalProperty { get; set; }
[Import("ProtectedInternalDelegate")]
internal Func<string> InternalImportProtectedInternalMethod { get; set; }
[Import("ProtectedInternalIGetString")]
internal IGetString InternalImportProtectedInternalNestedClass { get; set; }
public void VerifyIsBound()
{
Assert.Equal(PublicComponentWithProtectedInternalExports.ProtectedInternalFieldExpectedValue, InternalImportProtectedInternalField);
Assert.Equal(PublicComponentWithProtectedInternalExports.ProtectedInternalPropertyExpectedValue, InternalImportProtectedInternalProperty);
Assert.Equal(PublicComponentWithProtectedInternalExports.ProtectedInternalMethodExpectedValue, InternalImportProtectedInternalMethod());
Assert.Equal(PublicComponentWithProtectedInternalExports.ProtectedInternalNestedClassExpectedValue, InternalImportProtectedInternalNestedClass.GetString());
}
}
public class PublicComponentWithPrivateExports
{
public const string PrivateFieldExpectedValue = "PrivateField";
public const string PrivatePropertyExpectedValue = "PrivateProperty";
[Export("PrivateProperty")]
private string PrivateProperty { get { return PrivatePropertyExpectedValue; } }
public const string PrivateMethodExpectedValue = "PrivateMethod";
[Export("PrivateDelegate")]
private string PrivateMethod() { return PrivateMethodExpectedValue; }
public const string PrivateNestedClassExpectedValue = "PrivateNestedClass";
[Export("PrivateIGetString")]
private class PrivateNestedClass : IGetString
{
public string GetString() { return PrivateNestedClassExpectedValue; }
}
}
[Export]
public class PublicImportsExpectingPrivateExports
{
[Import("PrivateField")]
public string PublicImportPrivateField { get; set; }
[Import("PrivateProperty")]
public string PublicImportPrivateProperty { get; set; }
[Import("PrivateDelegate")]
public Func<string> PublicImportPrivateMethod { get; set; }
[Import("PrivateIGetString")]
public IGetString PublicImportPrivateNestedClass { get; set; }
public void VerifyIsBound()
{
Assert.Equal(PublicComponentWithPrivateExports.PrivateFieldExpectedValue, PublicImportPrivateField);
Assert.Equal(PublicComponentWithPrivateExports.PrivatePropertyExpectedValue, PublicImportPrivateProperty);
Assert.Equal(PublicComponentWithPrivateExports.PrivateMethodExpectedValue, PublicImportPrivateMethod());
Assert.Equal(PublicComponentWithPrivateExports.PrivateNestedClassExpectedValue, PublicImportPrivateNestedClass.GetString());
}
}
[Export]
internal class InternalImportsExpectingPrivateExports
{
[Import("PrivateField")]
internal string InternalImportPrivateField { get; set; }
[Import("PrivateProperty")]
internal string InternalImportPrivateProperty { get; set; }
[Import("PrivateDelegate")]
internal Func<string> InternalImportPrivateMethod { get; set; }
[Import("PrivateIGetString")]
internal IGetString InternalImportPrivateNestedClass { get; set; }
public void VerifyIsBound()
{
Assert.Equal(PublicComponentWithPrivateExports.PrivateFieldExpectedValue, InternalImportPrivateField);
Assert.Equal(PublicComponentWithPrivateExports.PrivatePropertyExpectedValue, InternalImportPrivateProperty);
Assert.Equal(PublicComponentWithPrivateExports.PrivateMethodExpectedValue, InternalImportPrivateMethod());
Assert.Equal(PublicComponentWithPrivateExports.PrivateNestedClassExpectedValue, InternalImportPrivateNestedClass.GetString());
}
}
public class TestContractType
{
public const string TestContractName = "TestContractName";
}
public class TestContractTypeWithoutName { }
public class TypeDerivingFromTestContractType : TestContractType { }
[Export(typeof(TestContractType))]
public class ExportedTypeWithContractType { }
public class TypeDerivingFromExportedTypeWithContractType : ExportedTypeWithContractType { }
[Export("ImportDefaultFunctions")]
public class ImportDefaultFunctions
{
[Import("FunctionWith0Args")]
public Func<int> MyFunction0;
[Import("FunctionWith1Arg")]
public Func<int, int> MyFunction1;
[Import("FunctionWith2Args")]
public Func<int, int, int> MyFunction2;
[Import("FunctionWith3Args")]
public Func<int, int, int, int> MyFunction3;
[Import("FunctionWith4Args")]
public Func<int, int, int, int, int> MyFunction4;
[Import("ActionWith0Args")]
public Action MyAction0;
[Import("ActionWith1Arg")]
public Action<int> MyAction1;
[Import("ActionWith2Args")]
public Action<int, int> MyAction2;
[Import("ActionWith3Args")]
public Action<int, int, int> MyAction3;
[Import("ActionWith4Args")]
public Action<int, int, int, int> MyAction4;
public void VerifyIsBound()
{
Assert.Equal(0, MyFunction0.Invoke());
Assert.Equal(1, MyFunction1.Invoke(1));
Assert.Equal(3, MyFunction2.Invoke(1, 2));
Assert.Equal(6, MyFunction3.Invoke(1, 2, 3));
Assert.Equal(10, MyFunction4.Invoke(1, 2, 3, 4));
MyAction0.Invoke();
MyAction1.Invoke(1);
MyAction2.Invoke(1, 2);
MyAction3.Invoke(1, 2, 3);
MyAction4.Invoke(1, 2, 3, 4);
}
}
public class ExportDefaultFunctions
{
[Export("FunctionWith0Args")]
public int MyFunction0()
{
return 0;
}
[Export("FunctionWith1Arg")]
public int MyFunction1(int i1)
{
return i1;
}
[Export("FunctionWith2Args")]
public int MyFunction2(int i1, int i2)
{
return i1 + i2;
}
[Export("FunctionWith3Args")]
public int MyFunction3(int i1, int i2, int i3)
{
return i1 + i2 + i3;
}
[Export("FunctionWith4Args")]
public int MyFunction4(int i1, int i2, int i3, int i4)
{
return i1 + i2 + i3 + i4;
}
[Export("ActionWith0Args")]
public void MyAction0()
{
}
[Export("ActionWith1Arg")]
public void MyAction1(int i1)
{
Assert.Equal(1, i1);
}
[Export("ActionWith2Args")]
public void MyAction2(int i1, int i2)
{
Assert.Equal(1, i1);
Assert.Equal(2, i2);
}
[Export("ActionWith3Args")]
public void MyAction3(int i1, int i2, int i3)
{
Assert.Equal(1, i1);
Assert.Equal(2, i2);
Assert.Equal(3, i3);
}
[Export("ActionWith4Args")]
public void MyAction4(int i1, int i2, int i3, int i4)
{
Assert.Equal(1, i1);
Assert.Equal(2, i2);
Assert.Equal(3, i3);
Assert.Equal(4, i4);
}
}
[Export]
public class CatalogComponentTest
{
}
[Export]
[PartNotDiscoverable]
public class CatalogComponentTestNonComponentPart
{
}
public interface ICatalogComponentTest
{
}
[Export(typeof(ICatalogComponentTest))]
public class CatalogComponentInterfaceTest1 : ICatalogComponentTest
{
}
public class CatalogComponentInterfaceTest2
{
[Export]
public ICatalogComponentTest ExportedInterface
{
get { return new CatalogComponentInterfaceTest1(); }
}
}
public static class StaticExportClass
{
[Export("StaticString")]
public static string StaticString { get { return "StaticString"; } }
}
[Export]
public class DisposableExportClass : IDisposable
{
public bool IsDisposed { get; set; }
public void Dispose()
{
Assert.False(IsDisposed);
IsDisposed = true;
}
}
public interface IServiceView
{
int GetSomeInt();
}
[Export("service1")]
public class Service
{
public int GetSomeInt()
{
return 5;
}
}
public class Client
{
private IServiceView mySerivce;
[Import("service1")]
public IServiceView MyService
{
get { return mySerivce; }
set { mySerivce = value; }
}
public int GetSomeValue()
{
return MyService.GetSomeInt() * 2;
}
}
[Export]
public class TrivialExporter
{
public bool done = false;
}
[Export]
public class TrivialImporter : IPartImportsSatisfiedNotification
{
[Import]
public TrivialExporter checker;
public void OnImportsSatisfied()
{
checker.done = true;
}
}
[Export]
public class UnnamedImportAndExport
{
[Import]
public IUnnamedExport ImportedValue;
}
[Export]
public class StaticExport
{
}
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class NonStaticExport
{
}
public interface IUnnamedExport
{
}
[Export(typeof(IUnnamedExport))]
public class UnnamedExport : IUnnamedExport
{
}
public interface IExportableTest
{
string Var1 { get; }
}
[AttributeUsage(AttributeTargets.All)]
[MetadataAttribute]
public class ExportableTestAttribute : Attribute
{
private string var1;
public string Var1
{
get { return var1; }
set { var1 = value; }
}
}
[AttributeUsage(AttributeTargets.All)]
[MetadataAttribute]
public class MetadataWithCollectionPropertyAttribute : Attribute
{
private List<string> values;
public IEnumerable<string> Values
{
get { return values; }
}
public MetadataWithCollectionPropertyAttribute(params string[] values)
{
this.values = new List<string>(values);
}
}
[Export]
[MetadataWithCollectionProperty("One", "two", "3")]
[PartNotDiscoverable]
public class ComponentWithCollectionProperty
{
}
public interface ICollectionOfStrings
{
IEnumerable<string> Values { get; }
}
public class SubtractProvider
{
[Export("One")]
public int One = 1;
[Export("Two")]
public int Two { get { return 2; } }
[Export("Add")]
[ExportableTest(Var1 = "sub")]
public Func<int, int, int> Subtract = (x, y) => x - y;
}
public class RealAddProvider
{
[Export("One")]
public int One = 1;
[Export("Two")]
public int Two { get { return 2; } }
[Export("Add")]
[ExportMetadata("Var1", "add")]
public int Add(int x, int y)
{
return x + y;
}
}
public class Consumer
{
[Import("One")]
public int a;
[Import("Two")]
public int b;
[Import("Add")]
public Func<int, int, int> op;
[Import("Add", AllowDefault = true)]
public Lazy<Func<int, int, int>> opInfo;
}
public class ConsumerOfMultiple
{
[ImportMany("Add")]
public IEnumerable<Lazy<Func<int, int, int>>> opInfo;
}
public interface IStrongValueMetadata
{
int value { get; set; }
}
public class UntypedExportImporter
{
[Import("untyped")]
public Export Export;
}
public class UntypedExportsImporter
{
[ImportMany("untyped")]
public IEnumerable<Export> Exports;
}
public class DerivedExport : Export
{
}
public class DerivedExportImporter
{
[Import("derived")]
public DerivedExport Export;
}
public class DerivedExportsImporter
{
[ImportMany("derived")]
public IEnumerable<DerivedExport> Exports;
}
[Export]
public class NotSoUniqueName
{
public int MyIntProperty { get { return 23; } }
}
public class NotSoUniqueName2
{
[Export]
public class NotSoUniqueName
{
public virtual string MyStringProperty { get { return "MyStringProperty"; } }
}
}
[Export]
public class MyExport
{
}
[Export]
public class MySharedPartExport
{
[Import("Value", AllowRecomposition = true)]
public int Value { get; set; }
}
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class MyNonSharedPartExport
{
[Import("Value")]
public int Value { get; set; }
}
public class ExportThatCantBeActivated
{
[Export("ExportMyString")]
public string MyString { get { return "MyString"; } }
[Import("ContractThatShouldNotexist")]
public string MissingImport { get; set; }
}
public class GenericContract1<T>
{
public class GenericContract2
{
public class GenericContract3<N>
{
}
}
}
public class GenericContract4<T, K>
{
public class GenericContract5<A, B>
{
public class GenericContract6<N, M>
{
}
}
}
public class OuterClassWithGenericNested
{
public class GenericNested<T>
{
}
}
public class GenericContract7 :
GenericContract4<string, string>.GenericContract5<int, int>.GenericContract6<double, double>
{ }
public class GenericContract8<T> : GenericContract1<string>.GenericContract2.GenericContract3<T> { }
public class NestedParent
{
public class NestedChild { }
}
public class ImporterOfExporterNotifyPropertyChanged
{
[Import("value", AllowRecomposition = true)]
public int Value;
[Import("secondValue")]
public int SecondValue;
}
public class ExporterNotifyPropertyChanged : System.ComponentModel.INotifyPropertyChanged
{
int theValue = 42;
[Export("value")]
public int Value
{
get { return theValue; }
set
{
theValue = value;
FirePropertyChange("Value");
}
}
[Export("secondValue")]
public int second = 2;
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
public void FirePropertyChange(string prop)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(prop));
}
}
}
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class DirectCycleNonSharedPart
{
[Import]
public DirectCycleNonSharedPart NonSharedPart { get; set; }
}
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class CycleNonSharedPart1
{
[Import]
public CycleNonSharedPart2 NonSharedPart2 { get; set; }
}
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class CycleNonSharedPart2
{
[Import]
public CycleNonSharedPart1 NonSharedPart1 { get; set; }
}
[Export]
public class CycleNonSharedPart
{
[Import]
public CycleNonSharedPart1 NonSharedPart1 { get; set; }
}
[Export]
public class CycleSharedPart1
{
[Import]
public CycleSharedPart2 SharedPart2 { get; set; }
}
[Export]
public class CycleSharedPart2
{
[Import]
public CycleSharedPart1 SharedPart2 { get; set; }
}
[Export]
public class CycleSharedPart
{
[Import]
public CycleSharedPart1 SharedPart1 { get; set; }
[Import]
public CycleSharedPart2 SharedPart2 { get; set; }
}
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class NoCycleNonSharedPart
{
[Import]
public SharedPartWithNoCycleNonSharedPart SharedPart { get; set; }
}
[Export]
public class SharedPartWithNoCycleNonSharedPart
{
[Import]
public NoCycleNonSharedPart NonSharedPart { get; set; }
}
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class CycleWithSharedPartAndNonSharedPart
{
[Import]
public SharedPartWithNoCycleNonSharedPart BeforeNonSharedPart { get; set; }
[Import]
public CycleWithNonSharedPartOnly NonSharedPart { get; set; }
[Import]
public SharedPartWithNoCycleNonSharedPart SharedPart { get; set; }
}
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class CycleWithNonSharedPartOnly
{
[Import]
public CycleWithSharedPartAndNonSharedPart NonSharedPart { get; set; }
}
[InheritedExport]
public class ExportWithGenericParameter<T>
{
}
public class ExportWithGenericParameterOfInt
{
[Export]
public ExportWithGenericParameter<int> GenericExport { get { return new ExportWithGenericParameter<int>(); } }
}
[Export]
public static class StaticExportWithGenericParameter<T>
{
}
[Export]
public class ExportWhichInheritsFromGeneric : ExportWithGenericParameter<string>
{
}
[Export]
public class ExportWithExceptionDuringConstruction
{
public ExportWithExceptionDuringConstruction()
{
throw new NotImplementedException();
}
}
[Export]
public class SimpleConstructorInjectedObject
{
[ImportingConstructor]
public SimpleConstructorInjectedObject([Import("CISimpleValue")]int value)
{
CISimpleValue = value;
}
public int CISimpleValue { get; private set; }
}
[Export]
public class ClassWithNoMarkedOrDefaultConstructor
{
public ClassWithNoMarkedOrDefaultConstructor(int blah) { }
}
public class ClassWhichOnlyHasImportingConstructorWithOneArgument
{
[ImportingConstructor]
public ClassWhichOnlyHasImportingConstructorWithOneArgument(int blah) { }
}
public class ClassWhichOnlyHasImportingConstructor
{
[ImportingConstructor]
public ClassWhichOnlyHasImportingConstructor() { }
}
public class ClassWhichOnlyHasDefaultConstructor
{
public ClassWhichOnlyHasDefaultConstructor() { }
}
[Export]
public class BaseExportForImportingConstructors
{
}
public class ClassWithOnlyHasImportingConstructorButInherits : BaseExportForImportingConstructors
{
[ImportingConstructor]
public ClassWithOnlyHasImportingConstructorButInherits(int blah) { }
}
public class ClassWithOnlyHasMultipleImportingConstructorButInherits : BaseExportForImportingConstructors
{
[ImportingConstructor]
public ClassWithOnlyHasMultipleImportingConstructorButInherits(int blah) { }
[ImportingConstructor]
public ClassWithOnlyHasMultipleImportingConstructorButInherits(string blah) { }
}
[Export]
public class ClassWithMultipleMarkedConstructors
{
[ImportingConstructor]
public ClassWithMultipleMarkedConstructors(int i) { }
[ImportingConstructor]
public ClassWithMultipleMarkedConstructors(string s) { }
public ClassWithMultipleMarkedConstructors() { }
}
[Export]
public class ClassWithOneMarkedAndOneDefaultConstructor
{
[ImportingConstructor]
public ClassWithOneMarkedAndOneDefaultConstructor(int i) { }
public ClassWithOneMarkedAndOneDefaultConstructor() { }
}
[Export]
public class ClassWithTwoZeroParameterConstructors
{
public ClassWithTwoZeroParameterConstructors() { }
static ClassWithTwoZeroParameterConstructors() { }
}
[Export]
public class ExceptionDuringINotifyImport : IPartImportsSatisfiedNotification
{
[ImportMany("Value")]
public IEnumerable<int> ValuesJustUsedToGetImportCompletedCalled { get; set; }
public void OnImportsSatisfied()
{
throw new NotImplementedException();
}
}
[Export]
public class ClassWithOptionalPostImport
{
[Import(AllowDefault = true)]
public IFormattable Formatter { get; set; }
}
[Export]
public class ClassWithOptionalPreImport
{
[ImportingConstructor]
public ClassWithOptionalPreImport([Import(AllowDefault = true)] IFormattable formatter)
{
this.Formatter = formatter;
}
public IFormattable Formatter { get; private set; }
}
[MetadataAttribute]
public class ThisIsMyMetadataMetadataAttribute : Attribute
{
public string Argument1 { get; set; }
public int Argument2 { get; set; }
public double Argument3 { get; set; }
public string Argument4 { get; set; }
public ThisIsMyMetadataMetadataAttribute()
{
}
public ThisIsMyMetadataMetadataAttribute(string Argument1, int Argument2)
{
this.Argument1 = Argument1;
this.Argument2 = Argument2;
}
}
[Export]
[ThisIsMyMetadataMetadataAttribute("One", 2, Argument3 = 3.0)]
public class ExportedTypeWithConcreteMetadata
{
}
public class Int32CollectionImporter
{
public Int32CollectionImporter()
{
Values = new Collection<int>();
}
[ImportMany("Value")]
public Collection<int> Values { get; private set; }
}
[PartNotDiscoverable]
public class Int32Exporter
{
public Int32Exporter(int value)
{
Value = value;
}
[Export("Value")]
public int Value { get; set; }
}
[PartNotDiscoverable]
public class Int32ExporterInternal
{
public Int32ExporterInternal(int value)
{
Value = value;
}
[Export("Value")]
public int Value { get; set; }
}
public class Int32Importer
{
public Int32Importer()
{
}
[Import("Value", AllowRecomposition = true)]
public int Value { get; set; }
}
public class Int32ImporterInternal
{
public Int32ImporterInternal()
{
}
[Import("Value")]
public int Value { get; set; }
}
}
| |
/*
* 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.Redshift.Model
{
/// <summary>
/// Container for the parameters to the DescribeClusterSnapshots operation.
/// <para> Returns one or more snapshot objects, which contain metadata about your cluster snapshots. By default, this operation returns
/// information about all snapshots of all clusters that are owned by you AWS customer account. No information is returned for snapshots owned
/// by inactive AWS customer accounts. </para>
/// </summary>
/// <seealso cref="Amazon.Redshift.AmazonRedshift.DescribeClusterSnapshots"/>
public class DescribeClusterSnapshotsRequest : AmazonWebServiceRequest
{
private string clusterIdentifier;
private string snapshotIdentifier;
private string snapshotType;
private DateTime? startTime;
private DateTime? endTime;
private int? maxRecords;
private string marker;
private string ownerAccount;
/// <summary>
/// The identifier of the cluster for which information about snapshots is requested.
///
/// </summary>
public string ClusterIdentifier
{
get { return this.clusterIdentifier; }
set { this.clusterIdentifier = value; }
}
/// <summary>
/// Sets the ClusterIdentifier property
/// </summary>
/// <param name="clusterIdentifier">The value to set for the ClusterIdentifier 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 DescribeClusterSnapshotsRequest WithClusterIdentifier(string clusterIdentifier)
{
this.clusterIdentifier = clusterIdentifier;
return this;
}
// Check to see if ClusterIdentifier property is set
internal bool IsSetClusterIdentifier()
{
return this.clusterIdentifier != null;
}
/// <summary>
/// The snapshot identifier of the snapshot about which to return information.
///
/// </summary>
public string SnapshotIdentifier
{
get { return this.snapshotIdentifier; }
set { this.snapshotIdentifier = value; }
}
/// <summary>
/// Sets the SnapshotIdentifier property
/// </summary>
/// <param name="snapshotIdentifier">The value to set for the SnapshotIdentifier 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 DescribeClusterSnapshotsRequest WithSnapshotIdentifier(string snapshotIdentifier)
{
this.snapshotIdentifier = snapshotIdentifier;
return this;
}
// Check to see if SnapshotIdentifier property is set
internal bool IsSetSnapshotIdentifier()
{
return this.snapshotIdentifier != null;
}
/// <summary>
/// The type of snapshots for which you are requesting information. By default, snapshots of all types are returned. Valid Values:
/// <c>automated</c> | <c>manual</c>
///
/// </summary>
public string SnapshotType
{
get { return this.snapshotType; }
set { this.snapshotType = value; }
}
/// <summary>
/// Sets the SnapshotType property
/// </summary>
/// <param name="snapshotType">The value to set for the SnapshotType 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 DescribeClusterSnapshotsRequest WithSnapshotType(string snapshotType)
{
this.snapshotType = snapshotType;
return this;
}
// Check to see if SnapshotType property is set
internal bool IsSetSnapshotType()
{
return this.snapshotType != null;
}
/// <summary>
/// A value that requests only snapshots created at or after the specified time. The time value is specified in ISO 8601 format. For more
/// information about ISO 8601, go to the <a href="http://en.wikipedia.org/wiki/ISO_8601">ISO8601 Wikipedia page.</a> Example:
/// <c>2012-07-16T18:00:00Z</c>
///
/// </summary>
public DateTime StartTime
{
get { return this.startTime ?? default(DateTime); }
set { this.startTime = value; }
}
/// <summary>
/// Sets the StartTime property
/// </summary>
/// <param name="startTime">The value to set for the StartTime 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 DescribeClusterSnapshotsRequest WithStartTime(DateTime startTime)
{
this.startTime = startTime;
return this;
}
// Check to see if StartTime property is set
internal bool IsSetStartTime()
{
return this.startTime.HasValue;
}
/// <summary>
/// A time value that requests only snapshots created at or before the specified time. The time value is specified in ISO 8601 format. For more
/// information about ISO 8601, go to the <a href="http://en.wikipedia.org/wiki/ISO_8601">ISO8601 Wikipedia page.</a> Example:
/// <c>2012-07-16T18:00:00Z</c>
///
/// </summary>
public DateTime EndTime
{
get { return this.endTime ?? default(DateTime); }
set { this.endTime = value; }
}
/// <summary>
/// Sets the EndTime property
/// </summary>
/// <param name="endTime">The value to set for the EndTime 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 DescribeClusterSnapshotsRequest WithEndTime(DateTime endTime)
{
this.endTime = endTime;
return this;
}
// Check to see if EndTime property is set
internal bool IsSetEndTime()
{
return this.endTime.HasValue;
}
/// <summary>
/// The maximum number of snapshot records to include in the response. If more records exist than the specified <c>MaxRecords</c> value, the
/// response returns a marker that you can use in a subsequent <a>DescribeClusterSnapshots</a> request in order to retrieve the next set of
/// snapshot records. Default: <c>100</c> Constraints: Must be at least 20 and no more than 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 DescribeClusterSnapshotsRequest 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 by a previous <a>DescribeClusterSnapshots</a> request to indicate the first snapshot that the request will
/// return.
///
/// </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 DescribeClusterSnapshotsRequest WithMarker(string marker)
{
this.marker = marker;
return this;
}
// Check to see if Marker property is set
internal bool IsSetMarker()
{
return this.marker != null;
}
/// <summary>
/// The AWS customer account used to create or copy the snapshot. Use this field to filter the results to snapshots owned by a particular
/// account. To describe snapshots you own, either specify your AWS customer account, or do not specify the parameter.
///
/// </summary>
public string OwnerAccount
{
get { return this.ownerAccount; }
set { this.ownerAccount = value; }
}
/// <summary>
/// Sets the OwnerAccount property
/// </summary>
/// <param name="ownerAccount">The value to set for the OwnerAccount 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 DescribeClusterSnapshotsRequest WithOwnerAccount(string ownerAccount)
{
this.ownerAccount = ownerAccount;
return this;
}
// Check to see if OwnerAccount property is set
internal bool IsSetOwnerAccount()
{
return this.ownerAccount != null;
}
}
}
| |
#region License
/*
* Copyright (C) 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region Imports
using System;
using System.Collections.Generic;
using System.Collections;
#endregion
namespace Spring.Collections.Generic
{
/// <summary>
/// Serve as based class to be inherited by the classes that needs to
/// implement both the <see cref="IList{T}"/> and the <see cref="IList"/>
/// interfaces.
/// </summary>
/// <typeparam name="T">Element type of the collection</typeparam>
/// <author>Kenneth Xu</author>
[Serializable]
public abstract class AbstractList<T> : AbstractCollection<T>, IList<T>, IList
{
#region IList<T> Members
/// <summary>
/// Determines the index of a specific item in the <see cref="IList{T}"/>.
/// This implementation search the list by interating through the
/// enumerator returned by the <see cref="AbstractCollection{T}.GetEnumerator()"/>
/// method.
/// </summary>
///
/// <returns>
/// The index of item if found in the list; otherwise, -1.
/// </returns>
///
/// <param name="item">The object to locate in the <see cref="IList{T}"/>.
/// </param>
public virtual int IndexOf(T item)
{
int index = 0;
foreach (T t in this)
{
if (t.Equals(item)) return index;
index++;
}
return -1;
}
/// <summary>
/// Inserts an item to the <see cref="IList{T}"/> at the specified index.
/// This implementation always throw <see cref="NotSupportedException"/>.
/// </summary>
///
/// <param name="item">
/// The object to insert into the <see cref="IList{T}"/>.</param>
/// <param name="index">
/// The zero-based index at which item should be inserted.</param>
/// <exception cref="NotSupportedException">
/// The <see cref="IList{T}"/> is read-only.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// index is not a valid index in the <see cref="IList{T}"/>.
/// </exception>
public virtual void Insert(int index, T item)
{
throw new NotSupportedException();
}
/// <summary>
/// Removes the <see cref="IList{T}"/> item at the specified index.
/// This implementation always throw <see cref="NotSupportedException"/>.
/// </summary>
///
/// <param name="index">
/// The zero-based index of the item to remove.</param>
/// <exception cref="NotSupportedException">
/// The <see cref="IList{T}"/> is read-only.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// index is not a valid index in the <see cref="IList{T}"/>.
/// </exception>
public virtual void RemoveAt(int index)
{
throw new NotSupportedException();
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <remarks>
/// <para>
/// The implementation of getter search the list by interating through the
/// enumerator returned by the <see cref="AbstractCollection{T}.GetEnumerator"/> method.
/// </para>
/// <para>
/// The setter throws the <see cref="NotSupportedException"/>.
/// </para>
/// </remarks>
/// <returns>
/// The element at the specified index.
/// </returns>
///
/// <param name="index">
/// The zero-based index of the element to get or set.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// index is not a valid index in the <see cref="IList{T}"/>.</exception>
/// <exception cref="NotSupportedException">The property is set and the
/// <see cref="IList{T}"/> is read-only.</exception>
public virtual T this[int index]
{
get
{
if (index<0) throw new ArgumentOutOfRangeException(
"index", index, "cannot be less then zero.");
IEnumerator<T> e = GetEnumerator();
for(int i=0; i<=index; i++)
{
if (!e.MoveNext()) throw new ArgumentOutOfRangeException(
"index", index, "list has only " + i + " elements");
}
return e.Current;
}
set{ throw new NotSupportedException(); }
}
#endregion
#region IList Members
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.IList"></see>.
/// </summary>
///
/// <returns>
/// The position into which the new element was inserted.
/// </returns>
///
/// <param name="value">The <see cref="T:System.Object"></see> to add
/// to the <see cref="T:System.Collections.IList"></see>. </param>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.IList"></see> is read-only.
/// -or-
/// The <see cref="T:System.Collections.IList"></see> has a fixed size.
/// </exception>
/// <filterpriority>2</filterpriority>
int IList.Add(object value)
{
return NonGenericAdd(value);
}
///<summary>
///Determines whether the <see cref="T:System.Collections.IList"></see>
/// contains a specific value.
///</summary>
///
///<returns>
///true if the <see cref="T:System.Object"></see> is found in the
/// <see cref="T:System.Collections.IList"></see>; otherwise, false.
///</returns>
///
///<param name="value">
/// The <see cref="T:System.Object"></see> to locate in the
/// <see cref="T:System.Collections.IList"></see>.
/// </param>
/// <filterpriority>2</filterpriority>
bool IList.Contains(object value)
{
return NonGenericContains(value);
}
///<summary>
///Determines the index of a specific item in the
/// <see cref="T:System.Collections.IList"></see>.
///</summary>
///
///<returns>
///The index of value if found in the list; otherwise, -1.
///</returns>
///
///<param name="value">
/// The <see cref="T:System.Object"></see> to locate in the
/// <see cref="T:System.Collections.IList"></see>.
/// </param>
/// <filterpriority>2</filterpriority>
int IList.IndexOf(object value)
{
return NonGenericIndexOf(value);
}
///<summary>
///Inserts an item to the <see cref="T:System.Collections.IList"></see>
/// at the specified index.
///</summary>
///
///<param name="value">
/// The <see cref="T:System.Object"></see> to insert into the
/// <see cref="T:System.Collections.IList"></see>.
/// </param>
///<param name="index">
/// The zero-based index at which value should be inserted.
/// </param>
///<exception cref="T:System.ArgumentOutOfRangeException">
/// index is not a valid index in the <see cref="T:System.Collections.IList"></see>.
/// </exception>
///<exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.IList"></see> is read-only.
/// -or-
/// The <see cref="T:System.Collections.IList"></see> has a fixed size.
/// </exception>
///<exception cref="T:System.NullReferenceException">
/// value is null reference in the <see cref="T:System.Collections.IList"></see>.
/// </exception>
/// <filterpriority>2</filterpriority>
void IList.Insert(int index, object value)
{
NonGenericInsert(index, value);
}
///<summary>
///Gets a value indicating whether the
/// <see cref="T:System.Collections.IList"></see>
/// has a fixed size.
///</summary>
///<remarks>Calls <see cref="IsFixedSize"/>.</remarks>
///<returns>
///true if the <see cref="T:System.Collections.IList"></see>
/// has a fixed size; otherwise, false.
///</returns>
///<filterpriority>2</filterpriority>
bool IList.IsFixedSize
{
get
{
return IsFixedSize;
}
}
///<summary>
///Removes the first occurrence of a specific object from
/// the <see cref="T:System.Collections.IList"></see>.
///</summary>
///
///<param name="value">
/// The <see cref="T:System.Object"></see> to remove from the
/// <see cref="T:System.Collections.IList"></see>.
/// </param>
///<exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.IList"></see> is read-only.
/// -or-
/// The <see cref="T:System.Collections.IList"></see> has a fixed size.
/// </exception>
/// <filterpriority>2</filterpriority>
void IList.Remove(object value)
{
NonGenericRemove(value);
}
///<summary>
///Gets or sets the element at the specified index.
///</summary>
///
///<returns>
///The element at the specified index.
///</returns>
///
///<param name="index">
/// The zero-based index of the element to get or set.
/// </param>
///<exception cref="T:System.ArgumentOutOfRangeException">
/// index is not a valid index in the <see cref="IList"></see>.
/// </exception>
///<exception cref="T:System.NotSupportedException">
/// The property is set and the <see cref="T:System.Collections.IList"></see>
/// is read-only.
/// </exception>
/// <filterpriority>2</filterpriority>
object IList.this[int index]
{
get { return NonGenericIndexerGet(index); }
set { NonGenericIndexerSet(index, value); }
}
#endregion
#region Protected Methods
/// <summary>
/// Called by implicit implementation of <see cref="IList.IsFixedSize"/>.
/// This implementation always return <c>false</c>.
/// </summary>
protected virtual bool IsFixedSize
{
get
{
return false;
}
}
#endregion
#region Non Generic Implementations - reserved to protect for sub class can override if necessary
private int NonGenericAdd(object value)
{
int index = Count;
Insert(index, (T)value);
return index;
}
private bool NonGenericContains(object value)
{
return value is T && Contains((T)value);
}
private int NonGenericIndexOf(object value)
{
return value is T ? IndexOf((T)value) : -1;
}
private void NonGenericInsert(int index, object value)
{
Insert(index, (T)value);
}
private void NonGenericRemove(object value)
{
if (value is T) Remove((T)value);
}
private object NonGenericIndexerGet(int index)
{
return this[index];
}
private void NonGenericIndexerSet(int index, object value)
{
this[index] = (T)value;
}
#endregion
}
}
| |
namespace StockSharp.Algo.Storages
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Reflection;
using StockSharp.Messages;
/// <summary>
/// Security native identifier storage.
/// </summary>
public interface INativeIdStorage
{
/// <summary>
/// Initialize the storage.
/// </summary>
void Init();
/// <summary>
/// Get native security identifiers for storage.
/// </summary>
/// <param name="name">Storage name.</param>
/// <returns>Security identifiers.</returns>
Tuple<SecurityId, object>[] Get(string name);
/// <summary>
/// Try add native security identifier to storage.
/// </summary>
/// <param name="name">Storage name.</param>
/// <param name="securityId">Security identifier.</param>
/// <param name="nativeId">Native (internal) trading system security id.</param>
/// <param name="isPersistable">Save the identifier as a permanent.</param>
/// <returns><see langword="true"/> if native identifier was added. Otherwise, <see langword="false" />.</returns>
bool TryAdd(string name, SecurityId securityId, object nativeId, bool isPersistable = true);
/// <summary>
/// Try get security identifier by native identifier.
/// </summary>
/// <param name="name">Storage name.</param>
/// <param name="nativeId">Native (internal) trading system security id.</param>
/// <returns>Security identifier.</returns>
SecurityId? TryGetByNativeId(string name, object nativeId);
/// <summary>
/// Try get native security identifier by identifier.
/// </summary>
/// <param name="name">Storage name.</param>
/// <param name="securityId">Security identifier.</param>
/// <returns>Native (internal) trading system security id.</returns>
object TryGetBySecurityId(string name, SecurityId securityId);
}
/// <summary>
/// CSV security native identifier storage.
/// </summary>
public sealed class CsvNativeIdStorage : INativeIdStorage
{
private readonly SyncObject _sync = new SyncObject();
private readonly Dictionary<string, PairSet<SecurityId, object>> _nativeIds = new Dictionary<string, PairSet<SecurityId, object>>(StringComparer.InvariantCultureIgnoreCase);
private readonly string _path;
/// <summary>
/// Initializes a new instance of the <see cref="CsvNativeIdStorage"/>.
/// </summary>
/// <param name="path">Path to storage.</param>
public CsvNativeIdStorage(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
_path = path.ToFullPath();
}
/// <summary>
/// Initialize the storage.
/// </summary>
public void Init()
{
if (!Directory.Exists(_path))
Directory.CreateDirectory(_path);
var files = Directory.GetFiles(_path, "*.csv");
var errors = new List<Exception>();
foreach (var fileName in files)
{
try
{
LoadFile(fileName);
}
catch (Exception ex)
{
errors.Add(ex);
}
}
if (errors.Count > 0)
throw new AggregateException(errors);
}
/// <summary>
/// Get native security identifiers for storage.
/// </summary>
/// <param name="name">Storage name.</param>
/// <returns>Security identifiers.</returns>
public Tuple<SecurityId, object>[] Get(string name)
{
if (name.IsEmpty())
throw new ArgumentNullException(nameof(name));
lock (_sync)
{
var nativeIds = _nativeIds.TryGetValue(name);
if (nativeIds == null)
return ArrayHelper.Empty<Tuple<SecurityId, object>>();
return nativeIds.Select(p => Tuple.Create(p.Key, p.Value)).ToArray();
}
}
/// <summary>
/// Try add native security identifier to storage.
/// </summary>
/// <param name="name">Storage name.</param>
/// <param name="securityId">Security identifier.</param>
/// <param name="nativeId">Native (internal) trading system security id.</param>
/// <param name="isPersistable">Save the identifier as a permanent.</param>
/// <returns><see langword="true"/> if native identifier was added. Otherwise, <see langword="false" />.</returns>
public bool TryAdd(string name, SecurityId securityId, object nativeId, bool isPersistable)
{
if (name.IsEmpty())
throw new ArgumentNullException(nameof(name));
if (nativeId == null)
throw new ArgumentNullException(nameof(nativeId));
lock (_sync)
{
var nativeIds = _nativeIds.SafeAdd(name);
var added = nativeIds.TryAdd(securityId, nativeId);
if (!added)
return false;
}
if (isPersistable)
Save(name, securityId, nativeId);
return true;
}
/// <summary>
/// Try get security identifier by native identifier.
/// </summary>
/// <param name="name">Storage name.</param>
/// <param name="nativeId">Native (internal) trading system security id.</param>
/// <returns>Security identifier.</returns>
public SecurityId? TryGetByNativeId(string name, object nativeId)
{
if (name.IsEmpty())
throw new ArgumentNullException(nameof(name));
lock (_sync)
{
var nativeIds = _nativeIds.TryGetValue(name);
if (nativeIds == null)
return null;
SecurityId securityId;
if (!nativeIds.TryGetKey(nativeId, out securityId))
return null;
return securityId;
}
}
/// <summary>
/// Try get native security identifier by identifier.
/// </summary>
/// <param name="name">Storage name.</param>
/// <param name="securityId">Security identifier.</param>
/// <returns>Native (internal) trading system security id.</returns>
public object TryGetBySecurityId(string name, SecurityId securityId)
{
if (name.IsEmpty())
throw new ArgumentNullException(nameof(name));
lock (_sync)
return _nativeIds.TryGetValue(name)?.TryGetValue(securityId);
}
private void Save(string name, SecurityId securityId, object nativeId)
{
CultureInfo.InvariantCulture.DoInCulture(() =>
{
var fileName = Path.Combine(_path, name + ".csv");
var appendHeader = !File.Exists(fileName);
using (var stream = new FileStream(fileName, FileMode.Append, FileAccess.Write))
using (var writer = new CsvFileWriter(stream))
{
var nativeIdType = nativeId.GetType();
var typleType = nativeIdType.GetGenericType(typeof(Tuple<,>));
if (appendHeader)
{
if (typleType == null)
{
writer.WriteRow(new[]
{
"Symbol",
"Board",
GetTypeName(nativeIdType),
});
}
else
{
dynamic tuple = nativeId;
writer.WriteRow(new[]
{
"Symbol",
"Board",
GetTypeName((Type)tuple.Item1.GetType()),
GetTypeName((Type)tuple.Item2.GetType()),
});
}
}
if (typleType == null)
{
writer.WriteRow(new[]
{
securityId.SecurityCode,
securityId.BoardCode,
nativeId.ToString()
});
}
else
{
dynamic tuple = nativeId;
writer.WriteRow(new[]
{
securityId.SecurityCode,
securityId.BoardCode,
(string)tuple.Item1.ToString(),
(string)tuple.Item2.ToString()
});
}
}
});
}
private static string GetTypeName(Type nativeIdType)
{
return Converter.GetAlias(nativeIdType) ?? nativeIdType.GetTypeName(false);
}
private void LoadFile(string fileName)
{
CultureInfo.InvariantCulture.DoInCulture(() =>
{
if (!File.Exists(fileName))
return;
var name = Path.GetFileNameWithoutExtension(fileName);
var pairs = new List<Tuple<SecurityId, object>>();
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
var reader = new FastCsvReader(stream, Encoding.UTF8);
reader.NextLine();
reader.Skip(2);
var type1 = reader.ReadString().To<Type>();
var type2 = reader.ReadString().To<Type>();
var isTuple = type2 != null;
while (reader.NextLine())
{
var securityId = new SecurityId
{
SecurityCode = reader.ReadString(),
BoardCode = reader.ReadString()
};
var nativeId = reader.ReadString().To(type1);
if (isTuple)
{
var nativeId2 = reader.ReadString().To(type2);
nativeId = typeof(Tuple<,>).MakeGenericType(type1, type2).CreateInstance(new[] { nativeId, nativeId2 });
}
pairs.Add(Tuple.Create(securityId, nativeId));
}
}
lock (_sync)
{
var nativeIds = _nativeIds.SafeAdd(name);
foreach (var tuple in pairs)
{
nativeIds.Add(tuple.Item1, tuple.Item2);
}
}
});
}
}
/// <summary>
/// In memory security native identifier storage.
/// </summary>
public class InMemoryNativeIdStorage : INativeIdStorage
{
private readonly SynchronizedDictionary<string, PairSet<SecurityId, object>> _nativeIds = new SynchronizedDictionary<string, PairSet<SecurityId, object>>(StringComparer.InvariantCultureIgnoreCase);
void INativeIdStorage.Init()
{
}
bool INativeIdStorage.TryAdd(string name, SecurityId securityId, object nativeId, bool isPersistable)
{
if (name.IsEmpty())
throw new ArgumentNullException(nameof(name));
if (nativeId == null)
throw new ArgumentNullException(nameof(nativeId));
lock (_nativeIds.SyncRoot)
return _nativeIds.SafeAdd(name).TryAdd(securityId, nativeId);
}
object INativeIdStorage.TryGetBySecurityId(string name, SecurityId securityId)
{
if (name.IsEmpty())
throw new ArgumentNullException(nameof(name));
lock (_nativeIds.SyncRoot)
return _nativeIds.TryGetValue(name)?.TryGetValue(securityId);
}
SecurityId? INativeIdStorage.TryGetByNativeId(string name, object nativeId)
{
if (name.IsEmpty())
throw new ArgumentNullException(nameof(name));
var securityId = default(SecurityId);
lock (_nativeIds.SyncRoot)
{
if (_nativeIds.TryGetValue(name)?.TryGetKey(nativeId, out securityId) != true)
return null;
}
return securityId;
}
Tuple<SecurityId, object>[] INativeIdStorage.Get(string name)
{
if (name.IsEmpty())
throw new ArgumentNullException(nameof(name));
lock (_nativeIds.SyncRoot)
return _nativeIds.TryGetValue(name)?.Select(p => Tuple.Create(p.Key, p.Value)).ToArray() ?? ArrayHelper.Empty<Tuple<SecurityId, object>>();
}
}
}
| |
// 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.Xml
{
public class UniqueId
{
private long _idLow;
private long _idHigh;
private string _s;
private const int guidLength = 16;
private const int uuidLength = 45;
private static readonly short[] s_char2val = new short[256]
{
/* 0-15 */
0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 16-31 */
0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 32-47 */
0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 48-63 */
0x000, 0x010, 0x020, 0x030, 0x040, 0x050, 0x060, 0x070, 0x080, 0x090, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 64-79 */
0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 80-95 */
0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 96-111 */
0x100, 0x0A0, 0x0B0, 0x0C0, 0x0D0, 0x0E0, 0x0F0, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 112-127 */
0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 0-15 */
0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 16-31 */
0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 32-47 */
0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 48-63 */
0x000, 0x001, 0x002, 0x003, 0x004, 0x005, 0x006, 0x007, 0x008, 0x009, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 64-79 */
0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 80-95 */
0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 96-111 */
0x100, 0x00A, 0x00B, 0x00C, 0x00D, 0x00E, 0x00F, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
/* 112-127 */
0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100, 0x100,
};
private const string val2char = "0123456789abcdef";
public UniqueId() : this(Guid.NewGuid())
{
}
public UniqueId(Guid guid) : this(guid.ToByteArray())
{
}
public UniqueId(byte[] guid) : this(guid, 0)
{
}
public unsafe UniqueId(byte[] guid, int offset)
{
if (guid == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(guid)));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > guid.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, guid.Length)));
if (guidLength > guid.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlArrayTooSmallInput, guidLength), nameof(guid)));
fixed (byte* pb = &guid[offset])
{
_idLow = UnsafeGetInt64(pb);
_idHigh = UnsafeGetInt64(&pb[8]);
}
}
public unsafe UniqueId(string value)
{
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value));
if (value.Length == 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.XmlInvalidUniqueId));
fixed (char* pch = value)
{
UnsafeParse(pch, value.Length);
}
_s = value;
}
public unsafe UniqueId(char[] chars, int offset, int count)
{
if (chars == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars)));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > chars.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - offset)));
if (count == 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.XmlInvalidUniqueId));
fixed (char* pch = &chars[offset])
{
UnsafeParse(pch, count);
}
if (!IsGuid)
{
_s = new string(chars, offset, count);
}
}
public int CharArrayLength
{
get
{
if (_s != null)
return _s.Length;
return uuidLength;
}
}
private unsafe int UnsafeDecode(short* char2val, char ch1, char ch2)
{
if ((ch1 | ch2) >= 0x80)
return 0x100;
return char2val[ch1] | char2val[0x80 + ch2];
}
private unsafe void UnsafeEncode(char* val2char, byte b, char* pch)
{
pch[0] = val2char[b >> 4];
pch[1] = val2char[b & 0x0F];
}
public bool IsGuid => ((_idLow | _idHigh) != 0);
private unsafe void UnsafeParse(char* chars, int charCount)
{
// 1 2 3 4
// 012345678901234567890123456789012345678901234
// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
if (charCount != uuidLength ||
chars[0] != 'u' || chars[1] != 'r' || chars[2] != 'n' || chars[3] != ':' ||
chars[4] != 'u' || chars[5] != 'u' || chars[6] != 'i' || chars[7] != 'd' || chars[8] != ':' ||
chars[17] != '-' || chars[22] != '-' || chars[27] != '-' || chars[32] != '-')
{
return;
}
byte* bytes = stackalloc byte[guidLength];
int i = 0;
int j = 0;
fixed (short* ps = &s_char2val[0])
{
short* _char2val = ps;
// 0 1 2 3 4
// 012345678901234567890123456789012345678901234
// urn:uuid:aabbccdd-eeff-gghh-0011-223344556677
//
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
// ddccbbaaffeehhgg0011223344556677
i = UnsafeDecode(_char2val, chars[15], chars[16]); bytes[0] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[13], chars[14]); bytes[1] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[11], chars[12]); bytes[2] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[9], chars[10]); bytes[3] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[20], chars[21]); bytes[4] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[18], chars[19]); bytes[5] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[25], chars[26]); bytes[6] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[23], chars[24]); bytes[7] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[28], chars[29]); bytes[8] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[30], chars[31]); bytes[9] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[33], chars[34]); bytes[10] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[35], chars[36]); bytes[11] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[37], chars[38]); bytes[12] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[39], chars[40]); bytes[13] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[41], chars[42]); bytes[14] = (byte)i; j |= i;
i = UnsafeDecode(_char2val, chars[43], chars[44]); bytes[15] = (byte)i; j |= i;
if (j >= 0x100)
return;
_idLow = UnsafeGetInt64(bytes);
_idHigh = UnsafeGetInt64(&bytes[8]);
}
}
public unsafe int ToCharArray(char[] chars, int offset)
{
int count = CharArrayLength;
if (chars == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars)));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (count > chars.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(chars), SR.Format(SR.XmlArrayTooSmallOutput, count)));
if (_s != null)
{
_s.CopyTo(0, chars, offset, count);
}
else
{
byte* bytes = stackalloc byte[guidLength];
UnsafeSetInt64(_idLow, bytes);
UnsafeSetInt64(_idHigh, &bytes[8]);
fixed (char* _pch = &chars[offset])
{
char* pch = _pch;
pch[0] = 'u';
pch[1] = 'r';
pch[2] = 'n';
pch[3] = ':';
pch[4] = 'u';
pch[5] = 'u';
pch[6] = 'i';
pch[7] = 'd';
pch[8] = ':';
pch[17] = '-';
pch[22] = '-';
pch[27] = '-';
pch[32] = '-';
fixed (char* ps = val2char)
{
char* _val2char = ps;
UnsafeEncode(_val2char, bytes[0], &pch[15]);
UnsafeEncode(_val2char, bytes[1], &pch[13]);
UnsafeEncode(_val2char, bytes[2], &pch[11]);
UnsafeEncode(_val2char, bytes[3], &pch[9]);
UnsafeEncode(_val2char, bytes[4], &pch[20]);
UnsafeEncode(_val2char, bytes[5], &pch[18]);
UnsafeEncode(_val2char, bytes[6], &pch[25]);
UnsafeEncode(_val2char, bytes[7], &pch[23]);
UnsafeEncode(_val2char, bytes[8], &pch[28]);
UnsafeEncode(_val2char, bytes[9], &pch[30]);
UnsafeEncode(_val2char, bytes[10], &pch[33]);
UnsafeEncode(_val2char, bytes[11], &pch[35]);
UnsafeEncode(_val2char, bytes[12], &pch[37]);
UnsafeEncode(_val2char, bytes[13], &pch[39]);
UnsafeEncode(_val2char, bytes[14], &pch[41]);
UnsafeEncode(_val2char, bytes[15], &pch[43]);
}
}
}
return count;
}
public bool TryGetGuid(out Guid guid)
{
byte[] buffer = new byte[guidLength];
if (!TryGetGuid(buffer, 0))
{
guid = Guid.Empty;
return false;
}
guid = new Guid(buffer);
return true;
}
public unsafe bool TryGetGuid(byte[] buffer, int offset)
{
if (!IsGuid)
return false;
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer)));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > buffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, buffer.Length)));
if (guidLength > buffer.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(buffer), SR.Format(SR.XmlArrayTooSmallOutput, guidLength)));
fixed (byte* pb = &buffer[offset])
{
UnsafeSetInt64(_idLow, pb);
UnsafeSetInt64(_idHigh, &pb[8]);
}
return true;
}
public unsafe override string ToString()
{
if (_s == null)
{
int length = CharArrayLength;
char[] chars = new char[length];
ToCharArray(chars, 0);
_s = new string(chars, 0, length);
}
return _s;
}
public static bool operator ==(UniqueId id1, UniqueId id2)
{
if (object.ReferenceEquals(id1, id2))
return true;
if (object.ReferenceEquals(id1, null) || object.ReferenceEquals(id2, null))
return false;
#pragma warning suppress 56506 // Microsoft, checks for whether id1 and id2 are null done above.
if (id1.IsGuid && id2.IsGuid)
{
return id1._idLow == id2._idLow && id1._idHigh == id2._idHigh;
}
return id1.ToString() == id2.ToString();
}
public static bool operator !=(UniqueId id1, UniqueId id2)
{
return !(id1 == id2);
}
public override bool Equals(object obj)
{
return this == (obj as UniqueId);
}
public override int GetHashCode()
{
if (IsGuid)
{
long hash = (_idLow ^ _idHigh);
return ((int)(hash >> 32)) ^ ((int)hash);
}
else
{
return ToString().GetHashCode();
}
}
private unsafe long UnsafeGetInt64(byte* pb)
{
int idLow = UnsafeGetInt32(pb);
int idHigh = UnsafeGetInt32(&pb[4]);
return (((long)idHigh) << 32) | ((uint)idLow);
}
private unsafe int UnsafeGetInt32(byte* pb)
{
int value = pb[3];
value <<= 8;
value |= pb[2];
value <<= 8;
value |= pb[1];
value <<= 8;
value |= pb[0];
return value;
}
private unsafe void UnsafeSetInt64(long value, byte* pb)
{
UnsafeSetInt32((int)value, pb);
UnsafeSetInt32((int)(value >> 32), &pb[4]);
}
private unsafe void UnsafeSetInt32(int value, byte* pb)
{
pb[0] = (byte)value;
value >>= 8;
pb[1] = (byte)value;
value >>= 8;
pb[2] = (byte)value;
value >>= 8;
pb[3] = (byte)value;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using MailGun.Models;
using MailGun.Models.AccountViewModels;
using MailGun.Services;
using System.Net.Http;
using System.Security.Authentication;
namespace MailGun.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(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
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 https://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);
try
{
await _emailSender.SendEmailAsync(model.Email,
"Confirm your account",
$"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
}
catch (Exception ex)
{
Console.WriteLine(
"Error: Failed to send out email to {0}:\n{1}.",
model.Email,
ex.Message
);
}
// await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return RedirectToLocal(returnUrl);
}
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 Challenge(properties, provider);
}
//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
return View(nameof(Login));
}
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.Principal.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 (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 https://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);
try
{
await _emailSender.SendEmailAsync(model.Email,
"Reset Password",
$"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
}
catch (Exception ex)
{
Console.WriteLine(
"Error: Failed to send recovery email to {0}:\n{1}.",
model.Email,
ex.Message
);
}
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(string.Empty, "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 Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
#endregion
}
}
| |
#region BSD License
/*
Copyright (c) 2004 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com)
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.
* The name of the author may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using Prebuild.Core.Attributes;
using Prebuild.Core.Interfaces;
using Prebuild.Core.Nodes;
using Prebuild.Core.Utilities;
namespace Prebuild.Core.Targets
{
/// <summary>
///
/// </summary>
[Target("xcode")]
public class XcodeTarget : ITarget
{
#region Fields
private Kernel m_Kernel;
#endregion
#region Private Methods
private static string PrependPath(string path)
{
string tmpPath = Helper.NormalizePath(path, '/');
Regex regex = new Regex(@"(\w):/(\w+)");
Match match = regex.Match(tmpPath);
//if(match.Success || tmpPath[0] == '.' || tmpPath[0] == '/')
//{
tmpPath = Helper.NormalizePath(tmpPath);
//}
// else
// {
// tmpPath = Helper.NormalizePath("./" + tmpPath);
// }
return tmpPath;
}
private static string BuildReference(SolutionNode solution, ReferenceNode refr)
{
string ret = "";
if (solution.ProjectsTable.ContainsKey(refr.Name))
{
ProjectNode project = (ProjectNode)solution.ProjectsTable[refr.Name];
string fileRef = FindFileReference(refr.Name, project);
string finalPath = Helper.NormalizePath(Helper.MakeFilePath(project.FullPath + "/${build.dir}/", refr.Name, "dll"), '/');
ret += finalPath;
return ret;
}
else
{
ProjectNode project = (ProjectNode)refr.Parent;
string fileRef = FindFileReference(refr.Name, project);
if (refr.Path != null || fileRef != null)
{
string finalPath = (refr.Path != null) ? Helper.NormalizePath(refr.Path + "/" + refr.Name + ".dll", '/') : fileRef;
ret += finalPath;
return ret;
}
try
{
//Assembly assem = Assembly.Load(refr.Name);
//if (assem != null)
//{
//ret += (refr.Name + ".dll");
//}
//else
//{
ret += (refr.Name + ".dll");
//}
}
catch (System.NullReferenceException e)
{
e.ToString();
ret += refr.Name + ".dll";
}
}
return ret;
}
private static string BuildReferencePath(SolutionNode solution, ReferenceNode refr)
{
string ret = "";
if (solution.ProjectsTable.ContainsKey(refr.Name))
{
ProjectNode project = (ProjectNode)solution.ProjectsTable[refr.Name];
string fileRef = FindFileReference(refr.Name, project);
string finalPath = Helper.NormalizePath(Helper.MakeReferencePath(project.FullPath + "/${build.dir}/"), '/');
ret += finalPath;
return ret;
}
else
{
ProjectNode project = (ProjectNode)refr.Parent;
string fileRef = FindFileReference(refr.Name, project);
if (refr.Path != null || fileRef != null)
{
string finalPath = (refr.Path != null) ? Helper.NormalizePath(refr.Path, '/') : fileRef;
ret += finalPath;
return ret;
}
try
{
Assembly assem = Assembly.Load(refr.Name);
if (assem != null)
{
ret += "";
}
else
{
ret += "";
}
}
catch (System.NullReferenceException e)
{
e.ToString();
ret += "";
}
}
return ret;
}
private static string FindFileReference(string refName, ProjectNode project)
{
foreach (ReferencePathNode refPath in project.ReferencePaths)
{
string fullPath = Helper.MakeFilePath(refPath.Path, refName, "dll");
if (File.Exists(fullPath))
{
return fullPath;
}
}
return null;
}
/// <summary>
/// Gets the XML doc file.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="conf">The conf.</param>
/// <returns></returns>
public static string GetXmlDocFile(ProjectNode project, ConfigurationNode conf)
{
if (conf == null)
{
throw new ArgumentNullException("conf");
}
if (project == null)
{
throw new ArgumentNullException("project");
}
string docFile = (string)conf.Options["XmlDocFile"];
// if(docFile != null && docFile.Length == 0)//default to assembly name if not specified
// {
// return Path.GetFileNameWithoutExtension(project.AssemblyName) + ".xml";
// }
return docFile;
}
private void WriteProject(SolutionNode solution, ProjectNode project)
{
string projFile = Helper.MakeFilePath(project.FullPath, project.Name + (project.Type == ProjectType.Library ? ".dll" : ".exe"), "build");
StreamWriter ss = new StreamWriter(projFile);
m_Kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(projFile));
bool hasDoc = false;
using (ss)
{
ss.WriteLine("<?xml version=\"1.0\" ?>");
ss.WriteLine("<project name=\"{0}\" default=\"build\">", project.Name);
ss.WriteLine(" <target name=\"{0}\">", "build");
ss.WriteLine(" <echo message=\"Build Directory is ${project::get-base-directory()}/${build.dir}\" />");
ss.WriteLine(" <mkdir dir=\"${project::get-base-directory()}/${build.dir}\" />");
ss.WriteLine(" <copy todir=\"${project::get-base-directory()}/${build.dir}\">");
ss.WriteLine(" <fileset basedir=\"${project::get-base-directory()}\">");
foreach (ReferenceNode refr in project.References)
{
if (refr.LocalCopy)
{
ss.WriteLine(" <include name=\"{0}", Helper.NormalizePath(Helper.MakePathRelativeTo(project.FullPath, BuildReference(solution, refr)) + "\" />", '/'));
}
}
ss.WriteLine(" </fileset>");
ss.WriteLine(" </copy>");
ss.Write(" <csc");
ss.Write(" target=\"{0}\"", project.Type.ToString().ToLower());
ss.Write(" debug=\"{0}\"", "${build.debug}");
foreach (ConfigurationNode conf in project.Configurations)
{
if (conf.Options.KeyFile != "")
{
ss.Write(" keyfile=\"{0}\"", conf.Options.KeyFile);
break;
}
}
foreach (ConfigurationNode conf in project.Configurations)
{
ss.Write(" unsafe=\"{0}\"", conf.Options.AllowUnsafe);
break;
}
foreach (ConfigurationNode conf in project.Configurations)
{
ss.Write(" define=\"{0}\"", conf.Options.CompilerDefines);
break;
}
foreach (ConfigurationNode conf in project.Configurations)
{
if (GetXmlDocFile(project, conf) != "")
{
ss.Write(" doc=\"{0}\"", "${project::get-base-directory()}/${build.dir}/" + GetXmlDocFile(project, conf));
hasDoc = true;
}
break;
}
ss.Write(" output=\"{0}", "${project::get-base-directory()}/${build.dir}/${project::get-name()}");
if (project.Type == ProjectType.Library)
{
ss.Write(".dll\"");
}
else
{
ss.Write(".exe\"");
}
if (project.AppIcon != null && project.AppIcon.Length != 0)
{
ss.Write(" win32icon=\"{0}\"", Helper.NormalizePath(project.AppIcon, '/'));
}
ss.WriteLine(">");
ss.WriteLine(" <resources prefix=\"{0}\" dynamicprefix=\"true\" >", project.RootNamespace);
foreach (string file in project.Files)
{
switch (project.Files.GetBuildAction(file))
{
case BuildAction.EmbeddedResource:
ss.WriteLine(" {0}", "<include name=\"" + Helper.NormalizePath(PrependPath(file), '/') + "\" />");
break;
default:
if (project.Files.GetSubType(file) != SubType.Code && project.Files.GetSubType(file) != SubType.Settings)
{
ss.WriteLine(" <include name=\"{0}\" />", file.Substring(0, file.LastIndexOf('.')) + ".resx");
}
break;
}
}
//if (project.Files.GetSubType(file).ToString() != "Code")
//{
// ps.WriteLine(" <EmbeddedResource Include=\"{0}\">", file.Substring(0, file.LastIndexOf('.')) + ".resx");
ss.WriteLine(" </resources>");
ss.WriteLine(" <sources failonempty=\"true\">");
foreach (string file in project.Files)
{
switch (project.Files.GetBuildAction(file))
{
case BuildAction.Compile:
ss.WriteLine(" <include name=\"" + Helper.NormalizePath(PrependPath(file), '/') + "\" />");
break;
default:
break;
}
}
ss.WriteLine(" </sources>");
ss.WriteLine(" <references basedir=\"${project::get-base-directory()}\">");
ss.WriteLine(" <lib>");
ss.WriteLine(" <include name=\"${project::get-base-directory()}\" />");
ss.WriteLine(" <include name=\"${project::get-base-directory()}/${build.dir}\" />");
ss.WriteLine(" </lib>");
foreach (ReferenceNode refr in project.References)
{
ss.WriteLine(" <include name=\"{0}", Helper.NormalizePath(Helper.MakePathRelativeTo(project.FullPath, BuildReference(solution, refr)) + "\" />", '/'));
}
ss.WriteLine(" </references>");
ss.WriteLine(" </csc>");
ss.WriteLine(" </target>");
ss.WriteLine(" <target name=\"clean\">");
ss.WriteLine(" <delete dir=\"${bin.dir}\" failonerror=\"false\" />");
ss.WriteLine(" <delete dir=\"${obj.dir}\" failonerror=\"false\" />");
ss.WriteLine(" </target>");
ss.WriteLine(" <target name=\"doc\" description=\"Creates documentation.\">");
if (hasDoc)
{
ss.WriteLine(" <property name=\"doc.target\" value=\"\" />");
ss.WriteLine(" <if test=\"${platform::is-unix()}\">");
ss.WriteLine(" <property name=\"doc.target\" value=\"Web\" />");
ss.WriteLine(" </if>");
ss.WriteLine(" <ndoc failonerror=\"false\" verbose=\"true\">");
ss.WriteLine(" <assemblies basedir=\"${project::get-base-directory()}\">");
ss.Write(" <include name=\"${build.dir}/${project::get-name()}");
if (project.Type == ProjectType.Library)
{
ss.WriteLine(".dll\" />");
}
else
{
ss.WriteLine(".exe\" />");
}
ss.WriteLine(" </assemblies>");
ss.WriteLine(" <summaries basedir=\"${project::get-base-directory()}\">");
ss.WriteLine(" <include name=\"${build.dir}/${project::get-name()}.xml\"/>");
ss.WriteLine(" </summaries>");
ss.WriteLine(" <referencepaths basedir=\"${project::get-base-directory()}\">");
ss.WriteLine(" <include name=\"${build.dir}\" />");
// foreach(ReferenceNode refr in project.References)
// {
// string path = Helper.NormalizePath(Helper.MakePathRelativeTo(project.FullPath, BuildReferencePath(solution, refr)), '/');
// if (path != "")
// {
// ss.WriteLine(" <include name=\"{0}\" />", path);
// }
// }
ss.WriteLine(" </referencepaths>");
ss.WriteLine(" <documenters>");
ss.WriteLine(" <documenter name=\"MSDN\">");
ss.WriteLine(" <property name=\"OutputDirectory\" value=\"${project::get-base-directory()}/${build.dir}/doc/${project::get-name()}\" />");
ss.WriteLine(" <property name=\"OutputTarget\" value=\"${doc.target}\" />");
ss.WriteLine(" <property name=\"HtmlHelpName\" value=\"${project::get-name()}\" />");
ss.WriteLine(" <property name=\"IncludeFavorites\" value=\"False\" />");
ss.WriteLine(" <property name=\"Title\" value=\"${project::get-name()} SDK Documentation\" />");
ss.WriteLine(" <property name=\"SplitTOCs\" value=\"False\" />");
ss.WriteLine(" <property name=\"DefaulTOC\" value=\"\" />");
ss.WriteLine(" <property name=\"ShowVisualBasic\" value=\"True\" />");
ss.WriteLine(" <property name=\"AutoDocumentConstructors\" value=\"True\" />");
ss.WriteLine(" <property name=\"ShowMissingSummaries\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"ShowMissingRemarks\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"ShowMissingParams\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"ShowMissingReturns\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"ShowMissingValues\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"DocumentInternals\" value=\"False\" />");
ss.WriteLine(" <property name=\"DocumentPrivates\" value=\"False\" />");
ss.WriteLine(" <property name=\"DocumentProtected\" value=\"True\" />");
ss.WriteLine(" <property name=\"DocumentEmptyNamespaces\" value=\"${build.debug}\" />");
ss.WriteLine(" <property name=\"IncludeAssemblyVersion\" value=\"True\" />");
ss.WriteLine(" </documenter>");
ss.WriteLine(" </documenters>");
ss.WriteLine(" </ndoc>");
}
ss.WriteLine(" </target>");
ss.WriteLine("</project>");
}
m_Kernel.CurrentWorkingDirectory.Pop();
}
private void WriteCombine(SolutionNode solution)
{
m_Kernel.Log.Write("Creating Xcode build files");
foreach (ProjectNode project in solution.Projects)
{
if (m_Kernel.AllowProject(project.FilterGroups))
{
m_Kernel.Log.Write("...Creating project: {0}", project.Name);
WriteProject(solution, project);
}
}
m_Kernel.Log.Write("");
DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(solution.FullPath, solution.Name + ".xcodeproj"));
if (!directoryInfo.Exists)
{
directoryInfo.Create();
}
string combFile = Helper.MakeFilePath(Path.Combine(solution.FullPath, solution.Name + ".xcodeproj"), "project", "pbxproj");
StreamWriter ss = new StreamWriter(combFile);
m_Kernel.CurrentWorkingDirectory.Push();
Helper.SetCurrentDir(Path.GetDirectoryName(combFile));
using (ss)
{
ss.WriteLine("<?xml version=\"1.0\" ?>");
ss.WriteLine("<project name=\"{0}\" default=\"build\">", solution.Name);
ss.WriteLine(" <echo message=\"Using '${nant.settings.currentframework}' Framework\"/>");
ss.WriteLine();
//ss.WriteLine(" <property name=\"dist.dir\" value=\"dist\" />");
//ss.WriteLine(" <property name=\"source.dir\" value=\"source\" />");
ss.WriteLine(" <property name=\"bin.dir\" value=\"bin\" />");
ss.WriteLine(" <property name=\"obj.dir\" value=\"obj\" />");
ss.WriteLine(" <property name=\"doc.dir\" value=\"doc\" />");
ss.WriteLine(" <property name=\"project.main.dir\" value=\"${project::get-base-directory()}\" />");
foreach (ConfigurationNode conf in solution.Configurations)
{
// Set the project.config to a non-debug configuration
if (conf.Options["DebugInformation"].ToString().ToLower() != "true")
{
ss.WriteLine(" <property name=\"project.config\" value=\"{0}\" />", conf.Name);
}
ss.WriteLine();
ss.WriteLine(" <target name=\"{0}\" description=\"\">", conf.Name);
ss.WriteLine(" <property name=\"project.config\" value=\"{0}\" />", conf.Name);
ss.WriteLine(" <property name=\"build.debug\" value=\"{0}\" />", conf.Options["DebugInformation"].ToString().ToLower());
ss.WriteLine(" </target>");
ss.WriteLine();
}
ss.WriteLine(" <target name=\"net-1.1\" description=\"Sets framework to .NET 1.1\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"net-1.1\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"net-2.0\" description=\"Sets framework to .NET 2.0\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"net-2.0\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"mono-2.0\" description=\"Sets framework to mono 2.0\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"mono-2.0\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"mono-1.0\" description=\"Sets framework to mono 1.0\">");
ss.WriteLine(" <property name=\"nant.settings.currentframework\" value=\"mono-1.0\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"init\" description=\"\">");
ss.WriteLine(" <call target=\"${project.config}\" />");
ss.WriteLine(" <sysinfo />");
ss.WriteLine(" <echo message=\"Platform ${sys.os.platform}\" />");
ss.WriteLine(" <property name=\"build.dir\" value=\"${bin.dir}/${project.config}\" />");
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"clean\" description=\"\">");
ss.WriteLine(" <echo message=\"Deleting all builds from all configurations\" />");
//ss.WriteLine(" <delete dir=\"${dist.dir}\" failonerror=\"false\" />");
ss.WriteLine(" <delete dir=\"${bin.dir}\" failonerror=\"false\" />");
ss.WriteLine(" <delete dir=\"${obj.dir}\" failonerror=\"false\" />");
//foreach(ProjectNode project in solution.Projects)
//{
// string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
// ss.Write(" <nant buildfile=\"{0}\"",
// Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + (project.Type == ProjectType.Library ? ".dll" : ".exe"), "build"),'/'));
// ss.WriteLine(" target=\"clean\" />");
//}
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"build\" depends=\"init\" description=\"\">");
foreach (ProjectNode project in solution.ProjectsTableOrder)
{
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.Write(" <nant buildfile=\"{0}\"",
Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + (project.Type == ProjectType.Library ? ".dll" : ".exe"), "build"), '/'));
ss.WriteLine(" target=\"build\" />");
}
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine(" <target name=\"build-release\" depends=\"Release, init, build\" description=\"Builds in Release mode\" />");
ss.WriteLine();
ss.WriteLine(" <target name=\"build-debug\" depends=\"Debug, init, build\" description=\"Builds in Debug mode\" />");
ss.WriteLine();
//ss.WriteLine(" <target name=\"package\" depends=\"clean, doc, copyfiles, zip\" description=\"Builds in Release mode\" />");
ss.WriteLine(" <target name=\"package\" depends=\"clean, doc\" description=\"Builds all\" />");
ss.WriteLine();
ss.WriteLine(" <target name=\"doc\" depends=\"build-release\">");
ss.WriteLine(" <echo message=\"Generating all documentation from all builds\" />");
foreach (ProjectNode project in solution.Projects)
{
string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
ss.Write(" <nant buildfile=\"{0}\"",
Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + (project.Type == ProjectType.Library ? ".dll" : ".exe"), "build"), '/'));
ss.WriteLine(" target=\"doc\" />");
}
ss.WriteLine(" </target>");
ss.WriteLine();
ss.WriteLine("</project>");
}
m_Kernel.CurrentWorkingDirectory.Pop();
}
private void CleanProject(ProjectNode project)
{
m_Kernel.Log.Write("...Cleaning project: {0}", project.Name);
string projectFile = Helper.MakeFilePath(project.FullPath, project.Name + (project.Type == ProjectType.Library ? ".dll" : ".exe"), "build");
Helper.DeleteIfExists(projectFile);
}
private void CleanSolution(SolutionNode solution)
{
m_Kernel.Log.Write("Cleaning Xcode build files for", solution.Name);
string slnFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "build");
Helper.DeleteIfExists(slnFile);
foreach (ProjectNode project in solution.Projects)
{
CleanProject(project);
}
m_Kernel.Log.Write("");
}
#endregion
#region ITarget Members
/// <summary>
/// Writes the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public void Write(Kernel kern)
{
if (kern == null)
{
throw new ArgumentNullException("kern");
}
m_Kernel = kern;
foreach (SolutionNode solution in kern.Solutions)
{
WriteCombine(solution);
}
m_Kernel = null;
}
/// <summary>
/// Cleans the specified kern.
/// </summary>
/// <param name="kern">The kern.</param>
public virtual void Clean(Kernel kern)
{
if (kern == null)
{
throw new ArgumentNullException("kern");
}
m_Kernel = kern;
foreach (SolutionNode sol in kern.Solutions)
{
CleanSolution(sol);
}
m_Kernel = null;
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get
{
return "xcode";
}
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Spatial;
using System.Diagnostics;
using System.Globalization;
using System.Web.Compilation;
using System.Web.Hosting;
using System.Web.UI.WebControls;
namespace System.Web.DynamicData {
/// <summary>
/// Default implementation of IFieldTemplateFactory. It uses user controls for the field templates.
/// </summary>
public class FieldTemplateFactory : IFieldTemplateFactory {
private const string IntegerField = "Integer";
private const string ForeignKeyField = "ForeignKey";
private const string ChildrenField = "Children";
private const string ManyToManyField = "ManyToMany";
private const string EnumerationField = "Enumeration";
private const string EditModePathModifier = "_Edit";
private const string InsertModePathModifier = "_Insert";
private Dictionary<Type, string> _typesToTemplateNames;
private Dictionary<Type, Type> _typesFallBacks;
private TemplateFactory _templateFactory;
/// <summary>
/// </summary>
public FieldTemplateFactory() {
InitTypesToTemplateNamesTable();
BuildTypeFallbackTable();
_templateFactory = new TemplateFactory("FieldTemplates");
}
// For unit test purpose
internal FieldTemplateFactory(VirtualPathProvider vpp)
: this() {
_templateFactory.VirtualPathProvider = vpp;
}
/// <summary>
/// Sets the folder containing the user controls. By default, this is ~/DynamicData/FieldTemplates/
/// </summary>
public string TemplateFolderVirtualPath {
get {
return _templateFactory.TemplateFolderVirtualPath;
}
set {
_templateFactory.TemplateFolderVirtualPath = value;
}
}
/// <summary>
/// The MetaModel that the factory is associated with
/// </summary>
public MetaModel Model {
get {
return _templateFactory.Model;
}
private set {
_templateFactory.Model = value;
}
}
private void InitTypesToTemplateNamesTable() {
_typesToTemplateNames = new Dictionary<Type, string>();
_typesToTemplateNames[typeof(int)] = FieldTemplateFactory.IntegerField;
_typesToTemplateNames[typeof(string)] = DataType.Text.ToString();
}
private void BuildTypeFallbackTable() {
_typesFallBacks = new Dictionary<Type, Type>();
_typesFallBacks[typeof(float)] = typeof(decimal);
_typesFallBacks[typeof(double)] = typeof(decimal);
_typesFallBacks[typeof(Int16)] = typeof(int);
_typesFallBacks[typeof(byte)] = typeof(int);
_typesFallBacks[typeof(long)] = typeof(int);
// Fall back to strings for most types
_typesFallBacks[typeof(char)] = typeof(string);
_typesFallBacks[typeof(int)] = typeof(string);
_typesFallBacks[typeof(decimal)] = typeof(string);
_typesFallBacks[typeof(Guid)] = typeof(string);
_typesFallBacks[typeof(DateTime)] = typeof(string);
_typesFallBacks[typeof(DateTimeOffset)] = typeof(string);
_typesFallBacks[typeof(TimeSpan)] = typeof(string);
_typesFallBacks[typeof(DbGeography)] = typeof(string);
_typesFallBacks[typeof(DbGeometry)] = typeof(string);
//
}
private Type GetFallBackType(Type t) {
// Check if there is a fallback type
Type fallbackType;
if (_typesFallBacks.TryGetValue(t, out fallbackType))
return fallbackType;
return null;
}
// Internal for unit test purpose
internal string GetFieldTemplateVirtualPathWithCaching(MetaColumn column, DataBoundControlMode mode, string uiHint) {
// Compute a cache key based on all the input paramaters
long cacheKey = Misc.CombineHashCodes(uiHint, column, mode);
Func<string> templatePathFactoryFunction = () => GetFieldTemplateVirtualPath(column, mode, uiHint);
return _templateFactory.GetTemplatePath(cacheKey, templatePathFactoryFunction);
}
/// <summary>
/// Returns the virtual path of the field template user control to be used, based on various pieces of data
/// </summary>
/// <param name="column">The MetaColumn for which the field template is needed</param>
/// <param name="mode">The mode (Readonly, Edit, Insert) for which the field template is needed</param>
/// <param name="uiHint">The UIHint (if any) that should affect the field template lookup</param>
/// <returns></returns>
public virtual string GetFieldTemplateVirtualPath(MetaColumn column, DataBoundControlMode mode, string uiHint) {
mode = PreprocessMode(column, mode);
bool hasDataTypeAttribute = column != null && column.DataTypeAttribute != null;
// Set the UIHint in some special cases, but don't do it if we already have one or
// if we have a DataTypeAttribute
if (String.IsNullOrEmpty(uiHint) && !hasDataTypeAttribute) {
// Check if it's an association
// Or if it is an enum
if (column is MetaForeignKeyColumn) {
uiHint = FieldTemplateFactory.ForeignKeyField;
} else if (column is MetaChildrenColumn) {
var childrenColumn = (MetaChildrenColumn)column;
if (childrenColumn.IsManyToMany) {
uiHint = FieldTemplateFactory.ManyToManyField;
}
else {
uiHint = FieldTemplateFactory.ChildrenField;
}
} else if (column.ColumnType.IsEnum) {
uiHint = FieldTemplateFactory.EnumerationField;
}
}
return GetVirtualPathWithModeFallback(uiHint, column, mode);
}
/// <summary>
/// Gets a chance to change the mode. e.g. an Edit mode request can be turned into ReadOnly mode
/// if the column is a primary key
/// </summary>
public virtual DataBoundControlMode PreprocessMode(MetaColumn column, DataBoundControlMode mode) {
if (column == null) {
throw new ArgumentNullException("column");
}
// Primary keys can't be edited, so put them in readonly mode. Note that this
// does not apply to Insert mode, which is fine
if (column.IsPrimaryKey && mode == DataBoundControlMode.Edit) {
mode = DataBoundControlMode.ReadOnly;
}
// Generated columns should never be editable/insertable
if (column.IsGenerated) {
mode = DataBoundControlMode.ReadOnly;
}
// ReadOnly columns cannot be edited nor inserted, and are always in Display mode
if (column.IsReadOnly) {
if (mode == DataBoundControlMode.Insert && column.AllowInitialValue) {
// but don't change the mode if we're in insert and an initial value is allowed
} else {
mode = DataBoundControlMode.ReadOnly;
}
}
// If initial value is not allowed set mode to ReadOnly
if (mode == DataBoundControlMode.Insert && !column.AllowInitialValue) {
mode = DataBoundControlMode.ReadOnly;
}
if (column is MetaForeignKeyColumn) {
// If the foreign key is part of the primary key (e.g. Order and Product in Order_Details table),
// change the mode to ReadOnly so that they can't be edited.
if (mode == DataBoundControlMode.Edit && ((MetaForeignKeyColumn)column).IsPrimaryKeyInThisTable) {
mode = DataBoundControlMode.ReadOnly;
}
}
return mode;
}
private string GetVirtualPathWithModeFallback(string templateName, MetaColumn column, DataBoundControlMode mode) {
// Try not only the requested mode, but others if needed. Basically:
// - an edit template can default to an item template
// - an insert template can default to an edit template, then to an item template
for (var currentMode = mode; currentMode >= 0; currentMode--) {
string virtualPath = GetVirtualPathForMode(templateName, column, currentMode);
if (virtualPath != null)
return virtualPath;
}
// We couldn't locate any field template at all, so give up
return null;
}
private string GetVirtualPathForMode(string templateName, MetaColumn column, DataBoundControlMode mode) {
// If we got a template name, try it
if (!String.IsNullOrEmpty(templateName)) {
string virtualPath = GetVirtualPathIfExists(templateName, column, mode);
if (virtualPath != null)
return virtualPath;
}
// Otherwise, use the column's type
return GetVirtualPathForTypeWithFallback(column.ColumnType, column, mode);
}
private string GetVirtualPathForTypeWithFallback(Type fieldType, MetaColumn column, DataBoundControlMode mode) {
string templateName;
string virtualPath;
// If we have a data type attribute
if (column.DataTypeAttribute != null) {
templateName = column.DataTypeAttribute.GetDataTypeName();
// Try to get the path from it
virtualPath = GetVirtualPathIfExists(templateName, column, mode);
if (virtualPath != null)
return virtualPath;
}
// Try the actual fully qualified type name (i.e. with the namespace)
virtualPath = GetVirtualPathIfExists(fieldType.FullName, column, mode);
if (virtualPath != null)
return virtualPath;
// Try the simple type name
virtualPath = GetVirtualPathIfExists(fieldType.Name, column, mode);
if (virtualPath != null)
return virtualPath;
// If our type name table has an entry for it, try it
if (_typesToTemplateNames.TryGetValue(fieldType, out templateName)) {
virtualPath = GetVirtualPathIfExists(templateName, column, mode);
if (virtualPath != null)
return virtualPath;
}
// Check if there is a fallback type
Type fallbackType = GetFallBackType(fieldType);
// If not, we've run out of options
if (fallbackType == null)
return null;
// If so, try it
return GetVirtualPathForTypeWithFallback(fallbackType, column, mode);
}
private string GetVirtualPathIfExists(string templateName, MetaColumn column, DataBoundControlMode mode) {
// Build the path
string virtualPath = BuildVirtualPath(templateName, column, mode);
// Check if it exists
if (_templateFactory.FileExists(virtualPath))
return virtualPath;
// If not, return null
return null;
}
/// <summary>
/// Build the virtual path to the field template user control based on the template name and mode.
/// By default, it returns names that look like TemplateName_ModeName.ascx, in the folder specified
/// by TemplateFolderVirtualPath.
/// </summary>
/// <param name="templateName"></param>
/// <param name="column"></param>
/// <param name="mode"></param>
/// <returns></returns>
public virtual string BuildVirtualPath(string templateName, MetaColumn column, DataBoundControlMode mode) {
if (String.IsNullOrEmpty(templateName)) {
throw new ArgumentNullException("templateName");
}
string modePathModifier = null;
switch (mode) {
case DataBoundControlMode.ReadOnly:
modePathModifier = String.Empty;
break;
case DataBoundControlMode.Edit:
modePathModifier = FieldTemplateFactory.EditModePathModifier;
break;
case DataBoundControlMode.Insert:
modePathModifier = FieldTemplateFactory.InsertModePathModifier;
break;
default:
Debug.Assert(false);
break;
}
return String.Format(CultureInfo.InvariantCulture,
TemplateFolderVirtualPath + "{0}{1}.ascx", templateName, modePathModifier);
}
#region IFieldTemplateFactory Members
public virtual void Initialize(MetaModel model) {
Model = model;
}
/// <summary>
/// See IFieldTemplateFactory for details.
/// </summary>
/// <returns></returns>
public virtual IFieldTemplate CreateFieldTemplate(MetaColumn column, DataBoundControlMode mode, string uiHint) {
string fieldTemplatePath = GetFieldTemplateVirtualPathWithCaching(column, mode, uiHint);
if (fieldTemplatePath == null)
return null;
return (IFieldTemplate)BuildManager.CreateInstanceFromVirtualPath(
fieldTemplatePath, typeof(IFieldTemplate));
}
#endregion
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Revision: 374175 $
* $LastChangedDate: 2006-04-26 22:12:57 +0200 (mer., 26 avr. 2006) $
* $LastChangedBy: gbayon $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2006/2005 - The Apache Software Foundation
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using IBatisNet.Common;
using IBatisNet.DataMapper.Exceptions;
namespace IBatisNet.DataMapper.Commands
{
/// <summary>
/// An implementation of <see cref="IDataReader"/> that will copy the contents
/// of the an open <see cref="IDataReader"/> to an in-memory <see cref="InMemoryDataReader"/> if the
/// session <see cref="IDbProvider"/> doesn't allow multiple open <see cref="IDataReader"/> with
/// the same <see cref="IDbConnection"/>.
/// </summary>
public class InMemoryDataReader : IDataReader
{
private int _currentRowIndex = 0;
private int _currentResultIndex = 0;
private bool _isClosed = false;
private InMemoryResultSet[] _results = null;
/// <summary>
/// Creates an InMemoryDataReader from a <see cref="IDataReader" />
/// </summary>
/// <param name="reader">The <see cref="IDataReader" /> which holds the records from the Database.</param>
public InMemoryDataReader(IDataReader reader)
{
ArrayList resultList = new ArrayList();
try
{
_currentResultIndex = 0;
_currentRowIndex = 0;
resultList.Add(new InMemoryResultSet(reader, true));
while (reader.NextResult())
{
resultList.Add(new InMemoryResultSet(reader, false));
}
_results = (InMemoryResultSet[])resultList.ToArray(typeof(InMemoryResultSet));
}
catch (Exception e)
{
throw new DataMapperException("There was a problem converting an IDataReader to an InMemoryDataReader", e);
}
finally
{
reader.Close();
reader.Dispose();
}
}
#region IDataReader Members
/// <summary>
/// Gets the number of rows changed, inserted, or deleted by execution of the SQL statement.
/// </summary>
public int RecordsAffected
{
get { throw new NotImplementedException("InMemoryDataReader only used for select IList statements !"); }
}
/// <summary>
/// Gets a value indicating whether the data reader is closed.
/// </summary>
public bool IsClosed
{
get { return _isClosed; }
}
/// <summary>
/// Advances the data reader to the next result, when reading the results of batch SQL statements.
/// </summary>
/// <returns></returns>
public bool NextResult()
{
_currentResultIndex++;
if (_currentResultIndex >= _results.Length)
{
_currentResultIndex--;
return false;
}
return true;
}
/// <summary>
/// Closes the IDataReader 0bject.
/// </summary>
public void Close()
{
_isClosed = true;
}
/// <summary>
/// Advances the IDataReader to the next record.
/// </summary>
/// <returns>true if there are more rows; otherwise, false.</returns>
public bool Read()
{
_currentRowIndex++;
if (_currentRowIndex >= _results[_currentResultIndex].RecordCount)
{
_currentRowIndex--;
return false;
}
return true;
}
/// <summary>
/// Gets a value indicating the depth of nesting for the current row.
/// </summary>
public int Depth
{
get { return _currentResultIndex; }
}
/// <summary>
/// Returns a DataTable that describes the column metadata of the IDataReader.
/// </summary>
/// <returns></returns>
public DataTable GetSchemaTable()
{
throw new NotImplementedException("GetSchemaTable() is not implemented, cause not use.");
}
#endregion
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
_isClosed = true;
_results = null;
}
#endregion
#region IDataRecord Members
/// <summary>
/// Gets the 32-bit signed integer value of the specified field.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public int GetInt32(int fieldIndex)
{
return (int)GetValue(fieldIndex);
}
/// <summary>
/// Gets the column with the specified name.
/// </summary>
public object this[string name]
{
get { return this[GetOrdinal(name)]; }
}
/// <summary>
/// Gets the column located at the specified index.
/// </summary>
public object this[int fieldIndex]
{
get { return GetValue(fieldIndex); }
}
/// <summary>
/// Return the value of the specified field.
/// </summary>
/// <param name="fieldIndex">The index of the field to find. </param>
/// <returns>The object which will contain the field value upon return.</returns>
public object GetValue(int fieldIndex)
{
return this.CurrentResultSet.GetValue(_currentRowIndex, fieldIndex);
}
/// <summary>
/// Return whether the specified field is set to null.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public bool IsDBNull(int fieldIndex)
{
return (GetValue(fieldIndex) == DBNull.Value);
}
/// <summary>
/// Reads a stream of bytes from the specified column offset into the buffer as an array,
/// starting at the given buffer offset.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <param name="dataIndex">The index within the field from which to begin the read operation. </param>
/// <param name="buffer">The buffer into which to read the stream of bytes. </param>
/// <param name="bufferIndex">The index for buffer to begin the read operation.</param>
/// <param name="length">The number of bytes to read. </param>
/// <returns>The actual number of bytes read.</returns>
public long GetBytes(int fieldIndex, long dataIndex, byte[] buffer, int bufferIndex, int length)
{
object value = GetValue(fieldIndex);
if (!(value is byte[]))
{
throw new InvalidCastException("Type is " + value.GetType().ToString());
}
if (buffer == null)
{
// Return length of data
return ((byte[])value).Length;
}
else
{
// Copy data into buffer
int availableLength = (int)(((byte[])value).Length - dataIndex);
if (availableLength < length)
{
length = availableLength;
}
Array.Copy((byte[])value, (int)dataIndex, buffer, bufferIndex, length);
return length;
}
}
/// <summary>
/// Gets the 8-bit unsigned integer value of the specified column.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public byte GetByte(int fieldIndex)
{
return (byte)GetValue(fieldIndex);
}
/// <summary>
/// Gets the Type information corresponding to the type of Object that would be returned from GetValue.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public Type GetFieldType(int fieldIndex)
{
return this.CurrentResultSet.GetFieldType(fieldIndex);
}
/// <summary>
/// Gets the fixed-position numeric value of the specified field.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public decimal GetDecimal(int fieldIndex)
{
return (decimal)GetValue(fieldIndex);
}
/// <summary>
/// Gets all the attribute fields in the collection for the current record.
/// </summary>
/// <param name="values"></param>
/// <returns></returns>
public int GetValues(object[] values)
{
return this.CurrentResultSet.GetValues(_currentRowIndex, values);
}
/// <summary>
/// Gets the name for the field to find.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public string GetName(int fieldIndex)
{
return this.CurrentResultSet.GetName(fieldIndex);
}
/// <summary>
/// Indicates the number of fields within the current record. This property is read-only.
/// </summary>
public int FieldCount
{
get { return this.CurrentResultSet.FieldCount; }
}
/// <summary>
///
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public long GetInt64(int fieldIndex)
{
return (long)GetValue(fieldIndex);
}
/// <summary>
///
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public double GetDouble(int fieldIndex)
{
return (double)GetValue(fieldIndex);
}
/// <summary>
/// Gets the value of the specified column as a Boolean.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public bool GetBoolean(int fieldIndex)
{
return (bool)GetValue(fieldIndex);
}
/// <summary>
/// Returns the GUID value of the specified field.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public Guid GetGuid(int fieldIndex)
{
return (Guid)GetValue(fieldIndex);
}
/// <summary>
/// Returns the value of the specified column as a DateTime object.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public DateTime GetDateTime(int fieldIndex)
{
return (DateTime)GetValue(fieldIndex);
}
/// <summary>
/// Returns the column ordinal, given the name of the column.
/// </summary>
/// <param name="colName">The name of the column. </param>
/// <returns>The value of the column.</returns>
public int GetOrdinal(string colName)
{
return this.CurrentResultSet.GetOrdinal(colName);
}
/// <summary>
/// Gets the database type information for the specified field.
/// </summary>
/// <param name="fieldIndex">The index of the field to find.</param>
/// <returns>The database type information for the specified field.</returns>
public string GetDataTypeName(int fieldIndex)
{
return this.CurrentResultSet.GetDataTypeName(fieldIndex);
}
/// <summary>
/// Returns the value of the specified column as a single-precision floating point number.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public float GetFloat(int fieldIndex)
{
return (float)GetValue(fieldIndex);
}
/// <summary>
/// Gets an IDataReader to be used when the field points to more remote structured data.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public IDataReader GetData(int fieldIndex)
{
throw new NotImplementedException("GetData(int) is not implemented, cause not use.");
}
/// <summary>
/// Reads a stream of characters from the specified column offset into the buffer as an array,
/// starting at the given buffer offset.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <param name="dataIndex">The index within the row from which to begin the read operation.</param>
/// <param name="buffer">The buffer into which to read the stream of bytes.</param>
/// <param name="bufferIndex">The index for buffer to begin the read operation. </param>
/// <param name="length">The number of bytes to read.</param>
/// <returns>The actual number of characters read.</returns>
public long GetChars(int fieldIndex, long dataIndex, char[] buffer, int bufferIndex, int length)
{
object value = GetValue(fieldIndex);
char[] valueBuffer = null;
if (value is char[])
{
valueBuffer = (char[])value;
}
else if (value is string)
{
valueBuffer = ((string)value).ToCharArray();
}
else
{
throw new InvalidCastException("Type is " + value.GetType().ToString());
}
if (buffer == null)
{
// Return length of data
return valueBuffer.Length;
}
else
{
// Copy data into buffer
Array.Copy(valueBuffer, (int)dataIndex, buffer, bufferIndex, length);
return valueBuffer.Length - dataIndex;
}
}
/// <summary>
/// Gets the string value of the specified field.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public string GetString(int fieldIndex)
{
return (string)GetValue(fieldIndex);
}
/// <summary>
/// Gets the character value of the specified column.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public char GetChar(int fieldIndex)
{
return (char)GetValue(fieldIndex);
}
/// <summary>
/// Gets the 16-bit signed integer value of the specified field.
/// </summary>
/// <param name="fieldIndex">The zero-based column ordinal. </param>
/// <returns>The value of the column.</returns>
public short GetInt16(int fieldIndex)
{
return (short)GetValue(fieldIndex);
}
#endregion
/// <summary>
/// Gets the current result set.
/// </summary>
/// <value>The current result set.</value>
private InMemoryResultSet CurrentResultSet
{
get { return _results[_currentResultIndex]; }
}
/// <summary>
/// Represent an in-memory result set
/// </summary>
private class InMemoryResultSet
{
// [row][column]
private readonly object[][] _records = null;
private int _fieldCount = 0;
private string[] _fieldsName = null;
private Type[] _fieldsType = null;
StringDictionary _fieldsNameLookup = new StringDictionary();
private string[] _dataTypeName = null;
/// <summary>
/// Creates an in-memory ResultSet from a <see cref="IDataReader" />
/// </summary>
/// <param name="isMidstream">
/// <c>true</c> if the <see cref="IDataReader"/> is already positioned on the record
/// to start reading from.
/// </param>
/// <param name="reader">The <see cref="IDataReader" /> which holds the records from the Database.</param>
public InMemoryResultSet(IDataReader reader, bool isMidstream)
{
// [record index][ columns values=object[ ] ]
ArrayList recordsList = new ArrayList();
_fieldCount = reader.FieldCount;
_fieldsName = new string[_fieldCount];
_fieldsType = new Type[_fieldCount];
_dataTypeName = new string[_fieldCount];
bool firstRow = true;
// if we are in the middle of processing the reader then don't bother
// to move to the next record - just use the current one.
// Copy the records in memory
while (isMidstream || reader.Read())
{
if (firstRow)
{
for (int fieldIndex = 0; fieldIndex < reader.FieldCount; fieldIndex++)
{
string fieldName = reader.GetName(fieldIndex);
_fieldsName[fieldIndex] = fieldName;
if (!_fieldsNameLookup.ContainsKey(fieldName))
{
_fieldsNameLookup.Add(fieldName, fieldIndex.ToString());
}
_fieldsType[fieldIndex] = reader.GetFieldType(fieldIndex);
_dataTypeName[fieldIndex] = reader.GetDataTypeName(fieldIndex);
}
}
firstRow = false;
object[] columnsValues = new object[_fieldCount];
reader.GetValues(columnsValues);
recordsList.Add(columnsValues);
isMidstream = false;
}
_records = (object[][])recordsList.ToArray(typeof(object[]));
}
/// <summary>
/// Gets the number of columns in the current row.
/// </summary>
/// <value>The number of columns in the current row.</value>
public int FieldCount
{
get { return _fieldCount; }
}
/// <summary>
/// Get a column value in a row
/// </summary>
/// <param name="rowIndex">The row index</param>
/// <param name="colIndex">The column index</param>
/// <returns>The column value</returns>
public object GetValue(int rowIndex, int colIndex)
{
return _records[rowIndex][colIndex];
}
/// <summary>
/// The number of record contained in the ResultSet.
/// </summary>
public int RecordCount
{
get { return _records.Length; }
}
/// <summary>
/// Gets the type of the field.
/// </summary>
/// <param name="colIndex">Index of the col.</param>
/// <returns>The type of the field.</returns>
public Type GetFieldType(int colIndex)
{
return _fieldsType[colIndex];
}
/// <summary>
/// Gets the name of the field.
/// </summary>
/// <param name="colIndex">Index of the col.</param>
/// <returns>The name of the field.</returns>
public string GetName(int colIndex)
{
return _fieldsName[colIndex];
}
/// <summary>
/// Gets the ordinal.
/// </summary>
/// <param name="colName">Name of the column.</param>
/// <returns>The ordinal of the column</returns>
public int GetOrdinal(string colName)
{
if (_fieldsNameLookup.ContainsKey(colName))
{
return Convert.ToInt32(_fieldsNameLookup[colName]);
}
else
{
throw new IndexOutOfRangeException(String.Format("No column with the specified name was found: {0}.", colName));
}
}
/// <summary>
/// Gets the name of the database type.
/// </summary>
/// <param name="colIndex">Index of the col.</param>
/// <returns>The name of the database type</returns>
public string GetDataTypeName(int colIndex)
{
return _dataTypeName[colIndex];
}
/// <summary>
/// Gets the values.
/// </summary>
/// <param name="rowIndex">Index of the row.</param>
/// <param name="values">The values.</param>
/// <returns></returns>
public int GetValues(int rowIndex, object[] values)
{
Array.Copy(_records[rowIndex], 0, values, 0, _fieldCount);
return _fieldCount;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using StackExchange.Redis;
using WorkflowCore.Interface;
using WorkflowCore.Models;
namespace WorkflowCore.Providers.Redis.Services
{
public class RedisPersistenceProvider : IPersistenceProvider
{
private readonly ILogger _logger;
private readonly string _connectionString;
private readonly string _prefix;
private const string WORKFLOW_SET = "workflows";
private const string SUBSCRIPTION_SET = "subscriptions";
private const string EVENT_SET = "events";
private const string RUNNABLE_INDEX = "runnable";
private const string EVENTSLUG_INDEX = "eventslug";
private readonly IConnectionMultiplexer _multiplexer;
private readonly IDatabase _redis;
private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
private readonly bool _removeComplete;
public bool SupportsScheduledCommands => false;
public RedisPersistenceProvider(string connectionString, string prefix, bool removeComplete, ILoggerFactory logFactory)
{
_connectionString = connectionString;
_prefix = prefix;
_logger = logFactory.CreateLogger(GetType());
_multiplexer = ConnectionMultiplexer.Connect(_connectionString);
_redis = _multiplexer.GetDatabase();
_removeComplete = removeComplete;
}
public async Task<string> CreateNewWorkflow(WorkflowInstance workflow, CancellationToken _ = default)
{
workflow.Id = Guid.NewGuid().ToString();
await PersistWorkflow(workflow);
return workflow.Id;
}
public async Task PersistWorkflow(WorkflowInstance workflow, CancellationToken _ = default)
{
var str = JsonConvert.SerializeObject(workflow, _serializerSettings);
await _redis.HashSetAsync($"{_prefix}.{WORKFLOW_SET}", workflow.Id, str);
if ((workflow.Status == WorkflowStatus.Runnable) && (workflow.NextExecution.HasValue))
await _redis.SortedSetAddAsync($"{_prefix}.{WORKFLOW_SET}.{RUNNABLE_INDEX}", workflow.Id, workflow.NextExecution.Value);
else
{
await _redis.SortedSetRemoveAsync($"{_prefix}.{WORKFLOW_SET}.{RUNNABLE_INDEX}", workflow.Id);
if (_removeComplete && workflow.Status == WorkflowStatus.Complete)
await _redis.HashDeleteAsync($"{_prefix}.{WORKFLOW_SET}", workflow.Id);
}
}
public async Task<IEnumerable<string>> GetRunnableInstances(DateTime asAt, CancellationToken _ = default)
{
var result = new List<string>();
var data = await _redis.SortedSetRangeByScoreAsync($"{_prefix}.{WORKFLOW_SET}.{RUNNABLE_INDEX}", -1, asAt.ToUniversalTime().Ticks);
foreach (var item in data)
result.Add(item);
return result;
}
public Task<IEnumerable<WorkflowInstance>> GetWorkflowInstances(WorkflowStatus? status, string type, DateTime? createdFrom, DateTime? createdTo, int skip,
int take)
{
throw new NotImplementedException();
}
public async Task<WorkflowInstance> GetWorkflowInstance(string Id, CancellationToken _ = default)
{
var raw = await _redis.HashGetAsync($"{_prefix}.{WORKFLOW_SET}", Id);
return JsonConvert.DeserializeObject<WorkflowInstance>(raw, _serializerSettings);
}
public async Task<IEnumerable<WorkflowInstance>> GetWorkflowInstances(IEnumerable<string> ids, CancellationToken _ = default)
{
if (ids == null)
{
return new List<WorkflowInstance>();
}
var raw = await _redis.HashGetAsync($"{_prefix}.{WORKFLOW_SET}", Array.ConvertAll(ids.ToArray(), x => (RedisValue)x));
return raw.Select(r => JsonConvert.DeserializeObject<WorkflowInstance>(r, _serializerSettings));
}
public async Task<string> CreateEventSubscription(EventSubscription subscription, CancellationToken _ = default)
{
subscription.Id = Guid.NewGuid().ToString();
var str = JsonConvert.SerializeObject(subscription, _serializerSettings);
await _redis.HashSetAsync($"{_prefix}.{SUBSCRIPTION_SET}", subscription.Id, str);
await _redis.SortedSetAddAsync($"{_prefix}.{SUBSCRIPTION_SET}.{EVENTSLUG_INDEX}.{subscription.EventName}-{subscription.EventKey}", subscription.Id, subscription.SubscribeAsOf.Ticks);
return subscription.Id;
}
public async Task<IEnumerable<EventSubscription>> GetSubscriptions(string eventName, string eventKey, DateTime asOf, CancellationToken _ = default)
{
var result = new List<EventSubscription>();
var data = await _redis.SortedSetRangeByScoreAsync($"{_prefix}.{SUBSCRIPTION_SET}.{EVENTSLUG_INDEX}.{eventName}-{eventKey}", -1, asOf.Ticks);
foreach (var id in data)
{
var raw = await _redis.HashGetAsync($"{_prefix}.{SUBSCRIPTION_SET}", id);
if (raw.HasValue)
result.Add(JsonConvert.DeserializeObject<EventSubscription>(raw, _serializerSettings));
}
return result;
}
public async Task TerminateSubscription(string eventSubscriptionId, CancellationToken _ = default)
{
var existingRaw = await _redis.HashGetAsync($"{_prefix}.{SUBSCRIPTION_SET}", eventSubscriptionId);
var existing = JsonConvert.DeserializeObject<EventSubscription>(existingRaw, _serializerSettings);
await _redis.HashDeleteAsync($"{_prefix}.{SUBSCRIPTION_SET}", eventSubscriptionId);
await _redis.SortedSetRemoveAsync($"{_prefix}.{SUBSCRIPTION_SET}.{EVENTSLUG_INDEX}.{existing.EventName}-{existing.EventKey}", eventSubscriptionId);
}
public async Task<EventSubscription> GetSubscription(string eventSubscriptionId, CancellationToken _ = default)
{
var raw = await _redis.HashGetAsync($"{_prefix}.{SUBSCRIPTION_SET}", eventSubscriptionId);
return JsonConvert.DeserializeObject<EventSubscription>(raw, _serializerSettings);
}
public async Task<EventSubscription> GetFirstOpenSubscription(string eventName, string eventKey, DateTime asOf, CancellationToken cancellationToken = default)
{
return (await GetSubscriptions(eventName, eventKey, asOf, cancellationToken)).FirstOrDefault(sub => string.IsNullOrEmpty(sub.ExternalToken));
}
public async Task<bool> SetSubscriptionToken(string eventSubscriptionId, string token, string workerId, DateTime expiry, CancellationToken _ = default)
{
var item = JsonConvert.DeserializeObject<EventSubscription>(await _redis.HashGetAsync($"{_prefix}.{SUBSCRIPTION_SET}", eventSubscriptionId), _serializerSettings);
if (item.ExternalToken != null)
return false;
item.ExternalToken = token;
item.ExternalWorkerId = workerId;
item.ExternalTokenExpiry = expiry;
var str = JsonConvert.SerializeObject(item, _serializerSettings);
await _redis.HashSetAsync($"{_prefix}.{SUBSCRIPTION_SET}", eventSubscriptionId, str);
return true;
}
public async Task ClearSubscriptionToken(string eventSubscriptionId, string token, CancellationToken _ = default)
{
var item = JsonConvert.DeserializeObject<EventSubscription>(await _redis.HashGetAsync($"{_prefix}.{SUBSCRIPTION_SET}", eventSubscriptionId), _serializerSettings);
if (item.ExternalToken != token)
return;
item.ExternalToken = null;
item.ExternalWorkerId = null;
item.ExternalTokenExpiry = null;
var str = JsonConvert.SerializeObject(item, _serializerSettings);
await _redis.HashSetAsync($"{_prefix}.{SUBSCRIPTION_SET}", eventSubscriptionId, str);
}
public async Task<string> CreateEvent(Event newEvent, CancellationToken _ = default)
{
newEvent.Id = Guid.NewGuid().ToString();
var str = JsonConvert.SerializeObject(newEvent, _serializerSettings);
await _redis.HashSetAsync($"{_prefix}.{EVENT_SET}", newEvent.Id, str);
await _redis.SortedSetAddAsync($"{_prefix}.{EVENT_SET}.{EVENTSLUG_INDEX}.{newEvent.EventName}-{newEvent.EventKey}", newEvent.Id, newEvent.EventTime.Ticks);
if (newEvent.IsProcessed)
await _redis.SortedSetRemoveAsync($"{_prefix}.{EVENT_SET}.{RUNNABLE_INDEX}", newEvent.Id);
else
await _redis.SortedSetAddAsync($"{_prefix}.{EVENT_SET}.{RUNNABLE_INDEX}", newEvent.Id, newEvent.EventTime.Ticks);
return newEvent.Id;
}
public async Task<Event> GetEvent(string id, CancellationToken _ = default)
{
var raw = await _redis.HashGetAsync($"{_prefix}.{EVENT_SET}", id);
return JsonConvert.DeserializeObject<Event>(raw, _serializerSettings);
}
public async Task<IEnumerable<string>> GetRunnableEvents(DateTime asAt, CancellationToken _ = default)
{
var result = new List<string>();
var data = await _redis.SortedSetRangeByScoreAsync($"{_prefix}.{EVENT_SET}.{RUNNABLE_INDEX}", -1, asAt.Ticks);
foreach (var item in data)
result.Add(item);
return result;
}
public async Task<IEnumerable<string>> GetEvents(string eventName, string eventKey, DateTime asOf, CancellationToken _ = default)
{
var result = new List<string>();
var data = await _redis.SortedSetRangeByScoreAsync($"{_prefix}.{EVENT_SET}.{EVENTSLUG_INDEX}.{eventName}-{eventKey}", asOf.Ticks);
foreach (var id in data)
result.Add(id);
return result;
}
public async Task MarkEventProcessed(string id, CancellationToken cancellationToken = default)
{
var evt = await GetEvent(id, cancellationToken);
evt.IsProcessed = true;
var str = JsonConvert.SerializeObject(evt, _serializerSettings);
await _redis.HashSetAsync($"{_prefix}.{EVENT_SET}", evt.Id, str);
await _redis.SortedSetRemoveAsync($"{_prefix}.{EVENT_SET}.{RUNNABLE_INDEX}", id);
}
public async Task MarkEventUnprocessed(string id, CancellationToken cancellationToken = default)
{
var evt = await GetEvent(id, cancellationToken);
evt.IsProcessed = false;
var str = JsonConvert.SerializeObject(evt, _serializerSettings);
await _redis.HashSetAsync($"{_prefix}.{EVENT_SET}", evt.Id, str);
await _redis.SortedSetAddAsync($"{_prefix}.{EVENT_SET}.{RUNNABLE_INDEX}", evt.Id, evt.EventTime.Ticks);
}
public Task PersistErrors(IEnumerable<ExecutionError> errors, CancellationToken _ = default)
{
return Task.CompletedTask;
}
public void EnsureStoreExists()
{
}
public Task ScheduleCommand(ScheduledCommand command)
{
throw new NotImplementedException();
}
public Task ProcessCommands(DateTimeOffset asOf, Func<ScheduledCommand, Task> action, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A physical CPU
/// First published in XenServer 4.0.
/// </summary>
public partial class Host_cpu : XenObject<Host_cpu>
{
#region Constructors
public Host_cpu()
{
}
public Host_cpu(string uuid,
XenRef<Host> host,
long number,
string vendor,
long speed,
string modelname,
long family,
long model,
string stepping,
string flags,
string features,
double utilisation,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.host = host;
this.number = number;
this.vendor = vendor;
this.speed = speed;
this.modelname = modelname;
this.family = family;
this.model = model;
this.stepping = stepping;
this.flags = flags;
this.features = features;
this.utilisation = utilisation;
this.other_config = other_config;
}
/// <summary>
/// Creates a new Host_cpu from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Host_cpu(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Host_cpu from a Proxy_Host_cpu.
/// </summary>
/// <param name="proxy"></param>
public Host_cpu(Proxy_Host_cpu proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Host_cpu.
/// </summary>
public override void UpdateFrom(Host_cpu update)
{
uuid = update.uuid;
host = update.host;
number = update.number;
vendor = update.vendor;
speed = update.speed;
modelname = update.modelname;
family = update.family;
model = update.model;
stepping = update.stepping;
flags = update.flags;
features = update.features;
utilisation = update.utilisation;
other_config = update.other_config;
}
internal void UpdateFrom(Proxy_Host_cpu proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
number = proxy.number == null ? 0 : long.Parse(proxy.number);
vendor = proxy.vendor == null ? null : proxy.vendor;
speed = proxy.speed == null ? 0 : long.Parse(proxy.speed);
modelname = proxy.modelname == null ? null : proxy.modelname;
family = proxy.family == null ? 0 : long.Parse(proxy.family);
model = proxy.model == null ? 0 : long.Parse(proxy.model);
stepping = proxy.stepping == null ? null : proxy.stepping;
flags = proxy.flags == null ? null : proxy.flags;
features = proxy.features == null ? null : proxy.features;
utilisation = Convert.ToDouble(proxy.utilisation);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_Host_cpu ToProxy()
{
Proxy_Host_cpu result_ = new Proxy_Host_cpu();
result_.uuid = uuid ?? "";
result_.host = host ?? "";
result_.number = number.ToString();
result_.vendor = vendor ?? "";
result_.speed = speed.ToString();
result_.modelname = modelname ?? "";
result_.family = family.ToString();
result_.model = model.ToString();
result_.stepping = stepping ?? "";
result_.flags = flags ?? "";
result_.features = features ?? "";
result_.utilisation = utilisation;
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Host_cpu
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("host"))
host = Marshalling.ParseRef<Host>(table, "host");
if (table.ContainsKey("number"))
number = Marshalling.ParseLong(table, "number");
if (table.ContainsKey("vendor"))
vendor = Marshalling.ParseString(table, "vendor");
if (table.ContainsKey("speed"))
speed = Marshalling.ParseLong(table, "speed");
if (table.ContainsKey("modelname"))
modelname = Marshalling.ParseString(table, "modelname");
if (table.ContainsKey("family"))
family = Marshalling.ParseLong(table, "family");
if (table.ContainsKey("model"))
model = Marshalling.ParseLong(table, "model");
if (table.ContainsKey("stepping"))
stepping = Marshalling.ParseString(table, "stepping");
if (table.ContainsKey("flags"))
flags = Marshalling.ParseString(table, "flags");
if (table.ContainsKey("features"))
features = Marshalling.ParseString(table, "features");
if (table.ContainsKey("utilisation"))
utilisation = Marshalling.ParseDouble(table, "utilisation");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(Host_cpu other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._host, other._host) &&
Helper.AreEqual2(this._number, other._number) &&
Helper.AreEqual2(this._vendor, other._vendor) &&
Helper.AreEqual2(this._speed, other._speed) &&
Helper.AreEqual2(this._modelname, other._modelname) &&
Helper.AreEqual2(this._family, other._family) &&
Helper.AreEqual2(this._model, other._model) &&
Helper.AreEqual2(this._stepping, other._stepping) &&
Helper.AreEqual2(this._flags, other._flags) &&
Helper.AreEqual2(this._features, other._features) &&
Helper.AreEqual2(this._utilisation, other._utilisation) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
internal static List<Host_cpu> ProxyArrayToObjectList(Proxy_Host_cpu[] input)
{
var result = new List<Host_cpu>();
foreach (var item in input)
result.Add(new Host_cpu(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Host_cpu server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Host_cpu.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given host_cpu.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
[Deprecated("XenServer 5.6")]
public static Host_cpu get_record(Session session, string _host_cpu)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_record(session.opaque_ref, _host_cpu);
else
return new Host_cpu(session.proxy.host_cpu_get_record(session.opaque_ref, _host_cpu ?? "").parse());
}
/// <summary>
/// Get a reference to the host_cpu instance with the specified UUID.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
[Deprecated("XenServer 5.6")]
public static XenRef<Host_cpu> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Host_cpu>.Create(session.proxy.host_cpu_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given host_cpu.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
public static string get_uuid(Session session, string _host_cpu)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_uuid(session.opaque_ref, _host_cpu);
else
return session.proxy.host_cpu_get_uuid(session.opaque_ref, _host_cpu ?? "").parse();
}
/// <summary>
/// Get the host field of the given host_cpu.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
public static XenRef<Host> get_host(Session session, string _host_cpu)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_host(session.opaque_ref, _host_cpu);
else
return XenRef<Host>.Create(session.proxy.host_cpu_get_host(session.opaque_ref, _host_cpu ?? "").parse());
}
/// <summary>
/// Get the number field of the given host_cpu.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
public static long get_number(Session session, string _host_cpu)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_number(session.opaque_ref, _host_cpu);
else
return long.Parse(session.proxy.host_cpu_get_number(session.opaque_ref, _host_cpu ?? "").parse());
}
/// <summary>
/// Get the vendor field of the given host_cpu.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
public static string get_vendor(Session session, string _host_cpu)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_vendor(session.opaque_ref, _host_cpu);
else
return session.proxy.host_cpu_get_vendor(session.opaque_ref, _host_cpu ?? "").parse();
}
/// <summary>
/// Get the speed field of the given host_cpu.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
public static long get_speed(Session session, string _host_cpu)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_speed(session.opaque_ref, _host_cpu);
else
return long.Parse(session.proxy.host_cpu_get_speed(session.opaque_ref, _host_cpu ?? "").parse());
}
/// <summary>
/// Get the modelname field of the given host_cpu.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
public static string get_modelname(Session session, string _host_cpu)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_modelname(session.opaque_ref, _host_cpu);
else
return session.proxy.host_cpu_get_modelname(session.opaque_ref, _host_cpu ?? "").parse();
}
/// <summary>
/// Get the family field of the given host_cpu.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
public static long get_family(Session session, string _host_cpu)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_family(session.opaque_ref, _host_cpu);
else
return long.Parse(session.proxy.host_cpu_get_family(session.opaque_ref, _host_cpu ?? "").parse());
}
/// <summary>
/// Get the model field of the given host_cpu.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
public static long get_model(Session session, string _host_cpu)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_model(session.opaque_ref, _host_cpu);
else
return long.Parse(session.proxy.host_cpu_get_model(session.opaque_ref, _host_cpu ?? "").parse());
}
/// <summary>
/// Get the stepping field of the given host_cpu.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
public static string get_stepping(Session session, string _host_cpu)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_stepping(session.opaque_ref, _host_cpu);
else
return session.proxy.host_cpu_get_stepping(session.opaque_ref, _host_cpu ?? "").parse();
}
/// <summary>
/// Get the flags field of the given host_cpu.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
public static string get_flags(Session session, string _host_cpu)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_flags(session.opaque_ref, _host_cpu);
else
return session.proxy.host_cpu_get_flags(session.opaque_ref, _host_cpu ?? "").parse();
}
/// <summary>
/// Get the features field of the given host_cpu.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
public static string get_features(Session session, string _host_cpu)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_features(session.opaque_ref, _host_cpu);
else
return session.proxy.host_cpu_get_features(session.opaque_ref, _host_cpu ?? "").parse();
}
/// <summary>
/// Get the utilisation field of the given host_cpu.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
public static double get_utilisation(Session session, string _host_cpu)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_utilisation(session.opaque_ref, _host_cpu);
else
return Convert.ToDouble(session.proxy.host_cpu_get_utilisation(session.opaque_ref, _host_cpu ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given host_cpu.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
public static Dictionary<string, string> get_other_config(Session session, string _host_cpu)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_other_config(session.opaque_ref, _host_cpu);
else
return Maps.convert_from_proxy_string_string(session.proxy.host_cpu_get_other_config(session.opaque_ref, _host_cpu ?? "").parse());
}
/// <summary>
/// Set the other_config field of the given host_cpu.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _host_cpu, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_cpu_set_other_config(session.opaque_ref, _host_cpu, _other_config);
else
session.proxy.host_cpu_set_other_config(session.opaque_ref, _host_cpu ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given host_cpu.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _host_cpu, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_cpu_add_to_other_config(session.opaque_ref, _host_cpu, _key, _value);
else
session.proxy.host_cpu_add_to_other_config(session.opaque_ref, _host_cpu ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given host_cpu. If the key is not in that Map, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_cpu">The opaque_ref of the given host_cpu</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _host_cpu, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.host_cpu_remove_from_other_config(session.opaque_ref, _host_cpu, _key);
else
session.proxy.host_cpu_remove_from_other_config(session.opaque_ref, _host_cpu ?? "", _key ?? "").parse();
}
/// <summary>
/// Return a list of all the host_cpus known to the system.
/// First published in XenServer 4.0.
/// Deprecated since XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
[Deprecated("XenServer 5.6")]
public static List<XenRef<Host_cpu>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_all(session.opaque_ref);
else
return XenRef<Host_cpu>.Create(session.proxy.host_cpu_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the host_cpu Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Host_cpu>, Host_cpu> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.host_cpu_get_all_records(session.opaque_ref);
else
return XenRef<Host_cpu>.Create<Proxy_Host_cpu>(session.proxy.host_cpu_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// the host the CPU is in
/// </summary>
[JsonConverter(typeof(XenRefConverter<Host>))]
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
Changed = true;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host = new XenRef<Host>(Helper.NullOpaqueRef);
/// <summary>
/// the number of the physical CPU within the host
/// </summary>
public virtual long number
{
get { return _number; }
set
{
if (!Helper.AreEqual(value, _number))
{
_number = value;
Changed = true;
NotifyPropertyChanged("number");
}
}
}
private long _number;
/// <summary>
/// the vendor of the physical CPU
/// </summary>
public virtual string vendor
{
get { return _vendor; }
set
{
if (!Helper.AreEqual(value, _vendor))
{
_vendor = value;
Changed = true;
NotifyPropertyChanged("vendor");
}
}
}
private string _vendor = "";
/// <summary>
/// the speed of the physical CPU
/// </summary>
public virtual long speed
{
get { return _speed; }
set
{
if (!Helper.AreEqual(value, _speed))
{
_speed = value;
Changed = true;
NotifyPropertyChanged("speed");
}
}
}
private long _speed;
/// <summary>
/// the model name of the physical CPU
/// </summary>
public virtual string modelname
{
get { return _modelname; }
set
{
if (!Helper.AreEqual(value, _modelname))
{
_modelname = value;
Changed = true;
NotifyPropertyChanged("modelname");
}
}
}
private string _modelname = "";
/// <summary>
/// the family (number) of the physical CPU
/// </summary>
public virtual long family
{
get { return _family; }
set
{
if (!Helper.AreEqual(value, _family))
{
_family = value;
Changed = true;
NotifyPropertyChanged("family");
}
}
}
private long _family;
/// <summary>
/// the model number of the physical CPU
/// </summary>
public virtual long model
{
get { return _model; }
set
{
if (!Helper.AreEqual(value, _model))
{
_model = value;
Changed = true;
NotifyPropertyChanged("model");
}
}
}
private long _model;
/// <summary>
/// the stepping of the physical CPU
/// </summary>
public virtual string stepping
{
get { return _stepping; }
set
{
if (!Helper.AreEqual(value, _stepping))
{
_stepping = value;
Changed = true;
NotifyPropertyChanged("stepping");
}
}
}
private string _stepping = "";
/// <summary>
/// the flags of the physical CPU (a decoded version of the features field)
/// </summary>
public virtual string flags
{
get { return _flags; }
set
{
if (!Helper.AreEqual(value, _flags))
{
_flags = value;
Changed = true;
NotifyPropertyChanged("flags");
}
}
}
private string _flags = "";
/// <summary>
/// the physical CPU feature bitmap
/// </summary>
public virtual string features
{
get { return _features; }
set
{
if (!Helper.AreEqual(value, _features))
{
_features = value;
Changed = true;
NotifyPropertyChanged("features");
}
}
}
private string _features = "";
/// <summary>
/// the current CPU utilisation
/// </summary>
public virtual double utilisation
{
get { return _utilisation; }
set
{
if (!Helper.AreEqual(value, _utilisation))
{
_utilisation = value;
Changed = true;
NotifyPropertyChanged("utilisation");
}
}
}
private double _utilisation;
/// <summary>
/// additional configuration
/// First published in XenServer 5.0.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.