context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using UnityEngine;
using System.Collections.Generic;
public class WorldGeneration
{
private static volatile WorldGeneration instance;
public static int seaLevel = 50;
public int treeHeightLine = 150;
private WorldGeneration ()
{
}
public static WorldGeneration Instance {
get {
if (instance == null)
instance = new WorldGeneration ();
return instance;
}
}
public void genRegionv2 (Region region)
{
BlockCounter counter = new BlockCounter (Region.regionXZ * Region.regionXZ * Region.regionY);
int x_offset = region.getBlockOffsetX ();
int y_offset = region.getBlockOffsetY ();
int z_offset = region.getBlockOffsetZ ();
for (int x=0; x<Region.regionXZ; x++) {
for (int z=0; z<Region.regionXZ; z++) {
int xi = x_offset + x;
int zi = z_offset + z;
//Read a tile from the overland map.
}
}
}
public void generateRegion (Region babyRegion)
{
//Create base level
//createBaseGround (babyRegion.data, babyRegion.getBlockOffsetY ());
//Create basic terrain (heightmap)
createPlains (babyRegion);
//TreePlanter.generateTrees (babyRegion);
//Create overhangs
//createPerlin3D (data, regionX, regionY, regionZ);
}
private void createMountains (Region region)
{
BlockCounter counter = new BlockCounter (Region.regionXZ * Region.regionXZ * Region.regionY);
int x_offset = region.getBlockOffsetX ();
int y_offset = region.getBlockOffsetY ();
int z_offset = region.getBlockOffsetZ ();
for (int x=0; x<Region.regionXZ; x++) {
for (int z=0; z<Region.regionXZ; z++) {
int xi = x_offset + x;
int zi = z_offset + z;
int stone = PerlinNoise (xi, 751, zi, 550, 15f, 2.2f) + 200;
int lowHills = PerlinNoise (xi, 400, zi, 200, 10f, 2.2f);
int roughness1 = PerlinNoise (xi, 231, zi, 20, 2f, 1.5f);
int roughness2 = PerlinNoise (xi, 845, zi, 50, 2f, 2.5f);
int roughness3 = PerlinNoise (xi, 19, zi, 100, 3f, 3.5f);
int val = stone + lowHills + roughness1 + roughness2 + roughness3;
for (int y=0; y<Region.regionY; y++) {
int yi = y_offset + y;
if (yi <= val) {
region.data [x, y, z] = 1;
counter.add (1);
} else {
counter.add (0);
}
}
}
}
//process flags
if (counter.isAirOnly ()) {
region.flags.isEmptyAir = true;
} else if (counter.isSingleSolidOnly ()) {
region.flags.isSingleSolid = true;
}
}
private void createPlains (Region region)
{
BlockCounter counter = new BlockCounter (Region.regionXZ * Region.regionXZ * Region.regionY);
int x_offset = region.getBlockOffsetX ();
int y_offset = region.getBlockOffsetY ();
int z_offset = region.getBlockOffsetZ ();
for (int x=0; x<region.data.GetLength(0); x++) {
for (int z=0; z<region.data.GetLength(2); z++) {
int xi = x_offset + x;
int zi = z_offset + z;
int highHills = PerlinNoise (xi, 751, zi, 50, 10f, 1.0f) + 128;
int lowHills = PerlinNoise (xi, 407, zi, 50, 10f, 1.0f) + 128;
//int val = (int)Math.Max (highHills, lowHills);
for (int y=0; y<region.data.GetLength(1); y++) {
int yi = y_offset + y;
if (yi <= highHills) {
counter.add (DirtBlock.blockId);
region.data [x, y, z] = DirtBlock.blockId;
} else if (yi <= lowHills) {
counter.add (GrassBlock.blockId);
region.data [x, y, z] = GrassBlock.blockId;
} else {
counter.add (0);
}
}
}
}
//process flags
if (counter.isAirOnly ()) {
region.flags.isEmptyAir = true;
} else if (counter.isSingleSolidOnly ()) {
region.flags.isSingleSolid = true;
}
}
private void createPerlin3D (byte[,,] data, int regionX, int regionY, int regionZ)
{
for (int x=0; x<data.GetLength(0); x++) {
for (int z=0; z<data.GetLength(2); z++) {
for (int y = 0; y<data.GetLength(1); y++) {
int xi = regionX + x;
int yi = regionY + y;
int zi = regionZ + z;
int stone = PerlinNoise (xi, yi, zi, 250, 10f, 0F);
if (yi >= 1 && stone > 5) {
data [x, y, z] = 0;
}
}
}
}
}
private void createBaseGround (byte[,,] data, int regionY)
{
for (int x=0; x<data.GetLength(0); x++) {
for (int z=0; z<data.GetLength(2); z++) {
for (int y=0; y<data.GetLength(1); y++) {
int yi = regionY + y;
if (yi < seaLevel) {
data [x, y, z] = 1;
} else {
data [x, y, z] = 0;
}
}
}
}
}
private int PerlinNoise (float x, int y, float z, float scale, float height, float power)
{
float rValue;
rValue = TutorialNoise.GetNoise (((double)x) / scale, ((double)y) / scale, ((double)z) / scale);
rValue *= height;
if (power != 0) {
rValue = Mathf.Pow (rValue, power);
}
return (int)rValue;
}
private class BlockCounter
{
private Dictionary<int, int> blocks;
private int regionVolume = 0;
public BlockCounter (int inVolume)
{
regionVolume = inVolume;
blocks = new Dictionary<int, int> (10);
}
public void add (int blockType)
{
if (!blocks.ContainsKey (blockType)) {
blocks.Add (blockType, 1);
} else {
int currentCount = blocks [blockType];
blocks.Remove (blockType);
blocks.Add (blockType, currentCount + 1);
}
}
public bool isAirOnly ()
{
if (blocks.Count > 1) {
return false; //There are at least two block types
} else if (blocks.ContainsKey (0)) {
int airCount = blocks [0]; //Air block type
if (airCount == regionVolume) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public bool isSingleSolidOnly ()
{
if (blocks.Count > 1) {
return false; //contains at least two block types.
} else {
foreach (KeyValuePair<int,int> kvp in blocks) {
if (kvp.Key != 0 && kvp.Value == regionVolume) {
return true;
}
}
return false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using DevExpress.CodeRush.Core;
namespace CR_XkeysEngine
{
public class XkeySelection
{
List<KeyBase> selectedKeys = new List<KeyBase>();
public XkeySelection()
{
}
public bool IsBlocked()
{
int blockedKeys = 0;
foreach (KeyBase key in selectedKeys)
{
Key xkey = key as Key;
if (xkey != null)
if (xkey.IsBlocked)
blockedKeys++;
else
return false;
}
return blockedKeys > 0;
}
public bool AllKeysRepeatIfHeldDown()
{
foreach (KeyBase key in selectedKeys)
if (!key.Repeating)
return false;
return true;
}
public bool HasOnlySingleKeys()
{
foreach (KeyBase key in selectedKeys)
if (key is KeyGroup)
return false;
return true;
}
public bool CanBeTall()
{
if (Count != 2)
return false;
// Two keys selected....
if (GetGroupType() != KeyGroupType.NoGroup)
return false;
// Both keys can be grouped...
KeyBase key1 = selectedKeys[0];
KeyBase key2 = selectedKeys[1];
if (key1.Column != key2.Column)
return false;
// Same column...
if (Math.Abs(key1.Row - key2.Row) != 1)
return false;
// Adjacent rows...
int topRow = Math.Min(key1.Row, key2.Row);
if (topRow == 1 || topRow > 5) // Tall keys cannot start on row 1 (zero indexed) or on or after row 6.
return false;
return true;
}
public bool CanBeWide()
{
if (Count != 2)
return false;
// Two keys selected....
if (GetGroupType() != KeyGroupType.NoGroup)
return false;
// Both keys can be grouped...
KeyBase key1 = selectedKeys[0];
KeyBase key2 = selectedKeys[1];
if (key1.Row != key2.Row)
return false;
// Same row...
int row = key1.Row;
if (Math.Abs(key1.Column - key2.Column) != 1)
return false;
// Adjacent columns...
int leftColumn = Math.Min(key1.Column, key2.Column);
if (row <= 1) // top two rows have 9 keys...
{
if (leftColumn > 7) // Wide keys cannot start on or after column 7 (zero indexed).
return false;
}
else // bottom section
{
if (leftColumn == 1 || leftColumn == 5 || leftColumn > 6) // Wide keys in the bottom section cannot start on column 1, 5, 7 or greater (zero indexed).
return false;
}
return true;
}
private int GetSmallestValueKeyIndex(KeyBase[] keys, Func<int, int> getValue)
{
int index = -1;
int lowestValue = -1;
for (int i = 0; i < keys.Length; i++)
{
int value = getValue(i);
if (lowestValue == -1 || value < lowestValue)
{
lowestValue = value;
index = i;
}
}
return index;
}
int GetTopKeyIndex(KeyBase[] keys)
{
return GetSmallestValueKeyIndex(keys, i => keys[i].Row);
}
int GetLeftKeyIndex(KeyBase[] keys)
{
return GetSmallestValueKeyIndex(keys, i => keys[i].Column);
}
bool HasKeyAt(KeyBase[] keys, int column, int row)
{
foreach (KeyBase key in keys)
if (key.Column == column && key.Row == row)
return true;
return false;
}
KeyBase GetTopLeftKey(KeyBase[] keys)
{
int topKeyIndex = GetTopKeyIndex(keys);
int leftKeyIndex = GetLeftKeyIndex(keys);
KeyBase topLeftKey = null;
int leftColumn = keys[leftKeyIndex].Column;
int topRow = keys[topKeyIndex].Row;
for (int i = 0; i < keys.Length; i++)
if (keys[i].IsAt(leftColumn, topRow))
topLeftKey = keys[i];
return topLeftKey;
}
public bool CanBeSquare()
{
if (Count != 4)
return false;
// Four keys selected....
if (GetGroupType() != KeyGroupType.NoGroup)
return false;
// All four keys can be grouped...
KeyBase[] keys = new KeyBase[4];
keys[0] = selectedKeys[0];
keys[1] = selectedKeys[1];
keys[2] = selectedKeys[2];
keys[3] = selectedKeys[3];
KeyBase topLeftKey = GetTopLeftKey(keys);
if (topLeftKey == null)
return false;
// OK, we have the top left key. Now let's see if the other three keys are in the positions we're expecting...
if (!(HasKeyAt(keys, topLeftKey.Column + 1, topLeftKey.Row) && HasKeyAt(keys, topLeftKey.Column, topLeftKey.Row + 1) && HasKeyAt(keys, topLeftKey.Column + 1, topLeftKey.Row + 1)))
return false;
// OK, we now know the four keys are adjacent. Finally, let's make sure the four keys are in a legal position on the x-keys...
if (topLeftKey.Row == 1 || topLeftKey.Row > 5)
return false;
if (topLeftKey.Row == 0 && topLeftKey.Column > 7)
return false;
if (topLeftKey.Row > 1)
if (topLeftKey.Column == 1 || topLeftKey.Column == 5 || topLeftKey.Column > 6)
return false;
return true;
}
public string GetName()
{
if (Count == 0)
return String.Empty;
string compareName = selectedKeys[0].Name;
for (int i = 1; i < Count; i++)
if (selectedKeys[i].Name != compareName)
return String.Empty;
return compareName;
}
public KeyGroupType GetGroupType()
{
if (Count != 1)
return KeyGroupType.NoGroup;
KeyGroup xkeyGroup = selectedKeys[0] as KeyGroup;
if (xkeyGroup != null)
return xkeyGroup.Type;
return KeyGroupType.NoGroup;
}
public void AddKey(KeyBase key)
{
selectedKeys.Add(key);
}
public int Count
{
get
{
return selectedKeys.Count;
}
}
public List<KeyBase> SelectedKeys
{
get
{
return selectedKeys;
}
}
}
}
| |
// 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.Reflection.Emit
{
using System;
using System.Collections.Generic;
using CultureInfo = System.Globalization.CultureInfo;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class DynamicMethod : MethodInfo
{
private RuntimeType[] m_parameterTypes;
internal IRuntimeMethodInfo m_methodHandle;
private RuntimeType m_returnType;
private DynamicILGenerator m_ilGenerator;
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
private DynamicILInfo m_DynamicILInfo;
private bool m_fInitLocals;
private RuntimeModule m_module;
internal bool m_skipVisibility;
internal RuntimeType m_typeOwner; // can be null
// We want the creator of the DynamicMethod to control who has access to the
// DynamicMethod (just like we do for delegates). However, a user can get to
// the corresponding RTDynamicMethod using Exception.TargetSite, StackFrame.GetMethod, etc.
// If we allowed use of RTDynamicMethod, the creator of the DynamicMethod would
// not be able to bound access to the DynamicMethod. Hence, we need to ensure that
// we do not allow direct use of RTDynamicMethod.
private RTDynamicMethod m_dynMethod;
// needed to keep the object alive during jitting
// assigned by the DynamicResolver ctor
internal DynamicResolver m_resolver;
// Always false unless we are in an immersive (non dev mode) process.
#if FEATURE_APPX
private bool m_profileAPICheck;
private RuntimeAssembly m_creatorAssembly;
#endif
internal bool m_restrictedSkipVisibility;
// The context when the method was created. We use this to do the RestrictedMemberAccess checks.
// These checks are done when the method is compiled. This can happen at an arbitrary time,
// when CreateDelegate or Invoke is called, or when another DynamicMethod executes OpCodes.Call.
// We capture the creation context so that we can do the checks against the same context,
// irrespective of when the method gets compiled. Note that the DynamicMethod does not know when
// it is ready for use since there is not API which indictates that IL generation has completed.
#if FEATURE_COMPRESSEDSTACK
internal CompressedStack m_creationContext;
#endif // FEATURE_COMPRESSEDSTACK
private static volatile InternalModuleBuilder s_anonymouslyHostedDynamicMethodsModule;
private static readonly object s_anonymouslyHostedDynamicMethodsModuleLock = new object();
//
// class initialization (ctor and init)
//
private DynamicMethod() { }
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
Type[] parameterTypes)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
returnType,
parameterTypes,
null, // owner
null, // m
false, // skipVisibility
true,
ref stackMark); // transparentMethod
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
Type[] parameterTypes,
bool restrictedSkipVisibility)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
returnType,
parameterTypes,
null, // owner
null, // m
restrictedSkipVisibility,
true,
ref stackMark); // transparentMethod
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
Type[] parameterTypes,
Module m) {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PerformSecurityCheck(m, ref stackMark, false);
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
returnType,
parameterTypes,
null, // owner
m, // m
false, // skipVisibility
false,
ref stackMark); // transparentMethod
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
Type[] parameterTypes,
Module m,
bool skipVisibility) {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PerformSecurityCheck(m, ref stackMark, skipVisibility);
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
returnType,
parameterTypes,
null, // owner
m, // m
skipVisibility,
false,
ref stackMark); // transparentMethod
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
MethodAttributes attributes,
CallingConventions callingConvention,
Type returnType,
Type[] parameterTypes,
Module m,
bool skipVisibility) {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PerformSecurityCheck(m, ref stackMark, skipVisibility);
Init(name,
attributes,
callingConvention,
returnType,
parameterTypes,
null, // owner
m, // m
skipVisibility,
false,
ref stackMark); // transparentMethod
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
Type[] parameterTypes,
Type owner) {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PerformSecurityCheck(owner, ref stackMark, false);
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
returnType,
parameterTypes,
owner, // owner
null, // m
false, // skipVisibility
false,
ref stackMark); // transparentMethod
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
Type[] parameterTypes,
Type owner,
bool skipVisibility) {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PerformSecurityCheck(owner, ref stackMark, skipVisibility);
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
returnType,
parameterTypes,
owner, // owner
null, // m
skipVisibility,
false,
ref stackMark); // transparentMethod
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
MethodAttributes attributes,
CallingConventions callingConvention,
Type returnType,
Type[] parameterTypes,
Type owner,
bool skipVisibility) {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PerformSecurityCheck(owner, ref stackMark, skipVisibility);
Init(name,
attributes,
callingConvention,
returnType,
parameterTypes,
owner, // owner
null, // m
skipVisibility,
false,
ref stackMark); // transparentMethod
}
// helpers for intialization
static private void CheckConsistency(MethodAttributes attributes, CallingConventions callingConvention) {
// only static public for method attributes
if ((attributes & ~MethodAttributes.MemberAccessMask) != MethodAttributes.Static)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags"));
if ((attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags"));
Contract.EndContractBlock();
// only standard or varargs supported
if (callingConvention != CallingConventions.Standard && callingConvention != CallingConventions.VarArgs)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags"));
// vararg is not supported at the moment
if (callingConvention == CallingConventions.VarArgs)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags"));
}
// We create a transparent assembly to host DynamicMethods. Since the assembly does not have any
// non-public fields (or any fields at all), it is a safe anonymous assembly to host DynamicMethods
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
private static RuntimeModule GetDynamicMethodsModule()
{
if (s_anonymouslyHostedDynamicMethodsModule != null)
return s_anonymouslyHostedDynamicMethodsModule;
lock (s_anonymouslyHostedDynamicMethodsModuleLock)
{
if (s_anonymouslyHostedDynamicMethodsModule != null)
return s_anonymouslyHostedDynamicMethodsModule;
ConstructorInfo transparencyCtor = typeof(SecurityTransparentAttribute).GetConstructor(Type.EmptyTypes);
CustomAttributeBuilder transparencyAttribute = new CustomAttributeBuilder(transparencyCtor, EmptyArray<Object>.Value);
List<CustomAttributeBuilder> assemblyAttributes = new List<CustomAttributeBuilder>();
assemblyAttributes.Add(transparencyAttribute);
#if !FEATURE_CORECLR
// On the desktop, we need to use the security rule set level 1 for anonymously hosted
// dynamic methods. In level 2, transparency rules are strictly enforced, which leads to
// errors when a fully trusted application causes a dynamic method to be generated that tries
// to call a method with a LinkDemand or a SecurityCritical method. To retain compatibility
// with the v2.0 and v3.x frameworks, these calls should be allowed.
//
// If this rule set was not explicitly called out, then the anonymously hosted dynamic methods
// assembly would inherit the rule set from the creating assembly - which would cause it to
// be level 2 because mscorlib.dll is using the level 2 rules.
ConstructorInfo securityRulesCtor = typeof(SecurityRulesAttribute).GetConstructor(new Type[] { typeof(SecurityRuleSet) });
CustomAttributeBuilder securityRulesAttribute =
new CustomAttributeBuilder(securityRulesCtor, new object[] { SecurityRuleSet.Level1 });
assemblyAttributes.Add(securityRulesAttribute);
#endif // !FEATURE_CORECLR
AssemblyName assemblyName = new AssemblyName("Anonymously Hosted DynamicMethods Assembly");
StackCrawlMark stackMark = StackCrawlMark.LookForMe;
AssemblyBuilder assembly = AssemblyBuilder.InternalDefineDynamicAssembly(
assemblyName,
AssemblyBuilderAccess.Run,
null, null, null, null, null,
ref stackMark,
assemblyAttributes,
SecurityContextSource.CurrentAssembly);
AppDomain.PublishAnonymouslyHostedDynamicMethodsAssembly(assembly.GetNativeHandle());
// this always gets the internal module.
s_anonymouslyHostedDynamicMethodsModule = (InternalModuleBuilder)assembly.ManifestModule;
}
return s_anonymouslyHostedDynamicMethodsModule;
}
[System.Security.SecurityCritical] // auto-generated
private unsafe void Init(String name,
MethodAttributes attributes,
CallingConventions callingConvention,
Type returnType,
Type[] signature,
Type owner,
Module m,
bool skipVisibility,
bool transparentMethod,
ref StackCrawlMark stackMark)
{
DynamicMethod.CheckConsistency(attributes, callingConvention);
// check and store the signature
if (signature != null) {
m_parameterTypes = new RuntimeType[signature.Length];
for (int i = 0; i < signature.Length; i++) {
if (signature[i] == null)
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidTypeInSignature"));
m_parameterTypes[i] = signature[i].UnderlyingSystemType as RuntimeType;
if ( m_parameterTypes[i] == null || !(m_parameterTypes[i] is RuntimeType) || m_parameterTypes[i] == (RuntimeType)typeof(void) )
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidTypeInSignature"));
}
}
else {
m_parameterTypes = Array.Empty<RuntimeType>();
}
// check and store the return value
m_returnType = (returnType == null) ? (RuntimeType)typeof(void) : returnType.UnderlyingSystemType as RuntimeType;
if ( (m_returnType == null) || !(m_returnType is RuntimeType) || m_returnType.IsByRef )
throw new NotSupportedException(Environment.GetResourceString("Arg_InvalidTypeInRetType"));
if (transparentMethod)
{
Contract.Assert(owner == null && m == null, "owner and m cannot be set for transparent methods");
m_module = GetDynamicMethodsModule();
if (skipVisibility)
{
m_restrictedSkipVisibility = true;
}
#if FEATURE_COMPRESSEDSTACK
m_creationContext = CompressedStack.Capture();
#endif // FEATURE_COMPRESSEDSTACK
}
else
{
Contract.Assert(m != null || owner != null, "PerformSecurityCheck should ensure that either m or owner is set");
Contract.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly");
Contract.Assert(m == null || owner == null, "m and owner cannot both be set");
if (m != null)
m_module = m.ModuleHandle.GetRuntimeModule(); // this returns the underlying module for all RuntimeModule and ModuleBuilder objects.
else
{
RuntimeType rtOwner = null;
if (owner != null)
rtOwner = owner.UnderlyingSystemType as RuntimeType;
if (rtOwner != null)
{
if (rtOwner.HasElementType || rtOwner.ContainsGenericParameters
|| rtOwner.IsGenericParameter || rtOwner.IsInterface)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeForDynamicMethod"));
m_typeOwner = rtOwner;
m_module = rtOwner.GetRuntimeModule();
}
}
m_skipVisibility = skipVisibility;
}
// initialize remaining fields
m_ilGenerator = null;
m_fInitLocals = true;
m_methodHandle = null;
if (name == null)
throw new ArgumentNullException("name");
#if FEATURE_APPX
if (AppDomain.ProfileAPICheck)
{
if (m_creatorAssembly == null)
m_creatorAssembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
if (m_creatorAssembly != null && !m_creatorAssembly.IsFrameworkAssembly())
m_profileAPICheck = true;
}
#endif // FEATURE_APPX
m_dynMethod = new RTDynamicMethod(this, name, attributes, callingConvention);
}
[System.Security.SecurityCritical] // auto-generated
private void PerformSecurityCheck(Module m, ref StackCrawlMark stackMark, bool skipVisibility)
{
if (m == null)
throw new ArgumentNullException("m");
Contract.EndContractBlock();
#if !FEATURE_CORECLR
RuntimeModule rtModule;
ModuleBuilder mb = m as ModuleBuilder;
if (mb != null)
rtModule = mb.InternalModule;
else
rtModule = m as RuntimeModule;
if (rtModule == null)
{
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeModule"), "m");
}
// The user cannot explicitly use this assembly
if (rtModule == s_anonymouslyHostedDynamicMethodsModule)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"), "m");
// ask for member access if skip visibility
if (skipVisibility)
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
#if !FEATURE_CORECLR
// ask for control evidence if outside of the caller assembly
RuntimeType callingType = RuntimeMethodHandle.GetCallerType(ref stackMark);
m_creatorAssembly = callingType.GetRuntimeAssembly();
if (m.Assembly != m_creatorAssembly)
{
// Demand the permissions of the assembly where the DynamicMethod will live
CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence,
m.Assembly.PermissionSet);
}
#else //FEATURE_CORECLR
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
#pragma warning restore 618
#endif //FEATURE_CORECLR
#endif //!FEATURE_CORECLR
}
[System.Security.SecurityCritical] // auto-generated
private void PerformSecurityCheck(Type owner, ref StackCrawlMark stackMark, bool skipVisibility)
{
if (owner == null)
throw new ArgumentNullException("owner");
#if !FEATURE_CORECLR
RuntimeType rtOwner = owner as RuntimeType;
if (rtOwner == null)
rtOwner = owner.UnderlyingSystemType as RuntimeType;
if (rtOwner == null)
throw new ArgumentNullException("owner", Environment.GetResourceString("Argument_MustBeRuntimeType"));
// get the type the call is coming from
RuntimeType callingType = RuntimeMethodHandle.GetCallerType(ref stackMark);
// ask for member access if skip visibility
if (skipVisibility)
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
else
{
// if the call is not coming from the same class ask for member access
if (callingType != rtOwner)
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
}
#if !FEATURE_CORECLR
m_creatorAssembly = callingType.GetRuntimeAssembly();
// ask for control evidence if outside of the caller module
if (rtOwner.Assembly != m_creatorAssembly)
{
// Demand the permissions of the assembly where the DynamicMethod will live
CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence,
owner.Assembly.PermissionSet);
}
#else //FEATURE_CORECLR
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
#pragma warning restore 618
#endif //FEATURE_CORECLR
#endif //!FEATURE_CORECLR
}
//
// Delegate and method creation
//
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public sealed override Delegate CreateDelegate(Type delegateType) {
if (m_restrictedSkipVisibility)
{
// Compile the method since accessibility checks are done as part of compilation.
GetMethodDescriptor();
System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(m_methodHandle);
}
MulticastDelegate d = (MulticastDelegate)Delegate.CreateDelegateNoSecurityCheck(delegateType, null, GetMethodDescriptor());
// stash this MethodInfo by brute force.
d.StoreDynamicMethod(GetMethodInfo());
return d;
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public sealed override Delegate CreateDelegate(Type delegateType, Object target) {
if (m_restrictedSkipVisibility)
{
// Compile the method since accessibility checks are done as part of compilation
GetMethodDescriptor();
System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(m_methodHandle);
}
MulticastDelegate d = (MulticastDelegate)Delegate.CreateDelegateNoSecurityCheck(delegateType, target, GetMethodDescriptor());
// stash this MethodInfo by brute force.
d.StoreDynamicMethod(GetMethodInfo());
return d;
}
#if FEATURE_APPX
internal bool ProfileAPICheck
{
get
{
return m_profileAPICheck;
}
[FriendAccessAllowed]
set
{
m_profileAPICheck = value;
}
}
#endif
// This is guaranteed to return a valid handle
[System.Security.SecurityCritical] // auto-generated
internal unsafe RuntimeMethodHandle GetMethodDescriptor() {
if (m_methodHandle == null) {
lock (this) {
if (m_methodHandle == null) {
if (m_DynamicILInfo != null)
m_DynamicILInfo.GetCallableMethod(m_module, this);
else {
if (m_ilGenerator == null || m_ilGenerator.ILOffset == 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadEmptyMethodBody", Name));
m_ilGenerator.GetCallableMethod(m_module, this);
}
}
}
}
return new RuntimeMethodHandle(m_methodHandle);
}
//
// MethodInfo api. They mostly forward to RTDynamicMethod
//
public override String ToString() { return m_dynMethod.ToString(); }
public override String Name { get { return m_dynMethod.Name; } }
public override Type DeclaringType { get { return m_dynMethod.DeclaringType; } }
public override Type ReflectedType { get { return m_dynMethod.ReflectedType; } }
public override Module Module { get { return m_dynMethod.Module; } }
// we cannot return a MethodHandle because we cannot track it via GC so this method is off limits
public override RuntimeMethodHandle MethodHandle { get { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } }
public override MethodAttributes Attributes { get { return m_dynMethod.Attributes; } }
public override CallingConventions CallingConvention { get { return m_dynMethod.CallingConvention; } }
public override MethodInfo GetBaseDefinition() { return this; }
[Pure]
public override ParameterInfo[] GetParameters() { return m_dynMethod.GetParameters(); }
public override MethodImplAttributes GetMethodImplementationFlags() { return m_dynMethod.GetMethodImplementationFlags(); }
//
// Security transparency accessors
//
// Since the dynamic method may not be JITed yet, we don't always have the runtime method handle
// which is needed to determine the official runtime transparency status of the dynamic method. We
// fall back to saying that the dynamic method matches the transparency of its containing module
// until we get a JITed version, since dynamic methods cannot have attributes of their own.
//
public override bool IsSecurityCritical
{
[SecuritySafeCritical]
get
{
if (m_methodHandle != null)
{
return RuntimeMethodHandle.IsSecurityCritical(m_methodHandle);
}
else if (m_typeOwner != null)
{
RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly;
Contract.Assert(assembly != null);
return assembly.IsAllSecurityCritical();
}
else
{
RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly;
Contract.Assert(assembly != null);
return assembly.IsAllSecurityCritical();
}
}
}
public override bool IsSecuritySafeCritical
{
[SecuritySafeCritical]
get
{
if (m_methodHandle != null)
{
return RuntimeMethodHandle.IsSecuritySafeCritical(m_methodHandle);
}
else if (m_typeOwner != null)
{
RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly;
Contract.Assert(assembly != null);
return assembly.IsAllPublicAreaSecuritySafeCritical();
}
else
{
RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly;
Contract.Assert(assembly != null);
return assembly.IsAllSecuritySafeCritical();
}
}
}
public override bool IsSecurityTransparent
{
[SecuritySafeCritical]
get
{
if (m_methodHandle != null)
{
return RuntimeMethodHandle.IsSecurityTransparent(m_methodHandle);
}
else if (m_typeOwner != null)
{
RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly;
Contract.Assert(assembly != null);
return !assembly.IsAllSecurityCritical();
}
else
{
RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly;
Contract.Assert(assembly != null);
return !assembly.IsAllSecurityCritical();
}
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_CallToVarArg"));
Contract.EndContractBlock();
//
// We do not demand any permission here because the caller already has access
// to the current DynamicMethod object, and it could just as easily emit another
// Transparent DynamicMethod to call the current DynamicMethod.
//
RuntimeMethodHandle method = GetMethodDescriptor();
// ignore obj since it's a static method
// create a signature object
Signature sig = new Signature(
this.m_methodHandle, m_parameterTypes, m_returnType, CallingConvention);
// verify arguments
int formalCount = sig.Arguments.Length;
int actualCount = (parameters != null) ? parameters.Length : 0;
if (formalCount != actualCount)
throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt"));
// if we are here we passed all the previous checks. Time to look at the arguments
Object retValue = null;
if (actualCount > 0)
{
Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, false);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
parameters[index] = arguments[index];
}
else
{
retValue = RuntimeMethodHandle.InvokeMethod(null, null, sig, false);
}
GC.KeepAlive(this);
return retValue;
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return m_dynMethod.GetCustomAttributes(attributeType, inherit);
}
public override Object[] GetCustomAttributes(bool inherit) { return m_dynMethod.GetCustomAttributes(inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_dynMethod.IsDefined(attributeType, inherit); }
public override Type ReturnType { get { return m_dynMethod.ReturnType; } }
public override ParameterInfo ReturnParameter { get { return m_dynMethod.ReturnParameter; } }
public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return m_dynMethod.ReturnTypeCustomAttributes; } }
//
// DynamicMethod specific methods
//
public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String parameterName) {
if (position < 0 || position > m_parameterTypes.Length)
throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_ParamSequence"));
position--; // it's 1 based. 0 is the return value
if (position >= 0) {
ParameterInfo[] parameters = m_dynMethod.LoadParameters();
parameters[position].SetName(parameterName);
parameters[position].SetAttributes(attributes);
}
return null;
}
[System.Security.SecuritySafeCritical] // auto-generated
public DynamicILInfo GetDynamicILInfo()
{
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#pragma warning restore 618
if (m_DynamicILInfo != null)
return m_DynamicILInfo;
return GetDynamicILInfo(new DynamicScope());
}
[System.Security.SecurityCritical] // auto-generated
internal DynamicILInfo GetDynamicILInfo(DynamicScope scope)
{
if (m_DynamicILInfo == null)
{
byte[] methodSignature = SignatureHelper.GetMethodSigHelper(
null, CallingConvention, ReturnType, null, null, m_parameterTypes, null, null).GetSignature(true);
m_DynamicILInfo = new DynamicILInfo(scope, this, methodSignature);
}
return m_DynamicILInfo;
}
public ILGenerator GetILGenerator() {
return GetILGenerator(64);
}
[System.Security.SecuritySafeCritical] // auto-generated
public ILGenerator GetILGenerator(int streamSize)
{
if (m_ilGenerator == null)
{
byte[] methodSignature = SignatureHelper.GetMethodSigHelper(
null, CallingConvention, ReturnType, null, null, m_parameterTypes, null, null).GetSignature(true);
m_ilGenerator = new DynamicILGenerator(this, methodSignature, streamSize);
}
return m_ilGenerator;
}
public bool InitLocals {
get {return m_fInitLocals;}
set {m_fInitLocals = value;}
}
//
// Internal API
//
internal MethodInfo GetMethodInfo() {
return m_dynMethod;
}
//////////////////////////////////////////////////////////////////////////////////////////////
// RTDynamicMethod
//
// this is actually the real runtime instance of a method info that gets used for invocation
// We need this so we never leak the DynamicMethod out via an exception.
// This way the DynamicMethod creator is the only one responsible for DynamicMethod access,
// and can control exactly who gets access to it.
//
internal class RTDynamicMethod : MethodInfo {
internal DynamicMethod m_owner;
ParameterInfo[] m_parameters;
String m_name;
MethodAttributes m_attributes;
CallingConventions m_callingConvention;
//
// ctors
//
private RTDynamicMethod() {}
internal RTDynamicMethod(DynamicMethod owner, String name, MethodAttributes attributes, CallingConventions callingConvention) {
m_owner = owner;
m_name = name;
m_attributes = attributes;
m_callingConvention = callingConvention;
}
//
// MethodInfo api
//
public override String ToString() {
return ReturnType.FormatTypeName() + " " + FormatNameAndSig();
}
public override String Name {
get { return m_name; }
}
public override Type DeclaringType {
get { return null; }
}
public override Type ReflectedType {
get { return null; }
}
public override Module Module {
get { return m_owner.m_module; }
}
public override RuntimeMethodHandle MethodHandle {
get { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); }
}
public override MethodAttributes Attributes {
get { return m_attributes; }
}
public override CallingConventions CallingConvention {
get { return m_callingConvention; }
}
public override MethodInfo GetBaseDefinition() {
return this;
}
[Pure]
public override ParameterInfo[] GetParameters() {
ParameterInfo[] privateParameters = LoadParameters();
ParameterInfo[] parameters = new ParameterInfo[privateParameters.Length];
Array.Copy(privateParameters, parameters, privateParameters.Length);
return parameters;
}
public override MethodImplAttributes GetMethodImplementationFlags() {
return MethodImplAttributes.IL | MethodImplAttributes.NoInlining;
}
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
// We want the creator of the DynamicMethod to control who has access to the
// DynamicMethod (just like we do for delegates). However, a user can get to
// the corresponding RTDynamicMethod using Exception.TargetSite, StackFrame.GetMethod, etc.
// If we allowed use of RTDynamicMethod, the creator of the DynamicMethod would
// not be able to bound access to the DynamicMethod. Hence, we do not allow
// direct use of RTDynamicMethod.
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "this");
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) {
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute)))
return new Object[] { new MethodImplAttribute(GetMethodImplementationFlags()) };
else
return EmptyArray<Object>.Value;
}
public override Object[] GetCustomAttributes(bool inherit) {
// support for MethodImplAttribute PCA
return new Object[] { new MethodImplAttribute(GetMethodImplementationFlags()) };
}
public override bool IsDefined(Type attributeType, bool inherit) {
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute)))
return true;
else
return false;
}
public override bool IsSecurityCritical
{
get { return m_owner.IsSecurityCritical; }
}
public override bool IsSecuritySafeCritical
{
get { return m_owner.IsSecuritySafeCritical; }
}
public override bool IsSecurityTransparent
{
get { return m_owner.IsSecurityTransparent; }
}
public override Type ReturnType
{
get
{
return m_owner.m_returnType;
}
}
public override ParameterInfo ReturnParameter {
get { return null; }
}
public override ICustomAttributeProvider ReturnTypeCustomAttributes {
get { return GetEmptyCAHolder(); }
}
//
// private implementation
//
internal ParameterInfo[] LoadParameters() {
if (m_parameters == null) {
Type[] parameterTypes = m_owner.m_parameterTypes;
ParameterInfo[] parameters = new ParameterInfo[parameterTypes.Length];
for (int i = 0; i < parameterTypes.Length; i++)
parameters[i] = new RuntimeParameterInfo(this, null, parameterTypes[i], i);
if (m_parameters == null)
// should we interlockexchange?
m_parameters = parameters;
}
return m_parameters;
}
// private implementation of CA for the return type
private ICustomAttributeProvider GetEmptyCAHolder() {
return new EmptyCAHolder();
}
///////////////////////////////////////////////////
// EmptyCAHolder
private class EmptyCAHolder : ICustomAttributeProvider {
internal EmptyCAHolder() {}
Object[] ICustomAttributeProvider.GetCustomAttributes(Type attributeType, bool inherit) {
return EmptyArray<Object>.Value;
}
Object[] ICustomAttributeProvider.GetCustomAttributes(bool inherit) {
return EmptyArray<Object>.Value;
}
bool ICustomAttributeProvider.IsDefined (Type attributeType, bool inherit) {
return false;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using OLEDB.Test.ModuleCore;
using Xunit;
namespace System.Xml.Tests
{
public partial class SubtreeReaderTest : CGenericTestModule
{
private static void RunTestCaseAsync(Func<CTestBase> testCaseGenerator)
{
CModInfo.CommandLine = "/async";
RunTestCase(testCaseGenerator);
}
private static void RunTestCase(Func<CTestBase> testCaseGenerator)
{
var module = new SubtreeReaderTest();
module.Init(null);
module.AddChild(testCaseGenerator());
module.Execute();
Assert.Equal(0, module.FailCount);
}
private static void RunTest(Func<CTestBase> testCaseGenerator)
{
RunTestCase(testCaseGenerator);
RunTestCaseAsync(testCaseGenerator);
}
[Fact]
[OuterLoop]
public static void InvalidXMLReader()
{
RunTest(() => new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ErrorConditionReader()
{
RunTest(() => new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void DepthReader()
{
RunTest(() => new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void NamespaceReader()
{
RunTest(() => new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void LookupNamespaceReader()
{
RunTest(() => new TCLookupNamespaceReader() { Attribute = new TestCase() { Name = "LookupNamespace", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void IsEmptyElementReader()
{
RunTest(() => new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void XmlSpaceReader()
{
RunTest(() => new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void XmlLangReader()
{
RunTest(() => new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void SkipReader()
{
RunTest(() => new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ReadOuterXmlReader()
{
RunTest(() => new TCReadOuterXmlReader() { Attribute = new TestCase() { Name = "ReadOuterXml", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeAccessReader()
{
RunTest(() => new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ThisNameReader()
{
RunTest(() => new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToAttributeReader()
{
RunTest(() => new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void GetAttributeOrdinalReader()
{
RunTest(() => new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void GetAttributeNameReader()
{
RunTest(() => new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ThisOrdinalReader()
{
RunTest(() => new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToAttributeOrdinalReader()
{
RunTest(() => new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToFirstAttributeReader()
{
RunTest(() => new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToNextAttributeReader()
{
RunTest(() => new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeTestReader()
{
RunTest(() => new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void XmlnsReader()
{
RunTest(() => new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name DCR50345", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void XmlnsPrefixReader()
{
RunTest(() => new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix DCR50881", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ReadInnerXmlReader()
{
RunTest(() => new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToContentReader()
{
RunTest(() => new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void IsStartElementReader()
{
RunTest(() => new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ReadStartElementReader()
{
RunTest(() => new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ReadEndElementReader()
{
RunTest(() => new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ResolveEntityReader()
{
RunTest(() => new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void HasValueReader()
{
RunTest(() => new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ReadAttributeValueReader()
{
RunTest(() => new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ReadReader()
{
RunTest(() => new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToElementReader()
{
RunTest(() => new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void DisposeReader()
{
RunTest(() => new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void BufferBoundariesReader()
{
RunTest(() => new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileBeforeRead()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterCloseInMiddle()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterClose()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterReadIsFalse()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } });
}
[Fact]
[OuterLoop]
public static void ReadSubtreeReader()
{
RunTest(() => new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToDescendantReader()
{
RunTest(() => new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToNextSiblingReader()
{
RunTest(() => new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ReadValueReader()
{
RunTest(() => new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ReadContentAsBase64Reader()
{
RunTest(() => new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ReadElementContentAsBase64Reader()
{
RunTest(() => new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ReadContentAsBinHexReader()
{
RunTest(() => new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ReadElementContentAsBinHexReader()
{
RunTest(() => new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "SubtreeReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToFollowingReader()
{
RunTest(() => new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "SubtreeReader" } });
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Xunit.Performance;
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Collections.Generic;
using Xunit;
[assembly: OptimizeForBenchmarks]
[assembly: MeasureInstructionsRetired]
public static class ConstantArgsULong
{
#if DEBUG
public const int Iterations = 1;
#else
public const int Iterations = 100000;
#endif
// Ints feeding math operations.
//
// Inlining in Bench0xp should enable constant folding
// Inlining in Bench0xn will not enable constant folding
static ulong Five = 5;
static ulong Ten = 10;
static ulong Id(ulong x)
{
return x;
}
static ulong F00(ulong x)
{
return x * x;
}
static bool Bench00p()
{
ulong t = 10;
ulong f = F00(t);
return (f == 100);
}
static bool Bench00n()
{
ulong t = Ten;
ulong f = F00(t);
return (f == 100);
}
static bool Bench00p1()
{
ulong t = Id(10);
ulong f = F00(t);
return (f == 100);
}
static bool Bench00n1()
{
ulong t = Id(Ten);
ulong f = F00(t);
return (f == 100);
}
static bool Bench00p2()
{
ulong t = Id(10);
ulong f = F00(Id(t));
return (f == 100);
}
static bool Bench00n2()
{
ulong t = Id(Ten);
ulong f = F00(Id(t));
return (f == 100);
}
static bool Bench00p3()
{
ulong t = 10;
ulong f = F00(Id(Id(t)));
return (f == 100);
}
static bool Bench00n3()
{
ulong t = Ten;
ulong f = F00(Id(Id(t)));
return (f == 100);
}
static bool Bench00p4()
{
ulong t = 5;
ulong f = F00(2 * t);
return (f == 100);
}
static bool Bench00n4()
{
ulong t = Five;
ulong f = F00(2 * t);
return (f == 100);
}
static ulong F01(ulong x)
{
return 1000 / x;
}
static bool Bench01p()
{
ulong t = 10;
ulong f = F01(t);
return (f == 100);
}
static bool Bench01n()
{
ulong t = Ten;
ulong f = F01(t);
return (f == 100);
}
static ulong F02(ulong x)
{
return 20 * (x / 2);
}
static bool Bench02p()
{
ulong t = 10;
ulong f = F02(t);
return (f == 100);
}
static bool Bench02n()
{
ulong t = Ten;
ulong f = F02(t);
return (f == 100);
}
static ulong F03(ulong x)
{
return 91 + 1009 % x;
}
static bool Bench03p()
{
ulong t = 10;
ulong f = F03(t);
return (f == 100);
}
static bool Bench03n()
{
ulong t = Ten;
ulong f = F03(t);
return (f == 100);
}
static ulong F04(ulong x)
{
return 50 * (x % 4);
}
static bool Bench04p()
{
ulong t = 10;
ulong f = F04(t);
return (f == 100);
}
static bool Bench04n()
{
ulong t = Ten;
ulong f = F04(t);
return (f == 100);
}
static ulong F06(ulong x)
{
return 110 - x;
}
static bool Bench06p()
{
ulong t = 10;
ulong f = F06(t);
return (f == 100);
}
static bool Bench06n()
{
ulong t = Ten;
ulong f = F06(t);
return (f == 100);
}
static ulong F07(ulong x)
{
return ~x + 111;
}
static bool Bench07p()
{
ulong t = 10;
ulong f = F07(t);
return (f == 100);
}
static bool Bench07n()
{
ulong t = Ten;
ulong f = F07(t);
return (f == 100);
}
static ulong F071(ulong x)
{
return (x ^ 0xFFFFFFFFFFFFFFFF) + 111;
}
static bool Bench07p1()
{
ulong t = 10;
ulong f = F071(t);
return (f == 100);
}
static bool Bench07n1()
{
ulong t = Ten;
ulong f = F071(t);
return (f == 100);
}
static ulong F08(ulong x)
{
return (x & 0x7) + 98;
}
static bool Bench08p()
{
ulong t = 10;
ulong f = F08(t);
return (f == 100);
}
static bool Bench08n()
{
ulong t = Ten;
ulong f = F08(t);
return (f == 100);
}
static ulong F09(ulong x)
{
return (x | 0x7) + 85;
}
static bool Bench09p()
{
ulong t = 10;
ulong f = F09(t);
return (f == 100);
}
static bool Bench09n()
{
ulong t = Ten;
ulong f = F09(t);
return (f == 100);
}
// Ulongs feeding comparisons.
//
// Inlining in Bench1xp should enable branch optimization
// Inlining in Bench1xn will not enable branch optimization
static ulong F10(ulong x)
{
return x == 10 ? 100u : 0u;
}
static bool Bench10p()
{
ulong t = 10;
ulong f = F10(t);
return (f == 100);
}
static bool Bench10n()
{
ulong t = Ten;
ulong f = F10(t);
return (f == 100);
}
static ulong F101(ulong x)
{
return x != 10 ? 0u : 100u;
}
static bool Bench10p1()
{
ulong t = 10;
ulong f = F101(t);
return (f == 100);
}
static bool Bench10n1()
{
ulong t = Ten;
ulong f = F101(t);
return (f == 100);
}
static ulong F102(ulong x)
{
return x >= 10 ? 100u : 0u;
}
static bool Bench10p2()
{
ulong t = 10;
ulong f = F102(t);
return (f == 100);
}
static bool Bench10n2()
{
ulong t = Ten;
ulong f = F102(t);
return (f == 100);
}
static ulong F103(ulong x)
{
return x <= 10 ? 100u : 0u;
}
static bool Bench10p3()
{
ulong t = 10;
ulong f = F103(t);
return (f == 100);
}
static bool Bench10n3()
{
ulong t = Ten;
ulong f = F102(t);
return (f == 100);
}
static ulong F11(ulong x)
{
if (x == 10)
{
return 100;
}
else
{
return 0;
}
}
static bool Bench11p()
{
ulong t = 10;
ulong f = F11(t);
return (f == 100);
}
static bool Bench11n()
{
ulong t = Ten;
ulong f = F11(t);
return (f == 100);
}
static ulong F111(ulong x)
{
if (x != 10)
{
return 0;
}
else
{
return 100;
}
}
static bool Bench11p1()
{
ulong t = 10;
ulong f = F111(t);
return (f == 100);
}
static bool Bench11n1()
{
ulong t = Ten;
ulong f = F111(t);
return (f == 100);
}
static ulong F112(ulong x)
{
if (x > 10)
{
return 0;
}
else
{
return 100;
}
}
static bool Bench11p2()
{
ulong t = 10;
ulong f = F112(t);
return (f == 100);
}
static bool Bench11n2()
{
ulong t = Ten;
ulong f = F112(t);
return (f == 100);
}
static ulong F113(ulong x)
{
if (x < 10)
{
return 0;
}
else
{
return 100;
}
}
static bool Bench11p3()
{
ulong t = 10;
ulong f = F113(t);
return (f == 100);
}
static bool Bench11n3()
{
ulong t = Ten;
ulong f = F113(t);
return (f == 100);
}
// Ununsed (or effectively unused) parameters
//
// Simple callee analysis may overstate inline benefit
static ulong F20(ulong x)
{
return 100;
}
static bool Bench20p()
{
ulong t = 10;
ulong f = F20(t);
return (f == 100);
}
static bool Bench20p1()
{
ulong t = Ten;
ulong f = F20(t);
return (f == 100);
}
static ulong F21(ulong x)
{
return x + 100 - x;
}
static bool Bench21p()
{
ulong t = 10;
ulong f = F21(t);
return (f == 100);
}
static bool Bench21n()
{
ulong t = Ten;
ulong f = F21(t);
return (f == 100);
}
static ulong F211(ulong x)
{
return x - x + 100;
}
static bool Bench21p1()
{
ulong t = 10;
ulong f = F211(t);
return (f == 100);
}
static bool Bench21n1()
{
ulong t = Ten;
ulong f = F211(t);
return (f == 100);
}
static ulong F22(ulong x)
{
if (x > 0)
{
return 100;
}
return 100;
}
static bool Bench22p()
{
ulong t = 10;
ulong f = F22(t);
return (f == 100);
}
static bool Bench22p1()
{
ulong t = Ten;
ulong f = F22(t);
return (f == 100);
}
static ulong F23(ulong x)
{
if (x > 0)
{
return 90 + x;
}
return 100;
}
static bool Bench23p()
{
ulong t = 10;
ulong f = F23(t);
return (f == 100);
}
static bool Bench23n()
{
ulong t = Ten;
ulong f = F23(t);
return (f == 100);
}
// Multiple parameters
static ulong F30(ulong x, ulong y)
{
return y * y;
}
static bool Bench30p()
{
ulong t = 10;
ulong f = F30(t, t);
return (f == 100);
}
static bool Bench30n()
{
ulong t = Ten;
ulong f = F30(t, t);
return (f == 100);
}
static bool Bench30p1()
{
ulong s = Ten;
ulong t = 10;
ulong f = F30(s, t);
return (f == 100);
}
static bool Bench30n1()
{
ulong s = 10;
ulong t = Ten;
ulong f = F30(s, t);
return (f == 100);
}
static bool Bench30p2()
{
ulong s = 10;
ulong t = 10;
ulong f = F30(s, t);
return (f == 100);
}
static bool Bench30n2()
{
ulong s = Ten;
ulong t = Ten;
ulong f = F30(s, t);
return (f == 100);
}
static bool Bench30p3()
{
ulong s = 10;
ulong t = s;
ulong f = F30(s, t);
return (f == 100);
}
static bool Bench30n3()
{
ulong s = Ten;
ulong t = s;
ulong f = F30(s, t);
return (f == 100);
}
static ulong F31(ulong x, ulong y, ulong z)
{
return z * z;
}
static bool Bench31p()
{
ulong t = 10;
ulong f = F31(t, t, t);
return (f == 100);
}
static bool Bench31n()
{
ulong t = Ten;
ulong f = F31(t, t, t);
return (f == 100);
}
static bool Bench31p1()
{
ulong r = Ten;
ulong s = Ten;
ulong t = 10;
ulong f = F31(r, s, t);
return (f == 100);
}
static bool Bench31n1()
{
ulong r = 10;
ulong s = 10;
ulong t = Ten;
ulong f = F31(r, s, t);
return (f == 100);
}
static bool Bench31p2()
{
ulong r = 10;
ulong s = 10;
ulong t = 10;
ulong f = F31(r, s, t);
return (f == 100);
}
static bool Bench31n2()
{
ulong r = Ten;
ulong s = Ten;
ulong t = Ten;
ulong f = F31(r, s, t);
return (f == 100);
}
static bool Bench31p3()
{
ulong r = 10;
ulong s = r;
ulong t = s;
ulong f = F31(r, s, t);
return (f == 100);
}
static bool Bench31n3()
{
ulong r = Ten;
ulong s = r;
ulong t = s;
ulong f = F31(r, s, t);
return (f == 100);
}
// Two args, both used
static ulong F40(ulong x, ulong y)
{
return x * x + y * y - 100;
}
static bool Bench40p()
{
ulong t = 10;
ulong f = F40(t, t);
return (f == 100);
}
static bool Bench40n()
{
ulong t = Ten;
ulong f = F40(t, t);
return (f == 100);
}
static bool Bench40p1()
{
ulong s = Ten;
ulong t = 10;
ulong f = F40(s, t);
return (f == 100);
}
static bool Bench40p2()
{
ulong s = 10;
ulong t = Ten;
ulong f = F40(s, t);
return (f == 100);
}
static ulong F41(ulong x, ulong y)
{
return x * y;
}
static bool Bench41p()
{
ulong t = 10;
ulong f = F41(t, t);
return (f == 100);
}
static bool Bench41n()
{
ulong t = Ten;
ulong f = F41(t, t);
return (f == 100);
}
static bool Bench41p1()
{
ulong s = 10;
ulong t = Ten;
ulong f = F41(s, t);
return (f == 100);
}
static bool Bench41p2()
{
ulong s = Ten;
ulong t = 10;
ulong f = F41(s, t);
return (f == 100);
}
private static IEnumerable<object[]> MakeArgs(params string[] args)
{
return args.Select(arg => new object[] { arg });
}
public static IEnumerable<object[]> TestFuncs = MakeArgs(
"Bench00p", "Bench00n",
"Bench00p1", "Bench00n1",
"Bench00p2", "Bench00n2",
"Bench00p3", "Bench00n3",
"Bench00p4", "Bench00n4",
"Bench01p", "Bench01n",
"Bench02p", "Bench02n",
"Bench03p", "Bench03n",
"Bench04p", "Bench04n",
"Bench06p", "Bench06n",
"Bench07p", "Bench07n",
"Bench07p1", "Bench07n1",
"Bench08p", "Bench08n",
"Bench09p", "Bench09n",
"Bench10p", "Bench10n",
"Bench10p1", "Bench10n1",
"Bench10p2", "Bench10n2",
"Bench10p3", "Bench10n3",
"Bench11p", "Bench11n",
"Bench11p1", "Bench11n1",
"Bench11p2", "Bench11n2",
"Bench11p3", "Bench11n3",
"Bench20p", "Bench20p1",
"Bench21p", "Bench21n",
"Bench21p1", "Bench21n1",
"Bench22p", "Bench22p1",
"Bench23p", "Bench23n",
"Bench30p", "Bench30n",
"Bench30p1", "Bench30n1",
"Bench30p2", "Bench30n2",
"Bench30p3", "Bench30n3",
"Bench31p", "Bench31n",
"Bench31p1", "Bench31n1",
"Bench31p2", "Bench31n2",
"Bench31p3", "Bench31n3",
"Bench40p", "Bench40n",
"Bench40p1", "Bench40p2",
"Bench41p", "Bench41n",
"Bench41p1", "Bench41p2"
);
static Func<bool> LookupFunc(object o)
{
TypeInfo t = typeof(ConstantArgsULong).GetTypeInfo();
MethodInfo m = t.GetDeclaredMethod((string) o);
return m.CreateDelegate(typeof(Func<bool>)) as Func<bool>;
}
[Benchmark]
[MemberData(nameof(TestFuncs))]
public static void Test(object funcName)
{
Func<bool> f = LookupFunc(funcName);
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Iterations; i++)
{
f();
}
}
}
}
static bool TestBase(Func<bool> f)
{
bool result = true;
for (int i = 0; i < Iterations; i++)
{
result &= f();
}
return result;
}
public static int Main()
{
bool result = true;
foreach(object[] o in TestFuncs)
{
string funcName = (string) o[0];
Func<bool> func = LookupFunc(funcName);
bool thisResult = TestBase(func);
if (!thisResult)
{
Console.WriteLine("{0} failed", funcName);
}
result &= thisResult;
}
return (result ? 100 : -1);
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using DevExpress.Mvvm.Native;
using DevExpress.Xpf.Core.Native;
namespace DevExpress.Mvvm.UI.Native {
public delegate void UnregisterCallback<E>(EventHandler<E> eventHandler) where E : EventArgs;
public interface IAnotherWeakEventHandler<E> where E : EventArgs {
EventHandler<E> Handler { get; }
}
public class AnotherWeakEventHandler<T, E> : IAnotherWeakEventHandler<E> where T : class where E : EventArgs {
private delegate void OpenEventHandler(T @this, object sender, E e);
private WeakReference m_TargetRef;
private OpenEventHandler m_OpenHandler;
private EventHandler<E> m_Handler;
private UnregisterCallback<E> m_Unregister;
public AnotherWeakEventHandler(EventHandler<E> eventHandler, UnregisterCallback<E> unregister) {
m_TargetRef = new WeakReference(eventHandler.Target);
m_OpenHandler = (OpenEventHandler)Delegate.CreateDelegate(typeof(OpenEventHandler), null, eventHandler.Method);
m_Handler = Invoke;
m_Unregister = unregister;
}
public void Invoke(object sender, E e) {
T target = (T)m_TargetRef.Target;
if(target != null)
m_OpenHandler.Invoke(target, sender, e);
else if(m_Unregister != null) {
m_Unregister(m_Handler);
m_Unregister = null;
}
}
public EventHandler<E> Handler { get { return m_Handler; } }
public static implicit operator EventHandler<E>(AnotherWeakEventHandler<T, E> weh) { return weh.m_Handler; }
}
public static class AnotherEventHandlerUtils {
public static EventHandler<E> MakeWeak<E>(EventHandler<E> eventHandler, UnregisterCallback<E> unregister) where E : EventArgs {
if(eventHandler == null)
throw new ArgumentNullException("eventHandler");
if(eventHandler.Method.IsStatic || eventHandler.Target == null)
throw new ArgumentException("Only instance methods are supported.", "eventHandler");
Type wehType = typeof(AnotherWeakEventHandler<,>).MakeGenericType(eventHandler.Method.DeclaringType, typeof(E));
ConstructorInfo wehConstructor = wehType.GetConstructor(new Type[] { typeof(EventHandler<E>), typeof(UnregisterCallback<E>) });
IAnotherWeakEventHandler<E> weh = (IAnotherWeakEventHandler<E>)wehConstructor.Invoke(new object[] { eventHandler, unregister });
return weh.Handler;
}
}
public interface IScreen {
Rect GetWorkingArea(System.Windows.Point point);
event Action WorkingAreaChanged;
}
public class PrimaryScreen : IScreen {
static PrimaryScreen() {
Microsoft.Win32.SystemEvents.DisplaySettingsChanged += SystemEvents_DisplaySettingsChanged;
}
static void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e) {
if(DisplaySettingsChanged != null)
DisplaySettingsChanged(sender, e);
}
static event EventHandler<EventArgs> DisplaySettingsChanged;
public PrimaryScreen() {
DisplaySettingsChanged += AnotherEventHandlerUtils.MakeWeak<EventArgs>((s, e) => {
if(WorkingAreaChanged != null)
WorkingAreaChanged();
}, handler => DisplaySettingsChanged -= handler);
}
public static System.Windows.Point GetDpi(System.Windows.Point screenPoint) {
System.Windows.Point graphicsDpi;
graphicsDpi = GetGraphicsDpi();
return new System.Windows.Point(graphicsDpi.X / 96, graphicsDpi.Y / 96);
}
public Rect GetWorkingArea(System.Windows.Point point) {
var dpi = GetDpi(point);
var area = Screen.GetWorkingArea(new System.Drawing.Point((int)point.X + 1, (int)point.Y + 1));
return new Rect(area.X / dpi.X, area.Y / dpi.Y, area.Width / dpi.X, area.Height / dpi.Y);
}
static System.Windows.Point GetGraphicsDpi() {
System.Windows.Point dpi;
using(var textBox = new System.Windows.Forms.TextBox()) {
using(var graphics = textBox.CreateGraphics()) {
dpi = new System.Windows.Point(graphics.DpiX, graphics.DpiY);
}
}
return dpi;
}
public event Action WorkingAreaChanged;
}
public class CustomNotifier {
internal
class ToastInfo {
public Window win;
public CustomNotification toast;
public Timer timer;
public TaskCompletionSource<NotificationResult> source;
}
readonly List<ToastInfo> toastsQueue = new List<ToastInfo>();
const int maxVisibleToasts = 3;
internal static NotificationPositioner<ToastInfo> positioner;
IScreen screen;
System.Windows.Point currentScreenPosition = new System.Windows.Point();
public Style Style { get; set; }
public CustomNotifier(IScreen screen = null) {
this.screen = screen ?? new PrimaryScreen();
this.screen.WorkingAreaChanged += screen_WorkingAreaChanged;
UpdatePositioner(NotificationPosition.TopRight, maxVisibleToasts);
}
List<ToastInfo> VisibleItems {
get { return positioner.Items.Where(i => i != null).ToList(); }
}
public void ChangeScreen(System.Windows.Point position) {
if(VisibleItems.Any() || currentScreenPosition == position)
return;
currentScreenPosition = position;
UpdatePositioner(positioner.position, positioner.maxCount);
}
void screen_WorkingAreaChanged() {
positioner.Update(screen.GetWorkingArea(currentScreenPosition));
foreach (ToastInfo info in VisibleItems) {
info.timer.Stop();
info.timer.Start();
var newPos = positioner.GetItemPosition(info);
info.win.Left = newPos.X;
info.win.Top = newPos.Y;
}
}
public void UpdatePositioner(NotificationPosition position, int maxCount) {
if(positioner == null) {
positioner = new NotificationPositioner<ToastInfo>();
}
positioner.Update(screen.GetWorkingArea(currentScreenPosition), position, maxCount);
}
public Task<NotificationResult> ShowAsync(CustomNotification toast, int msDuration = 3000) {
var info = new ToastInfo {
toast = toast,
timer = new Timer() { Interval = msDuration },
source = new TaskCompletionSource<NotificationResult>()
};
toastsQueue.Add(info);
ShowNext();
return info.source.Task;
}
void ShowNext() {
if(!positioner.HasEmptySlot() || !toastsQueue.Any())
return;
ToastInfo info = toastsQueue[0];
toastsQueue.RemoveAt(0);
var content = new ToastContentControl() { Toast = info.toast };
content.Content = info.toast.ViewModel;
content.Style = Style;
if(ContentTemplateSelector == null) {
content.ContentTemplate = ContentTemplate ?? NotificationServiceTemplatesHelper.DefaultCustomToastTemplate;
}
content.ContentTemplateSelector = ContentTemplateSelector;
try {
info.win = new ToastWindow();
} catch {
content.TimeOutCommand.Execute(null);
return;
}
info.win.Content = content;
info.win.DataContext = info.toast.ViewModel;
if(double.IsNaN(content.Width) || double.IsNaN(content.Height))
throw new InvalidOperationException("The height or width of a custom notification can not be set to Auto");
System.Windows.Point position = positioner.Add(info, content.Width, content.Height);
info.win.Left = position.X;
info.win.Top = position.Y;
try {
info.win.Show();
} catch(System.ComponentModel.Win32Exception) {
content.TimeOutCommand.Execute(null);
return;
}
info.timer.Tick += (s, e) => {
content.TimeOutCommand.Execute(null);
info.timer.Stop();
};
info.timer.Start();
}
internal void Activate(CustomNotification toast) {
RemoveVisibleToast(toast, NotificationResult.Activated);
ShowNext();
}
internal void Dismiss(CustomNotification toast) {
RemoveVisibleToast(toast, NotificationResult.UserCanceled);
ShowNext();
}
internal void TimeOut(CustomNotification toast) {
RemoveVisibleToast(toast, NotificationResult.TimedOut);
ShowNext();
}
internal void Hide(CustomNotification toast) {
ToastInfo info = toastsQueue.FirstOrDefault(i => i.toast == toast);
if(info != null) {
toastsQueue.Remove(info);
info.source.SetResult(NotificationResult.ApplicationHidden);
return;
}
RemoveVisibleToast(toast, NotificationResult.ApplicationHidden);
ShowNext();
}
void RemoveVisibleToast(CustomNotification toast, NotificationResult result) {
ToastInfo info = GetVisibleToastInfo(toast);
if(info == null) {
return;
}
info.win.Close();
info.timer.Stop();
positioner.Remove(info);
info.source.SetResult(result);
}
private ToastInfo GetVisibleToastInfo(CustomNotification toast) {
return positioner.Items.FirstOrDefault(t => t != null && t.toast == toast);
}
internal void StopTimer(CustomNotification toast) {
GetVisibleToastInfo(toast).Do(t => t.timer.Stop());
}
internal void ResetTimer(CustomNotification toast) {
GetVisibleToastInfo(toast).Do(t => t.timer.Start());
}
public DataTemplate ContentTemplate { get; set; }
public DataTemplateSelector ContentTemplateSelector { get; set; }
}
}
| |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="none" email=""/>
// <version>$Revision: 3205 $</version>
// </file>
using System;
using System.Drawing;
using System.Text;
namespace ICSharpCode.TextEditor.Document
{
public enum BracketMatchingStyle {
Before,
After
}
public class DefaultTextEditorProperties : ITextEditorProperties
{
int tabIndent = 4;
int indentationSize = 4;
IndentStyle indentStyle = IndentStyle.Smart;
DocumentSelectionMode documentSelectionMode = DocumentSelectionMode.Normal;
Encoding encoding = System.Text.Encoding.UTF8;
BracketMatchingStyle bracketMatchingStyle = BracketMatchingStyle.After;
FontContainer fontContainer;
static Font DefaultFont;
public DefaultTextEditorProperties()
{
if (DefaultFont == null) {
DefaultFont = new Font("Courier New", 10);
}
this.fontContainer = new FontContainer(DefaultFont);
}
bool allowCaretBeyondEOL = false;
bool showMatchingBracket = true;
bool showLineNumbers = true;
bool showSpaces = false;
bool showTabs = false;
bool showEOLMarker = false;
bool showInvalidLines = false;
bool isIconBarVisible = false;
bool enableFolding = true;
bool showHorizontalRuler = false;
bool showVerticalRuler = true;
bool convertTabsToSpaces = false;
System.Drawing.Text.TextRenderingHint textRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault;
bool mouseWheelScrollDown = true;
bool mouseWheelTextZoom = true;
bool hideMouseCursor = false;
bool cutCopyWholeLine = true;
int verticalRulerRow = 80;
LineViewerStyle lineViewerStyle = LineViewerStyle.None;
string lineTerminator = "\r\n";
bool autoInsertCurlyBracket = true;
bool supportReadOnlySegments = false;
public int TabIndent {
get {
return tabIndent;
}
set {
tabIndent = value;
}
}
public int IndentationSize {
get { return indentationSize; }
set { indentationSize = value; }
}
public IndentStyle IndentStyle {
get {
return indentStyle;
}
set {
indentStyle = value;
}
}
public DocumentSelectionMode DocumentSelectionMode {
get {
return documentSelectionMode;
}
set {
documentSelectionMode = value;
}
}
public bool AllowCaretBeyondEOL {
get {
return allowCaretBeyondEOL;
}
set {
allowCaretBeyondEOL = value;
}
}
public bool ShowMatchingBracket {
get {
return showMatchingBracket;
}
set {
showMatchingBracket = value;
}
}
public bool ShowLineNumbers {
get {
return showLineNumbers;
}
set {
showLineNumbers = value;
}
}
public bool ShowSpaces {
get {
return showSpaces;
}
set {
showSpaces = value;
}
}
public bool ShowTabs {
get {
return showTabs;
}
set {
showTabs = value;
}
}
public bool ShowEOLMarker {
get {
return showEOLMarker;
}
set {
showEOLMarker = value;
}
}
public bool ShowInvalidLines {
get {
return showInvalidLines;
}
set {
showInvalidLines = value;
}
}
public bool IsIconBarVisible {
get {
return isIconBarVisible;
}
set {
isIconBarVisible = value;
}
}
public bool EnableFolding {
get {
return enableFolding;
}
set {
enableFolding = value;
}
}
public bool ShowHorizontalRuler {
get {
return showHorizontalRuler;
}
set {
showHorizontalRuler = value;
}
}
public bool ShowVerticalRuler {
get {
return showVerticalRuler;
}
set {
showVerticalRuler = value;
}
}
public bool ConvertTabsToSpaces {
get {
return convertTabsToSpaces;
}
set {
convertTabsToSpaces = value;
}
}
public System.Drawing.Text.TextRenderingHint TextRenderingHint {
get { return textRenderingHint; }
set { textRenderingHint = value; }
}
public bool MouseWheelScrollDown {
get {
return mouseWheelScrollDown;
}
set {
mouseWheelScrollDown = value;
}
}
public bool MouseWheelTextZoom {
get {
return mouseWheelTextZoom;
}
set {
mouseWheelTextZoom = value;
}
}
public bool HideMouseCursor {
get {
return hideMouseCursor;
}
set {
hideMouseCursor = value;
}
}
public bool CutCopyWholeLine {
get {
return cutCopyWholeLine;
}
set {
cutCopyWholeLine = value;
}
}
public Encoding Encoding {
get {
return encoding;
}
set {
encoding = value;
}
}
public int VerticalRulerRow {
get {
return verticalRulerRow;
}
set {
verticalRulerRow = value;
}
}
public LineViewerStyle LineViewerStyle {
get {
return lineViewerStyle;
}
set {
lineViewerStyle = value;
}
}
public string LineTerminator {
get {
return lineTerminator;
}
set {
lineTerminator = value;
}
}
public bool AutoInsertCurlyBracket {
get {
return autoInsertCurlyBracket;
}
set {
autoInsertCurlyBracket = value;
}
}
public Font Font {
get {
return fontContainer.DefaultFont;
}
set {
fontContainer.DefaultFont = value;
}
}
public FontContainer FontContainer {
get {
return fontContainer;
}
}
public BracketMatchingStyle BracketMatchingStyle {
get {
return bracketMatchingStyle;
}
set {
bracketMatchingStyle = value;
}
}
public bool SupportReadOnlySegments {
get {
return supportReadOnlySegments;
}
set {
supportReadOnlySegments = 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 Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
internal const string AnonymousPipeName = "anonymous";
private static readonly Task<int> s_zeroTask = Task.FromResult(0);
private SafePipeHandle _handle;
private bool _canRead;
private bool _canWrite;
private bool _isAsync;
private bool _isCurrentUserOnly;
private bool _isMessageComplete;
private bool _isFromExistingHandle;
private bool _isHandleExposed;
private PipeTransmissionMode _readMode;
private PipeTransmissionMode _transmissionMode;
private PipeDirection _pipeDirection;
private uint _outBufferSize;
private PipeState _state;
protected PipeStream(PipeDirection direction, int bufferSize)
{
if (direction < PipeDirection.In || direction > PipeDirection.InOut)
{
throw new ArgumentOutOfRangeException(nameof(direction), SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
}
if (bufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Init(direction, PipeTransmissionMode.Byte, (uint)bufferSize);
}
protected PipeStream(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
{
if (direction < PipeDirection.In || direction > PipeDirection.InOut)
{
throw new ArgumentOutOfRangeException(nameof(direction), SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
}
if (transmissionMode < PipeTransmissionMode.Byte || transmissionMode > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException(nameof(transmissionMode), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
if (outBufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(outBufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Init(direction, transmissionMode, (uint)outBufferSize);
}
private void Init(PipeDirection direction, PipeTransmissionMode transmissionMode, uint outBufferSize)
{
Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");
Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
// always defaults to this until overridden
_readMode = transmissionMode;
_transmissionMode = transmissionMode;
_pipeDirection = direction;
if ((_pipeDirection & PipeDirection.In) != 0)
{
_canRead = true;
}
if ((_pipeDirection & PipeDirection.Out) != 0)
{
_canWrite = true;
}
_outBufferSize = outBufferSize;
// This should always default to true
_isMessageComplete = true;
_state = PipeState.WaitingToConnect;
}
// Once a PipeStream has a handle ready, it should call this method to set up the PipeStream. If
// the pipe is in a connected state already, it should also set the IsConnected (protected) property.
// This method may also be called to uninitialize a handle, setting it to null.
protected void InitializeHandle(SafePipeHandle handle, bool isExposed, bool isAsync)
{
if (isAsync && handle != null)
{
InitializeAsyncHandle(handle);
}
_handle = handle;
_isAsync = isAsync;
// track these separately; _isHandleExposed will get updated if accessed though the property
_isHandleExposed = isExposed;
_isFromExistingHandle = isExposed;
}
public override int Read(byte[] buffer, int offset, int count)
{
if (_isAsync)
{
return ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
}
CheckReadWriteArgs(buffer, offset, count);
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
CheckReadOperations();
return ReadCore(new Span<byte>(buffer, offset, count));
}
public override int Read(Span<byte> buffer)
{
if (_isAsync)
{
return base.Read(buffer);
}
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
CheckReadOperations();
return ReadCore(buffer);
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckReadWriteArgs(buffer, offset, count);
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckReadOperations();
if (!_isAsync)
{
return base.ReadAsync(buffer, offset, count, cancellationToken);
}
if (count == 0)
{
UpdateMessageCompletion(false);
return s_zeroTask;
}
return ReadAsyncCore(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask();
}
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
{
if (!_isAsync)
{
return base.ReadAsync(buffer, cancellationToken);
}
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
}
CheckReadOperations();
if (buffer.Length == 0)
{
UpdateMessageCompletion(false);
return new ValueTask<int>(0);
}
return ReadAsyncCore(buffer, cancellationToken);
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (_isAsync)
return TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state);
else
return base.BeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
if (_isAsync)
return TaskToApm.End<int>(asyncResult);
else
return base.EndRead(asyncResult);
}
public override void Write(byte[] buffer, int offset, int count)
{
if (_isAsync)
{
WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
return;
}
CheckReadWriteArgs(buffer, offset, count);
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
CheckWriteOperations();
WriteCore(new ReadOnlySpan<byte>(buffer, offset, count));
}
public override void Write(ReadOnlySpan<byte> buffer)
{
if (_isAsync)
{
base.Write(buffer);
return;
}
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
CheckWriteOperations();
WriteCore(buffer);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckReadWriteArgs(buffer, offset, count);
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckWriteOperations();
if (!_isAsync)
{
return base.WriteAsync(buffer, offset, count, cancellationToken);
}
if (count == 0)
{
return Task.CompletedTask;
}
return WriteAsyncCore(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken);
}
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
{
if (!_isAsync)
{
return base.WriteAsync(buffer, cancellationToken);
}
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask(Task.FromCanceled<int>(cancellationToken));
}
CheckWriteOperations();
if (buffer.Length == 0)
{
return default;
}
return new ValueTask(WriteAsyncCore(buffer, cancellationToken));
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (_isAsync)
return TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state);
else
return base.BeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (_isAsync)
TaskToApm.End(asyncResult);
else
base.EndWrite(asyncResult);
}
private void CheckReadWriteArgs(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
[Conditional("DEBUG")]
private static void DebugAssertHandleValid(SafePipeHandle handle)
{
Debug.Assert(handle != null, "handle is null");
Debug.Assert(!handle.IsClosed, "handle is closed");
}
// Reads a byte from the pipe stream. Returns the byte cast to an int
// or -1 if the connection has been broken.
public override unsafe int ReadByte()
{
byte b;
return Read(new Span<byte>(&b, 1)) > 0 ? b : -1;
}
public override unsafe void WriteByte(byte value)
{
Write(new ReadOnlySpan<byte>(&value, 1));
}
// Does nothing on PipeStreams. We cannot call Interop.FlushFileBuffers here because we can deadlock
// if the other end of the pipe is no longer interested in reading from the pipe.
public override void Flush()
{
CheckWriteOperations();
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
try
{
Flush();
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
protected override void Dispose(bool disposing)
{
try
{
// Nothing will be done differently based on whether we are
// disposing vs. finalizing.
if (_handle != null && !_handle.IsClosed)
{
_handle.Dispose();
}
DisposeCore(disposing);
}
finally
{
base.Dispose(disposing);
}
_state = PipeState.Closed;
}
// ********************** Public Properties *********************** //
// APIs use coarser definition of connected, but these map to internal
// Connected/Disconnected states. Note that setter is protected; only
// intended to be called by custom PipeStream concrete children
public bool IsConnected
{
get
{
return State == PipeState.Connected;
}
protected set
{
_state = (value) ? PipeState.Connected : PipeState.Disconnected;
}
}
public bool IsAsync
{
get { return _isAsync; }
}
// Set by the most recent call to Read or EndRead. Will be false if there are more buffer in the
// message, otherwise it is set to true.
public bool IsMessageComplete
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
// omitting pipe broken exception to allow reader to finish getting message
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
// don't need to check transmission mode; just care about read mode. Always use
// cached mode; otherwise could throw for valid message when other side is shutting down
if (_readMode != PipeTransmissionMode.Message)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeReadModeNotMessage);
}
return _isMessageComplete;
}
}
internal void UpdateMessageCompletion(bool completion)
{
// Set message complete to true because the pipe is broken as well.
// Need this to signal to readers to stop reading.
_isMessageComplete = (completion || _state == PipeState.Broken);
}
public SafePipeHandle SafePipeHandle
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
if (_handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
if (_handle.IsClosed)
{
throw Error.GetPipeNotOpen();
}
_isHandleExposed = true;
return _handle;
}
}
internal SafePipeHandle InternalHandle
{
get
{
return _handle;
}
}
protected bool IsHandleExposed
{
get
{
return _isHandleExposed;
}
}
public override bool CanRead
{
get
{
return _canRead;
}
}
public override bool CanWrite
{
get
{
return _canWrite;
}
}
public override bool CanSeek
{
get
{
return false;
}
}
public override long Length
{
get
{
throw Error.GetSeekNotSupported();
}
}
public override long Position
{
get
{
throw Error.GetSeekNotSupported();
}
set
{
throw Error.GetSeekNotSupported();
}
}
public override void SetLength(long value)
{
throw Error.GetSeekNotSupported();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw Error.GetSeekNotSupported();
}
// anonymous pipe ends and named pipe server can get/set properties when broken
// or connected. Named client overrides
protected internal virtual void CheckPipePropertyOperations()
{
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
// Reads can be done in Connected and Broken. In the latter,
// read returns 0 bytes
protected internal void CheckReadOperations()
{
// Invalid operation
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
// Writes can only be done in connected state
protected internal void CheckWriteOperations()
{
// Invalid operation
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// IOException
if (_state == PipeState.Broken)
{
throw new IOException(SR.IO_PipeBroken);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
internal PipeState State
{
get
{
return _state;
}
set
{
_state = value;
}
}
internal bool IsCurrentUserOnly
{
get
{
return _isCurrentUserOnly;
}
set
{
_isCurrentUserOnly = value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
/*
* C# Wrapper around the Oscilloscope DLL
*
* (C)2006 Dustin Spicuzza
*
* This library interface 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; only
* version 2.1 of the License.
*
* Some comments/function declarations taken from the original "oscilloscope-lib" documentation
*
*/
// regsvr32 Osc_DLL.dll
namespace LibOscilloscope
{
public sealed class Oscilloscope : IDisposable
{
#region External declarations
/*
* C-style function declarations
*
int (__cdecl * AtOpenLib) (int Prm);
int (__cdecl * ScopeCreate) (int Prm , char * P_IniName, char * P_IniSuffix);
int (__cdecl * ScopeDestroy) (int ScopeHandle);
int (__cdecl * ScopeShow) (int ScopeHandle);
int (__cdecl * ScopeHide) (int ScopeHandle);
int (__cdecl * ScopeCleanBuffers) (int ScopeHandle);
int (__cdecl * ShowNext) (int ScopeHandle, double * PArrDbl);
int (__cdecl * ExternalNext) (int ScopeHandle, double * PDbl);
int (__cdecl * QuickUpDate) (int ScopeHandle);
*/
[DllImport("Osc_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int AtOpenLib
(int Prm);
[DllImport("Osc_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int ScopeCreate(
int Prm,
[MarshalAs(UnmanagedType.LPStr)] StringBuilder P_IniName,
[MarshalAs(UnmanagedType.LPStr)] StringBuilder P_IniSuffix);
[DllImport("Osc_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int ScopeDestroy
(int ScopeHandle);
[DllImport("Osc_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int ScopeShow
(int ScopeHandle);
[DllImport("Osc_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int ScopeHide
(int ScopeHandle);
[DllImport("Osc_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int ScopeCleanBuffers
(int ScopeHandle);
[DllImport("Osc_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int ShowNext
(int ScopeHandle,
double[] PArrDbl);
[DllImport("Osc_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int ExternalNext
(int ScopeHandle,
ref double PDbl);
[DllImport("Osc_DLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int QuickUpDate
(int ScopeHandle);
#endregion
#region Static members
static bool initialized = false;
/// <summary>
/// Creates a new Oscilloscope. Returns the object if successful,
/// otherwise returns null. Generally, if it returns null then
/// it cannot find the correct DLL to load
/// </summary>
/// <returns>Oscilloscope instance</returns>
public static Oscilloscope Create()
{
return Create(null, null);
}
/// <summary>
/// Creates a new Oscilloscope. Returns the object if successful,
/// otherwise returns null. Generally, if it returns null then
/// it cannot find the correct DLL to load
/// </summary>
/// <param name="IniName">Name of INI file with scope settings</param>
/// <param name="IniSuffix">Section name suffix (see manual)</param>
/// <returns>Oscilloscope instance</returns>
public static Oscilloscope Create(string IniName, string IniSuffix)
{
int handle;
try
{
if (!initialized)
{
// initialize
if (AtOpenLib(0) == -1)
return null;
// set to true
initialized = true;
}
}
catch
{
// return
return null;
}
// create the scope
handle = ScopeCreate(0, new StringBuilder(IniName), new StringBuilder(IniSuffix));
if (handle != 0)
{
return new Oscilloscope(handle);
}
return null;
}
#endregion
int scopeHandle;
bool _disposed = false;
private Oscilloscope()
{
}
private Oscilloscope(int handle)
{
scopeHandle = handle;
}
~Oscilloscope()
{
Dispose();
}
/// <summary>
/// Shows the scope
/// </summary>
public void Show()
{
if (!_disposed)
ScopeShow(scopeHandle);
}
/// <summary>
/// Hides the scope from view
/// </summary>
public void Hide()
{
if (!_disposed)
ScopeHide(scopeHandle);
}
/// <summary>
/// Clears the buffer of the scope
/// </summary>
public void Clear()
{
if (!_disposed)
ScopeCleanBuffers(scopeHandle);
}
/// <summary>
/// Add data to the scope
/// </summary>
/// <param name="beam1">Data for first beam</param>
/// <param name="beam2">Data for second beam</param>
/// <param name="beam3">Data for third beam</param>
public void AddData(double beam1, double beam2, double beam3)
{
if (!_disposed)
{
double[] PArrDbl = new double[3];
PArrDbl[0] = beam1;
PArrDbl[1] = beam2;
PArrDbl[2] = beam3;
ShowNext(scopeHandle, PArrDbl);
}
}
/// <summary>
/// Add data to the 'external' trigger function signal
/// </summary>
/// <param name="data">The data</param>
public void AddExternalData(double data)
{
if (!_disposed)
ExternalNext(scopeHandle, ref data);
}
/// <summary>
/// Quickly refreshes screen of oscilloscope. Calling this function is
/// not usually required. Recommended for using in situations when
/// intensive data stream is going into oscilloscope
/// </summary>
public void Update()
{
if (!_disposed)
{
QuickUpDate(scopeHandle);
}
}
#region IDisposable Members
/// <summary>
/// Dispose the object
/// </summary>
public void Dispose()
{
if (!_disposed)
{
ScopeDestroy(scopeHandle);
_disposed = true;
}
}
/// <summary>
/// True if object is already disposed
/// </summary>
public bool IsDisposed
{
get
{
return _disposed;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
using Xunit.Sdk;
using System.Linq;
using System;
namespace Flatbox.RegularExpressions.Tests
{
public static class AssertExtensions
{
private static bool IsFullFramework => RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework");
public static void Throws<T>(Action action, string message)
where T : Exception
{
Assert.Equal(Assert.Throws<T>(action).Message, message);
}
public static void Throws<T>(string netCoreParamName, string netFxParamName, Action action)
where T : ArgumentException
{
T exception = Assert.Throws<T>(action);
if (netFxParamName == null && IsFullFramework)
{
// Param name varies between NETFX versions -- skip checking it
return;
}
string expectedParamName =
IsFullFramework ?
netFxParamName : netCoreParamName;
if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native"))
Assert.Equal(expectedParamName, exception.ParamName);
}
public static T Throws<T>(string paramName, Action action)
where T : ArgumentException
{
T exception = Assert.Throws<T>(action);
if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native"))
Assert.Equal(paramName, exception.ParamName);
return exception;
}
public static T Throws<T>(string paramName, Func<object> testCode)
where T : ArgumentException
{
T exception = Assert.Throws<T>(testCode);
if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native"))
Assert.Equal(paramName, exception.ParamName);
return exception;
}
public static async Task<T> ThrowsAsync<T>(string paramName, Func<Task> testCode)
where T : ArgumentException
{
T exception = await Assert.ThrowsAsync<T>(testCode);
if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native"))
Assert.Equal(paramName, exception.ParamName);
return exception;
}
public static void Throws<TNetCoreExceptionType, TNetFxExceptionType>(string paramName, Action action)
where TNetCoreExceptionType : ArgumentException
where TNetFxExceptionType : ArgumentException
{
Throws<TNetCoreExceptionType, TNetFxExceptionType>(paramName, paramName, action);
}
public static void Throws<TNetCoreExceptionType, TNetFxExceptionType>(string netCoreParamName, string netFxParamName, Action action)
where TNetCoreExceptionType : ArgumentException
where TNetFxExceptionType : ArgumentException
{
if (IsFullFramework)
{
Throws<TNetFxExceptionType>(netFxParamName, action);
}
else
{
Throws<TNetCoreExceptionType>(netCoreParamName, action);
}
}
public static void ThrowsAny(Type firstExceptionType, Type secondExceptionType, Action action)
{
ThrowsAnyInternal(action, firstExceptionType, secondExceptionType);
}
private static void ThrowsAnyInternal(Action action, params Type[] exceptionTypes)
{
try
{
action();
}
catch (Exception e)
{
Type exceptionType = e.GetType();
if (exceptionTypes.Any(t => t.Equals(exceptionType)))
return;
throw new XunitException($"Expected one of: ({string.Join<Type>(", ", exceptionTypes)}) -> Actual: ({e.GetType()})");
}
throw new XunitException($"Expected one of: ({string.Join<Type>(", ", exceptionTypes)}) -> Actual: No exception thrown");
}
public static void ThrowsAny<TFirstExceptionType, TSecondExceptionType>(Action action)
where TFirstExceptionType : Exception
where TSecondExceptionType : Exception
{
ThrowsAnyInternal(action, typeof(TFirstExceptionType), typeof(TSecondExceptionType));
}
public static void ThrowsAny<TFirstExceptionType, TSecondExceptionType, TThirdExceptionType>(Action action)
where TFirstExceptionType : Exception
where TSecondExceptionType : Exception
where TThirdExceptionType : Exception
{
ThrowsAnyInternal(action, typeof(TFirstExceptionType), typeof(TSecondExceptionType), typeof(TThirdExceptionType));
}
public static void ThrowsIf<T>(bool condition, Action action)
where T : Exception
{
if (condition)
{
Assert.Throws<T>(action);
}
else
{
action();
}
}
private static string AddOptionalUserMessage(string message, string userMessage)
{
if (userMessage == null)
return message;
else
return $"{message} {userMessage}";
}
/// <summary>
/// Validate that a given value is greater than another value.
/// </summary>
/// <param name="actual">The value that should be greater than <paramref name="greaterThan"/>.</param>
/// <param name="greaterThan">The value that <paramref name="actual"/> should be greater than.</param>
public static void GreaterThan<T>(T actual, T greaterThan, string userMessage = null) where T : IComparable
{
if (actual == null)
throw new XunitException(
greaterThan == null
? AddOptionalUserMessage($"Expected: <null> to be greater than <null>.", userMessage)
: AddOptionalUserMessage($"Expected: <null> to be greater than {greaterThan}.", userMessage));
if (actual.CompareTo(greaterThan) <= 0)
throw new XunitException(AddOptionalUserMessage($"Expected: {actual} to be greater than {greaterThan}", userMessage));
}
/// <summary>
/// Validate that a given value is less than another value.
/// </summary>
/// <param name="actual">The value that should be less than <paramref name="lessThan"/>.</param>
/// <param name="lessThan">The value that <paramref name="actual"/> should be less than.</param>
public static void LessThan<T>(T actual, T lessThan, string userMessage = null) where T : IComparable
{
if (actual == null)
{
if (lessThan == null)
{
throw new XunitException(AddOptionalUserMessage($"Expected: <null> to be less than <null>.", userMessage));
}
else
{
// Null is always less than non-null
return;
}
}
if (actual.CompareTo(lessThan) >= 0)
throw new XunitException(AddOptionalUserMessage($"Expected: {actual} to be less than {lessThan}", userMessage));
}
/// <summary>
/// Validate that a given value is less than or equal to another value.
/// </summary>
/// <param name="actual">The value that should be less than or equal to <paramref name="lessThanOrEqualTo"/></param>
/// <param name="lessThanOrEqualTo">The value that <paramref name="actual"/> should be less than or equal to.</param>
public static void LessThanOrEqualTo<T>(T actual, T lessThanOrEqualTo, string userMessage = null) where T : IComparable
{
// null, by definition is always less than or equal to
if (actual == null)
return;
if (actual.CompareTo(lessThanOrEqualTo) > 0)
throw new XunitException(AddOptionalUserMessage($"Expected: {actual} to be less than or equal to {lessThanOrEqualTo}", userMessage));
}
/// <summary>
/// Validate that a given value is greater than or equal to another value.
/// </summary>
/// <param name="actual">The value that should be greater than or equal to <paramref name="greaterThanOrEqualTo"/></param>
/// <param name="greaterThanOrEqualTo">The value that <paramref name="actual"/> should be greater than or equal to.</param>
public static void GreaterThanOrEqualTo<T>(T actual, T greaterThanOrEqualTo, string userMessage = null) where T : IComparable
{
// null, by definition is always less than or equal to
if (actual == null)
{
if (greaterThanOrEqualTo == null)
{
// We're equal
return;
}
else
{
// Null is always less than non-null
throw new XunitException(AddOptionalUserMessage($"Expected: <null> to be greater than or equal to <null>.", userMessage));
}
}
if (actual.CompareTo(greaterThanOrEqualTo) < 0)
throw new XunitException(AddOptionalUserMessage($"Expected: {actual} to be greater than or equal to {greaterThanOrEqualTo}", userMessage));
}
/// <summary>
/// Validates that the actual byte array is equal to the expected byte array. XUnit only displays the first 5 values
/// of each collection if the test fails. This doesn't display at what point or how the equality assertion failed.
/// </summary>
/// <param name="expected">The byte array that <paramref name="actual"/> should be equal to.</param>
/// <param name="actual"></param>
public static void Equal(byte[] expected, byte[] actual)
{
try
{
Assert.Equal(expected, actual);
}
catch (AssertActualExpectedException)
{
string expectedString = string.Join(", ", expected);
string actualString = string.Join(", ", actual);
throw new AssertActualExpectedException(expectedString, actualString, 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.
namespace System.Xml
{
using System;
using System.IO;
using System.Security;
using System.Collections;
using System.Net;
using System.Net.Cache;
using System.Runtime.Versioning;
using System.Net.Http;
//
// XmlDownloadManager
//
internal partial class XmlDownloadManager
{
private Hashtable _connections;
internal Stream GetStream(Uri uri, ICredentials credentials, IWebProxy proxy,
RequestCachePolicy cachePolicy)
{
if (uri.Scheme == "file")
{
return new FileStream(uri.LocalPath, FileMode.Open, FileAccess.Read, FileShare.Read, 1);
}
else
{
return GetNonFileStream(uri, credentials, proxy, cachePolicy);
}
}
private Stream GetNonFileStream(Uri uri, ICredentials credentials, IWebProxy proxy,
RequestCachePolicy cachePolicy)
{
HttpClient client = new HttpClient();
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, uri);
lock (this)
{
if (_connections == null)
{
_connections = new Hashtable();
}
}
HttpResponseMessage resp = client.SendAsync(req).GetAwaiter().GetResult();
Stream respStream = new MemoryStream();
resp.Content.CopyToAsync(respStream);
return respStream;
}
internal void Remove(string host)
{
lock (this)
{
OpenedHost openedHost = (OpenedHost)_connections[host];
if (openedHost != null)
{
if (--openedHost.nonCachedConnectionsCount == 0)
{
_connections.Remove(host);
}
}
}
}
}
//
// OpenedHost
//
internal class OpenedHost
{
internal int nonCachedConnectionsCount;
}
//
// XmlRegisteredNonCachedStream
//
internal class XmlRegisteredNonCachedStream : Stream
{
protected Stream stream;
private XmlDownloadManager _downloadManager;
private string _host;
internal XmlRegisteredNonCachedStream(Stream stream, XmlDownloadManager downloadManager, string host)
{
this.stream = stream;
_downloadManager = downloadManager;
_host = host;
}
~XmlRegisteredNonCachedStream()
{
if (_downloadManager != null)
{
_downloadManager.Remove(_host);
}
stream = null;
// The base class, Stream, provides its own finalizer
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing && stream != null)
{
if (_downloadManager != null)
{
_downloadManager.Remove(_host);
}
stream.Dispose();
}
stream = null;
GC.SuppressFinalize(this); // do not call finalizer
}
finally
{
base.Dispose(disposing);
}
}
//
// Stream
//
public /*override*/ IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return null; //stream.BeginRead(buffer, offset, count, callback, state);
}
public /*override*/ IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return null; //stream.BeginWrite(buffer, offset, count, callback, state);
}
public /*override*/ int EndRead(IAsyncResult asyncResult)
{
return -1; //stream.EndRead(asyncResult);
}
public /*override*/ void EndWrite(IAsyncResult asyncResult)
{
//stream.EndWrite(asyncResult);
}
public override void Flush()
{
stream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return stream.Read(buffer, offset, count);
}
public override int ReadByte()
{
return stream.ReadByte();
}
public override long Seek(long offset, SeekOrigin origin)
{
return stream.Seek(offset, origin);
}
public override void SetLength(long value)
{
stream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
stream.Write(buffer, offset, count);
}
public override void WriteByte(byte value)
{
stream.WriteByte(value);
}
public override Boolean CanRead
{
get { return stream.CanRead; }
}
public override Boolean CanSeek
{
get { return stream.CanSeek; }
}
public override Boolean CanWrite
{
get { return stream.CanWrite; }
}
public override long Length
{
get { return stream.Length; }
}
public override long Position
{
get { return stream.Position; }
set { stream.Position = value; }
}
}
//
// XmlCachedStream
//
internal class XmlCachedStream : MemoryStream
{
private const int MoveBufferSize = 4096;
private Uri _uri;
internal XmlCachedStream(Uri uri, Stream stream)
: base()
{
_uri = uri;
try
{
byte[] bytes = new byte[MoveBufferSize];
int read = 0;
while ((read = stream.Read(bytes, 0, MoveBufferSize)) > 0)
{
this.Write(bytes, 0, read);
}
base.Position = 0;
}
finally
{
stream.Dispose();
}
}
}
}
| |
//
// CDocumentParser.cs
//
// Author:
// Levi Bard <taktaktaktaktaktaktaktaktaktak@gmail.com>
//
// Copyright (c) 2009 Levi Bard
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using MonoDevelop.Core;
using MonoDevelop.Projects;
using MonoDevelop.Ide;
using MonoDevelop.Ide.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using MonoDevelop.Core.Text;
namespace CBinding.Parser
{
/// <summary>
/// Ctags-based document parser helper
/// </summary>
public class CDocumentParser: TypeSystemParser
{
public override System.Threading.Tasks.Task<ParsedDocument> Parse (ParseOptions options, System.Threading.CancellationToken cancellationToken)
{
var fileName = options.FileName;
var project = options.Project;
var doc = new DefaultParsedDocument (fileName);
doc.Flags |= ParsedDocumentFlags.NonSerializable;
ProjectInformation pi = ProjectInformationManager.Instance.Get (project);
string content = options.Content.Text;
string[] contentLines = content.Split (new string[]{Environment.NewLine}, StringSplitOptions.None);
var globals = new DefaultUnresolvedTypeDefinition ("", GettextCatalog.GetString ("(Global Scope)"));
lock (pi) {
// Add containers to type list
foreach (LanguageItem li in pi.Containers ()) {
if (null == li.Parent && FilePath.Equals (li.File, fileName)) {
var tmp = AddLanguageItem (pi, globals, li, contentLines) as IUnresolvedTypeDefinition;
if (null != tmp){ /*doc.TopLevelTypeDefinitions.Add (tmp);*/ }
}
}
// Add global category for unscoped symbols
foreach (LanguageItem li in pi.InstanceMembers ()) {
if (null == li.Parent && FilePath.Equals (li.File, fileName)) {
AddLanguageItem (pi, globals, li, contentLines);
}
}
}
//doc.TopLevelTypeDefinitions.Add (globals);
return System.Threading.Tasks.Task.FromResult((ParsedDocument)doc);
}
/// <summary>
/// Finds the end of a function's definition by matching braces.
/// </summary>
/// <param name="content">
/// A <see cref="System.String"/> array: each line of the content to be searched.
/// </param>
/// <param name="startLine">
/// A <see cref="System.Int32"/>: The earliest line at which the function may start.
/// </param>
/// <returns>
/// A <see cref="System.Int32"/>: The detected end of the function.
/// </returns>
static int FindFunctionEnd (string[] content, int startLine) {
int start = FindFunctionStart (content, startLine);
if (0 > start){ return startLine; }
int count = 0;
for (int i= start; i<content.Length; ++i) {
foreach (char c in content[i]) {
switch (c) {
case '{':
++count;
break;
case '}':
if (0 >= --count) {
return i;
}
break;
}
}
}
return startLine;
}
/// <summary>
/// Finds the start of a function's definition.
/// </summary>
/// <param name="content">
/// A <see cref="System.String"/> array: each line of the content to be searched.
/// </param>
/// <param name="startLine">
/// A <see cref="System.Int32"/>: The earliest line at which the function may start.
/// </param>
/// <returns>
/// A <see cref="System.Int32"/>: The detected start of the function
/// definition, or -1.
/// </returns>
static int FindFunctionStart (string[] content, int startLine) {
int semicolon = -1;
int bracket = -1;
for (int i=startLine; i<content.Length; ++i) {
semicolon = content[i].IndexOf (';');
bracket = content[i].IndexOf ('{');
if (0 <= semicolon) {
return (0 > bracket ^ semicolon < bracket)? -1: i;
} else if (0 <= bracket) {
return i;
}
}
return -1;
}
static readonly Regex paramExpression = new Regex (@"(?<type>[^\s]+)\s+(?<subtype>[*&]*)(?<name>[^\s[]+)(?<array>\[.*)?", RegexOptions.Compiled);
static object AddLanguageItem (ProjectInformation pi, DefaultUnresolvedTypeDefinition klass, LanguageItem li, string[] contentLines)
{
if (li is Class || li is Structure || li is Enumeration) {
var type = LanguageItemToIType (pi, li, contentLines);
klass.NestedTypes.Add (type);
return type;
}
if (li is Function) {
var method = FunctionToIMethod (pi, klass, (Function)li, contentLines);
klass.Members.Add (method);
return method;
}
var field = LanguageItemToIField (klass, li, contentLines);
klass.Members.Add (field);
return field;
}
/// <summary>
/// Create an IMember from a LanguageItem,
/// using the source document to locate declaration bounds.
/// </summary>
/// <param name="pi">
/// A <see cref="ProjectInformation"/> for the current project.
/// </param>
/// <param name="item">
/// A <see cref="LanguageItem"/>: The item to convert.
/// </param>
/// <param name="contentLines">
/// A <see cref="System.String[]"/>: The document in which item is defined.
/// </param>
static DefaultUnresolvedTypeDefinition LanguageItemToIType (ProjectInformation pi, LanguageItem item, string[] contentLines)
{
var klass = new DefaultUnresolvedTypeDefinition ("", item.File);
if (item is Class || item is Structure) {
klass.Region = new DomRegion ((int)item.Line, 1, FindFunctionEnd (contentLines, (int)item.Line-1) + 2, 1);
klass.Kind = item is Class ? TypeKind.Class : TypeKind.Struct;
foreach (LanguageItem li in pi.AllItems ()) {
if (klass.Equals (li.Parent) && FilePath.Equals (li.File, item.File))
AddLanguageItem (pi, klass, li, contentLines);
}
return klass;
}
klass.Region = new DomRegion ((int)item.Line, 1, (int)item.Line + 1, 1);
klass.Kind = TypeKind.Enum;
return klass;
}
static IUnresolvedField LanguageItemToIField (IUnresolvedTypeDefinition type, LanguageItem item, string[] contentLines)
{
var result = new DefaultUnresolvedField (type, item.Name);
result.Region = new DomRegion ((int)item.Line, 1, (int)item.Line + 1, 1);
return result;
}
static IUnresolvedMethod FunctionToIMethod (ProjectInformation pi, IUnresolvedTypeDefinition type, Function function, string[] contentLines)
{
var method = new DefaultUnresolvedMethod (type, function.Name);
method.Region = new DomRegion ((int)function.Line, 1, FindFunctionEnd (contentLines, (int)function.Line-1)+2, 1);
Match match;
bool abort = false;
var parameters = new List<IUnresolvedParameter> ();
foreach (string parameter in function.Parameters) {
match = paramExpression.Match (parameter);
if (null == match) {
abort = true;
break;
}
var typeRef = new DefaultUnresolvedTypeDefinition (string.Format ("{0}{1}{2}", match.Groups["type"].Value, match.Groups["subtype"].Value, match.Groups["array"].Value));
var p = new DefaultUnresolvedParameter (typeRef, match.Groups["name"].Value);
parameters.Add (p);
}
if (!abort)
parameters.ForEach (p => method.Parameters.Add (p));
return method;
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="FormattedTextSymbols.cs company=Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description:
// Formatting a single style, single reading direction text symbols
//
// History:
// 08/16/2004 : wchao - Created it
//
//---------------------------------------------------------------------------
using System;
using System.Security;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using MS.Internal;
using MS.Internal.Text.TextInterface;
using MS.Internal.Shaping;
using System.Globalization;
using MS.Internal.FontCache;
namespace MS.Internal.TextFormatting
{
/// <summary>
/// Formatted form of TextSymbols
/// </summary>
internal sealed class FormattedTextSymbols
{
private Glyphs[] _glyphs;
private bool _rightToLeft;
private TextFormattingMode _textFormattingMode;
private bool _isSideways;
/// <summary>
/// Construct a formatted run
/// </summary>
/// <SecurityNote>
/// Critical - this method has unsafe blocks, calls Critical methods (Instance, etc.)
/// Safe - it doesn't expose any critical data
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
public FormattedTextSymbols(
GlyphingCache glyphingCache,
TextRun textSymbols,
bool rightToLeft,
double scalingFactor,
TextFormattingMode textFormattingMode,
bool isSideways
)
{
_textFormattingMode = textFormattingMode;
_isSideways = isSideways;
ITextSymbols symbols = textSymbols as ITextSymbols;
Debug.Assert(symbols != null);
// break down a single text run into pieces
IList<TextShapeableSymbols> shapeables = symbols.GetTextShapeableSymbols(
glyphingCache,
textSymbols.CharacterBufferReference,
textSymbols.Length,
rightToLeft, // This is a bool indicating the RTL
// based on the bidi level of text (if applicable).
// For FormattedTextSymbols it is equal to paragraph flow direction.
rightToLeft, // This is the flow direction of the paragraph as
// specified by the user. DWrite needs the paragraph
// flow direction of the paragraph
// while WPF algorithms need the RTL of the text based on
// Bidi if possible.
null, // cultureInfo
null, // textModifierScope
_textFormattingMode,
_isSideways
);
Debug.Assert(shapeables != null && shapeables.Count > 0);
_rightToLeft = rightToLeft;
_glyphs = new Glyphs[shapeables.Count];
CharacterBuffer charBuffer = textSymbols.CharacterBufferReference.CharacterBuffer;
int offsetToFirstChar = textSymbols.CharacterBufferReference.OffsetToFirstChar;
int i = 0;
int ich = 0;
while (i < shapeables.Count)
{
TextShapeableSymbols current = shapeables[i] as TextShapeableSymbols;
Debug.Assert(current != null);
int cch = current.Length;
int j;
// make a separate character buffer for glyphrun persistence
char[] charArray = new char[cch];
for (j = 0; j < cch; j++)
charArray[j] = charBuffer[offsetToFirstChar + ich + j];
if (current.IsShapingRequired)
{
ushort[] clusterMap;
ushort[] glyphIndices;
int[] glyphAdvances;
GlyphOffset[] glyphOffsets;
//
unsafe
{
fixed (char* fixedCharArray = &charArray[0])
{
MS.Internal.Text.TextInterface.TextAnalyzer textAnalyzer = MS.Internal.FontCache.DWriteFactory.Instance.CreateTextAnalyzer();
GlyphTypeface glyphTypeface = current.GlyphTypeFace;
DWriteFontFeature[][] fontFeatures;
uint[] fontFeatureRanges;
uint unsignedCch = checked((uint)cch);
LSRun.CompileFeatureSet(current.Properties.TypographyProperties, unsignedCch, out fontFeatures, out fontFeatureRanges);
textAnalyzer.GetGlyphsAndTheirPlacements(
(ushort*)fixedCharArray,
unsignedCch,
glyphTypeface.FontDWrite,
glyphTypeface.BlankGlyphIndex,
false, // no sideway support yet
/************************************************************************************************/
//
rightToLeft,
current.Properties.CultureInfo,
/************************************************************************************************/
fontFeatures,
fontFeatureRanges,
current.Properties.FontRenderingEmSize,
scalingFactor,
Util.PixelsPerDip,
_textFormattingMode,
current.ItemProps,
out clusterMap,
out glyphIndices,
out glyphAdvances,
out glyphOffsets
);
}
_glyphs[i] = new Glyphs(
current,
charArray,
glyphAdvances,
clusterMap,
glyphIndices,
glyphOffsets,
scalingFactor
);
}
}
else
{
// shaping not required,
// bypass glyphing process altogether
int[] nominalAdvances = new int[charArray.Length];
unsafe
{
fixed (char* fixedCharArray = &charArray[0])
fixed (int* fixedNominalAdvances = &nominalAdvances[0])
{
current.GetAdvanceWidthsUnshaped(
fixedCharArray,
cch,
scalingFactor, // format resolution specified per em,
fixedNominalAdvances
);
}
}
_glyphs[i] = new Glyphs(
current,
charArray,
nominalAdvances,
scalingFactor
);
}
i++;
ich += cch;
}
}
/// <summary>
/// Total formatted width
/// </summary>
public double Width
{
get
{
Debug.Assert(_glyphs != null);
double width = 0;
foreach (Glyphs glyphs in _glyphs)
{
width += glyphs.Width;
}
return width;
}
}
/// <summary>
/// Draw all formatted glyphruns
/// </summary>
/// <returns>drawing bounding box</returns>
public Rect Draw(
DrawingContext drawingContext,
Point currentOrigin
)
{
Rect inkBoundingBox = Rect.Empty;
Debug.Assert(_glyphs != null);
foreach (Glyphs glyphs in _glyphs)
{
GlyphRun glyphRun = glyphs.CreateGlyphRun(currentOrigin, _rightToLeft);
Rect boundingBox;
if (glyphRun != null)
{
boundingBox = glyphRun.ComputeInkBoundingBox();
if (drawingContext != null)
{
// Emit glyph run background.
glyphRun.EmitBackground(drawingContext, glyphs.BackgroundBrush);
drawingContext.PushGuidelineY1(currentOrigin.Y);
try
{
drawingContext.DrawGlyphRun(glyphs.ForegroundBrush, glyphRun);
}
finally
{
drawingContext.Pop();
}
}
}
else
{
boundingBox = Rect.Empty;
}
if (!boundingBox.IsEmpty)
{
// glyph run's ink bounding box is relative to its origin
boundingBox.X += glyphRun.BaselineOrigin.X;
boundingBox.Y += glyphRun.BaselineOrigin.Y;
}
// accumulate overall ink bounding box
inkBoundingBox.Union(boundingBox);
if (_rightToLeft)
{
currentOrigin.X -= glyphs.Width;
}
else
{
currentOrigin.X += glyphs.Width;
}
}
return inkBoundingBox;
}
/// <summary>
/// All glyph properties used during GlyphRun construction
/// </summary>
/// <remarks>
/// We should be able to get rid off this type and just store GlyphRuns
/// once GlyphRun gets refactor'd so that it contains no drawing time
/// positioning data inside.
/// </remarks>
private sealed class Glyphs
{
private TextShapeableSymbols _shapeable;
private char[] _charArray;
private ushort[] _clusterMap;
private ushort[] _glyphIndices;
private double[] _glyphAdvances;
private IList<Point> _glyphOffsets;
private double _width;
/// <summary>
/// Construct a nominal description of glyph data
/// </summary>
internal Glyphs(
TextShapeableSymbols shapeable,
char[] charArray,
int[] nominalAdvances,
double scalingFactor
) :
this(
shapeable,
charArray,
nominalAdvances,
null, // clusterMap
null, // glyphIndices
null, // glyphOffsets
scalingFactor
)
{}
/// <summary>
/// Construct a full description of glyph data
/// </summary>
internal Glyphs(
TextShapeableSymbols shapeable,
char[] charArray,
int[] glyphAdvances,
ushort[] clusterMap,
ushort[] glyphIndices,
GlyphOffset[] glyphOffsets,
double scalingFactor
)
{
_shapeable = shapeable;
_charArray = charArray;
// create double array for glyph run creation, because Shaping is all done in
// ideal units. FormattedTextSymbol is used to draw text collapsing symbols
// which usually contains very few glyphs. Using double[] and Point[] directly
// is more efficient.
_glyphAdvances = new double[glyphAdvances.Length];
double ToReal = 1.0 / scalingFactor;
for (int i = 0; i < glyphAdvances.Length; i++)
{
_glyphAdvances[i] = glyphAdvances[i] * ToReal;
_width += _glyphAdvances[i];
}
if (glyphIndices != null)
{
_clusterMap = clusterMap;
if (glyphOffsets != null)
{
_glyphOffsets = new PartialArray<Point>(new Point[glyphOffsets.Length]);
for (int i = 0; i < glyphOffsets.Length; i++)
{
_glyphOffsets[i] = new Point(
glyphOffsets[i].du * ToReal,
glyphOffsets[i].dv * ToReal
);
}
}
Debug.Assert(glyphAdvances.Length <= glyphIndices.Length);
if (glyphAdvances.Length != glyphIndices.Length)
{
_glyphIndices = new ushort[glyphAdvances.Length];
for (int i = 0; i < glyphAdvances.Length; i++)
{
_glyphIndices[i] = glyphIndices[i];
}
}
else
{
_glyphIndices = glyphIndices;
}
}
}
/// <summary>
/// Total formatted width
/// </summary>
public double Width
{
get { return _width; }
}
/// <summary>
/// Construct a GlyphRun object given the specified drawing origin
/// </summary>
internal GlyphRun CreateGlyphRun(
Point currentOrigin,
bool rightToLeft
)
{
if (!_shapeable.IsShapingRequired)
{
return _shapeable.ComputeUnshapedGlyphRun(
currentOrigin,
_charArray,
_glyphAdvances
);
}
return _shapeable.ComputeShapedGlyphRun(
currentOrigin,
_charArray,
_clusterMap,
_glyphIndices,
_glyphAdvances,
_glyphOffsets,
rightToLeft,
false // sideways not yet supported
);
}
public Brush ForegroundBrush
{
get { return _shapeable.Properties.ForegroundBrush; }
}
public Brush BackgroundBrush
{
get { return _shapeable.Properties.BackgroundBrush; }
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using log4net;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework
{
public enum ProfileShape : byte
{
Circle = 0,
Square = 1,
IsometricTriangle = 2,
EquilateralTriangle = 3,
RightTriangle = 4,
HalfCircle = 5
}
public enum HollowShape : byte
{
Same = 0,
Circle = 16,
Square = 32,
Triangle = 48
}
public enum PCodeEnum : byte
{
Primitive = 9,
Avatar = 47,
Grass = 95,
NewTree = 111,
ParticleSystem = 143,
Tree = 255
}
public enum Extrusion : byte
{
Straight = 16,
Curve1 = 32,
Curve2 = 48,
Flexible = 128
}
[Serializable]
public class PrimitiveBaseShape
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly byte[] DEFAULT_TEXTURE = new Primitive.TextureEntry(new UUID("89556747-24cb-43ed-920b-47caed15465f")).GetBytes();
private byte[] m_textureEntry;
private ushort _pathBegin;
private byte _pathCurve;
private ushort _pathEnd;
private sbyte _pathRadiusOffset;
private byte _pathRevolutions;
private byte _pathScaleX;
private byte _pathScaleY;
private byte _pathShearX;
private byte _pathShearY;
private sbyte _pathSkew;
private sbyte _pathTaperX;
private sbyte _pathTaperY;
private sbyte _pathTwist;
private sbyte _pathTwistBegin;
private byte _pCode;
private ushort _profileBegin;
private ushort _profileEnd;
private ushort _profileHollow;
private Vector3 _scale;
private byte _state;
private byte _lastattach;
private ProfileShape _profileShape;
private HollowShape _hollowShape;
// Sculpted
[XmlIgnore] private UUID _sculptTexture;
[XmlIgnore] private byte _sculptType;
[XmlIgnore] private byte[] _sculptData = Utils.EmptyBytes;
// Flexi
[XmlIgnore] private int _flexiSoftness;
[XmlIgnore] private float _flexiTension;
[XmlIgnore] private float _flexiDrag;
[XmlIgnore] private float _flexiGravity;
[XmlIgnore] private float _flexiWind;
[XmlIgnore] private float _flexiForceX;
[XmlIgnore] private float _flexiForceY;
[XmlIgnore] private float _flexiForceZ;
//Bright n sparkly
[XmlIgnore] private float _lightColorR;
[XmlIgnore] private float _lightColorG;
[XmlIgnore] private float _lightColorB;
[XmlIgnore] private float _lightColorA = 1.0f;
[XmlIgnore] private float _lightRadius;
[XmlIgnore] private float _lightCutoff;
[XmlIgnore] private float _lightFalloff;
[XmlIgnore] private float _lightIntensity = 1.0f;
[XmlIgnore] private bool _flexiEntry;
[XmlIgnore] private bool _lightEntry;
[XmlIgnore] private bool _sculptEntry;
// Light Projection Filter
[XmlIgnore] private bool _projectionEntry;
[XmlIgnore] private UUID _projectionTextureID;
[XmlIgnore] private float _projectionFOV;
[XmlIgnore] private float _projectionFocus;
[XmlIgnore] private float _projectionAmb;
public byte ProfileCurve
{
get { return (byte)((byte)HollowShape | (byte)ProfileShape); }
set
{
// Handle hollow shape component
byte hollowShapeByte = (byte)(value & 0xf0);
if (!Enum.IsDefined(typeof(HollowShape), hollowShapeByte))
{
m_log.WarnFormat(
"[SHAPE]: Attempt to set a ProfileCurve with a hollow shape value of {0}, which isn't a valid enum. Replacing with default shape.",
hollowShapeByte);
this._hollowShape = HollowShape.Same;
}
else
{
this._hollowShape = (HollowShape)hollowShapeByte;
}
// Handle profile shape component
byte profileShapeByte = (byte)(value & 0xf);
if (!Enum.IsDefined(typeof(ProfileShape), profileShapeByte))
{
m_log.WarnFormat(
"[SHAPE]: Attempt to set a ProfileCurve with a profile shape value of {0}, which isn't a valid enum. Replacing with square.",
profileShapeByte);
this._profileShape = ProfileShape.Square;
}
else
{
this._profileShape = (ProfileShape)profileShapeByte;
}
}
}
/// <summary>
/// Entries to store media textures on each face
/// </summary>
/// Do not change this value directly - always do it through an IMoapModule.
/// Lock before manipulating.
public MediaList Media { get; set; }
public PrimitiveBaseShape()
{
PCode = (byte)PCodeEnum.Primitive;
m_textureEntry = DEFAULT_TEXTURE;
}
/// <summary>
/// Construct a PrimitiveBaseShape object from a OpenMetaverse.Primitive object
/// </summary>
/// <param name="prim"></param>
public PrimitiveBaseShape(Primitive prim)
{
// m_log.DebugFormat("[PRIMITIVE BASE SHAPE]: Creating from {0}", prim.ID);
PCode = (byte)prim.PrimData.PCode;
State = prim.PrimData.State;
LastAttachPoint = prim.PrimData.State;
PathBegin = Primitive.PackBeginCut(prim.PrimData.PathBegin);
PathEnd = Primitive.PackEndCut(prim.PrimData.PathEnd);
PathScaleX = Primitive.PackPathScale(prim.PrimData.PathScaleX);
PathScaleY = Primitive.PackPathScale(prim.PrimData.PathScaleY);
PathShearX = (byte)Primitive.PackPathShear(prim.PrimData.PathShearX);
PathShearY = (byte)Primitive.PackPathShear(prim.PrimData.PathShearY);
PathSkew = Primitive.PackPathTwist(prim.PrimData.PathSkew);
ProfileBegin = Primitive.PackBeginCut(prim.PrimData.ProfileBegin);
ProfileEnd = Primitive.PackEndCut(prim.PrimData.ProfileEnd);
Scale = prim.Scale;
PathCurve = (byte)prim.PrimData.PathCurve;
ProfileCurve = (byte)prim.PrimData.ProfileCurve;
ProfileHollow = Primitive.PackProfileHollow(prim.PrimData.ProfileHollow);
PathRadiusOffset = Primitive.PackPathTwist(prim.PrimData.PathRadiusOffset);
PathRevolutions = Primitive.PackPathRevolutions(prim.PrimData.PathRevolutions);
PathTaperX = Primitive.PackPathTaper(prim.PrimData.PathTaperX);
PathTaperY = Primitive.PackPathTaper(prim.PrimData.PathTaperY);
PathTwist = Primitive.PackPathTwist(prim.PrimData.PathTwist);
PathTwistBegin = Primitive.PackPathTwist(prim.PrimData.PathTwistBegin);
m_textureEntry = prim.Textures.GetBytes();
if (prim.Sculpt != null)
{
SculptEntry = (prim.Sculpt.Type != OpenMetaverse.SculptType.None);
SculptData = prim.Sculpt.GetBytes();
SculptTexture = prim.Sculpt.SculptTexture;
SculptType = (byte)prim.Sculpt.Type;
}
else
{
SculptType = (byte)OpenMetaverse.SculptType.None;
}
}
[XmlIgnore]
public Primitive.TextureEntry Textures
{
get
{
// m_log.DebugFormat("[SHAPE]: get m_textureEntry length {0}", m_textureEntry.Length);
try { return new Primitive.TextureEntry(m_textureEntry, 0, m_textureEntry.Length); }
catch { }
m_log.Warn("[SHAPE]: Failed to decode texture, length=" + ((m_textureEntry != null) ? m_textureEntry.Length : 0));
return new Primitive.TextureEntry(UUID.Zero);
}
set { m_textureEntry = value.GetBytes(); }
}
public byte[] TextureEntry
{
get { return m_textureEntry; }
set
{
if (value == null)
m_textureEntry = new byte[1];
else
m_textureEntry = value;
}
}
public static PrimitiveBaseShape Default
{
get
{
PrimitiveBaseShape boxShape = CreateBox();
boxShape.SetScale(0.5f);
return boxShape;
}
}
public static PrimitiveBaseShape Create()
{
PrimitiveBaseShape shape = new PrimitiveBaseShape();
return shape;
}
public static PrimitiveBaseShape CreateBox()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Straight;
shape._profileShape = ProfileShape.Square;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public static PrimitiveBaseShape CreateSphere()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Curve1;
shape._profileShape = ProfileShape.HalfCircle;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public static PrimitiveBaseShape CreateCylinder()
{
PrimitiveBaseShape shape = Create();
shape._pathCurve = (byte) Extrusion.Curve1;
shape._profileShape = ProfileShape.Square;
shape._pathScaleX = 100;
shape._pathScaleY = 100;
return shape;
}
public static PrimitiveBaseShape CreateMesh(int numberOfFaces, UUID meshAssetID)
{
PrimitiveBaseShape shape = new PrimitiveBaseShape();
shape._pathScaleX = 100;
shape._pathScaleY = 100;
if(numberOfFaces <= 0) // oops ?
numberOfFaces = 1;
switch(numberOfFaces)
{
case 1: // torus
shape.ProfileCurve = (byte)ProfileShape.Circle | (byte)HollowShape.Triangle;
shape.PathCurve = (byte)Extrusion.Curve1;
shape._pathScaleY = 150;
break;
case 2: // torus with hollow (a sl viewer whould see 4 faces on a hollow sphere)
shape.ProfileCurve = (byte)ProfileShape.Circle | (byte)HollowShape.Triangle;
shape.PathCurve = (byte)Extrusion.Curve1;
shape.ProfileHollow = 27500;
shape._pathScaleY = 150;
break;
case 3: // cylinder
shape.ProfileCurve = (byte)ProfileShape.Circle | (byte)HollowShape.Triangle;
shape.PathCurve = (byte)Extrusion.Straight;
break;
case 4: // cylinder with hollow
shape.ProfileCurve = (byte)ProfileShape.Circle | (byte)HollowShape.Triangle;
shape.PathCurve = (byte)Extrusion.Straight;
shape.ProfileHollow = 27500;
break;
case 5: // prism
shape.ProfileCurve = (byte)ProfileShape.EquilateralTriangle | (byte)HollowShape.Triangle;
shape.PathCurve = (byte)Extrusion.Straight;
break;
case 6: // box
shape.ProfileCurve = (byte)ProfileShape.Square | (byte)HollowShape.Triangle;
shape.PathCurve = (byte)Extrusion.Straight;
break;
case 7: // box with hollow
shape.ProfileCurve = (byte)ProfileShape.Square | (byte)HollowShape.Triangle;
shape.PathCurve = (byte)Extrusion.Straight;
shape.ProfileHollow = 27500;
break;
default: // 8 faces box with cut
shape.ProfileCurve = (byte)ProfileShape.Square | (byte)HollowShape.Triangle;
shape.PathCurve = (byte)Extrusion.Straight;
shape.ProfileBegin = 9375;
break;
}
shape.SculptEntry = true;
shape.SculptType = (byte)OpenMetaverse.SculptType.Mesh;
shape.SculptTexture = meshAssetID;
return shape;
}
public void SetScale(float side)
{
_scale = new Vector3(side, side, side);
}
public void SetHeigth(float height)
{
_scale.Z = height;
}
public void SetRadius(float radius)
{
_scale.X = _scale.Y = radius * 2f;
}
// TODO: void returns need to change of course
public virtual void GetMesh()
{
}
public PrimitiveBaseShape Copy()
{
return (PrimitiveBaseShape) MemberwiseClone();
}
public static PrimitiveBaseShape CreateCylinder(float radius, float heigth)
{
PrimitiveBaseShape shape = CreateCylinder();
shape.SetHeigth(heigth);
shape.SetRadius(radius);
return shape;
}
public void SetPathRange(Vector3 pathRange)
{
_pathBegin = Primitive.PackBeginCut(pathRange.X);
_pathEnd = Primitive.PackEndCut(pathRange.Y);
}
public void SetPathRange(float begin, float end)
{
_pathBegin = Primitive.PackBeginCut(begin);
_pathEnd = Primitive.PackEndCut(end);
}
public void SetSculptProperties(byte sculptType, UUID SculptTextureUUID)
{
_sculptType = sculptType;
_sculptTexture = SculptTextureUUID;
}
public void SetProfileRange(Vector3 profileRange)
{
_profileBegin = Primitive.PackBeginCut(profileRange.X);
_profileEnd = Primitive.PackEndCut(profileRange.Y);
}
public void SetProfileRange(float begin, float end)
{
_profileBegin = Primitive.PackBeginCut(begin);
_profileEnd = Primitive.PackEndCut(end);
}
public byte[] ExtraParams
{
get
{
return ExtraParamsToBytes();
}
set
{
ReadInExtraParamsBytes(value);
}
}
public ushort PathBegin {
get {
return _pathBegin;
}
set {
_pathBegin = value;
}
}
public byte PathCurve {
get {
return _pathCurve;
}
set {
_pathCurve = value;
}
}
public ushort PathEnd {
get {
return _pathEnd;
}
set {
_pathEnd = value;
}
}
public sbyte PathRadiusOffset {
get {
return _pathRadiusOffset;
}
set {
_pathRadiusOffset = value;
}
}
public byte PathRevolutions {
get {
return _pathRevolutions;
}
set {
_pathRevolutions = value;
}
}
public byte PathScaleX {
get {
return _pathScaleX;
}
set {
_pathScaleX = value;
}
}
public byte PathScaleY {
get {
return _pathScaleY;
}
set {
_pathScaleY = value;
}
}
public byte PathShearX {
get {
return _pathShearX;
}
set {
_pathShearX = value;
}
}
public byte PathShearY {
get {
return _pathShearY;
}
set {
_pathShearY = value;
}
}
public sbyte PathSkew {
get {
return _pathSkew;
}
set {
_pathSkew = value;
}
}
public sbyte PathTaperX {
get {
return _pathTaperX;
}
set {
_pathTaperX = value;
}
}
public sbyte PathTaperY {
get {
return _pathTaperY;
}
set {
_pathTaperY = value;
}
}
public sbyte PathTwist {
get {
return _pathTwist;
}
set {
_pathTwist = value;
}
}
public sbyte PathTwistBegin {
get {
return _pathTwistBegin;
}
set {
_pathTwistBegin = value;
}
}
public byte PCode {
get {
return _pCode;
}
set {
_pCode = value;
}
}
public ushort ProfileBegin {
get {
return _profileBegin;
}
set {
_profileBegin = value;
}
}
public ushort ProfileEnd {
get {
return _profileEnd;
}
set {
_profileEnd = value;
}
}
public ushort ProfileHollow {
get {
return _profileHollow;
}
set {
_profileHollow = value;
}
}
public Vector3 Scale {
get {
return _scale;
}
set {
_scale = value;
}
}
public byte State {
get {
return _state;
}
set {
_state = value;
}
}
public byte LastAttachPoint {
get {
return _lastattach;
}
set {
_lastattach = value;
}
}
public ProfileShape ProfileShape {
get {
return _profileShape;
}
set {
_profileShape = value;
}
}
public HollowShape HollowShape {
get {
return _hollowShape;
}
set {
_hollowShape = value;
}
}
public UUID SculptTexture {
get {
return _sculptTexture;
}
set {
_sculptTexture = value;
}
}
public byte SculptType
{
get
{
return _sculptType;
}
set
{
_sculptType = value;
}
}
// This is only used at runtime. For sculpties this holds the texture data, and for meshes
// the mesh data.
public byte[] SculptData
{
get
{
return _sculptData;
}
set
{
// m_log.DebugFormat("[PRIMITIVE BASE SHAPE]: Setting SculptData to data with length {0}", value.Length);
_sculptData = value;
}
}
public int FlexiSoftness
{
get
{
return _flexiSoftness;
}
set
{
_flexiSoftness = value;
}
}
public float FlexiTension {
get {
return _flexiTension;
}
set {
_flexiTension = value;
}
}
public float FlexiDrag {
get {
return _flexiDrag;
}
set {
_flexiDrag = value;
}
}
public float FlexiGravity {
get {
return _flexiGravity;
}
set {
_flexiGravity = value;
}
}
public float FlexiWind {
get {
return _flexiWind;
}
set {
_flexiWind = value;
}
}
public float FlexiForceX {
get {
return _flexiForceX;
}
set {
_flexiForceX = value;
}
}
public float FlexiForceY {
get {
return _flexiForceY;
}
set {
_flexiForceY = value;
}
}
public float FlexiForceZ {
get {
return _flexiForceZ;
}
set {
_flexiForceZ = value;
}
}
public float LightColorR {
get {
return _lightColorR;
}
set {
if (value < 0)
_lightColorR = 0;
else if (value > 1.0f)
_lightColorR = 1.0f;
else
_lightColorR = value;
}
}
public float LightColorG {
get {
return _lightColorG;
}
set {
if (value < 0)
_lightColorG = 0;
else if (value > 1.0f)
_lightColorG = 1.0f;
else
_lightColorG = value;
}
}
public float LightColorB {
get {
return _lightColorB;
}
set {
if (value < 0)
_lightColorB = 0;
else if (value > 1.0f)
_lightColorB = 1.0f;
else
_lightColorB = value;
}
}
public float LightColorA {
get {
return _lightColorA;
}
set {
if (value < 0)
_lightColorA = 0;
else if (value > 1.0f)
_lightColorA = 1.0f;
else
_lightColorA = value;
}
}
public float LightRadius {
get {
return _lightRadius;
}
set {
_lightRadius = value;
}
}
public float LightCutoff {
get {
return _lightCutoff;
}
set {
_lightCutoff = value;
}
}
public float LightFalloff {
get {
return _lightFalloff;
}
set {
_lightFalloff = value;
}
}
public float LightIntensity {
get {
return _lightIntensity;
}
set {
_lightIntensity = value;
}
}
public bool FlexiEntry {
get {
return _flexiEntry;
}
set {
_flexiEntry = value;
}
}
public bool LightEntry {
get {
return _lightEntry;
}
set {
_lightEntry = value;
}
}
public bool SculptEntry {
get {
return _sculptEntry;
}
set {
_sculptEntry = value;
}
}
public bool ProjectionEntry {
get {
return _projectionEntry;
}
set {
_projectionEntry = value;
}
}
public UUID ProjectionTextureUUID {
get {
return _projectionTextureID;
}
set {
_projectionTextureID = value;
}
}
public float ProjectionFOV {
get {
return _projectionFOV;
}
set {
_projectionFOV = value;
}
}
public float ProjectionFocus {
get {
return _projectionFocus;
}
set {
_projectionFocus = value;
}
}
public float ProjectionAmbiance {
get {
return _projectionAmb;
}
set {
_projectionAmb = value;
}
}
public ulong GetMeshKey(Vector3 size, float lod)
{
return GetMeshKey(size, lod, false);
}
public ulong GetMeshKey(Vector3 size, float lod, bool convex)
{
ulong hash = 5381;
hash = djb2(hash, this.PathCurve);
hash = djb2(hash, (byte)((byte)this.HollowShape | (byte)this.ProfileShape));
hash = djb2(hash, this.PathBegin);
hash = djb2(hash, this.PathEnd);
hash = djb2(hash, this.PathScaleX);
hash = djb2(hash, this.PathScaleY);
hash = djb2(hash, this.PathShearX);
hash = djb2(hash, this.PathShearY);
hash = djb2(hash, (byte)this.PathTwist);
hash = djb2(hash, (byte)this.PathTwistBegin);
hash = djb2(hash, (byte)this.PathRadiusOffset);
hash = djb2(hash, (byte)this.PathTaperX);
hash = djb2(hash, (byte)this.PathTaperY);
hash = djb2(hash, this.PathRevolutions);
hash = djb2(hash, (byte)this.PathSkew);
hash = djb2(hash, this.ProfileBegin);
hash = djb2(hash, this.ProfileEnd);
hash = djb2(hash, this.ProfileHollow);
// TODO: Separate scale out from the primitive shape data (after
// scaling is supported at the physics engine level)
byte[] scaleBytes = size.GetBytes();
for (int i = 0; i < scaleBytes.Length; i++)
hash = djb2(hash, scaleBytes[i]);
// Include LOD in hash, accounting for endianness
byte[] lodBytes = new byte[4];
Buffer.BlockCopy(BitConverter.GetBytes(lod), 0, lodBytes, 0, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(lodBytes, 0, 4);
}
for (int i = 0; i < lodBytes.Length; i++)
hash = djb2(hash, lodBytes[i]);
// include sculpt UUID
if (this.SculptEntry)
{
scaleBytes = this.SculptTexture.GetBytes();
for (int i = 0; i < scaleBytes.Length; i++)
hash = djb2(hash, scaleBytes[i]);
}
if(convex)
hash = djb2(hash, 0xa5);
return hash;
}
private ulong djb2(ulong hash, byte c)
{
return ((hash << 5) + hash) + (ulong)c;
}
private ulong djb2(ulong hash, ushort c)
{
hash = ((hash << 5) + hash) + (ulong)((byte)c);
return ((hash << 5) + hash) + (ulong)(c >> 8);
}
public byte[] ExtraParamsToBytes()
{
// m_log.DebugFormat("[EXTRAPARAMS]: Called ExtraParamsToBytes()");
ushort FlexiEP = 0x10;
ushort LightEP = 0x20;
ushort SculptEP = 0x30;
ushort ProjectionEP = 0x40;
int i = 0;
uint TotalBytesLength = 1; // ExtraParamsNum
uint ExtraParamsNum = 0;
if (_flexiEntry)
{
ExtraParamsNum++;
TotalBytesLength += 16;// data
TotalBytesLength += 2 + 4; // type
}
if (_lightEntry)
{
ExtraParamsNum++;
TotalBytesLength += 16;// data
TotalBytesLength += 2 + 4; // type
}
if (_sculptEntry)
{
ExtraParamsNum++;
TotalBytesLength += 17;// data
TotalBytesLength += 2 + 4; // type
}
if (_projectionEntry)
{
ExtraParamsNum++;
TotalBytesLength += 28;// data
TotalBytesLength += 2 + 4;// type
}
byte[] returnbytes = new byte[TotalBytesLength];
// uint paramlength = ExtraParamsNum;
// Stick in the number of parameters
returnbytes[i++] = (byte)ExtraParamsNum;
if (_flexiEntry)
{
byte[] FlexiData = GetFlexiBytes();
returnbytes[i++] = (byte)(FlexiEP % 256);
returnbytes[i++] = (byte)((FlexiEP >> 8) % 256);
returnbytes[i++] = (byte)(FlexiData.Length % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 8) % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 16) % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 24) % 256);
Array.Copy(FlexiData, 0, returnbytes, i, FlexiData.Length);
i += FlexiData.Length;
}
if (_lightEntry)
{
byte[] LightData = GetLightBytes();
returnbytes[i++] = (byte)(LightEP % 256);
returnbytes[i++] = (byte)((LightEP >> 8) % 256);
returnbytes[i++] = (byte)(LightData.Length % 256);
returnbytes[i++] = (byte)((LightData.Length >> 8) % 256);
returnbytes[i++] = (byte)((LightData.Length >> 16) % 256);
returnbytes[i++] = (byte)((LightData.Length >> 24) % 256);
Array.Copy(LightData, 0, returnbytes, i, LightData.Length);
i += LightData.Length;
}
if (_sculptEntry)
{
byte[] SculptData = GetSculptBytes();
returnbytes[i++] = (byte)(SculptEP % 256);
returnbytes[i++] = (byte)((SculptEP >> 8) % 256);
returnbytes[i++] = (byte)(SculptData.Length % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 8) % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 16) % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 24) % 256);
Array.Copy(SculptData, 0, returnbytes, i, SculptData.Length);
i += SculptData.Length;
}
if (_projectionEntry)
{
byte[] ProjectionData = GetProjectionBytes();
returnbytes[i++] = (byte)(ProjectionEP % 256);
returnbytes[i++] = (byte)((ProjectionEP >> 8) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length >> 16) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length >> 20) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length >> 24) % 256);
Array.Copy(ProjectionData, 0, returnbytes, i, ProjectionData.Length);
i += ProjectionData.Length;
}
if (!_flexiEntry && !_lightEntry && !_sculptEntry && !_projectionEntry)
{
byte[] returnbyte = new byte[1];
returnbyte[0] = 0;
return returnbyte;
}
return returnbytes;
}
public void ReadInUpdateExtraParam(ushort type, bool inUse, byte[] data)
{
const ushort FlexiEP = 0x10;
const ushort LightEP = 0x20;
const ushort SculptEP = 0x30;
const ushort ProjectionEP = 0x40;
switch (type)
{
case FlexiEP:
if (!inUse)
{
_flexiEntry = false;
return;
}
ReadFlexiData(data, 0);
break;
case LightEP:
if (!inUse)
{
_lightEntry = false;
return;
}
ReadLightData(data, 0);
break;
case SculptEP:
if (!inUse)
{
_sculptEntry = false;
return;
}
ReadSculptData(data, 0);
break;
case ProjectionEP:
if (!inUse)
{
_projectionEntry = false;
return;
}
ReadProjectionData(data, 0);
break;
}
}
public void ReadInExtraParamsBytes(byte[] data)
{
if (data == null || data.Length == 1)
return;
const ushort FlexiEP = 0x10;
const ushort LightEP = 0x20;
const ushort SculptEP = 0x30;
const ushort ProjectionEP = 0x40;
bool lGotFlexi = false;
bool lGotLight = false;
bool lGotSculpt = false;
bool lGotFilter = false;
int i = 0;
byte extraParamCount = 0;
if (data.Length > 0)
{
extraParamCount = data[i++];
}
for (int k = 0; k < extraParamCount; k++)
{
ushort epType = Utils.BytesToUInt16(data, i);
i += 2;
// uint paramLength = Helpers.BytesToUIntBig(data, i);
i += 4;
switch (epType)
{
case FlexiEP:
ReadFlexiData(data, i);
i += 16;
lGotFlexi = true;
break;
case LightEP:
ReadLightData(data, i);
i += 16;
lGotLight = true;
break;
case SculptEP:
ReadSculptData(data, i);
i += 17;
lGotSculpt = true;
break;
case ProjectionEP:
ReadProjectionData(data, i);
i += 28;
lGotFilter = true;
break;
}
}
if (!lGotFlexi)
_flexiEntry = false;
if (!lGotLight)
_lightEntry = false;
if (!lGotSculpt)
_sculptEntry = false;
if (!lGotFilter)
_projectionEntry = false;
}
public void ReadSculptData(byte[] data, int pos)
{
UUID SculptUUID;
byte SculptTypel;
if (data.Length-pos >= 17)
{
_sculptEntry = true;
byte[] SculptTextureUUID = new byte[16];
SculptTypel = data[16 + pos];
Array.Copy(data, pos, SculptTextureUUID,0, 16);
SculptUUID = new UUID(SculptTextureUUID, 0);
}
else
{
_sculptEntry = false;
SculptUUID = UUID.Zero;
SculptTypel = 0x00;
}
if (_sculptEntry)
{
if (_sculptType != (byte)1 && _sculptType != (byte)2 && _sculptType != (byte)3 && _sculptType != (byte)4)
_sculptType = 4;
}
_sculptTexture = SculptUUID;
_sculptType = SculptTypel;
//m_log.Info("[SCULPT]:" + SculptUUID.ToString());
}
public byte[] GetSculptBytes()
{
byte[] data = new byte[17];
_sculptTexture.GetBytes().CopyTo(data, 0);
data[16] = (byte)_sculptType;
return data;
}
public void ReadFlexiData(byte[] data, int pos)
{
if (data.Length-pos >= 16)
{
_flexiEntry = true;
_flexiSoftness = ((data[pos] & 0x80) >> 6) | ((data[pos + 1] & 0x80) >> 7);
_flexiTension = (float)(data[pos++] & 0x7F) / 10.0f;
_flexiDrag = (float)(data[pos++] & 0x7F) / 10.0f;
_flexiGravity = (float)(data[pos++] / 10.0f) - 10.0f;
_flexiWind = (float)data[pos++] / 10.0f;
Vector3 lForce = new Vector3(data, pos);
_flexiForceX = lForce.X;
_flexiForceY = lForce.Y;
_flexiForceZ = lForce.Z;
}
else
{
_flexiEntry = false;
_flexiSoftness = 0;
_flexiTension = 0.0f;
_flexiDrag = 0.0f;
_flexiGravity = 0.0f;
_flexiWind = 0.0f;
_flexiForceX = 0f;
_flexiForceY = 0f;
_flexiForceZ = 0f;
}
}
public byte[] GetFlexiBytes()
{
byte[] data = new byte[16];
int i = 0;
// Softness is packed in the upper bits of tension and drag
data[i] = (byte)((_flexiSoftness & 2) << 6);
data[i + 1] = (byte)((_flexiSoftness & 1) << 7);
data[i++] |= (byte)((byte)(_flexiTension * 10.01f) & 0x7F);
data[i++] |= (byte)((byte)(_flexiDrag * 10.01f) & 0x7F);
data[i++] = (byte)((_flexiGravity + 10.0f) * 10.01f);
data[i++] = (byte)(_flexiWind * 10.01f);
Vector3 lForce = new Vector3(_flexiForceX, _flexiForceY, _flexiForceZ);
lForce.GetBytes().CopyTo(data, i);
return data;
}
public void ReadLightData(byte[] data, int pos)
{
if (data.Length - pos >= 16)
{
_lightEntry = true;
Color4 lColor = new Color4(data, pos, false);
_lightIntensity = lColor.A;
_lightColorA = 1f;
_lightColorR = lColor.R;
_lightColorG = lColor.G;
_lightColorB = lColor.B;
_lightRadius = Utils.BytesToFloat(data, pos + 4);
_lightCutoff = Utils.BytesToFloat(data, pos + 8);
_lightFalloff = Utils.BytesToFloat(data, pos + 12);
}
else
{
_lightEntry = false;
_lightColorA = 1f;
_lightColorR = 0f;
_lightColorG = 0f;
_lightColorB = 0f;
_lightRadius = 0f;
_lightCutoff = 0f;
_lightFalloff = 0f;
_lightIntensity = 0f;
}
}
public byte[] GetLightBytes()
{
byte[] data = new byte[16];
// Alpha channel in color is intensity
Color4 tmpColor = new Color4(_lightColorR,_lightColorG,_lightColorB,_lightIntensity);
tmpColor.GetBytes().CopyTo(data, 0);
Utils.FloatToBytes(_lightRadius).CopyTo(data, 4);
Utils.FloatToBytes(_lightCutoff).CopyTo(data, 8);
Utils.FloatToBytes(_lightFalloff).CopyTo(data, 12);
return data;
}
public void ReadProjectionData(byte[] data, int pos)
{
byte[] ProjectionTextureUUID = new byte[16];
if (data.Length - pos >= 28)
{
_projectionEntry = true;
Array.Copy(data, pos, ProjectionTextureUUID,0, 16);
_projectionTextureID = new UUID(ProjectionTextureUUID, 0);
_projectionFOV = Utils.BytesToFloat(data, pos + 16);
_projectionFocus = Utils.BytesToFloat(data, pos + 20);
_projectionAmb = Utils.BytesToFloat(data, pos + 24);
}
else
{
_projectionEntry = false;
_projectionTextureID = UUID.Zero;
_projectionFOV = 0f;
_projectionFocus = 0f;
_projectionAmb = 0f;
}
}
public byte[] GetProjectionBytes()
{
byte[] data = new byte[28];
_projectionTextureID.GetBytes().CopyTo(data, 0);
Utils.FloatToBytes(_projectionFOV).CopyTo(data, 16);
Utils.FloatToBytes(_projectionFocus).CopyTo(data, 20);
Utils.FloatToBytes(_projectionAmb).CopyTo(data, 24);
return data;
}
/// <summary>
/// Creates a OpenMetaverse.Primitive and populates it with converted PrimitiveBaseShape values
/// </summary>
/// <returns></returns>
public Primitive ToOmvPrimitive()
{
// position and rotation defaults here since they are not available in PrimitiveBaseShape
return ToOmvPrimitive(new Vector3(0.0f, 0.0f, 0.0f),
new Quaternion(0.0f, 0.0f, 0.0f, 1.0f));
}
/// <summary>
/// Creates a OpenMetaverse.Primitive and populates it with converted PrimitiveBaseShape values
/// </summary>
/// <param name="position"></param>
/// <param name="rotation"></param>
/// <returns></returns>
public Primitive ToOmvPrimitive(Vector3 position, Quaternion rotation)
{
OpenMetaverse.Primitive prim = new OpenMetaverse.Primitive();
prim.Scale = this.Scale;
prim.Position = position;
prim.Rotation = rotation;
if (this.SculptEntry)
{
prim.Sculpt = new Primitive.SculptData();
prim.Sculpt.Type = (OpenMetaverse.SculptType)this.SculptType;
prim.Sculpt.SculptTexture = this.SculptTexture;
}
prim.PrimData.PathShearX = this.PathShearX < 128 ? (float)this.PathShearX * 0.01f : (float)(this.PathShearX - 256) * 0.01f;
prim.PrimData.PathShearY = this.PathShearY < 128 ? (float)this.PathShearY * 0.01f : (float)(this.PathShearY - 256) * 0.01f;
prim.PrimData.PathBegin = (float)this.PathBegin * 2.0e-5f;
prim.PrimData.PathEnd = 1.0f - (float)this.PathEnd * 2.0e-5f;
prim.PrimData.PathScaleX = (200 - this.PathScaleX) * 0.01f;
prim.PrimData.PathScaleY = (200 - this.PathScaleY) * 0.01f;
prim.PrimData.PathTaperX = this.PathTaperX * 0.01f;
prim.PrimData.PathTaperY = this.PathTaperY * 0.01f;
prim.PrimData.PathTwistBegin = this.PathTwistBegin * 0.01f;
prim.PrimData.PathTwist = this.PathTwist * 0.01f;
prim.PrimData.ProfileBegin = (float)this.ProfileBegin * 2.0e-5f;
prim.PrimData.ProfileEnd = 1.0f - (float)this.ProfileEnd * 2.0e-5f;
prim.PrimData.ProfileHollow = (float)this.ProfileHollow * 2.0e-5f;
prim.PrimData.profileCurve = this.ProfileCurve;
prim.PrimData.ProfileHole = (HoleType)this.HollowShape;
prim.PrimData.PathCurve = (PathCurve)this.PathCurve;
prim.PrimData.PathRadiusOffset = 0.01f * this.PathRadiusOffset;
prim.PrimData.PathRevolutions = 1.0f + 0.015f * this.PathRevolutions;
prim.PrimData.PathSkew = 0.01f * this.PathSkew;
prim.PrimData.PCode = OpenMetaverse.PCode.Prim;
prim.PrimData.State = 0;
if (this.FlexiEntry)
{
prim.Flexible = new Primitive.FlexibleData();
prim.Flexible.Drag = this.FlexiDrag;
prim.Flexible.Force = new Vector3(this.FlexiForceX, this.FlexiForceY, this.FlexiForceZ);
prim.Flexible.Gravity = this.FlexiGravity;
prim.Flexible.Softness = this.FlexiSoftness;
prim.Flexible.Tension = this.FlexiTension;
prim.Flexible.Wind = this.FlexiWind;
}
if (this.LightEntry)
{
prim.Light = new Primitive.LightData();
prim.Light.Color = new Color4(this.LightColorR, this.LightColorG, this.LightColorB, this.LightColorA);
prim.Light.Cutoff = this.LightCutoff;
prim.Light.Falloff = this.LightFalloff;
prim.Light.Intensity = this.LightIntensity;
prim.Light.Radius = this.LightRadius;
}
prim.Textures = this.Textures;
prim.Properties = new Primitive.ObjectProperties();
prim.Properties.Name = "Object";
prim.Properties.Description = "";
prim.Properties.CreatorID = UUID.Zero;
prim.Properties.GroupID = UUID.Zero;
prim.Properties.OwnerID = UUID.Zero;
prim.Properties.Permissions = new Permissions();
prim.Properties.SalePrice = 10;
prim.Properties.SaleType = new SaleType();
return prim;
}
/// <summary>
/// Encapsulates a list of media entries.
/// </summary>
/// This class is necessary because we want to replace auto-serialization of MediaEntry with something more
/// OSD like and less vulnerable to change.
public class MediaList : List<MediaEntry>, IXmlSerializable
{
public const string MEDIA_TEXTURE_TYPE = "sl";
public MediaList() : base() {}
public MediaList(IEnumerable<MediaEntry> collection) : base(collection) {}
public MediaList(int capacity) : base(capacity) {}
public XmlSchema GetSchema()
{
return null;
}
public string ToXml()
{
lock (this)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter xtw = new XmlTextWriter(sw))
{
xtw.WriteStartElement("OSMedia");
xtw.WriteAttributeString("type", MEDIA_TEXTURE_TYPE);
xtw.WriteAttributeString("version", "0.1");
OSDArray meArray = new OSDArray();
foreach (MediaEntry me in this)
{
OSD osd = (null == me ? new OSD() : me.GetOSD());
meArray.Add(osd);
}
xtw.WriteStartElement("OSData");
xtw.WriteRaw(OSDParser.SerializeLLSDXmlString(meArray));
xtw.WriteEndElement();
xtw.WriteEndElement();
xtw.Flush();
return sw.ToString();
}
}
}
}
public void WriteXml(XmlWriter writer)
{
writer.WriteRaw(ToXml());
}
public static MediaList FromXml(string rawXml)
{
MediaList ml = new MediaList();
ml.ReadXml(rawXml);
if(ml.Count == 0)
return null;
return ml;
}
public void ReadXml(string rawXml)
{
try
{
using (StringReader sr = new StringReader(rawXml))
{
using (XmlTextReader xtr = new XmlTextReader(sr))
{
xtr.MoveToContent();
string type = xtr.GetAttribute("type");
//m_log.DebugFormat("[MOAP]: Loaded media texture entry with type {0}", type);
if (type != MEDIA_TEXTURE_TYPE)
return;
xtr.ReadStartElement("OSMedia");
OSD osdp = OSDParser.DeserializeLLSDXml(xtr.ReadInnerXml());
if(osdp == null || !(osdp is OSDArray))
return;
OSDArray osdMeArray = osdp as OSDArray;
if(osdMeArray.Count == 0)
return;
foreach (OSD osdMe in osdMeArray)
{
MediaEntry me = (osdMe is OSDMap ? MediaEntry.FromOSD(osdMe) : new MediaEntry());
Add(me);
}
}
}
}
catch
{
m_log.Debug("PrimitiveBaseShape] error decoding MOAP xml" );
}
}
public void ReadXml(XmlReader reader)
{
if (reader.IsEmptyElement)
return;
ReadXml(reader.ReadInnerXml());
}
}
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
namespace Valle.TpvFinal
{
public partial class Tpv
{
private global::Gtk.VBox vbox1;
private global::Gtk.HBox hbox1;
private global::Gtk.Label lblNomMesas;
private global::Gtk.Label lblNomCamarero;
private global::Gtk.Label lblTarifa;
private global::Gtk.HBox hbox2;
private global::Gtk.VBox vbox2;
private global::Gtk.ScrolledWindow scrollNotasGtk;
private global::Gtk.TreeView lstNotas;
private global::Gtk.HBox hbox4;
private global::Valle.GtkUtilidades.MiLabel lblDisplayInf;
private global::Valle.GtkUtilidades.MiLabel lblDisplay;
private global::Gtk.Table table1;
private global::Valle.GtkUtilidades.MiBoton btn4;
private global::Valle.GtkUtilidades.MiBoton btn5;
private global::Valle.GtkUtilidades.MiBoton btn6;
private global::Valle.GtkUtilidades.MiBoton btn7;
private global::Valle.GtkUtilidades.MiBoton btn8;
private global::Valle.GtkUtilidades.MiBoton btn9;
private global::Gtk.Button btnBorrar;
private global::Gtk.Button btnBorrNum;
private global::Valle.GtkUtilidades.MiBoton btnC;
private global::Gtk.Button btnCaja;
private global::Gtk.Button btnCamareros;
private global::Valle.GtkUtilidades.MiBoton btnCero;
private global::Valle.GtkUtilidades.MiBoton btnDos;
private global::Gtk.Button btnFavoritos;
private global::Gtk.Button btnImprimir;
private global::Gtk.VBox vbox3;
private global::Gtk.Image image14;
private global::Gtk.Label label1;
private global::Gtk.Button btnMesas;
private global::Gtk.Button btnOpciones;
private global::Gtk.Button btnSalir;
private global::Gtk.Button btnSecciones;
private global::Gtk.Button btnTarifa;
private global::Valle.GtkUtilidades.MiBoton btnTres;
private global::Valle.GtkUtilidades.MiBoton btnUno;
private global::Valle.GtkUtilidades.ScrollTactil scrollNotas;
private global::Gtk.HBox hbox3;
private global::Gtk.VBox vbox7;
private global::Gtk.Button btnAbrirCajon;
private global::Gtk.VBox vbox8;
private global::Gtk.Image image18;
private global::Gtk.Label label4;
private global::Gtk.Button btnHerrDesglose;
private global::Gtk.VBox vbox5;
private global::Gtk.Image image17;
private global::Gtk.Label label3;
private global::Gtk.Button btnVarios;
private global::Gtk.Button btnVariosConNombre;
private global::Gtk.Table pneArticulos;
private global::Gtk.VButtonBox vbuttonbox2;
private global::Gtk.Button btnBuscador;
private global::Gtk.VBox vbox4;
private global::Gtk.Image image16;
private global::Gtk.Label label2;
private global::Gtk.Button btnPgArriba;
private global::Gtk.Button btnPgAbajo;
protected virtual void Build ()
{
global::Stetic.Gui.Initialize (this);
// Widget Valle.TpvFinal.Tpv
this.Name = "Valle.TpvFinal.Tpv";
this.Title = global::Mono.Unix.Catalog.GetString ("Tpv");
this.Decorated = false;
this.SkipTaskbarHint = true;
// Container child Valle.TpvFinal.Tpv.Gtk.Container+ContainerChild
this.vbox1 = new global::Gtk.VBox ();
this.vbox1.Name = "vbox1";
this.vbox1.Spacing = 6;
this.vbox1.BorderWidth = ((uint)(6));
// Container child vbox1.Gtk.Box+BoxChild
this.hbox1 = new global::Gtk.HBox ();
this.hbox1.Name = "hbox1";
this.hbox1.Spacing = 6;
this.hbox1.BorderWidth = ((uint)(3));
// Container child hbox1.Gtk.Box+BoxChild
this.lblNomMesas = new global::Gtk.Label ();
this.lblNomMesas.Name = "lblNomMesas";
this.lblNomMesas.LabelProp = global::Mono.Unix.Catalog.GetString ("<span size='x-large'>Barra</span>");
this.lblNomMesas.UseMarkup = true;
this.hbox1.Add (this.lblNomMesas);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.lblNomMesas]));
w1.Position = 0;
// Container child hbox1.Gtk.Box+BoxChild
this.lblNomCamarero = new global::Gtk.Label ();
this.lblNomCamarero.Name = "lblNomCamarero";
this.lblNomCamarero.LabelProp = global::Mono.Unix.Catalog.GetString ("<span size='x-large'>Cajero</span>");
this.lblNomCamarero.UseMarkup = true;
this.hbox1.Add (this.lblNomCamarero);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.lblNomCamarero]));
w2.Position = 1;
w2.Fill = false;
// Container child hbox1.Gtk.Box+BoxChild
this.lblTarifa = new global::Gtk.Label ();
this.lblTarifa.Name = "lblTarifa";
this.lblTarifa.LabelProp = global::Mono.Unix.Catalog.GetString ("<span size='x-large' foreground=\"red\">T : 1</span>");
this.lblTarifa.UseMarkup = true;
this.hbox1.Add (this.lblTarifa);
global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.lblTarifa]));
w3.Position = 2;
w3.Fill = false;
this.vbox1.Add (this.hbox1);
global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.hbox1]));
w4.Position = 0;
w4.Expand = false;
w4.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.hbox2 = new global::Gtk.HBox ();
this.hbox2.Name = "hbox2";
this.hbox2.Spacing = 6;
// Container child hbox2.Gtk.Box+BoxChild
this.vbox2 = new global::Gtk.VBox ();
this.vbox2.Name = "vbox2";
this.vbox2.Spacing = 6;
// Container child vbox2.Gtk.Box+BoxChild
this.scrollNotasGtk = new global::Gtk.ScrolledWindow ();
this.scrollNotasGtk.Name = "scrollNotasGtk";
this.scrollNotasGtk.ShadowType = ((global::Gtk.ShadowType)(1));
// Container child scrollNotasGtk.Gtk.Container+ContainerChild
this.lstNotas = new global::Gtk.TreeView ();
this.lstNotas.CanFocus = true;
this.lstNotas.Name = "lstNotas";
this.scrollNotasGtk.Add (this.lstNotas);
this.vbox2.Add (this.scrollNotasGtk);
global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.vbox2[this.scrollNotasGtk]));
w6.Position = 0;
// Container child vbox2.Gtk.Box+BoxChild
this.hbox4 = new global::Gtk.HBox ();
this.hbox4.Name = "hbox4";
this.hbox4.Spacing = 6;
// Container child hbox4.Gtk.Box+BoxChild
this.lblDisplayInf = new global::Valle.GtkUtilidades.MiLabel ();
this.lblDisplayInf.WidthRequest = 120;
this.lblDisplayInf.HeightRequest = 50;
this.lblDisplayInf.Events = ((global::Gdk.EventMask)(256));
this.lblDisplayInf.Name = "lblDisplayInf";
this.hbox4.Add (this.lblDisplayInf);
global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.hbox4[this.lblDisplayInf]));
w7.Position = 0;
w7.Expand = false;
w7.Fill = false;
// Container child hbox4.Gtk.Box+BoxChild
this.lblDisplay = new global::Valle.GtkUtilidades.MiLabel ();
this.lblDisplay.Events = ((global::Gdk.EventMask)(256));
this.lblDisplay.Name = "lblDisplay";
this.hbox4.Add (this.lblDisplay);
global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.hbox4[this.lblDisplay]));
w8.Position = 1;
this.vbox2.Add (this.hbox4);
global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(this.vbox2[this.hbox4]));
w9.Position = 1;
w9.Expand = false;
w9.Fill = false;
this.hbox2.Add (this.vbox2);
global::Gtk.Box.BoxChild w10 = ((global::Gtk.Box.BoxChild)(this.hbox2[this.vbox2]));
w10.Position = 0;
// Container child hbox2.Gtk.Box+BoxChild
this.table1 = new global::Gtk.Table (((uint)(4)), ((uint)(6)), false);
this.table1.Name = "table1";
this.table1.RowSpacing = ((uint)(6));
this.table1.ColumnSpacing = ((uint)(6));
// Container child table1.Gtk.Table+TableChild
this.btn4 = new global::Valle.GtkUtilidades.MiBoton ();
this.btn4.WidthRequest = 50;
this.btn4.HeightRequest = 50;
this.btn4.Events = ((global::Gdk.EventMask)(256));
this.btn4.Name = "btn4";
this.table1.Add (this.btn4);
global::Gtk.Table.TableChild w11 = ((global::Gtk.Table.TableChild)(this.table1[this.btn4]));
w11.TopAttach = ((uint)(1));
w11.BottomAttach = ((uint)(2));
w11.LeftAttach = ((uint)(1));
w11.RightAttach = ((uint)(2));
w11.XOptions = ((global::Gtk.AttachOptions)(4));
w11.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btn5 = new global::Valle.GtkUtilidades.MiBoton ();
this.btn5.WidthRequest = 50;
this.btn5.HeightRequest = 50;
this.btn5.Events = ((global::Gdk.EventMask)(256));
this.btn5.Name = "btn5";
this.table1.Add (this.btn5);
global::Gtk.Table.TableChild w12 = ((global::Gtk.Table.TableChild)(this.table1[this.btn5]));
w12.TopAttach = ((uint)(1));
w12.BottomAttach = ((uint)(2));
w12.LeftAttach = ((uint)(2));
w12.RightAttach = ((uint)(3));
w12.XOptions = ((global::Gtk.AttachOptions)(4));
w12.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btn6 = new global::Valle.GtkUtilidades.MiBoton ();
this.btn6.WidthRequest = 50;
this.btn6.HeightRequest = 50;
this.btn6.Events = ((global::Gdk.EventMask)(256));
this.btn6.Name = "btn6";
this.table1.Add (this.btn6);
global::Gtk.Table.TableChild w13 = ((global::Gtk.Table.TableChild)(this.table1[this.btn6]));
w13.TopAttach = ((uint)(1));
w13.BottomAttach = ((uint)(2));
w13.LeftAttach = ((uint)(3));
w13.RightAttach = ((uint)(4));
w13.XOptions = ((global::Gtk.AttachOptions)(4));
w13.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btn7 = new global::Valle.GtkUtilidades.MiBoton ();
this.btn7.WidthRequest = 50;
this.btn7.HeightRequest = 50;
this.btn7.Events = ((global::Gdk.EventMask)(256));
this.btn7.Name = "btn7";
this.table1.Add (this.btn7);
global::Gtk.Table.TableChild w14 = ((global::Gtk.Table.TableChild)(this.table1[this.btn7]));
w14.TopAttach = ((uint)(2));
w14.BottomAttach = ((uint)(3));
w14.LeftAttach = ((uint)(1));
w14.RightAttach = ((uint)(2));
w14.XOptions = ((global::Gtk.AttachOptions)(4));
w14.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btn8 = new global::Valle.GtkUtilidades.MiBoton ();
this.btn8.WidthRequest = 50;
this.btn8.HeightRequest = 50;
this.btn8.Events = ((global::Gdk.EventMask)(256));
this.btn8.Name = "btn8";
this.table1.Add (this.btn8);
global::Gtk.Table.TableChild w15 = ((global::Gtk.Table.TableChild)(this.table1[this.btn8]));
w15.TopAttach = ((uint)(2));
w15.BottomAttach = ((uint)(3));
w15.LeftAttach = ((uint)(2));
w15.RightAttach = ((uint)(3));
w15.XOptions = ((global::Gtk.AttachOptions)(4));
w15.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btn9 = new global::Valle.GtkUtilidades.MiBoton ();
this.btn9.WidthRequest = 50;
this.btn9.HeightRequest = 50;
this.btn9.Events = ((global::Gdk.EventMask)(256));
this.btn9.Name = "btn9";
this.table1.Add (this.btn9);
global::Gtk.Table.TableChild w16 = ((global::Gtk.Table.TableChild)(this.table1[this.btn9]));
w16.TopAttach = ((uint)(2));
w16.BottomAttach = ((uint)(3));
w16.LeftAttach = ((uint)(3));
w16.RightAttach = ((uint)(4));
w16.XOptions = ((global::Gtk.AttachOptions)(4));
w16.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btnBorrar = new global::Gtk.Button ();
this.btnBorrar.HeightRequest = 85;
this.btnBorrar.CanFocus = true;
this.btnBorrar.Name = "btnBorrar";
this.btnBorrar.UseUnderline = true;
// Container child btnBorrar.Gtk.Container+ContainerChild
global::Gtk.Alignment w17 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w18 = new global::Gtk.HBox ();
w18.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w19 = new global::Gtk.Image ();
w19.Pixbuf = new global::Gdk.Pixbuf (global::System.IO.Path.Combine (global::System.AppDomain.CurrentDomain.BaseDirectory, "./iconos/ERASE00C.ICO"));
w18.Add (w19);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w21 = new global::Gtk.Label ();
w18.Add (w21);
w17.Add (w18);
this.btnBorrar.Add (w17);
this.table1.Add (this.btnBorrar);
global::Gtk.Table.TableChild w25 = ((global::Gtk.Table.TableChild)(this.table1[this.btnBorrar]));
w25.TopAttach = ((uint)(2));
w25.BottomAttach = ((uint)(3));
w25.XOptions = ((global::Gtk.AttachOptions)(4));
w25.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btnBorrNum = new global::Gtk.Button ();
this.btnBorrNum.CanFocus = true;
this.btnBorrNum.Name = "btnBorrNum";
this.btnBorrNum.UseUnderline = true;
// Container child btnBorrNum.Gtk.Container+ContainerChild
global::Gtk.Alignment w26 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w27 = new global::Gtk.HBox ();
w27.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w28 = new global::Gtk.Image ();
w28.Pixbuf = new global::Gdk.Pixbuf (global::System.IO.Path.Combine (global::System.AppDomain.CurrentDomain.BaseDirectory, "./iconos/Backspace.ICO"));
w27.Add (w28);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w30 = new global::Gtk.Label ();
w27.Add (w30);
w26.Add (w27);
this.btnBorrNum.Add (w26);
this.table1.Add (this.btnBorrNum);
global::Gtk.Table.TableChild w34 = ((global::Gtk.Table.TableChild)(this.table1[this.btnBorrNum]));
w34.TopAttach = ((uint)(3));
w34.BottomAttach = ((uint)(4));
w34.LeftAttach = ((uint)(3));
w34.RightAttach = ((uint)(4));
w34.XOptions = ((global::Gtk.AttachOptions)(4));
w34.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btnC = new global::Valle.GtkUtilidades.MiBoton ();
this.btnC.WidthRequest = 50;
this.btnC.HeightRequest = 50;
this.btnC.Events = ((global::Gdk.EventMask)(256));
this.btnC.Name = "btnC";
this.btnC.Texto = "C";
this.table1.Add (this.btnC);
global::Gtk.Table.TableChild w35 = ((global::Gtk.Table.TableChild)(this.table1[this.btnC]));
w35.TopAttach = ((uint)(3));
w35.BottomAttach = ((uint)(4));
w35.LeftAttach = ((uint)(1));
w35.RightAttach = ((uint)(2));
w35.XOptions = ((global::Gtk.AttachOptions)(4));
w35.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btnCaja = new global::Gtk.Button ();
this.btnCaja.HeightRequest = 85;
this.btnCaja.CanFocus = true;
this.btnCaja.Name = "btnCaja";
this.btnCaja.UseUnderline = true;
// Container child btnCaja.Gtk.Container+ContainerChild
global::Gtk.Alignment w36 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w37 = new global::Gtk.HBox ();
w37.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w38 = new global::Gtk.Image ();
w38.Pixbuf = new global::Gdk.Pixbuf (global::System.IO.Path.Combine (global::System.AppDomain.CurrentDomain.BaseDirectory, "./iconos/CASH01B.ICO"));
w37.Add (w38);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w40 = new global::Gtk.Label ();
w37.Add (w40);
w36.Add (w37);
this.btnCaja.Add (w36);
this.table1.Add (this.btnCaja);
global::Gtk.Table.TableChild w44 = ((global::Gtk.Table.TableChild)(this.table1[this.btnCaja]));
w44.TopAttach = ((uint)(3));
w44.BottomAttach = ((uint)(4));
w44.XOptions = ((global::Gtk.AttachOptions)(4));
w44.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btnCamareros = new global::Gtk.Button ();
this.btnCamareros.CanFocus = true;
this.btnCamareros.Name = "btnCamareros";
this.btnCamareros.UseUnderline = true;
// Container child btnCamareros.Gtk.Container+ContainerChild
global::Gtk.Alignment w45 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w46 = new global::Gtk.HBox ();
w46.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w47 = new global::Gtk.Image ();
w47.Pixbuf = new global::Gdk.Pixbuf (global::System.IO.Path.Combine (global::System.AppDomain.CurrentDomain.BaseDirectory, "./iconos/NET14.ICO"));
w46.Add (w47);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w49 = new global::Gtk.Label ();
w49.LabelProp = global::Mono.Unix.Catalog.GetString ("Camareros");
w49.UseUnderline = true;
w46.Add (w49);
w45.Add (w46);
this.btnCamareros.Add (w45);
this.table1.Add (this.btnCamareros);
global::Gtk.Table.TableChild w53 = ((global::Gtk.Table.TableChild)(this.table1[this.btnCamareros]));
w53.TopAttach = ((uint)(2));
w53.BottomAttach = ((uint)(3));
w53.LeftAttach = ((uint)(4));
w53.RightAttach = ((uint)(5));
w53.XOptions = ((global::Gtk.AttachOptions)(4));
w53.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btnCero = new global::Valle.GtkUtilidades.MiBoton ();
this.btnCero.WidthRequest = 50;
this.btnCero.HeightRequest = 50;
this.btnCero.Events = ((global::Gdk.EventMask)(256));
this.btnCero.Name = "btnCero";
this.table1.Add (this.btnCero);
global::Gtk.Table.TableChild w54 = ((global::Gtk.Table.TableChild)(this.table1[this.btnCero]));
w54.TopAttach = ((uint)(3));
w54.BottomAttach = ((uint)(4));
w54.LeftAttach = ((uint)(2));
w54.RightAttach = ((uint)(3));
w54.XOptions = ((global::Gtk.AttachOptions)(4));
w54.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btnDos = new global::Valle.GtkUtilidades.MiBoton ();
this.btnDos.WidthRequest = 85;
this.btnDos.HeightRequest = 50;
this.btnDos.Events = ((global::Gdk.EventMask)(256));
this.btnDos.Name = "btnDos";
this.table1.Add (this.btnDos);
global::Gtk.Table.TableChild w55 = ((global::Gtk.Table.TableChild)(this.table1[this.btnDos]));
w55.LeftAttach = ((uint)(2));
w55.RightAttach = ((uint)(3));
w55.XOptions = ((global::Gtk.AttachOptions)(4));
w55.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btnFavoritos = new global::Gtk.Button ();
this.btnFavoritos.CanFocus = true;
this.btnFavoritos.Name = "btnFavoritos";
this.btnFavoritos.UseUnderline = true;
// Container child btnFavoritos.Gtk.Container+ContainerChild
global::Gtk.Alignment w56 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w57 = new global::Gtk.HBox ();
w57.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w58 = new global::Gtk.Image ();
w58.Pixbuf = new global::Gdk.Pixbuf (global::System.IO.Path.Combine (global::System.AppDomain.CurrentDomain.BaseDirectory, "./iconos/{{F02B.ICO"));
w57.Add (w58);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w60 = new global::Gtk.Label ();
w60.LabelProp = global::Mono.Unix.Catalog.GetString ("Favoritos");
w60.UseUnderline = true;
w57.Add (w60);
w56.Add (w57);
this.btnFavoritos.Add (w56);
this.table1.Add (this.btnFavoritos);
global::Gtk.Table.TableChild w64 = ((global::Gtk.Table.TableChild)(this.table1[this.btnFavoritos]));
w64.TopAttach = ((uint)(3));
w64.BottomAttach = ((uint)(4));
w64.LeftAttach = ((uint)(4));
w64.RightAttach = ((uint)(5));
w64.XOptions = ((global::Gtk.AttachOptions)(4));
w64.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btnImprimir = new global::Gtk.Button ();
this.btnImprimir.CanFocus = true;
this.btnImprimir.Name = "btnImprimir";
// Container child btnImprimir.Gtk.Container+ContainerChild
this.vbox3 = new global::Gtk.VBox ();
this.vbox3.Name = "vbox3";
this.vbox3.Spacing = 6;
// Container child vbox3.Gtk.Box+BoxChild
this.image14 = new global::Gtk.Image ();
this.image14.Name = "image14";
this.image14.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-print", global::Gtk.IconSize.Dialog);
this.vbox3.Add (this.image14);
global::Gtk.Box.BoxChild w65 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.image14]));
w65.Position = 0;
// Container child vbox3.Gtk.Box+BoxChild
this.label1 = new global::Gtk.Label ();
this.label1.Name = "label1";
this.label1.LabelProp = global::Mono.Unix.Catalog.GetString (" Imprimir\nPreimprimir");
this.vbox3.Add (this.label1);
global::Gtk.Box.BoxChild w66 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.label1]));
w66.Position = 1;
w66.Expand = false;
w66.Fill = false;
this.btnImprimir.Add (this.vbox3);
this.btnImprimir.Label = null;
this.table1.Add (this.btnImprimir);
global::Gtk.Table.TableChild w68 = ((global::Gtk.Table.TableChild)(this.table1[this.btnImprimir]));
w68.TopAttach = ((uint)(3));
w68.BottomAttach = ((uint)(4));
w68.LeftAttach = ((uint)(5));
w68.RightAttach = ((uint)(6));
w68.XOptions = ((global::Gtk.AttachOptions)(4));
w68.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btnMesas = new global::Gtk.Button ();
this.btnMesas.CanFocus = true;
this.btnMesas.Name = "btnMesas";
this.btnMesas.UseUnderline = true;
// Container child btnMesas.Gtk.Container+ContainerChild
global::Gtk.Alignment w69 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w70 = new global::Gtk.HBox ();
w70.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w71 = new global::Gtk.Image ();
w71.Pixbuf = new global::Gdk.Pixbuf (global::System.IO.Path.Combine (global::System.AppDomain.CurrentDomain.BaseDirectory, "./iconos/TABLE00B.ICO"));
w70.Add (w71);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w73 = new global::Gtk.Label ();
w73.LabelProp = global::Mono.Unix.Catalog.GetString ("Mesas");
w73.UseUnderline = true;
w70.Add (w73);
w69.Add (w70);
this.btnMesas.Add (w69);
this.table1.Add (this.btnMesas);
global::Gtk.Table.TableChild w77 = ((global::Gtk.Table.TableChild)(this.table1[this.btnMesas]));
w77.TopAttach = ((uint)(2));
w77.BottomAttach = ((uint)(3));
w77.LeftAttach = ((uint)(5));
w77.RightAttach = ((uint)(6));
w77.XOptions = ((global::Gtk.AttachOptions)(4));
w77.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btnOpciones = new global::Gtk.Button ();
this.btnOpciones.CanFocus = true;
this.btnOpciones.Name = "btnOpciones";
// Container child btnOpciones.Gtk.Container+ContainerChild
global::Gtk.Alignment w78 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w79 = new global::Gtk.HBox ();
w79.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w80 = new global::Gtk.Image ();
w80.Pixbuf = new global::Gdk.Pixbuf (global::System.IO.Path.Combine (global::System.AppDomain.CurrentDomain.BaseDirectory, "./iconos/configure_toolbars.gif"));
w79.Add (w80);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w82 = new global::Gtk.Label ();
w82.LabelProp = global::Mono.Unix.Catalog.GetString ("Opciones");
w79.Add (w82);
w78.Add (w79);
this.btnOpciones.Add (w78);
this.table1.Add (this.btnOpciones);
global::Gtk.Table.TableChild w86 = ((global::Gtk.Table.TableChild)(this.table1[this.btnOpciones]));
w86.LeftAttach = ((uint)(4));
w86.RightAttach = ((uint)(5));
w86.XOptions = ((global::Gtk.AttachOptions)(4));
w86.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btnSalir = new global::Gtk.Button ();
this.btnSalir.WidthRequest = 85;
this.btnSalir.CanFocus = true;
this.btnSalir.Name = "btnSalir";
this.btnSalir.UseUnderline = true;
// Container child btnSalir.Gtk.Container+ContainerChild
global::Gtk.Alignment w87 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w88 = new global::Gtk.HBox ();
w88.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w89 = new global::Gtk.Image ();
w89.Pixbuf = new global::Gdk.Pixbuf (global::System.IO.Path.Combine (global::System.AppDomain.CurrentDomain.BaseDirectory, "./iconos/exit.gif"));
w88.Add (w89);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w91 = new global::Gtk.Label ();
w88.Add (w91);
w87.Add (w88);
this.btnSalir.Add (w87);
this.table1.Add (this.btnSalir);
global::Gtk.Table.TableChild w95 = ((global::Gtk.Table.TableChild)(this.table1[this.btnSalir]));
w95.LeftAttach = ((uint)(5));
w95.RightAttach = ((uint)(6));
w95.XOptions = ((global::Gtk.AttachOptions)(4));
w95.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btnSecciones = new global::Gtk.Button ();
this.btnSecciones.CanFocus = true;
this.btnSecciones.Name = "btnSecciones";
// Container child btnSecciones.Gtk.Container+ContainerChild
global::Gtk.Alignment w96 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w97 = new global::Gtk.HBox ();
w97.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w98 = new global::Gtk.Image ();
w98.Pixbuf = new global::Gdk.Pixbuf (global::System.IO.Path.Combine (global::System.AppDomain.CurrentDomain.BaseDirectory, "./iconos/ALPH03A.ICO"));
w97.Add (w98);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w100 = new global::Gtk.Label ();
w100.LabelProp = global::Mono.Unix.Catalog.GetString ("Secciones");
w97.Add (w100);
w96.Add (w97);
this.btnSecciones.Add (w96);
this.table1.Add (this.btnSecciones);
global::Gtk.Table.TableChild w104 = ((global::Gtk.Table.TableChild)(this.table1[this.btnSecciones]));
w104.TopAttach = ((uint)(1));
w104.BottomAttach = ((uint)(2));
w104.LeftAttach = ((uint)(4));
w104.RightAttach = ((uint)(5));
w104.XOptions = ((global::Gtk.AttachOptions)(4));
w104.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btnTarifa = new global::Gtk.Button ();
this.btnTarifa.CanFocus = true;
this.btnTarifa.Name = "btnTarifa";
this.btnTarifa.UseUnderline = true;
// Container child btnTarifa.Gtk.Container+ContainerChild
global::Gtk.Alignment w105 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w106 = new global::Gtk.HBox ();
w106.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w107 = new global::Gtk.Image ();
w107.Pixbuf = new global::Gdk.Pixbuf (global::System.IO.Path.Combine (global::System.AppDomain.CurrentDomain.BaseDirectory, "./iconos/euro.png"));
w106.Add (w107);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w109 = new global::Gtk.Label ();
w109.LabelProp = global::Mono.Unix.Catalog.GetString ("Tarifa");
w109.UseUnderline = true;
w106.Add (w109);
w105.Add (w106);
this.btnTarifa.Add (w105);
this.table1.Add (this.btnTarifa);
global::Gtk.Table.TableChild w113 = ((global::Gtk.Table.TableChild)(this.table1[this.btnTarifa]));
w113.TopAttach = ((uint)(1));
w113.BottomAttach = ((uint)(2));
w113.LeftAttach = ((uint)(5));
w113.RightAttach = ((uint)(6));
w113.XOptions = ((global::Gtk.AttachOptions)(4));
w113.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btnTres = new global::Valle.GtkUtilidades.MiBoton ();
this.btnTres.WidthRequest = 85;
this.btnTres.HeightRequest = 50;
this.btnTres.Events = ((global::Gdk.EventMask)(256));
this.btnTres.Name = "btnTres";
this.table1.Add (this.btnTres);
global::Gtk.Table.TableChild w114 = ((global::Gtk.Table.TableChild)(this.table1[this.btnTres]));
w114.LeftAttach = ((uint)(3));
w114.RightAttach = ((uint)(4));
w114.XOptions = ((global::Gtk.AttachOptions)(4));
w114.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.btnUno = new global::Valle.GtkUtilidades.MiBoton ();
this.btnUno.WidthRequest = 85;
this.btnUno.HeightRequest = 50;
this.btnUno.Events = ((global::Gdk.EventMask)(256));
this.btnUno.Name = "btnUno";
this.table1.Add (this.btnUno);
global::Gtk.Table.TableChild w115 = ((global::Gtk.Table.TableChild)(this.table1[this.btnUno]));
w115.LeftAttach = ((uint)(1));
w115.RightAttach = ((uint)(2));
w115.XOptions = ((global::Gtk.AttachOptions)(4));
w115.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.scrollNotas = new global::Valle.GtkUtilidades.ScrollTactil ();
this.scrollNotas.WidthRequest = 95;
this.scrollNotas.HeightRequest = 156;
this.scrollNotas.Events = ((global::Gdk.EventMask)(256));
this.scrollNotas.Name = "scrollNotas";
this.table1.Add (this.scrollNotas);
global::Gtk.Table.TableChild w116 = ((global::Gtk.Table.TableChild)(this.table1[this.scrollNotas]));
w116.BottomAttach = ((uint)(2));
w116.XOptions = ((global::Gtk.AttachOptions)(4));
w116.YOptions = ((global::Gtk.AttachOptions)(4));
this.hbox2.Add (this.table1);
global::Gtk.Box.BoxChild w117 = ((global::Gtk.Box.BoxChild)(this.hbox2[this.table1]));
w117.Position = 1;
w117.Expand = false;
w117.Fill = false;
this.vbox1.Add (this.hbox2);
global::Gtk.Box.BoxChild w118 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.hbox2]));
w118.Position = 1;
w118.Expand = false;
w118.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.hbox3 = new global::Gtk.HBox ();
this.hbox3.Name = "hbox3";
this.hbox3.Spacing = 6;
// Container child hbox3.Gtk.Box+BoxChild
this.vbox7 = new global::Gtk.VBox ();
this.vbox7.Name = "vbox7";
this.vbox7.Spacing = 6;
// Container child vbox7.Gtk.Box+BoxChild
this.btnAbrirCajon = new global::Gtk.Button ();
this.btnAbrirCajon.WidthRequest = 85;
this.btnAbrirCajon.HeightRequest = 85;
this.btnAbrirCajon.CanFocus = true;
this.btnAbrirCajon.Name = "btnAbrirCajon";
// Container child btnAbrirCajon.Gtk.Container+ContainerChild
this.vbox8 = new global::Gtk.VBox ();
this.vbox8.Name = "vbox8";
this.vbox8.Spacing = 6;
// Container child vbox8.Gtk.Box+BoxChild
this.image18 = new global::Gtk.Image ();
this.image18.Name = "image18";
this.image18.Pixbuf = new global::Gdk.Pixbuf (global::System.IO.Path.Combine (global::System.AppDomain.CurrentDomain.BaseDirectory, "./iconos/STARTUP.ICO"));
this.vbox8.Add (this.image18);
global::Gtk.Box.BoxChild w119 = ((global::Gtk.Box.BoxChild)(this.vbox8[this.image18]));
w119.Position = 0;
w119.Expand = false;
w119.Fill = false;
// Container child vbox8.Gtk.Box+BoxChild
this.label4 = new global::Gtk.Label ();
this.label4.Name = "label4";
this.label4.LabelProp = global::Mono.Unix.Catalog.GetString ("Abrir\nCajon");
this.vbox8.Add (this.label4);
global::Gtk.Box.BoxChild w120 = ((global::Gtk.Box.BoxChild)(this.vbox8[this.label4]));
w120.Position = 1;
w120.Expand = false;
w120.Fill = false;
this.btnAbrirCajon.Add (this.vbox8);
this.btnAbrirCajon.Label = null;
this.vbox7.Add (this.btnAbrirCajon);
global::Gtk.Box.BoxChild w122 = ((global::Gtk.Box.BoxChild)(this.vbox7[this.btnAbrirCajon]));
w122.Position = 0;
w122.Expand = false;
w122.Fill = false;
// Container child vbox7.Gtk.Box+BoxChild
this.btnHerrDesglose = new global::Gtk.Button ();
this.btnHerrDesglose.CanFocus = true;
this.btnHerrDesglose.Name = "btnHerrDesglose";
// Container child btnHerrDesglose.Gtk.Container+ContainerChild
this.vbox5 = new global::Gtk.VBox ();
this.vbox5.Name = "vbox5";
this.vbox5.Spacing = 6;
// Container child vbox5.Gtk.Box+BoxChild
this.image17 = new global::Gtk.Image ();
this.image17.Name = "image17";
this.image17.Pixbuf = new global::Gdk.Pixbuf (global::System.IO.Path.Combine (global::System.AppDomain.CurrentDomain.BaseDirectory, "./iconos/Comment.ico"));
this.vbox5.Add (this.image17);
global::Gtk.Box.BoxChild w123 = ((global::Gtk.Box.BoxChild)(this.vbox5[this.image17]));
w123.Position = 0;
w123.Expand = false;
w123.Fill = false;
// Container child vbox5.Gtk.Box+BoxChild
this.label3 = new global::Gtk.Label ();
this.label3.Name = "label3";
this.label3.LabelProp = global::Mono.Unix.Catalog.GetString ("Opciones\nDesglose");
this.vbox5.Add (this.label3);
global::Gtk.Box.BoxChild w124 = ((global::Gtk.Box.BoxChild)(this.vbox5[this.label3]));
w124.Position = 1;
w124.Expand = false;
w124.Fill = false;
this.btnHerrDesglose.Add (this.vbox5);
this.btnHerrDesglose.Label = null;
this.vbox7.Add (this.btnHerrDesglose);
global::Gtk.Box.BoxChild w126 = ((global::Gtk.Box.BoxChild)(this.vbox7[this.btnHerrDesglose]));
w126.Position = 1;
w126.Expand = false;
w126.Fill = false;
// Container child vbox7.Gtk.Box+BoxChild
this.btnVarios = new global::Gtk.Button ();
this.btnVarios.WidthRequest = 0;
this.btnVarios.HeightRequest = 85;
this.btnVarios.CanFocus = true;
this.btnVarios.Name = "btnVarios";
this.btnVarios.UseUnderline = true;
this.btnVarios.Label = global::Mono.Unix.Catalog.GetString ("Varios");
this.vbox7.Add (this.btnVarios);
global::Gtk.Box.BoxChild w127 = ((global::Gtk.Box.BoxChild)(this.vbox7[this.btnVarios]));
w127.Position = 2;
w127.Expand = false;
w127.Fill = false;
// Container child vbox7.Gtk.Box+BoxChild
this.btnVariosConNombre = new global::Gtk.Button ();
this.btnVariosConNombre.WidthRequest = 0;
this.btnVariosConNombre.HeightRequest = 85;
this.btnVariosConNombre.CanFocus = true;
this.btnVariosConNombre.Name = "btnVariosConNombre";
this.btnVariosConNombre.UseUnderline = true;
this.btnVariosConNombre.Label = global::Mono.Unix.Catalog.GetString (" Varios\nCon nombre");
this.vbox7.Add (this.btnVariosConNombre);
global::Gtk.Box.BoxChild w128 = ((global::Gtk.Box.BoxChild)(this.vbox7[this.btnVariosConNombre]));
w128.Position = 3;
w128.Expand = false;
w128.Fill = false;
this.hbox3.Add (this.vbox7);
global::Gtk.Box.BoxChild w129 = ((global::Gtk.Box.BoxChild)(this.hbox3[this.vbox7]));
w129.Position = 0;
w129.Expand = false;
w129.Fill = false;
// Container child hbox3.Gtk.Box+BoxChild
this.pneArticulos = new global::Gtk.Table (((uint)(4)), ((uint)(8)), true);
this.pneArticulos.Name = "pneArticulos";
this.pneArticulos.RowSpacing = ((uint)(6));
this.pneArticulos.ColumnSpacing = ((uint)(6));
this.hbox3.Add (this.pneArticulos);
global::Gtk.Box.BoxChild w130 = ((global::Gtk.Box.BoxChild)(this.hbox3[this.pneArticulos]));
w130.Position = 1;
// Container child hbox3.Gtk.Box+BoxChild
this.vbuttonbox2 = new global::Gtk.VButtonBox ();
this.vbuttonbox2.Name = "vbuttonbox2";
this.vbuttonbox2.Spacing = 3;
this.vbuttonbox2.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(3));
// Container child vbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnBuscador = new global::Gtk.Button ();
this.btnBuscador.WidthRequest = 100;
this.btnBuscador.HeightRequest = 95;
this.btnBuscador.CanFocus = true;
this.btnBuscador.Name = "btnBuscador";
// Container child btnBuscador.Gtk.Container+ContainerChild
this.vbox4 = new global::Gtk.VBox ();
this.vbox4.Name = "vbox4";
this.vbox4.Spacing = 6;
// Container child vbox4.Gtk.Box+BoxChild
this.image16 = new global::Gtk.Image ();
this.image16.Name = "image16";
this.image16.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-find", global::Gtk.IconSize.Dialog);
this.vbox4.Add (this.image16);
global::Gtk.Box.BoxChild w131 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.image16]));
w131.Position = 0;
w131.Fill = false;
// Container child vbox4.Gtk.Box+BoxChild
this.label2 = new global::Gtk.Label ();
this.label2.Name = "label2";
this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("Buscar");
this.vbox4.Add (this.label2);
global::Gtk.Box.BoxChild w132 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.label2]));
w132.Position = 1;
w132.Expand = false;
w132.Fill = false;
this.btnBuscador.Add (this.vbox4);
this.btnBuscador.Label = null;
this.vbuttonbox2.Add (this.btnBuscador);
global::Gtk.ButtonBox.ButtonBoxChild w134 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.vbuttonbox2[this.btnBuscador]));
w134.Expand = false;
w134.Fill = false;
// Container child vbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnPgArriba = new global::Gtk.Button ();
this.btnPgArriba.HeightRequest = 117;
this.btnPgArriba.CanFocus = true;
this.btnPgArriba.Name = "btnPgArriba";
this.btnPgArriba.UseUnderline = true;
// Container child btnPgArriba.Gtk.Container+ContainerChild
global::Gtk.Alignment w135 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w136 = new global::Gtk.HBox ();
w136.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w137 = new global::Gtk.Image ();
w137.Pixbuf = new global::Gdk.Pixbuf (global::System.IO.Path.Combine (global::System.AppDomain.CurrentDomain.BaseDirectory, "./iconos/ARROW12Dx.ICO"));
w136.Add (w137);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w139 = new global::Gtk.Label ();
w136.Add (w139);
w135.Add (w136);
this.btnPgArriba.Add (w135);
this.vbuttonbox2.Add (this.btnPgArriba);
global::Gtk.ButtonBox.ButtonBoxChild w143 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.vbuttonbox2[this.btnPgArriba]));
w143.Position = 1;
w143.Expand = false;
w143.Fill = false;
// Container child vbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnPgAbajo = new global::Gtk.Button ();
this.btnPgAbajo.CanFocus = true;
this.btnPgAbajo.Name = "btnPgAbajo";
this.btnPgAbajo.UseUnderline = true;
// Container child btnPgAbajo.Gtk.Container+ContainerChild
global::Gtk.Alignment w144 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w145 = new global::Gtk.HBox ();
w145.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w146 = new global::Gtk.Image ();
w146.Pixbuf = new global::Gdk.Pixbuf (global::System.IO.Path.Combine (global::System.AppDomain.CurrentDomain.BaseDirectory, "./iconos/ARROW12Ax.ICO"));
w145.Add (w146);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w148 = new global::Gtk.Label ();
w145.Add (w148);
w144.Add (w145);
this.btnPgAbajo.Add (w144);
this.vbuttonbox2.Add (this.btnPgAbajo);
global::Gtk.ButtonBox.ButtonBoxChild w152 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.vbuttonbox2[this.btnPgAbajo]));
w152.Position = 2;
w152.Expand = false;
w152.Fill = false;
this.hbox3.Add (this.vbuttonbox2);
global::Gtk.Box.BoxChild w153 = ((global::Gtk.Box.BoxChild)(this.hbox3[this.vbuttonbox2]));
w153.Position = 2;
w153.Expand = false;
w153.Fill = false;
this.vbox1.Add (this.hbox3);
global::Gtk.Box.BoxChild w154 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.hbox3]));
w154.Position = 2;
w154.Expand = false;
w154.Fill = false;
this.Add (this.vbox1);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
int width=0,height=0;
this.RootWindow.GetSize(out width,out height);
this.DefaultWidth = width;
this.DefaultHeight = height;
this.DeleteEvent += new global::Gtk.DeleteEventHandler (this.OnDeleteEvent);
this.lstNotas.SelectCursorRow += new global::Gtk.SelectCursorRowHandler (this.OnLstNotasSelectCursorRow);
this.btnUno.ClickBoton += new global::Valle.GtkUtilidades.MiBoton.OnEjAccionTecla (this.OnBtnNumerico);
this.btnTres.ClickBoton += new global::Valle.GtkUtilidades.MiBoton.OnEjAccionTecla (this.OnBtnNumerico);
this.btnTarifa.Clicked += new global::System.EventHandler (this.OnBtnTarifaClicked);
this.btnSecciones.Clicked += new global::System.EventHandler (this.OnBtnSeccionesClicked);
this.btnSalir.Clicked += new global::System.EventHandler (this.OnBtnSalirClicked);
this.btnOpciones.Clicked += new global::System.EventHandler (this.OnBtnOpcionesClicked);
this.btnMesas.Clicked += new global::System.EventHandler (this.OnBtnMesasClicked);
this.btnImprimir.Clicked += new global::System.EventHandler (this.OnBtnImprimirClicked);
this.btnFavoritos.Clicked += new global::System.EventHandler (this.OnBtnFavoritosClicked);
this.btnDos.ClickBoton += new global::Valle.GtkUtilidades.MiBoton.OnEjAccionTecla (this.OnBtnNumerico);
this.btnCero.ClickBoton += new global::Valle.GtkUtilidades.MiBoton.OnEjAccionTecla (this.OnBtnNumerico);
this.btnCamareros.Clicked += new global::System.EventHandler (this.OnBtnCamarerosClicked);
this.btnCaja.Clicked += new global::System.EventHandler (this.OnBtnCajaClicked);
this.btnC.ClickBoton += new global::Valle.GtkUtilidades.MiBoton.OnEjAccionTecla (this.OnBtnNumerico);
this.btnBorrNum.Clicked += new global::System.EventHandler (this.OnBtnBorrNumClicked);
this.btnBorrar.Clicked += new global::System.EventHandler (this.OnBtnBorrarClicked);
this.btn9.ClickBoton += new global::Valle.GtkUtilidades.MiBoton.OnEjAccionTecla (this.OnBtnNumerico);
this.btn8.ClickBoton += new global::Valle.GtkUtilidades.MiBoton.OnEjAccionTecla (this.OnBtnNumerico);
this.btn7.ClickBoton += new global::Valle.GtkUtilidades.MiBoton.OnEjAccionTecla (this.OnBtnNumerico);
this.btn6.ClickBoton += new global::Valle.GtkUtilidades.MiBoton.OnEjAccionTecla (this.OnBtnNumerico);
this.btn5.ClickBoton += new global::Valle.GtkUtilidades.MiBoton.OnEjAccionTecla (this.OnBtnNumerico);
this.btn4.ClickBoton += new global::Valle.GtkUtilidades.MiBoton.OnEjAccionTecla (this.OnBtnNumerico);
this.btnAbrirCajon.Clicked += new global::System.EventHandler (this.OnBtnAbrirCajonClicked);
this.btnHerrDesglose.Clicked += new global::System.EventHandler (this.OnBtnHerrDesgloseClicked);
this.btnVarios.Clicked += new global::System.EventHandler (this.OnBtnVariosClicked);
this.btnVariosConNombre.Clicked += new global::System.EventHandler (this.OnBtnVariosConNombreClicked);
this.btnBuscador.Clicked += new global::System.EventHandler (this.OnBtnBuscadorClicked);
this.btnPgArriba.Clicked += new global::System.EventHandler (this.OnBtnPgArribaClicked);
this.btnPgAbajo.Clicked += new global::System.EventHandler (this.OnBtnPgAbajoClicked);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Xml; //Required for Content Type File manipulation
using System.Diagnostics;
using System.IO.Compression;
namespace System.IO.Packaging
{
/// <summary>
/// ZipPackage is a specific implementation for the abstract Package
/// class, corresponding to the Zip file format.
/// This is a part of the Packaging Layer APIs.
/// </summary>
public sealed class ZipPackage : Package
{
#region Public Methods
#region PackagePart Methods
/// <summary>
/// This method is for custom implementation for the underlying file format
/// Adds a new item to the zip archive corresponding to the PackagePart in the package.
/// </summary>
/// <param name="partUri">PartName</param>
/// <param name="contentType">Content type of the part</param>
/// <param name="compressionOption">Compression option for this part</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">If partUri parameter is null</exception>
/// <exception cref="ArgumentNullException">If contentType parameter is null</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
/// <exception cref="ArgumentOutOfRangeException">If CompressionOption enumeration [compressionOption] does not have one of the valid values</exception>
protected override PackagePart CreatePartCore(Uri partUri,
string contentType,
CompressionOption compressionOption)
{
//Validating the PartUri - this method will do the argument checking required for uri.
partUri = PackUriHelper.ValidatePartUri(partUri);
if (contentType == null)
throw new ArgumentNullException(nameof(contentType));
Package.ThrowIfCompressionOptionInvalid(compressionOption);
// Convert Metro CompressionOption to Zip CompressionMethodEnum.
CompressionLevel level;
GetZipCompressionMethodFromOpcCompressionOption(compressionOption,
out level);
// Create new Zip item.
// We need to remove the leading "/" character at the beginning of the part name.
// The partUri object must be a ValidatedPartUri
string zipItemName = ((PackUriHelper.ValidatedPartUri)partUri).PartUriString.Substring(1);
ZipArchiveEntry zipArchiveEntry = _zipArchive.CreateEntry(zipItemName, level);
//Store the content type of this part in the content types stream.
_contentTypeHelper.AddContentType((PackUriHelper.ValidatedPartUri)partUri, new ContentType(contentType), level);
return new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry, _zipStreamManager, (PackUriHelper.ValidatedPartUri)partUri, contentType, compressionOption);
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// Returns the part after reading the actual physical bits. The method
/// returns a null to indicate that the part corresponding to the specified
/// Uri was not found in the container.
/// This method does not throw an exception if a part does not exist.
/// </summary>
/// <param name="partUri"></param>
/// <returns></returns>
protected override PackagePart GetPartCore(Uri partUri)
{
//Currently the design has two aspects which makes it possible to return
//a null from this method -
// 1. All the parts are loaded at Package.Open time and as such, this
// method would not be invoked, unless the user is asking for -
// i. a part that does not exist - we can safely return null
// ii.a part(interleaved/non-interleaved) that was added to the
// underlying package by some other means, and the user wants to
// access the updated part. This is currently not possible as the
// underlying zip i/o layer does not allow for FileShare.ReadWrite.
// 2. Also, its not a straightforward task to determine if a new part was
// added as we need to look for atomic as well as interleaved parts and
// this has to be done in a case sensitive manner. So, effectively
// we will have to go through the entire list of zip items to determine
// if there are any updates.
// If ever the design changes, then this method must be updated accordingly
return null;
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// Deletes the part corresponding to the uri specified. Deleting a part that does not
/// exists is not an error and so we do not throw an exception in that case.
/// </summary>
/// <param name="partUri"></param>
/// <exception cref="ArgumentNullException">If partUri parameter is null</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
protected override void DeletePartCore(Uri partUri)
{
//Validating the PartUri - this method will do the argument checking required for uri.
partUri = PackUriHelper.ValidatePartUri(partUri);
string partZipName = GetZipItemNameFromOpcName(PackUriHelper.GetStringForPartUri(partUri));
ZipArchiveEntry zipArchiveEntry = _zipArchive.GetEntry(partZipName);
if (zipArchiveEntry != null)
{
// Case of an atomic part.
zipArchiveEntry.Delete();
}
//Delete the content type for this part if it was specified as an override
_contentTypeHelper.DeleteContentType((PackUriHelper.ValidatedPartUri)partUri);
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// This is the method that knows how to get the actual parts from the underlying
/// zip archive.
/// </summary>
/// <remarks>
/// <para>
/// Some or all of the parts may be interleaved. The Part object for an interleaved part encapsulates
/// the Uri of the proper part name and the ZipFileInfo of the initial piece.
/// This function does not go through the extra work of checking piece naming validity
/// throughout the package.
/// </para>
/// <para>
/// This means that interleaved parts without an initial piece will be silently ignored.
/// Other naming anomalies get caught at the Stream level when an I/O operation involves
/// an anomalous or missing piece.
/// </para>
/// <para>
/// This function reads directly from the underlying IO layer and is supposed to be called
/// just once in the lifetime of a package (at init time).
/// </para>
/// </remarks>
/// <returns>An array of ZipPackagePart.</returns>
protected override PackagePart[] GetPartsCore()
{
List<PackagePart> parts = new List<PackagePart>(InitialPartListSize);
// The list of files has to be searched linearly (1) to identify the content type
// stream, and (2) to identify parts.
System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipArchiveEntries = _zipArchive.Entries;
// We have already identified the [ContentTypes].xml pieces if any are present during
// the initialization of ZipPackage object
// Record parts and ignored items.
foreach (ZipArchiveEntry zipArchiveEntry in zipArchiveEntries)
{
//Returns false if -
// a. its a content type item
// b. items that have either a leading or trailing slash.
if (IsZipItemValidOpcPartOrPiece(zipArchiveEntry.FullName))
{
Uri partUri = new Uri(GetOpcNameFromZipItemName(zipArchiveEntry.FullName), UriKind.Relative);
PackUriHelper.ValidatedPartUri validatedPartUri;
if (PackUriHelper.TryValidatePartUri(partUri, out validatedPartUri))
{
ContentType contentType = _contentTypeHelper.GetContentType(validatedPartUri);
if (contentType != null)
{
// In case there was some redundancy between pieces and/or the atomic
// part, it will be detected at this point because the part's Uri (which
// is independent of interleaving) will already be in the dictionary.
parts.Add(new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry,
_zipStreamManager, validatedPartUri, contentType.ToString(), GetCompressionOptionFromZipFileInfo(zipArchiveEntry)));
}
}
//If not valid part uri we can completely ignore this zip file item. Even if later someone adds
//a new part, the corresponding zip item can never map to one of these items
}
// If IsZipItemValidOpcPartOrPiece returns false, it implies that either the zip file Item
// starts or ends with a "/" and as such we can completely ignore this zip file item. Even if later
// a new part gets added, its corresponding zip item cannot map to one of these items.
}
return parts.ToArray();
}
#endregion PackagePart Methods
#region Other Methods
/// <summary>
/// This method is for custom implementation corresponding to the underlying zip file format.
/// </summary>
protected override void FlushCore()
{
//Save the content type file to the archive.
_contentTypeHelper.SaveToFile();
}
/// <summary>
/// Closes the underlying ZipArchive object for this container
/// </summary>
/// <param name="disposing">True if called during Dispose, false if called during Finalize</param>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_contentTypeHelper != null)
{
_contentTypeHelper.SaveToFile();
}
if (_zipStreamManager != null)
{
_zipStreamManager.Dispose();
}
if (_zipArchive != null)
{
_zipArchive.Dispose();
}
// _containerStream may be opened given a file name, in which case it should be closed here.
// _containerStream may be passed into the constructor, in which case, it should not be closed here.
if (_shouldCloseContainerStream)
{
_containerStream.Dispose();
}
else
{
}
_containerStream = null;
}
}
finally
{
base.Dispose(disposing);
}
}
#endregion Other Methods
#endregion Public Methods
#region Internal Constructors
/// <summary>
/// Internal constructor that is called by the OpenOnFile static method.
/// </summary>
/// <param name="path">File path to the container.</param>
/// <param name="packageFileMode">Container is opened in the specified mode if possible</param>
/// <param name="packageFileAccess">Container is opened with the specified access if possible</param>
/// <param name="share">Container is opened with the specified share if possible</param>
internal ZipPackage(string path, FileMode packageFileMode, FileAccess packageFileAccess, FileShare share)
: base(packageFileAccess)
{
ZipArchive zipArchive = null;
ContentTypeHelper contentTypeHelper = null;
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
try
{
_containerStream = new FileStream(path, _packageFileMode, _packageFileAccess, share);
_shouldCloseContainerStream = true;
ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update;
if (packageFileAccess == FileAccess.Read)
zipArchiveMode = ZipArchiveMode.Read;
else if (packageFileAccess == FileAccess.Write)
zipArchiveMode = ZipArchiveMode.Create;
else if (packageFileAccess == FileAccess.ReadWrite)
zipArchiveMode = ZipArchiveMode.Update;
zipArchive = new ZipArchive(_containerStream, zipArchiveMode, true, Text.Encoding.UTF8);
_zipStreamManager = new ZipStreamManager(zipArchive, _packageFileMode, _packageFileAccess);
contentTypeHelper = new ContentTypeHelper(zipArchive, _packageFileMode, _packageFileAccess, _zipStreamManager);
}
catch
{
if (zipArchive != null)
{
zipArchive.Dispose();
}
throw;
}
_zipArchive = zipArchive;
_contentTypeHelper = contentTypeHelper;
}
/// <summary>
/// Internal constructor that is called by the Open(Stream) static methods.
/// </summary>
/// <param name="s"></param>
/// <param name="packageFileMode"></param>
/// <param name="packageFileAccess"></param>
internal ZipPackage(Stream s, FileMode packageFileMode, FileAccess packageFileAccess)
: base(packageFileAccess)
{
ZipArchive zipArchive = null;
ContentTypeHelper contentTypeHelper = null;
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
try
{
if (s.CanSeek)
{
switch (packageFileMode)
{
case FileMode.Open:
if (s.Length == 0)
{
throw new FileFormatException(SR.ZipZeroSizeFileIsNotValidArchive);
}
break;
case FileMode.CreateNew:
if (s.Length != 0)
{
throw new IOException(SR.CreateNewOnNonEmptyStream);
}
break;
case FileMode.Create:
if (s.Length != 0)
{
s.SetLength(0); // Discard existing data
}
break;
}
}
ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update;
if (packageFileAccess == FileAccess.Read)
zipArchiveMode = ZipArchiveMode.Read;
else if (packageFileAccess == FileAccess.Write)
zipArchiveMode = ZipArchiveMode.Create;
else if (packageFileAccess == FileAccess.ReadWrite)
zipArchiveMode = ZipArchiveMode.Update;
zipArchive = new ZipArchive(s, zipArchiveMode, true, Text.Encoding.UTF8);
_zipStreamManager = new ZipStreamManager(zipArchive, packageFileMode, packageFileAccess);
contentTypeHelper = new ContentTypeHelper(zipArchive, packageFileMode, packageFileAccess, _zipStreamManager);
}
catch (InvalidDataException)
{
throw new FileFormatException("File contains corrupted data.");
}
catch
{
if (zipArchive != null)
{
zipArchive.Dispose();
}
throw;
}
_containerStream = s;
_shouldCloseContainerStream = false;
_zipArchive = zipArchive;
_contentTypeHelper = contentTypeHelper;
}
#endregion Internal Constructors
#region Internal Methods
// More generic function than GetZipItemNameFromPartName. In particular, it will handle piece names.
internal static string GetZipItemNameFromOpcName(string opcName)
{
Debug.Assert(opcName != null && opcName.Length > 0);
return opcName.Substring(1);
}
// More generic function than GetPartNameFromZipItemName. In particular, it will handle piece names.
internal static string GetOpcNameFromZipItemName(string zipItemName)
{
return string.Concat(ForwardSlashString, zipItemName);
}
// Convert from Metro CompressionOption to ZipFileInfo compression properties.
internal static void GetZipCompressionMethodFromOpcCompressionOption(
CompressionOption compressionOption,
out CompressionLevel compressionLevel)
{
switch (compressionOption)
{
case CompressionOption.NotCompressed:
{
compressionLevel = CompressionLevel.NoCompression;
}
break;
case CompressionOption.Normal:
{
compressionLevel = CompressionLevel.Optimal;
}
break;
case CompressionOption.Maximum:
{
compressionLevel = CompressionLevel.Optimal;
}
break;
case CompressionOption.Fast:
{
compressionLevel = CompressionLevel.Fastest;
}
break;
case CompressionOption.SuperFast:
{
compressionLevel = CompressionLevel.Fastest;
}
break;
// fall-through is not allowed
default:
{
Debug.Assert(false, "Encountered an invalid CompressionOption enum value");
goto case CompressionOption.NotCompressed;
}
}
}
#endregion Internal Methods
internal FileMode PackageFileMode
{
get
{
return _packageFileMode;
}
}
#region Private Methods
//returns a boolean indicating if the underlying zip item is a valid metro part or piece
// This mainly excludes the content type item, as well as entries with leading or trailing
// slashes.
private bool IsZipItemValidOpcPartOrPiece(string zipItemName)
{
Debug.Assert(zipItemName != null, "The parameter zipItemName should not be null");
//check if the zip item is the Content type item -case sensitive comparison
// The following test will filter out an atomic content type file, with name
// "[Content_Types].xml", as well as an interleaved one, with piece names such as
// "[Content_Types].xml/[0].piece" or "[Content_Types].xml/[5].last.piece".
if (zipItemName.StartsWith(ContentTypeHelper.ContentTypeFileName, StringComparison.OrdinalIgnoreCase))
return false;
else
{
//Could be an empty zip folder
//We decided to ignore zip items that contain a "/" as this could be a folder in a zip archive
//Some of the tools support this and some don't. There is no way ensure that the zip item never have
//a leading "/", although this is a requirement we impose on items created through our API
//Therefore we ignore them at the packaging api level.
if (zipItemName.StartsWith(ForwardSlashString, StringComparison.Ordinal))
return false;
//This will ignore the folder entries found in the zip package created by some zip tool
//PartNames ending with a "/" slash is also invalid so we are skipping these entries,
//this will also prevent the PackUriHelper.CreatePartUri from throwing when it encounters a
// partname ending with a "/"
if (zipItemName.EndsWith(ForwardSlashString, StringComparison.Ordinal))
return false;
else
return true;
}
}
// convert from Zip CompressionMethodEnum and DeflateOptionEnum to Metro CompressionOption
private static CompressionOption GetCompressionOptionFromZipFileInfo(ZipArchiveEntry zipFileInfo)
{
// Note: we can't determine compression method / level from the ZipArchiveEntry.
CompressionOption result = CompressionOption.Normal;
return result;
}
#endregion Private Methods
#region Private Members
private const int InitialPartListSize = 50;
private const int InitialPieceNameListSize = 50;
private ZipArchive _zipArchive;
private Stream _containerStream; // stream we are opened in if Open(Stream) was called
private bool _shouldCloseContainerStream;
private ContentTypeHelper _contentTypeHelper; // manages the content types for all the parts in the container
private ZipStreamManager _zipStreamManager; // manages streams for all parts, avoiding opening streams multiple times
private FileAccess _packageFileAccess;
private FileMode _packageFileMode;
private const string ForwardSlashString = "/"; //Required for creating a part name from a zip item name
//IEqualityComparer for extensions
private static readonly ExtensionEqualityComparer s_extensionEqualityComparer = new ExtensionEqualityComparer();
#endregion Private Members
/// <summary>
/// ExtensionComparer
/// The Extensions are stored in the Default Dictionary in their original form,
/// however they are compared in a normalized manner.
/// Equivalence for extensions in the content type stream, should follow
/// the same rules as extensions of partnames. Also, by the time this code is invoked,
/// we have already validated, that the extension is in the correct format as per the
/// part name rules.So we are simplifying the logic here to just convert the extensions
/// to Upper invariant form and then compare them.
/// </summary>
private sealed class ExtensionEqualityComparer : IEqualityComparer<string>
{
bool IEqualityComparer<string>.Equals(string extensionA, string extensionB)
{
Debug.Assert(extensionA != null, "extension should not be null");
Debug.Assert(extensionB != null, "extension should not be null");
//Important Note: any change to this should be made in accordance
//with the rules for comparing/normalizing partnames.
//Refer to PackUriHelper.ValidatedPartUri.GetNormalizedPartUri method.
//Currently normalization just involves upper-casing ASCII and hence the simplification.
return (string.CompareOrdinal(extensionA.ToUpperInvariant(), extensionB.ToUpperInvariant()) == 0);
}
int IEqualityComparer<string>.GetHashCode(string extension)
{
Debug.Assert(extension != null, "extension should not be null");
//Important Note: any change to this should be made in accordance
//with the rules for comparing/normalizing partnames.
//Refer to PackUriHelper.ValidatedPartUri.GetNormalizedPartUri method.
//Currently normalization just involves upper-casing ASCII and hence the simplification.
return extension.ToUpperInvariant().GetHashCode();
}
}
/// <summary>
/// This is a helper class that maintains the Content Types File related to
/// this ZipPackage.
/// </summary>
private class ContentTypeHelper
{
/// <summary>
/// Initialize the object without uploading any information from the package.
/// Complete initialization in read mode also involves calling ParseContentTypesFile
/// to deserialize content type information.
/// </summary>
internal ContentTypeHelper(ZipArchive zipArchive, FileMode packageFileMode, FileAccess packageFileAccess, ZipStreamManager zipStreamManager)
{
_zipArchive = zipArchive; //initialized in the ZipPackage constructor
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
_zipStreamManager = zipStreamManager; //initialized in the ZipPackage constructor
// The extensions are stored in the default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
_defaultDictionary = new Dictionary<string, ContentType>(s_defaultDictionaryInitialSize, s_extensionEqualityComparer);
// Identify the content type file or files before identifying parts and piece sequences.
// This is necessary because the name of the content type stream is not a part name and
// the information it contains is needed to recognize valid parts.
if (_zipArchive.Mode == ZipArchiveMode.Read || _zipArchive.Mode == ZipArchiveMode.Update)
ParseContentTypesFile(_zipArchive.Entries);
//No contents to persist to the disk -
_dirty = false; //by default
//Lazy initialize these members as required
//_overrideDictionary - Overrides should be rare
//_contentTypeFileInfo - We will either find an atomin part, or
//_contentTypeStreamPieces - an interleaved part
//_contentTypeStreamExists - defaults to false - not yet found
}
internal static string ContentTypeFileName
{
get
{
return s_contentTypesFile;
}
}
//Adds the Default entry if it is the first time we come across
//the extension for the partUri, does nothing if the content type
//corresponding to the default entry for the extension matches or
//adds a override corresponding to this part and content type.
//This call is made when a new part is being added to the package.
// This method assumes the partUri is valid.
internal void AddContentType(PackUriHelper.ValidatedPartUri partUri, ContentType contentType,
CompressionLevel compressionLevel)
{
//save the compressionOption and deflateOption that should be used
//to create the content type item later
if (!_contentTypeStreamExists)
{
_cachedCompressionLevel = compressionLevel;
}
// Figure out whether the mapping matches a default entry, can be made into a new
// default entry, or has to be entered as an override entry.
bool foundMatchingDefault = false;
string extension = partUri.PartUriExtension;
// Need to create an override entry?
if (extension.Length == 0
|| (_defaultDictionary.ContainsKey(extension)
&& !(foundMatchingDefault =
_defaultDictionary[extension].AreTypeAndSubTypeEqual(contentType))))
{
AddOverrideElement(partUri, contentType);
}
// Else, either there is already a mapping from extension to contentType,
// or one needs to be created.
else if (!foundMatchingDefault)
{
AddDefaultElement(extension, contentType);
}
}
//Returns the content type for the part, if present, else returns null.
internal ContentType GetContentType(PackUriHelper.ValidatedPartUri partUri)
{
//Step 1: Check if there is an override entry present corresponding to the
//partUri provided. Override takes precedence over the default entries
if (_overrideDictionary != null)
{
if (_overrideDictionary.ContainsKey(partUri))
return _overrideDictionary[partUri];
}
//Step 2: Check if there is a default entry corresponding to the
//extension of the partUri provided.
string extension = partUri.PartUriExtension;
if (_defaultDictionary.ContainsKey(extension))
return _defaultDictionary[extension];
//Step 3: If we did not find an entry in the override and the default
//dictionaries, this is an error condition
return null;
}
//Deletes the override entry corresponding to the partUri, if it exists
internal void DeleteContentType(PackUriHelper.ValidatedPartUri partUri)
{
if (_overrideDictionary != null)
{
if (_overrideDictionary.Remove(partUri))
_dirty = true;
}
}
internal void SaveToFile()
{
if (_dirty)
{
//Lazy init: Initialize when the first part is added.
if (!_contentTypeStreamExists)
{
_contentTypeZipArchiveEntry = _zipArchive.CreateEntry(s_contentTypesFile, _cachedCompressionLevel);
_contentTypeStreamExists = true;
}
// delete and re-create entry for content part. When writing this, the stream will not truncate the content
// if the XML is shorter than the existing content part.
var contentTypefullName = _contentTypeZipArchiveEntry.FullName;
var thisArchive = _contentTypeZipArchiveEntry.Archive;
_zipStreamManager.Close(_contentTypeZipArchiveEntry);
_contentTypeZipArchiveEntry.Delete();
_contentTypeZipArchiveEntry = thisArchive.CreateEntry(contentTypefullName);
using (Stream s = _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite))
{
// use UTF-8 encoding by default
using (XmlWriter writer = XmlWriter.Create(s, new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8 }))
{
writer.WriteStartDocument();
// write root element tag - Types
writer.WriteStartElement(s_typesTagName, s_typesNamespaceUri);
// for each default entry
foreach (string key in _defaultDictionary.Keys)
{
WriteDefaultElement(writer, key, _defaultDictionary[key]);
}
if (_overrideDictionary != null)
{
// for each override entry
foreach (PackUriHelper.ValidatedPartUri key in _overrideDictionary.Keys)
{
WriteOverrideElement(writer, key, _overrideDictionary[key]);
}
}
// end of Types tag
writer.WriteEndElement();
// close the document
writer.WriteEndDocument();
_dirty = false;
}
}
}
}
private void EnsureOverrideDictionary()
{
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using the PartUriComparer
if (_overrideDictionary == null)
_overrideDictionary = new Dictionary<PackUriHelper.ValidatedPartUri, ContentType>(s_overrideDictionaryInitialSize);
}
private void ParseContentTypesFile(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles)
{
// Find the content type stream, allowing for interleaving. Naming collisions
// (as between an atomic and an interleaved part) will result in an exception being thrown.
Stream s = OpenContentTypeStream(zipFiles);
// Allow non-existent content type stream.
if (s == null)
return;
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.IgnoreWhitespace = true;
using (s)
using (XmlReader reader = XmlReader.Create(s, xrs))
{
//This method expects the reader to be in ReadState.Initial.
//It will make the first read call.
PackagingUtilities.PerformInitialReadAndVerifyEncoding(reader);
//Note: After the previous method call the reader should be at the first tag in the markup.
//MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
// look for our root tag and namespace pair - ignore others in case of version changes
// Make sure that the current node read is an Element
if ((reader.NodeType == XmlNodeType.Element)
&& (reader.Depth == 0)
&& (string.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0)
&& (string.CompareOrdinal(reader.Name, s_typesTagName) == 0))
{
//There should be a namespace Attribute present at this level.
//Also any other attribute on the <Types> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) > 0)
{
throw new XmlException(SR.TypesTagHasExtraAttributes, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// start tag encountered
// now parse individual Default and Override tags
while (reader.Read())
{
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
//If MoveToContent() takes us to the end of the content
if (reader.NodeType == XmlNodeType.None)
continue;
// Make sure that the current node read is an element
// Currently we expect the Default and Override Tag at Depth 1
if (reader.NodeType == XmlNodeType.Element
&& reader.Depth == 1
&& (string.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0)
&& (string.CompareOrdinal(reader.Name, s_defaultTagName) == 0))
{
ProcessDefaultTagAttributes(reader);
}
else
if (reader.NodeType == XmlNodeType.Element
&& reader.Depth == 1
&& (string.CompareOrdinal(reader.NamespaceURI, s_typesNamespaceUri) == 0)
&& (string.CompareOrdinal(reader.Name, s_overrideTagName) == 0))
{
ProcessOverrideTagAttributes(reader);
}
else
if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == 0 && string.CompareOrdinal(reader.Name, s_typesTagName) == 0)
continue;
else
{
throw new XmlException(SR.TypesXmlDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
}
}
else
{
throw new XmlException(SR.TypesElementExpected, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
}
}
/// <summary>
/// Find the content type stream, allowing for interleaving. Naming collisions
/// (as between an atomic and an interleaved part) will result in an exception being thrown.
/// Return null if no content type stream has been found.
/// </summary>
/// <remarks>
/// The input array is lexicographically sorted
/// </remarks>
private Stream OpenContentTypeStream(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles)
{
foreach (ZipArchiveEntry zipFileInfo in zipFiles)
{
if (zipFileInfo.Name.ToUpperInvariant().StartsWith(s_contentTypesFileUpperInvariant, StringComparison.Ordinal))
{
// Atomic name.
if (zipFileInfo.Name.Length == ContentTypeFileName.Length)
{
// Record the file info.
_contentTypeZipArchiveEntry = zipFileInfo;
}
}
}
// If an atomic file was found, open a stream on it.
if (_contentTypeZipArchiveEntry != null)
{
_contentTypeStreamExists = true;
return _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite);
}
// No content type stream was found.
return null;
}
// Process the attributes for the Default tag
private void ProcessDefaultTagAttributes(XmlReader reader)
{
//There could be a namespace Attribute present at this level.
//Also any other attribute on the <Default> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 2)
throw new XmlException(SR.DefaultTagDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
// get the required Extension and ContentType attributes
string extensionAttributeValue = reader.GetAttribute(s_extensionAttributeName);
ValidateXmlAttribute(s_extensionAttributeName, extensionAttributeValue, s_defaultTagName, reader);
string contentTypeAttributeValue = reader.GetAttribute(s_contentTypeAttributeName);
ThrowIfXmlAttributeMissing(s_contentTypeAttributeName, contentTypeAttributeValue, s_defaultTagName, reader);
// The extensions are stored in the Default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
PackUriHelper.ValidatedPartUri temporaryUri = PackUriHelper.ValidatePartUri(
new Uri(s_temporaryPartNameWithoutExtension + extensionAttributeValue, UriKind.Relative));
_defaultDictionary.Add(temporaryUri.PartUriExtension, new ContentType(contentTypeAttributeValue));
//Skip the EndElement for Default Tag
if (!reader.IsEmptyElement)
ProcessEndElement(reader, s_defaultTagName);
}
// Process the attributes for the Default tag
private void ProcessOverrideTagAttributes(XmlReader reader)
{
//There could be a namespace Attribute present at this level.
//Also any other attribute on the <Override> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 2)
throw new XmlException(SR.OverrideTagDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
// get the required Extension and ContentType attributes
string partNameAttributeValue = reader.GetAttribute(s_partNameAttributeName);
ValidateXmlAttribute(s_partNameAttributeName, partNameAttributeValue, s_overrideTagName, reader);
string contentTypeAttributeValue = reader.GetAttribute(s_contentTypeAttributeName);
ThrowIfXmlAttributeMissing(s_contentTypeAttributeName, contentTypeAttributeValue, s_overrideTagName, reader);
PackUriHelper.ValidatedPartUri partUri = PackUriHelper.ValidatePartUri(new Uri(partNameAttributeValue, UriKind.Relative));
//Lazy initializing - ensure that the override dictionary has been initialized
EnsureOverrideDictionary();
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using PartUriComparer.
_overrideDictionary.Add(partUri, new ContentType(contentTypeAttributeValue));
//Skip the EndElement for Override Tag
if (!reader.IsEmptyElement)
ProcessEndElement(reader, s_overrideTagName);
}
//If End element is present for Relationship then we process it
private void ProcessEndElement(XmlReader reader, string elementName)
{
Debug.Assert(!reader.IsEmptyElement, "This method should only be called it the Relationship Element is not empty");
reader.Read();
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
reader.MoveToContent();
if (reader.NodeType == XmlNodeType.EndElement && string.CompareOrdinal(elementName, reader.LocalName) == 0)
return;
else
throw new XmlException(SR.Format(SR.ElementIsNotEmptyElement, elementName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
private void AddOverrideElement(PackUriHelper.ValidatedPartUri partUri, ContentType contentType)
{
//Delete any entry corresponding in the Override dictionary
//corresponding to the PartUri for which the contentType is being added.
//This is to compensate for dead override entries in the content types file.
DeleteContentType(partUri);
//Lazy initializing - ensure that the override dictionary has been initialized
EnsureOverrideDictionary();
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using PartUriComparer.
_overrideDictionary.Add(partUri, contentType);
_dirty = true;
}
private void AddDefaultElement(string extension, ContentType contentType)
{
// The extensions are stored in the Default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
_defaultDictionary.Add(extension, contentType);
_dirty = true;
}
private void WriteOverrideElement(XmlWriter xmlWriter, PackUriHelper.ValidatedPartUri partUri, ContentType contentType)
{
xmlWriter.WriteStartElement(s_overrideTagName);
xmlWriter.WriteAttributeString(s_partNameAttributeName,
partUri.PartUriString);
xmlWriter.WriteAttributeString(s_contentTypeAttributeName, contentType.ToString());
xmlWriter.WriteEndElement();
}
private void WriteDefaultElement(XmlWriter xmlWriter, string extension, ContentType contentType)
{
xmlWriter.WriteStartElement(s_defaultTagName);
xmlWriter.WriteAttributeString(s_extensionAttributeName, extension);
xmlWriter.WriteAttributeString(s_contentTypeAttributeName, contentType.ToString());
xmlWriter.WriteEndElement();
}
//Validate if the required XML attribute is present and not an empty string
private void ValidateXmlAttribute(string attributeName, string attributeValue, string tagName, XmlReader reader)
{
ThrowIfXmlAttributeMissing(attributeName, attributeValue, tagName, reader);
//Checking for empty attribute
if (attributeValue == string.Empty)
throw new XmlException(SR.Format(SR.RequiredAttributeEmpty, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
//Validate if the required Content type XML attribute is present
//Content type of a part can be empty
private void ThrowIfXmlAttributeMissing(string attributeName, string attributeValue, string tagName, XmlReader reader)
{
if (attributeValue == null)
throw new XmlException(SR.Format(SR.RequiredAttributeMissing, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
private Dictionary<PackUriHelper.ValidatedPartUri, ContentType> _overrideDictionary;
private Dictionary<string, ContentType> _defaultDictionary;
private ZipArchive _zipArchive;
private FileMode _packageFileMode;
private FileAccess _packageFileAccess;
private ZipStreamManager _zipStreamManager;
private ZipArchiveEntry _contentTypeZipArchiveEntry;
private bool _contentTypeStreamExists;
private bool _dirty;
private CompressionLevel _cachedCompressionLevel;
private static readonly string s_contentTypesFile = "[Content_Types].xml";
private static readonly string s_contentTypesFileUpperInvariant = "[CONTENT_TYPES].XML";
private static readonly int s_defaultDictionaryInitialSize = 16;
private static readonly int s_overrideDictionaryInitialSize = 8;
//Xml tag specific strings for the Content Type file
private static readonly string s_typesNamespaceUri = "http://schemas.openxmlformats.org/package/2006/content-types";
private static readonly string s_typesTagName = "Types";
private static readonly string s_defaultTagName = "Default";
private static readonly string s_extensionAttributeName = "Extension";
private static readonly string s_contentTypeAttributeName = "ContentType";
private static readonly string s_overrideTagName = "Override";
private static readonly string s_partNameAttributeName = "PartName";
private static readonly string s_temporaryPartNameWithoutExtension = "/tempfiles/sample.";
}
}
}
| |
/*
* Copyright 2016 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace FlatBuffers.Test
{
[FlatBuffersTestClass]
public class FlatBufferBuilderTests
{
private FlatBufferBuilder CreateBuffer(bool forceDefaults = true)
{
var fbb = new FlatBufferBuilder(16) {ForceDefaults = forceDefaults};
fbb.StartObject(1);
return fbb;
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddBool_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddBool(0, false, false);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(bool), endOffset-storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddSByte_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddSbyte(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(sbyte), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddByte_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddByte(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(byte), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddShort_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddShort(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(short), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddUShort_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddUshort(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(ushort), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddInt_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddInt(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(int), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddUInt_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddUint(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(uint), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddLong_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddLong(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(long), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddULong_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddUlong(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(ulong), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddFloat_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddFloat(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(float), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WithForceDefaults_WhenAddDouble_AndDefaultValue_OffsetIncreasesBySize()
{
var fbb = CreateBuffer();
var storedOffset = fbb.Offset;
fbb.AddDouble(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(sizeof(double), endOffset - storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddBool_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddBool(0, false, false);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddSByte_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddSbyte(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddByte_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddByte(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddShort_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddShort(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddUShort_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddUshort(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddInt_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddInt(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddUInt_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddUint(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddLong_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddLong(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddULong_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddUlong(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddFloat_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddFloat(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
[FlatBuffersTestMethod]
public void FlatBufferBuilder_WhenAddDouble_AndDefaultValue_OffsetIsUnchanged()
{
var fbb = CreateBuffer(false);
var storedOffset = fbb.Offset;
fbb.AddDouble(0, 0, 0);
var endOffset = fbb.Offset;
Assert.AreEqual(endOffset, storedOffset);
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\GameViewportClient.h:55
namespace UnrealEngine
{
public partial class UGameViewportClient : UScriptViewportClient
{
public UGameViewportClient(IntPtr adress)
: base(adress)
{
}
public UGameViewportClient(UObject Parent = null, string Name = "GameViewportClient")
: base(IntPtr.Zero)
{
NativePointer = E_NewObject_UGameViewportClient(Parent, Name);
NativeManager.AddNativeWrapper(NativePointer, this);
}
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int E_PROP_UGameViewportClient_MaxSplitscreenPlayers_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UGameViewportClient_MaxSplitscreenPlayers_SET(IntPtr Ptr, int Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int E_PROP_UGameViewportClient_ViewModeIndex_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_UGameViewportClient_ViewModeIndex_SET(IntPtr Ptr, int Value);
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_NewObject_UGameViewportClient(IntPtr Parent, string Name);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UGameViewportClient_CalculateDeadZoneForAllSides(IntPtr self, IntPtr lPlayer, IntPtr canvas, float fTopSafeZone, float fBottomSafeZone, float fLeftSafeZone, float fRightSafeZone, bool bUseMaxPercent);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern StringWrapper E_UGameViewportClient_ConsoleCommand(IntPtr self, string command);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int E_UGameViewportClient_ConvertLocalPlayerToGamePlayerIndex(IntPtr self, IntPtr lPlayer);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_DetachViewportClient(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_DrawTitleSafeArea(IntPtr self, IntPtr canvas);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_DrawTransition(IntPtr self, IntPtr canvas);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_DrawTransitionMessage(IntPtr self, IntPtr canvas, string message);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UGameViewportClient_GetDisableSplitscreenOverride(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UGameViewportClient_GetMousePosition(IntPtr self, IntPtr mousePosition);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_GetPixelSizeOfScreen(IntPtr self, float width, float height, IntPtr canvas, int localPlayerIndex);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_GetSubtitleRegion(IntPtr self, IntPtr minPos, IntPtr maxPos);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UGameViewportClient_GetUseMouseForTouch(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_GetViewportSize(IntPtr self, IntPtr viewportSize);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UGameViewportClient_HandleToggleFullscreenCommand(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UGameViewportClient_HasBottomSafeZone(IntPtr self, int localPlayerIndex);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UGameViewportClient_HasLeftSafeZone(IntPtr self, int localPlayerIndex);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UGameViewportClient_HasRightSafeZone(IntPtr self, int localPlayerIndex);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UGameViewportClient_HasTopSafeZone(IntPtr self, int localPlayerIndex);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UGameViewportClient_IsExclusiveFullscreenViewport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UGameViewportClient_IsFullScreenViewport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UGameViewportClient_IsSimulateInEditorViewport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_LayoutPlayers(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_NotifyPlayerAdded(IntPtr self, int playerIndex, IntPtr addedPlayer);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_NotifyPlayerRemoved(IntPtr self, int playerIndex, IntPtr removedPlayer);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_PostRender(IntPtr self, IntPtr canvas);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_RebuildCursors(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_RemoveAllViewportWidgets(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_SetCaptureMouseOnClick(IntPtr self, byte mode);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_SetConsoleTarget(IntPtr self, int playerIndex);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_SetDisableSplitscreenOverride(IntPtr self, bool bDisabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_SetDropDetail(IntPtr self, float deltaSeconds);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_SetHideCursorDuringCapture(IntPtr self, bool inHideCursorDuringCapture);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_SetIgnoreInput(IntPtr self, bool ignore);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_SetLockDuringCapture(IntPtr self, bool inLockDuringCapture);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_SetMouseLockMode(IntPtr self, byte inMouseLockMode);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_SetSuppressTransitionMessage(IntPtr self, bool bSuppress);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern ObjectPointerDescription E_UGameViewportClient_SetupInitialLocalPlayer(IntPtr self, string outError);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_SetUseSoftwareCursorWidgets(IntPtr self, bool bInUseSoftwareCursorWidgets);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_UGameViewportClient_ShouldForceFullscreenViewport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_ShowTitleSafeArea(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_SSSwapControllers(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_Tick(IntPtr self, float deltaTime);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_UpdateActiveSplitscreenType(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_UGameViewportClient_VerifyPathRenderingComponents(IntPtr self);
#endregion
#region Property
public int MaxSplitscreenPlayers
{
get => E_PROP_UGameViewportClient_MaxSplitscreenPlayers_GET(NativePointer);
set => E_PROP_UGameViewportClient_MaxSplitscreenPlayers_SET(NativePointer, value);
}
/// <summary>
/// see enum EViewModeIndex
/// </summary>
public int ViewModeIndex
{
get => E_PROP_UGameViewportClient_ViewModeIndex_GET(NativePointer);
set => E_PROP_UGameViewportClient_ViewModeIndex_SET(NativePointer, value);
}
#endregion
#region ExternMethods
/// <summary>
/// pixel size of the deadzone for all sides (right/left/top/bottom) based on which local player it is
/// </summary>
/// <return>true</return>
public bool CalculateDeadZoneForAllSides(ULocalPlayer lPlayer, UCanvas canvas, float fTopSafeZone, float fBottomSafeZone, float fLeftSafeZone, float fRightSafeZone, bool bUseMaxPercent = false)
=> E_UGameViewportClient_CalculateDeadZoneForAllSides(this, lPlayer, canvas, fTopSafeZone, fBottomSafeZone, fLeftSafeZone, fRightSafeZone, bUseMaxPercent);
/// <summary>
/// Process Console Command
/// </summary>
/// <param name="command">command to process</param>
public virtual string ConsoleCommand(string command)
=> E_UGameViewportClient_ConsoleCommand(this, command);
/// <summary>
/// Convert a LocalPlayer to it's index in the GamePlayer array
/// <para>@returns -1 if the index could not be found. </para>
/// </summary>
/// <param name="lPlayer">Player to get the index of</param>
public int ConvertLocalPlayerToGamePlayerIndex(ULocalPlayer lPlayer)
=> E_UGameViewportClient_ConvertLocalPlayerToGamePlayerIndex(this, lPlayer);
/// <summary>
/// Cleans up all rooted or referenced objects created or managed by the GameViewportClient. This method is called
/// <para>when this GameViewportClient has been disassociated with the game engine (i.e. is no longer the engine's GameViewport). </para>
/// </summary>
public virtual void DetachViewportClient()
=> E_UGameViewportClient_DetachViewportClient(this);
/// <summary>
/// Draw the safe area using the current TitleSafeZone settings.
/// </summary>
/// <param name="canvas">Canvas on which to draw</param>
public virtual void DrawTitleSafeArea(UCanvas canvas)
=> E_UGameViewportClient_DrawTitleSafeArea(this, canvas);
/// <summary>
/// Displays the transition screen.
/// </summary>
/// <param name="canvas">The canvas to use for rendering.</param>
public virtual void DrawTransition(UCanvas canvas)
=> E_UGameViewportClient_DrawTransition(this, canvas);
/// <summary>
/// Print a centered transition message with a drop shadow.
/// </summary>
/// <param name="canvas">The canvas to use for rendering.</param>
/// <param name="message">Transition message</param>
public virtual void DrawTransitionMessage(UCanvas canvas, string message)
=> E_UGameViewportClient_DrawTransitionMessage(this, canvas, message);
/// <summary>
/// Determines whether splitscreen is forced to be turned off
/// </summary>
public bool GetDisableSplitscreenOverride()
=> E_UGameViewportClient_GetDisableSplitscreenOverride(this);
/// <summary>
/// </summary>
/// <return>mouse</return>
public bool GetMousePosition(FVector2D mousePosition)
=> E_UGameViewportClient_GetMousePosition(this, mousePosition);
/// <summary>
/// Get the total pixel size of the screen.
/// <para>This is different from the pixel size of the viewport since we could be in splitscreen </para>
/// </summary>
public void GetPixelSizeOfScreen(float width, float height, UCanvas canvas, int localPlayerIndex)
=> E_UGameViewportClient_GetPixelSizeOfScreen(this, width, height, canvas, localPlayerIndex);
/// <summary>
/// called before rending subtitles to allow the game viewport to determine the size of the subtitle area
/// </summary>
/// <param name="min">top left bounds of subtitle region (0 to 1)</param>
/// <param name="max">bottom right bounds of subtitle region (0 to 1)</param>
public virtual void GetSubtitleRegion(FVector2D minPos, FVector2D maxPos)
=> E_UGameViewportClient_GetSubtitleRegion(this, minPos, maxPos);
protected bool GetUseMouseForTouch()
=> E_UGameViewportClient_GetUseMouseForTouch(this);
/// <summary>
/// Retrieve the size of the main viewport.
/// </summary>
/// <param name="out_ViewportSize">out] will be filled in with the size of the main viewport</param>
public void GetViewportSize(FVector2D viewportSize)
=> E_UGameViewportClient_GetViewportSize(this, viewportSize);
public bool HandleToggleFullscreenCommand()
=> E_UGameViewportClient_HandleToggleFullscreenCommand(this);
/// <summary>
/// Whether the player at LocalPlayerIndex's viewport has a "bottom of viewport" safezone or not.
/// </summary>
public bool HasBottomSafeZone(int localPlayerIndex)
=> E_UGameViewportClient_HasBottomSafeZone(this, localPlayerIndex);
/// <summary>
/// Whether the player at LocalPlayerIndex's viewport has a "left of viewport" safezone or not.
/// </summary>
public bool HasLeftSafeZone(int localPlayerIndex)
=> E_UGameViewportClient_HasLeftSafeZone(this, localPlayerIndex);
/// <summary>
/// Whether the player at LocalPlayerIndex's viewport has a "right of viewport" safezone or not.
/// </summary>
public bool HasRightSafeZone(int localPlayerIndex)
=> E_UGameViewportClient_HasRightSafeZone(this, localPlayerIndex);
/// <summary>
/// Whether the player at LocalPlayerIndex's viewport has a "top of viewport" safezone or not.
/// </summary>
public bool HasTopSafeZone(int localPlayerIndex)
=> E_UGameViewportClient_HasTopSafeZone(this, localPlayerIndex);
/// <summary>
/// </summary>
/// <return>If</return>
public bool IsExclusiveFullscreenViewport()
=> E_UGameViewportClient_IsExclusiveFullscreenViewport(this);
/// <summary>
/// </summary>
/// <return>Whether</return>
public bool IsFullScreenViewport()
=> E_UGameViewportClient_IsFullScreenViewport(this);
/// <summary>
/// </summary>
/// <return>true</return>
public bool IsSimulateInEditorViewport()
=> E_UGameViewportClient_IsSimulateInEditorViewport(this);
/// <summary>
/// Called before rendering to allow the game viewport to allocate subregions to players.
/// </summary>
public virtual void LayoutPlayers()
=> E_UGameViewportClient_LayoutPlayers(this);
/// <summary>
/// Notifies all interactions that a new player has been added to the list of active players.
/// </summary>
/// <param name="playerIndex">the index [into the GamePlayers array] where the player was inserted</param>
/// <param name="addedPlayer">the player that was added</param>
public virtual void NotifyPlayerAdded(int playerIndex, ULocalPlayer addedPlayer)
=> E_UGameViewportClient_NotifyPlayerAdded(this, playerIndex, addedPlayer);
/// <summary>
/// Notifies all interactions that a new player has been added to the list of active players.
/// </summary>
/// <param name="playerIndex">the index [into the GamePlayers array] where the player was located</param>
/// <param name="removedPlayer">the player that was removed</param>
public virtual void NotifyPlayerRemoved(int playerIndex, ULocalPlayer removedPlayer)
=> E_UGameViewportClient_NotifyPlayerRemoved(this, playerIndex, removedPlayer);
/// <summary>
/// Called after rendering the player views and HUDs to render menus, the console, etc.
/// <para>This is the last rendering call in the render loop </para>
/// </summary>
/// <param name="canvas">The canvas to use for rendering.</param>
public virtual void PostRender(UCanvas canvas)
=> E_UGameViewportClient_PostRender(this, canvas);
/// <summary>
/// Recreates cursor widgets from UISettings class.
/// </summary>
public void RebuildCursors()
=> E_UGameViewportClient_RebuildCursors(this);
/// <summary>
/// This function removes all widgets from the viewport overlay
/// </summary>
public void RemoveAllViewportWidgets()
=> E_UGameViewportClient_RemoveAllViewportWidgets(this);
/// <summary>
/// Set the mouse capture behavior when the viewport is clicked
/// </summary>
public void SetCaptureMouseOnClick(EMouseCaptureMode mode)
=> E_UGameViewportClient_SetCaptureMouseOnClick(this, (byte)mode);
public virtual void SetConsoleTarget(int playerIndex)
=> E_UGameViewportClient_SetConsoleTarget(this, playerIndex);
/// <summary>
/// Allows game code to disable splitscreen (useful when in menus)
/// </summary>
public void SetDisableSplitscreenOverride(bool bDisabled)
=> E_UGameViewportClient_SetDisableSplitscreenOverride(this, bDisabled);
/// <summary>
/// Sets bDropDetail and other per-frame detail level flags on the current WorldSettings
/// <para>@see UWorld </para>
/// </summary>
/// <param name="deltaSeconds">amount of time passed since last tick</param>
public virtual void SetDropDetail(float deltaSeconds)
=> E_UGameViewportClient_SetDropDetail(this, deltaSeconds);
/// <summary>
/// Sets whether or not the cursor is hidden when the viewport captures the mouse
/// </summary>
public void SetHideCursorDuringCapture(bool inHideCursorDuringCapture)
=> E_UGameViewportClient_SetHideCursorDuringCapture(this, inHideCursorDuringCapture);
/// <summary>
/// Set whether to ignore input.
/// </summary>
public void SetIgnoreInput(bool ignore)
=> E_UGameViewportClient_SetIgnoreInput(this, ignore);
/// <summary>
/// Sets whether or not the cursor is locked to the viewport when the viewport captures the mouse
/// </summary>
public void SetLockDuringCapture(bool inLockDuringCapture)
=> E_UGameViewportClient_SetLockDuringCapture(this, inLockDuringCapture);
/// <summary>
/// Sets the current mouse cursor lock mode when the viewport is clicked
/// </summary>
public void SetMouseLockMode(EMouseLockMode inMouseLockMode)
=> E_UGameViewportClient_SetMouseLockMode(this, (byte)inMouseLockMode);
/// <summary>
/// Controls suppression of the blue transition text messages
/// </summary>
/// <param name="bSuppress">Pass true to suppress messages</param>
public void SetSuppressTransitionMessage(bool bSuppress)
=> E_UGameViewportClient_SetSuppressTransitionMessage(this, bSuppress);
/// <summary>
/// Initialize the game viewport.
/// </summary>
/// <param name="outError">If an error occurs, returns the error description.</param>
/// <return>False</return>
public virtual ULocalPlayer SetupInitialLocalPlayer(string outError)
=> E_UGameViewportClient_SetupInitialLocalPlayer(this, outError);
/// <summary>
/// Sets whether or not the software cursor widgets are used.
/// <para>If no software cursor widgets are set this setting has no meaningful effect. </para>
/// </summary>
public void SetUseSoftwareCursorWidgets(bool bInUseSoftwareCursorWidgets)
=> E_UGameViewportClient_SetUseSoftwareCursorWidgets(this, bInUseSoftwareCursorWidgets);
/// <summary>
/// Determine whether a fullscreen viewport should be used in cases where there are multiple players.
/// </summary>
/// <return>true</return>
public bool ShouldForceFullscreenViewport()
=> E_UGameViewportClient_ShouldForceFullscreenViewport(this);
public virtual void ShowTitleSafeArea()
=> E_UGameViewportClient_ShowTitleSafeArea(this);
public virtual void SSSwapControllers()
=> E_UGameViewportClient_SSSwapControllers(this);
/// <summary>
/// Called every frame to allow the game viewport to update time based state.
/// </summary>
/// <param name="deltaTime">The time since the last call to Tick.</param>
public virtual void Tick(float deltaTime)
=> E_UGameViewportClient_Tick(this, deltaTime);
/// <summary>
/// Sets the value of ActiveSplitscreenConfiguration based on the desired split-screen layout type, current number of players, and any other
/// <para>factors that might affect the way the screen should be laid out. </para>
/// </summary>
public virtual void UpdateActiveSplitscreenType()
=> E_UGameViewportClient_UpdateActiveSplitscreenType(this);
/// <summary>
/// Make sure all navigation objects have appropriate path rendering components set. Called when EngineShowFlags.Navigation is set.
/// </summary>
public virtual void VerifyPathRenderingComponents()
=> E_UGameViewportClient_VerifyPathRenderingComponents(this);
#endregion
public static implicit operator IntPtr(UGameViewportClient self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator UGameViewportClient(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<UGameViewportClient>(PtrDesc);
}
}
}
| |
/*
* Copyright 2002-2015 Drew Noakes
*
* Modified by Yakov Danilov <yakodani@gmail.com> for Imazen LLC (Ported from Java to C#)
* 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.
*
* More information about this project is available at:
*
* https://drewnoakes.com/code/exif/
* https://github.com/drewnoakes/metadata-extractor
*/
using Com.Drew.Lang;
using Com.Drew.Metadata;
using JetBrains.Annotations;
using Sharpen;
namespace Com.Drew.Metadata.Exif
{
/// <summary>
/// Provides human-readable string representations of tag values stored in a
/// <see cref="GpsDirectory"/>
/// .
/// </summary>
/// <author>Drew Noakes https://drewnoakes.com</author>
public class GpsDescriptor : TagDescriptor<GpsDirectory>
{
public GpsDescriptor([NotNull] GpsDirectory directory)
: base(directory)
{
}
[CanBeNull]
public override string GetDescription(int tagType)
{
switch (tagType)
{
case GpsDirectory.TagVersionId:
{
return GetGpsVersionIdDescription();
}
case GpsDirectory.TagAltitude:
{
return GetGpsAltitudeDescription();
}
case GpsDirectory.TagAltitudeRef:
{
return GetGpsAltitudeRefDescription();
}
case GpsDirectory.TagStatus:
{
return GetGpsStatusDescription();
}
case GpsDirectory.TagMeasureMode:
{
return GetGpsMeasureModeDescription();
}
case GpsDirectory.TagSpeedRef:
{
return GetGpsSpeedRefDescription();
}
case GpsDirectory.TagTrackRef:
case GpsDirectory.TagImgDirectionRef:
case GpsDirectory.TagDestBearingRef:
{
return GetGpsDirectionReferenceDescription(tagType);
}
case GpsDirectory.TagTrack:
case GpsDirectory.TagImgDirection:
case GpsDirectory.TagDestBearing:
{
return GetGpsDirectionDescription(tagType);
}
case GpsDirectory.TagDestDistanceRef:
{
return GetGpsDestinationReferenceDescription();
}
case GpsDirectory.TagTimeStamp:
{
return GetGpsTimeStampDescription();
}
case GpsDirectory.TagLongitude:
{
// three rational numbers -- displayed in HH"MM"SS.ss
return GetGpsLongitudeDescription();
}
case GpsDirectory.TagLatitude:
{
// three rational numbers -- displayed in HH"MM"SS.ss
return GetGpsLatitudeDescription();
}
case GpsDirectory.TagDifferential:
{
return GetGpsDifferentialDescription();
}
default:
{
return base.GetDescription(tagType);
}
}
}
[CanBeNull]
private string GetGpsVersionIdDescription()
{
return GetVersionBytesDescription(GpsDirectory.TagVersionId, 1);
}
[CanBeNull]
public virtual string GetGpsLatitudeDescription()
{
GeoLocation location = _directory.GetGeoLocation();
return location == null ? null : GeoLocation.DecimalToDegreesMinutesSecondsString(location.GetLatitude());
}
[CanBeNull]
public virtual string GetGpsLongitudeDescription()
{
GeoLocation location = _directory.GetGeoLocation();
return location == null ? null : GeoLocation.DecimalToDegreesMinutesSecondsString(location.GetLongitude());
}
[CanBeNull]
public virtual string GetGpsTimeStampDescription()
{
// time in hour, min, sec
Rational[] timeComponents = _directory.GetRationalArray(GpsDirectory.TagTimeStamp);
DecimalFormat df = new DecimalFormat("00.00");
return timeComponents == null ? null : Sharpen.Extensions.StringFormat("%02d:%02d:%s UTC", timeComponents[0].IntValue(), timeComponents[1].IntValue(), df.Format(timeComponents[2].DoubleValue()));
}
[CanBeNull]
public virtual string GetGpsDestinationReferenceDescription()
{
string value = _directory.GetString(GpsDirectory.TagDestDistanceRef);
if (value == null)
{
return null;
}
string distanceRef = Sharpen.Extensions.Trim(value);
if (Sharpen.Runtime.EqualsIgnoreCase("K", distanceRef))
{
return "kilometers";
}
else
{
if (Sharpen.Runtime.EqualsIgnoreCase("M", distanceRef))
{
return "miles";
}
else
{
if (Sharpen.Runtime.EqualsIgnoreCase("N", distanceRef))
{
return "knots";
}
else
{
return "Unknown (" + distanceRef + ")";
}
}
}
}
[CanBeNull]
public virtual string GetGpsDirectionDescription(int tagType)
{
Rational angle = _directory.GetRational(tagType);
// provide a decimal version of rational numbers in the description, to avoid strings like "35334/199 degrees"
string value = angle != null ? new DecimalFormat("0.##").Format(angle.DoubleValue()) : _directory.GetString(tagType);
return value == null || Sharpen.Extensions.Trim(value).Length == 0 ? null : Sharpen.Extensions.Trim(value) + " degrees";
}
[CanBeNull]
public virtual string GetGpsDirectionReferenceDescription(int tagType)
{
string value = _directory.GetString(tagType);
if (value == null)
{
return null;
}
string gpsDistRef = Sharpen.Extensions.Trim(value);
if (Sharpen.Runtime.EqualsIgnoreCase("T", gpsDistRef))
{
return "True direction";
}
else
{
if (Sharpen.Runtime.EqualsIgnoreCase("M", gpsDistRef))
{
return "Magnetic direction";
}
else
{
return "Unknown (" + gpsDistRef + ")";
}
}
}
[CanBeNull]
public virtual string GetGpsSpeedRefDescription()
{
string value = _directory.GetString(GpsDirectory.TagSpeedRef);
if (value == null)
{
return null;
}
string gpsSpeedRef = Sharpen.Extensions.Trim(value);
if (Sharpen.Runtime.EqualsIgnoreCase("K", gpsSpeedRef))
{
return "kph";
}
else
{
if (Sharpen.Runtime.EqualsIgnoreCase("M", gpsSpeedRef))
{
return "mph";
}
else
{
if (Sharpen.Runtime.EqualsIgnoreCase("N", gpsSpeedRef))
{
return "knots";
}
else
{
return "Unknown (" + gpsSpeedRef + ")";
}
}
}
}
[CanBeNull]
public virtual string GetGpsMeasureModeDescription()
{
string value = _directory.GetString(GpsDirectory.TagMeasureMode);
if (value == null)
{
return null;
}
string gpsSpeedMeasureMode = Sharpen.Extensions.Trim(value);
if (Sharpen.Runtime.EqualsIgnoreCase("2", gpsSpeedMeasureMode))
{
return "2-dimensional measurement";
}
else
{
if (Sharpen.Runtime.EqualsIgnoreCase("3", gpsSpeedMeasureMode))
{
return "3-dimensional measurement";
}
else
{
return "Unknown (" + gpsSpeedMeasureMode + ")";
}
}
}
[CanBeNull]
public virtual string GetGpsStatusDescription()
{
string value = _directory.GetString(GpsDirectory.TagStatus);
if (value == null)
{
return null;
}
string gpsStatus = Sharpen.Extensions.Trim(value);
if (Sharpen.Runtime.EqualsIgnoreCase("A", gpsStatus))
{
return "Active (Measurement in progress)";
}
else
{
if (Sharpen.Runtime.EqualsIgnoreCase("V", gpsStatus))
{
return "Void (Measurement Interoperability)";
}
else
{
return "Unknown (" + gpsStatus + ")";
}
}
}
[CanBeNull]
public virtual string GetGpsAltitudeRefDescription()
{
return GetIndexedDescription(GpsDirectory.TagAltitudeRef, "Sea level", "Below sea level");
}
[CanBeNull]
public virtual string GetGpsAltitudeDescription()
{
Rational value = _directory.GetRational(GpsDirectory.TagAltitude);
return value == null ? null : value.IntValue() + " metres";
}
[CanBeNull]
public virtual string GetGpsDifferentialDescription()
{
return GetIndexedDescription(GpsDirectory.TagDifferential, "No Correction", "Differential Corrected");
}
[CanBeNull]
public virtual string GetDegreesMinutesSecondsDescription()
{
GeoLocation location = _directory.GetGeoLocation();
return location == null ? null : location.ToDMSString();
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ResultsDialog.Designer.cs" company="None">
// Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace TQVaultAE.GUI
{
/// <summary>
/// Results dialog form designer class
/// </summary>
internal partial class ResultsDialog
{
/// <summary>
/// Data Grid View for displaying the search results
/// </summary>
private System.Windows.Forms.DataGridView resultsDataGridView;
/// <summary>
/// Data Grid View item column
/// </summary>
private System.Windows.Forms.DataGridViewTextBoxColumn item;
/// <summary>
/// Data Grid View quality column
/// </summary>
private System.Windows.Forms.DataGridViewTextBoxColumn quality;
/// <summary>
/// Data Grid View container name column
/// </summary>
private System.Windows.Forms.DataGridViewTextBoxColumn containerName;
/// <summary>
/// Data Grid View container type column
/// </summary>
private System.Windows.Forms.DataGridViewTextBoxColumn containerType;
/// <summary>
/// Data Grid View level column
/// </summary>
private System.Windows.Forms.DataGridViewTextBoxColumn level;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (this.components != null))
{
this.components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle6 = new System.Windows.Forms.DataGridViewCellStyle();
this.resultsDataGridView = new System.Windows.Forms.DataGridView();
this.item = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.quality = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.containerName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.containerType = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.level = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.resultsDataGridView)).BeginInit();
this.SuspendLayout();
//
// resultsDataGridView
//
this.resultsDataGridView.AllowUserToAddRows = false;
this.resultsDataGridView.AllowUserToDeleteRows = false;
this.resultsDataGridView.AllowUserToResizeRows = false;
this.resultsDataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
this.resultsDataGridView.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders;
this.resultsDataGridView.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(46)))), ((int)(((byte)(31)))), ((int)(((byte)(21)))));
this.resultsDataGridView.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.Color.Black;
dataGridViewCellStyle1.Font = new System.Drawing.Font("Albertus MT Light", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle1.ForeColor = System.Drawing.Color.White;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.Color.Gold;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.Color.White;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.resultsDataGridView.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.resultsDataGridView.ColumnHeadersHeight = 24;
this.resultsDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
this.resultsDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.item,
this.quality,
this.containerName,
this.containerType,
this.level});
this.resultsDataGridView.GridColor = System.Drawing.Color.Khaki;
this.resultsDataGridView.Location = new System.Drawing.Point(8, 28);
this.resultsDataGridView.MultiSelect = false;
this.resultsDataGridView.Name = "resultsDataGridView";
this.resultsDataGridView.ReadOnly = true;
this.resultsDataGridView.RowHeadersVisible = false;
this.resultsDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.resultsDataGridView.ShowCellToolTips = false;
this.resultsDataGridView.ShowEditingIcon = false;
this.resultsDataGridView.Size = new System.Drawing.Size(821, 451);
this.resultsDataGridView.TabIndex = 1;
this.resultsDataGridView.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.ResultsDataGridViewCellDoubleClick);
this.resultsDataGridView.CellMouseEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.ResultsDataGridViewCellMouseEnter);
this.resultsDataGridView.CellMouseLeave += new System.Windows.Forms.DataGridViewCellEventHandler(this.ResultsDataGridViewCellMouseLeave);
this.resultsDataGridView.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.ResultsDataGridViewRowEnter);
this.resultsDataGridView.RowLeave += new System.Windows.Forms.DataGridViewCellEventHandler(this.ResultsDataGridViewRowLeave);
this.resultsDataGridView.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.ResultsDataGridViewKeyPress);
this.resultsDataGridView.MouseLeave += new System.EventHandler(this.ResultsDataGridViewMouseLeave);
//
// item
//
this.item.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
dataGridViewCellStyle2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(46)))), ((int)(((byte)(31)))), ((int)(((byte)(21)))));
dataGridViewCellStyle2.Font = new System.Drawing.Font("Albertus MT Light", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle2.ForeColor = System.Drawing.Color.White;
dataGridViewCellStyle2.SelectionBackColor = System.Drawing.Color.Gold;
dataGridViewCellStyle2.SelectionForeColor = System.Drawing.Color.Black;
this.item.DefaultCellStyle = dataGridViewCellStyle2;
this.item.HeaderText = "Item";
this.item.Name = "item";
this.item.ReadOnly = true;
this.item.Width = 54;
//
// quality
//
this.quality.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
dataGridViewCellStyle3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(46)))), ((int)(((byte)(31)))), ((int)(((byte)(21)))));
dataGridViewCellStyle3.Font = new System.Drawing.Font("Albertus MT Light", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle3.ForeColor = System.Drawing.Color.White;
dataGridViewCellStyle3.SelectionBackColor = System.Drawing.Color.Gold;
dataGridViewCellStyle3.SelectionForeColor = System.Drawing.Color.Black;
this.quality.DefaultCellStyle = dataGridViewCellStyle3;
this.quality.HeaderText = "Quality";
this.quality.Name = "quality";
this.quality.ReadOnly = true;
this.quality.Width = 73;
//
// containerName
//
this.containerName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
dataGridViewCellStyle4.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(46)))), ((int)(((byte)(31)))), ((int)(((byte)(21)))));
dataGridViewCellStyle4.Font = new System.Drawing.Font("Albertus MT Light", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle4.ForeColor = System.Drawing.Color.White;
dataGridViewCellStyle4.SelectionBackColor = System.Drawing.Color.Gold;
dataGridViewCellStyle4.SelectionForeColor = System.Drawing.Color.Black;
this.containerName.DefaultCellStyle = dataGridViewCellStyle4;
this.containerName.HeaderText = "Container";
this.containerName.Name = "containerName";
this.containerName.ReadOnly = true;
this.containerName.Width = 84;
//
// containerType
//
this.containerType.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
dataGridViewCellStyle5.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(46)))), ((int)(((byte)(31)))), ((int)(((byte)(21)))));
dataGridViewCellStyle5.Font = new System.Drawing.Font("Albertus MT Light", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle5.ForeColor = System.Drawing.Color.White;
dataGridViewCellStyle5.SelectionBackColor = System.Drawing.Color.Gold;
dataGridViewCellStyle5.SelectionForeColor = System.Drawing.Color.Black;
this.containerType.DefaultCellStyle = dataGridViewCellStyle5;
this.containerType.HeaderText = "ContainerType";
this.containerType.Name = "containerType";
this.containerType.ReadOnly = true;
this.containerType.Width = 111;
//
// level
//
this.level.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
dataGridViewCellStyle6.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(46)))), ((int)(((byte)(31)))), ((int)(((byte)(21)))));
dataGridViewCellStyle6.Font = new System.Drawing.Font("Albertus MT Light", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle6.ForeColor = System.Drawing.Color.White;
dataGridViewCellStyle6.SelectionBackColor = System.Drawing.Color.Gold;
dataGridViewCellStyle6.SelectionForeColor = System.Drawing.Color.Black;
this.level.DefaultCellStyle = dataGridViewCellStyle6;
this.level.HeaderText = "Level";
this.level.Name = "level";
this.level.ReadOnly = true;
this.level.Width = 45;
//
// ResultsDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(46)))), ((int)(((byte)(31)))), ((int)(((byte)(21)))));
this.ClientSize = new System.Drawing.Size(837, 497);
this.Controls.Add(this.resultsDataGridView);
this.DrawCustomBorder = true;
this.Font = new System.Drawing.Font("Albertus MT Light", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ForeColor = System.Drawing.Color.White;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Margin = new System.Windows.Forms.Padding(4);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ResultsDialog";
this.OriginalFormSize = new System.Drawing.Size(837, 497);
this.Padding = new System.Windows.Forms.Padding(8, 28, 8, 18);
this.ResizeCustomAllowed = true;
this.ShowIcon = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Results";
this.Shown += new System.EventHandler(this.ResultsDialogShown);
this.Resize += new System.EventHandler(this.ResultsDialog_Resize);
this.Controls.SetChildIndex(this.resultsDataGridView, 0);
((System.ComponentModel.ISupportInitialize)(this.resultsDataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
}
}
| |
using Codex.ObjectModel;
using Codex.View;
using Codex.Web.Mvc.Rendering;
#if __WASM__
using Windows.Storage;
#endif
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace Codex.Uno.Shared
{
using static ViewBuilder;
using static MainController;
public class RightPaneView
{
public static FrameworkElement Create(RightPaneViewModel viewModel)
{
return new Grid()
.WithChildren(
Row(Star, CreateViewPane(viewModel)),
//Row(1, viewModel.SourceFile == null ? new Border() { Background = B(Colors.OrangeRed) } : CreateEditor(viewModel.SourceFile)),
Row(Auto, CreateDetailsPane(viewModel.SourceFile))
);
}
private static FrameworkElement CreateViewPane(RightPaneViewModel viewModel)
{
var content = viewModel.SourceFile == null ? "" : new SourceFileRenderer(viewModel.SourceFile).RenderHtml();
var control = new WasmHtmlContentControl
{
HtmlContent = content
};
control.VerticalAlignment = VerticalAlignment.Stretch;
if (viewModel.SourceFile == null)
{
#if __WASM__
loadOverview();
async void loadOverview()
{
var overviewPath = Path.GetFullPath("overview");
var file = await StorageFile.GetFileFromApplicationUriAsync(new System.Uri("ms-appx:///Assets/Overview.html"));
var newFile = await file.CopyAsync(Windows.Storage.ApplicationData.Current.LocalFolder, file.Name, NameCollisionOption.ReplaceExisting);
using var stream = await newFile.OpenStreamForReadAsync();
using var reader = new StreamReader(stream);
var text = reader.ReadToEnd();
control.HtmlContent = text;
}
#else
return new TextBlock()
{
Text = content
};
#endif
}
return control;
}
private static FrameworkElement CreateDetailsPane(IBoundSourceFile sourceFile)
{
var info = sourceFile?.SourceFile?.Info;
var random = new Random();
var border = new Border()
{
Background = B(random.Next()),
Padding = new Thickness(8)
};
if (info != null)
{
var encodedFilePath = HttpUtility.UrlEncode(info.ProjectRelativePath);
var details = new Grid()
.WithChildren
(
Column(Auto),
Column(Star),
Row(Auto),
Row(Auto),
Row(0, Column(0, Apply(DetailsTextBlockStyle, Text(
"File: ",
Link(info.ProjectRelativePath, $"/?leftProject={info.ProjectId}&file={encodedFilePath}"),
"(", Link("Download", $"/download/{info.ProjectId}/?filePath={encodedFilePath}"), ")")))),
Row(1, Column(0, Apply(DetailsTextBlockStyle, Text(
"Project: ", Link(info.ProjectId, $"/?leftProject={info.ProjectId}"))))),
Row(0, Column(1, Apply(RightDetailsTextBlockStyle, Text(Link(info.RepoRelativePath, info.WebAddress))))),
Row(1, Column(1, Tip(
Apply(RightDetailsTextBlockStyle, Text("Indexed on: ", sourceFile.Commit?.DateUploaded.ToLocalTime().ToString() ?? "Unknown")),
$"Index: {sourceFile.Commit?.CommitId}")))
);
border.Child = details;
}
return border;
}
private static Action<TextBlock> RightDetailsTextBlockStyle = t =>
{
t.HorizontalAlignment = HorizontalAlignment.Right;
DetailsTextBlockStyle(t);
};
private static Action<TextBlock> DetailsTextBlockStyle = t =>
{
t.Margin = new Thickness(1);
t.FontFamily = SegoeUI;
t.Foreground = B(Colors.Gray);
t.Height = 21;
t.FontSize = 16;
};
private static FrameworkElement CreateEditor(IBoundSourceFile sourceFile)
{
//var editor = new CodeEditor()
//{
// Text = sourceFile?.SourceFile.Content ?? "EMPTY",
//};
//async void hookLanguage()
//{
// await editor.Languages.RegisterAsync(new ILanguageExtensionPoint()
// {
// Id = "Codex"
// });
// await editor.Languages.RegisterColorProviderAsync("Codex", new CodexEditorLanguage(sourceFile));
// Console.WriteLine("Setting language");
// editor.CodeLanguage = "Codex";
// Console.WriteLine("Set language");
//}
//editor.Loaded += (s, e) =>
//{
// if (editor.IsEditorLoaded)
// {
// hookLanguage();
// }
//};
var editor = new ContentControl()
{
Content = "NO EDITOR"
};
return editor;
}
private class CodexEditorLanguage
{
private static IDictionary<string, Color> ClassificationMap = new Dictionary<string, Color>
{
{ "xml - delimiter", Constants.ClassificationXmlDelimiter },
{ "xml - name", Constants.ClassificationXmlName },
{ "xml - attribute name", Constants.ClassificationXmlAttributeName },
{ "xml - attribute quotes", Constants.ClassificationXmlAttributeQuotes },
{ "xml - attribute value", Constants.ClassificationXmlAttributeValue },
{ "xml - entity reference", Constants.ClassificationXmlEntityReference },
{ "xml - cdata section", Constants.ClassificationXmlCDataSection },
{ "xml - processing instruction", Constants.ClassificationXmlProcessingInstruction },
{ "xml - comment", Constants.ClassificationComment },
{ "keyword", Constants.ClassificationKeyword },
{ "keyword - control", Constants.ClassificationKeyword },
{ "identifier", Constants.ClassificationIdentifier },
{ "class name", Constants.ClassificationTypeName },
{ "struct name", Constants.ClassificationTypeName },
{ "interface name", Constants.ClassificationTypeName },
{ "enum name", Constants.ClassificationTypeName },
{ "delegate name", Constants.ClassificationTypeName },
{ "module name", Constants.ClassificationTypeName },
{ "type parameter name", Constants.ClassificationTypeName },
{ "preprocessor keyword", Constants.ClassificationKeyword },
{ "xml doc comment - delimiter", Constants.ClassificationComment },
{ "xml doc comment - name", Constants.ClassificationComment },
{ "xml doc comment - text", Constants.ClassificationComment },
{ "xml doc comment - comment", Constants.ClassificationComment },
{ "xml doc comment - entity reference", Constants.ClassificationComment },
{ "xml doc comment - attribute name", Constants.ClassificationComment },
{ "xml doc comment - attribute quotes", Constants.ClassificationComment },
{ "xml doc comment - attribute value", Constants.ClassificationComment },
{ "xml doc comment - cdata section", Constants.ClassificationComment },
{ "xml literal - delimiter", Constants.ClassificationXmlLiteralDelimiter },
{ "xml literal - name", Constants.ClassificationXmlLiteralName },
{ "xml literal - attribute name", Constants.ClassificationXmlLiteralAttributeName },
{ "xml literal - attribute quotes", Constants.ClassificationXmlLiteralAttributeQuotes },
{ "xml literal - attribute value", Constants.ClassificationXmlLiteralAttributeValue },
{ "xml literal - entity reference", Constants.ClassificationXmlLiteralEntityReference },
{ "xml literal - cdata section", Constants.ClassificationXmlLiteralCDataSection },
{ "xml literal - processing instruction", Constants.ClassificationXmlLiteralProcessingInstruction },
{ "xml literal - embedded expression", Constants.ClassificationXmlLiteralEmbeddedExpression },
{ "xml literal - comment", Constants.ClassificationComment },
{ "comment", Constants.ClassificationComment },
{ "string", Constants.ClassificationLiteral },
{ "string - verbatim", Constants.ClassificationLiteral },
{ "excluded code", Constants.ClassificationExcludedCode },
};
public class Constants
{
public static readonly Color ClassificationIdentifier = C(0xffff00);
public static readonly Color ClassificationKeyword = Colors.Blue;
public static readonly Color ClassificationTypeName = C(0x2b91af);
public static readonly Color ClassificationComment = C(0x008000);
public static readonly Color ClassificationLiteral = C(0xa31515);
public static readonly Color ClassificationXmlDelimiter = Colors.Blue;
public static readonly Color ClassificationXmlName = C(0xa31515);
public static readonly Color ClassificationXmlAttributeName = Colors.Red;
public static readonly Color ClassificationXmlAttributeValue = Colors.Blue;
public static readonly Color ClassificationXmlAttributeQuotes = default;
public static readonly Color ClassificationXmlEntityReference = Colors.Red;
public static readonly Color ClassificationXmlCDataSection = C(0x808080);
public static readonly Color ClassificationXmlProcessingInstruction = C(0x808080);
public static readonly Color ClassificationXmlLiteralDelimiter = C(0x6464b9);
public static readonly Color ClassificationXmlLiteralName = C(0x844646);
public static readonly Color ClassificationXmlLiteralAttributeName = C(0xb96464);
public static readonly Color ClassificationXmlLiteralAttributeValue = C(0x6464b9);
public static readonly Color ClassificationXmlLiteralAttributeQuotes = C(0x555555);
public static readonly Color ClassificationXmlLiteralEntityReference = C(0xb96464);
public static readonly Color ClassificationXmlLiteralCDataSection = C(0xc0c0c0);
public static readonly Color ClassificationXmlLiteralEmbeddedExpression = C(0xb96464);
public static readonly Color ClassificationXmlLiteralProcessingInstruction = C(0xc0c0c0);
public static readonly Color ClassificationExcludedCode = C(0x808080);
public static readonly Color ClassificationPunctuation = default;
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.IO;
using System.Globalization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Xml;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System.Text;
namespace Newtonsoft.Json
{
/// <summary>
/// Provides methods for converting between common language runtime types and JSON types.
/// </summary>
/// <example>
/// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\SerializationTests.cs" region="SerializeObject" title="Serializing and Deserializing JSON with JsonConvert" />
/// </example>
public static class JsonConvert
{
/// <summary>
/// Gets or sets a function that creates default <see cref="JsonSerializerSettings"/>.
/// Default settings are automatically used by serialization methods on <see cref="JsonConvert"/>,
/// and <see cref="JToken.ToObject{T}()"/> and <see cref="JToken.FromObject(object)"/> on <see cref="JToken"/>.
/// To serialize without using any default settings create a <see cref="JsonSerializer"/> with
/// <see cref="JsonSerializer.Create()"/>.
/// </summary>
public static Func<JsonSerializerSettings> DefaultSettings { get; set; }
/// <summary>
/// Represents JavaScript's boolean value true as a string. This field is read-only.
/// </summary>
public static readonly string True = "true";
/// <summary>
/// Represents JavaScript's boolean value false as a string. This field is read-only.
/// </summary>
public static readonly string False = "false";
/// <summary>
/// Represents JavaScript's null as a string. This field is read-only.
/// </summary>
public static readonly string Null = "null";
/// <summary>
/// Represents JavaScript's undefined as a string. This field is read-only.
/// </summary>
public static readonly string Undefined = "undefined";
/// <summary>
/// Represents JavaScript's positive infinity as a string. This field is read-only.
/// </summary>
public static readonly string PositiveInfinity = "Infinity";
/// <summary>
/// Represents JavaScript's negative infinity as a string. This field is read-only.
/// </summary>
public static readonly string NegativeInfinity = "-Infinity";
/// <summary>
/// Represents JavaScript's NaN as a string. This field is read-only.
/// </summary>
public static readonly string NaN = "NaN";
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value)
{
return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
}
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="format">The format the date will be converted to.</param>
/// <param name="timeZoneHandling">The time zone handling when the date is converted to a string.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
{
DateTime updatedDateTime = DateTimeUtils.EnsureDateTime(value, timeZoneHandling);
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
writer.Write('"');
DateTimeUtils.WriteDateTimeString(writer, updatedDateTime, format, null, CultureInfo.InvariantCulture);
writer.Write('"');
return writer.ToString();
}
}
/// <summary>
/// Converts the <see cref="Boolean"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Boolean"/>.</returns>
public static string ToString(bool value)
{
return (value) ? True : False;
}
/// <summary>
/// Converts the <see cref="Char"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Char"/>.</returns>
public static string ToString(char value)
{
return ToString(char.ToString(value));
}
/// <summary>
/// Converts the <see cref="Enum"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Enum"/>.</returns>
public static string ToString(Enum value)
{
return value.ToString("D");
}
/// <summary>
/// Converts the <see cref="Int32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int32"/>.</returns>
public static string ToString(int value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int16"/>.</returns>
public static string ToString(short value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt16"/>.</returns>
public static string ToString(ushort value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt32"/>.</returns>
public static string ToString(uint value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int64"/>.</returns>
public static string ToString(long value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt64"/>.</returns>
public static string ToString(ulong value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Single"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Single"/>.</returns>
public static string ToString(float value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
}
private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
if (floatFormatHandling == FloatFormatHandling.Symbol || !(double.IsInfinity(value) || double.IsNaN(value)))
return text;
if (floatFormatHandling == FloatFormatHandling.DefaultValue)
return (!nullable) ? "0.0" : Null;
return quoteChar + text + quoteChar;
}
/// <summary>
/// Converts the <see cref="Double"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Double"/>.</returns>
public static string ToString(double value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
{
return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
}
private static string EnsureDecimalPlace(double value, string text)
{
if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1)
return text;
return text + ".0";
}
private static string EnsureDecimalPlace(string text)
{
if (text.IndexOf('.') != -1)
return text;
return text + ".0";
}
/// <summary>
/// Converts the <see cref="Byte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Byte"/>.</returns>
public static string ToString(byte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="SByte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
public static string ToString(sbyte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Decimal"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
public static string ToString(decimal value)
{
return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
}
/// <summary>
/// Converts the <see cref="Guid"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Guid"/>.</returns>
public static string ToString(Guid value)
{
return ToString(value, '"');
}
internal static string ToString(Guid value, char quoteChar)
{
string text;
string qc;
text = value.ToString("D", CultureInfo.InvariantCulture);
qc = quoteChar.ToString(CultureInfo.InvariantCulture);
return qc + text + qc;
}
/// <summary>
/// Converts the <see cref="TimeSpan"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="TimeSpan"/>.</returns>
public static string ToString(TimeSpan value)
{
return ToString(value, '"');
}
internal static string ToString(TimeSpan value, char quoteChar)
{
return ToString(value.ToString(), quoteChar);
}
/// <summary>
/// Converts the <see cref="Uri"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Uri"/>.</returns>
public static string ToString(Uri value)
{
if (value == null)
return Null;
return ToString(value, '"');
}
internal static string ToString(Uri value, char quoteChar)
{
return ToString(value.OriginalString, quoteChar);
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value)
{
return ToString(value, '"');
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="delimiter">The string delimiter character.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value, char delimiter)
{
return ToString(value, delimiter, StringEscapeHandling.Default);
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="delimiter">The string delimiter character.</param>
/// <param name="stringEscapeHandling">The string escape handling.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value, char delimiter, StringEscapeHandling stringEscapeHandling)
{
if (delimiter != '"' && delimiter != '\'')
throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter");
return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, true, stringEscapeHandling);
}
/// <summary>
/// Converts the <see cref="Object"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Object"/>.</returns>
public static string ToString(object value)
{
if (value == null)
return Null;
PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(value.GetType());
switch (typeCode)
{
case PrimitiveTypeCode.String:
return ToString((string)value);
case PrimitiveTypeCode.Char:
return ToString((char)value);
case PrimitiveTypeCode.Boolean:
return ToString((bool)value);
case PrimitiveTypeCode.SByte:
return ToString((sbyte)value);
case PrimitiveTypeCode.Int16:
return ToString((short)value);
case PrimitiveTypeCode.UInt16:
return ToString((ushort)value);
case PrimitiveTypeCode.Int32:
return ToString((int)value);
case PrimitiveTypeCode.Byte:
return ToString((byte)value);
case PrimitiveTypeCode.UInt32:
return ToString((uint)value);
case PrimitiveTypeCode.Int64:
return ToString((long)value);
case PrimitiveTypeCode.UInt64:
return ToString((ulong)value);
case PrimitiveTypeCode.Single:
return ToString((float)value);
case PrimitiveTypeCode.Double:
return ToString((double)value);
case PrimitiveTypeCode.DateTime:
return ToString((DateTime)value);
case PrimitiveTypeCode.Decimal:
return ToString((decimal)value);
case PrimitiveTypeCode.Guid:
return ToString((Guid)value);
case PrimitiveTypeCode.Uri:
return ToString((Uri)value);
case PrimitiveTypeCode.TimeSpan:
return ToString((TimeSpan)value);
}
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
#region Serialize
/// <summary>
/// Serializes the specified object to a JSON string.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value)
{
return SerializeObject(value, null, (JsonSerializerSettings)null);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Formatting formatting)
{
return SerializeObject(value, formatting, (JsonSerializerSettings)null);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="converters">A collection converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return SerializeObject(value, null, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting and a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="converters">A collection converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return SerializeObject(value, null, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, JsonSerializerSettings settings)
{
return SerializeObject(value, null, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a type, formatting and <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be used.</param>
/// <param name="type">
/// The type of the value being serialized.
/// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match.
/// Specifing the type is optional.
/// </param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Type type, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
return SerializeObjectInternal(value, type, jsonSerializer);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting and <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings)
{
return SerializeObject(value, null, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a type, formatting and <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be used.</param>
/// <param name="type">
/// The type of the value being serialized.
/// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match.
/// Specifing the type is optional.
/// </param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Type type, Formatting formatting, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
jsonSerializer.Formatting = formatting;
return SerializeObjectInternal(value, type, jsonSerializer);
}
private static string SerializeObjectInternal(object value, Type type, JsonSerializer jsonSerializer)
{
StringBuilder sb = new StringBuilder(256);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = jsonSerializer.Formatting;
jsonSerializer.Serialize(jsonWriter, value, type);
}
return sw.ToString();
}
#endregion
#region Deserialize
/// <summary>
/// Deserializes the JSON to a .NET object.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value)
{
return DeserializeObject(value, null, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to a .NET object using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, JsonSerializerSettings settings)
{
return DeserializeObject(value, null, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type)
{
return DeserializeObject(value, type, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value)
{
return DeserializeObject<T>(value, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type.
/// </summary>
/// <typeparam name="T">
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be infered from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
{
return DeserializeObject<T>(value);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <typeparam name="T">
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be infered from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be used.
/// </param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings)
{
return DeserializeObject<T>(value, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value, params JsonConverter[] converters)
{
return (T)DeserializeObject(value, typeof(T), converters);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The object to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value, JsonSerializerSettings settings)
{
return (T)DeserializeObject(value, typeof(T), settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return DeserializeObject(value, type, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize to.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
{
ValidationUtils.ArgumentNotNull(value, "value");
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
// by default DeserializeObject should check for additional content
if (!jsonSerializer.IsCheckAdditionalContentSet())
jsonSerializer.CheckAdditionalContent = true;
using (var reader = new JsonTextReader(new StringReader(value)))
{
return jsonSerializer.Deserialize(reader, type);
}
}
#endregion
/// <summary>
/// Populates the object with values from the JSON string.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public static void PopulateObject(string value, object target)
{
PopulateObject(value, target, null);
}
/// <summary>
/// Populates the object with values from the JSON string using <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be used.
/// </param>
public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
using (JsonReader jsonReader = new JsonTextReader(new StringReader(value)))
{
jsonSerializer.Populate(jsonReader, target);
if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment)
throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
}
}
}
}
| |
#region Copyright and License
// Copyright 2010..2015 Alexander Reinert
//
// This file is part of the ARSoft.Tools.Net - C# DNS client/server and SPF Library (http://arsofttoolsnet.codeplex.com/)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using MailTester.ARSoft.Tools.Net.Dns.DnsRecord;
using MailTester.ARSoft.Tools.Net.Dns.DynamicUpdate;
using MailTester.ARSoft.Tools.Net.Dns.EDns;
using MailTester.ARSoft.Tools.Net.Dns.TSig;
namespace MailTester.ARSoft.Tools.Net.Dns
{
/// <summary>
/// Base class for a dns answer
/// </summary>
public abstract class DnsMessageBase
{
protected ushort Flags;
protected internal List<DnsQuestion> Questions = new List<DnsQuestion>();
protected internal List<DnsRecordBase> AnswerRecords = new List<DnsRecordBase>();
protected internal List<DnsRecordBase> AuthorityRecords = new List<DnsRecordBase>();
private List<DnsRecordBase> _additionalRecords = new List<DnsRecordBase>();
/// <summary>
/// Gets or sets the entries in the additional records section
/// </summary>
public List<DnsRecordBase> AdditionalRecords
{
get { return _additionalRecords; }
set { _additionalRecords = (value ?? new List<DnsRecordBase>()); }
}
internal abstract bool IsTcpUsingRequested { get; }
internal abstract bool IsTcpResendingRequested { get; }
internal abstract bool IsTcpNextMessageWaiting(bool isSubsequentResponseMessage);
#region Header
/// <summary>
/// Gets or sets the transaction identifier (ID) of the message
/// </summary>
public ushort TransactionID { get; set; }
/// <summary>
/// Gets or sets the query (QR) flag
/// </summary>
public bool IsQuery
{
get { return (Flags & 0x8000) == 0; }
set
{
if (value)
{
Flags &= 0x7fff;
}
else
{
Flags |= 0x8000;
}
}
}
/// <summary>
/// Gets or sets the Operation Code (OPCODE)
/// </summary>
public OperationCode OperationCode
{
get { return (OperationCode) ((Flags & 0x7800) >> 11); }
set
{
ushort clearedOp = (ushort) (Flags & 0x8700);
Flags = (ushort) (clearedOp | (ushort) value << 11);
}
}
/// <summary>
/// Gets or sets the return code (RCODE)
/// </summary>
public ReturnCode ReturnCode
{
get
{
ReturnCode rcode = (ReturnCode) (Flags & 0x000f);
OptRecord ednsOptions = EDnsOptions;
if (ednsOptions == null)
{
return rcode;
}
else
{
return (rcode | ednsOptions.ExtendedReturnCode);
}
}
set
{
OptRecord ednsOptions = EDnsOptions;
if ((ushort) value > 15)
{
if (ednsOptions == null)
{
throw new ArgumentOutOfRangeException("value", "ReturnCodes greater than 15 only allowed in edns messages");
}
else
{
ednsOptions.ExtendedReturnCode = value;
}
}
else
{
if (ednsOptions != null)
{
ednsOptions.ExtendedReturnCode = 0;
}
}
ushort clearedOp = (ushort) (Flags & 0xfff0);
Flags = (ushort) (clearedOp | ((ushort) value & 0x0f));
}
}
#endregion
#region EDNS
/// <summary>
/// Enables or disables EDNS
/// </summary>
public bool IsEDnsEnabled
{
get
{
if (_additionalRecords != null)
{
return _additionalRecords.Any(record => (record.RecordType == RecordType.Opt));
}
else
{
return false;
}
}
set
{
if (value && !IsEDnsEnabled)
{
if (_additionalRecords == null)
{
_additionalRecords = new List<DnsRecordBase>();
}
_additionalRecords.Add(new OptRecord());
}
else if (!value && IsEDnsEnabled)
{
_additionalRecords.RemoveAll(record => (record.RecordType == RecordType.Opt));
}
}
}
/// <summary>
/// Gets or set the OptRecord for the EDNS options
/// </summary>
public OptRecord EDnsOptions
{
get
{
if (_additionalRecords != null)
{
return (OptRecord) _additionalRecords.Find(record => (record.RecordType == RecordType.Opt));
}
else
{
return null;
}
}
set
{
if (value == null)
{
IsEDnsEnabled = false;
}
else if (IsEDnsEnabled)
{
int pos = _additionalRecords.FindIndex(record => (record.RecordType == RecordType.Opt));
_additionalRecords[pos] = value;
}
else
{
if (_additionalRecords == null)
{
_additionalRecords = new List<DnsRecordBase>();
}
_additionalRecords.Add(value);
}
}
}
/// <summary>
/// <para>Gets or sets the DNSSEC answer OK (DO) flag</para>
/// <para>
/// Defined in
/// <see cref="!:http://tools.ietf.org/html/rfc4035">RFC 4035</see>
/// and
/// <see cref="!:http://tools.ietf.org/html/rfc3225">RFC 3225</see>
/// </para>
/// </summary>
public bool IsDnsSecOk
{
get
{
OptRecord ednsOptions = EDnsOptions;
return (ednsOptions != null) && ednsOptions.IsDnsSecOk;
}
set
{
OptRecord ednsOptions = EDnsOptions;
if (ednsOptions == null)
{
if (value)
{
throw new ArgumentOutOfRangeException("value", "Setting DO flag is allowed in edns messages only");
}
}
else
{
ednsOptions.IsDnsSecOk = value;
}
}
}
#endregion
#region TSig
/// <summary>
/// Gets or set the TSigRecord for the tsig signed messages
/// </summary>
public TSigRecord TSigOptions { get; set; }
internal static DnsMessageBase CreateByFlag(byte[] data, DnsServer.SelectTsigKey tsigKeySelector, byte[] originalMac)
{
int flagPosition = 2;
ushort flags = ParseUShort(data, ref flagPosition);
DnsMessageBase res;
switch ((OperationCode) ((flags & 0x7800) >> 11))
{
case OperationCode.Update:
res = new DnsUpdateMessage();
break;
default:
res = new DnsMessage();
break;
}
res.ParseInternal(data, tsigKeySelector, originalMac);
return res;
}
internal static TMessage Parse<TMessage>(byte[] data)
where TMessage : DnsMessageBase, new()
{
return Parse<TMessage>(data, null, null);
}
internal static TMessage Parse<TMessage>(byte[] data, DnsServer.SelectTsigKey tsigKeySelector, byte[] originalMac)
where TMessage : DnsMessageBase, new()
{
TMessage result = new TMessage();
result.ParseInternal(data, tsigKeySelector, originalMac);
return result;
}
private void ParseInternal(byte[] data, DnsServer.SelectTsigKey tsigKeySelector, byte[] originalMac)
{
int currentPosition = 0;
TransactionID = ParseUShort(data, ref currentPosition);
Flags = ParseUShort(data, ref currentPosition);
int questionCount = ParseUShort(data, ref currentPosition);
int answerRecordCount = ParseUShort(data, ref currentPosition);
int authorityRecordCount = ParseUShort(data, ref currentPosition);
int additionalRecordCount = ParseUShort(data, ref currentPosition);
ParseQuestions(data, ref currentPosition, questionCount);
ParseSection(data, ref currentPosition, AnswerRecords, answerRecordCount);
ParseSection(data, ref currentPosition, AuthorityRecords, authorityRecordCount);
ParseSection(data, ref currentPosition, _additionalRecords, additionalRecordCount);
if (_additionalRecords.Count > 0)
{
int tSigPos = _additionalRecords.FindIndex(record => (record.RecordType == RecordType.TSig));
if (tSigPos == (_additionalRecords.Count - 1))
{
TSigOptions = (TSigRecord) _additionalRecords[tSigPos];
_additionalRecords.RemoveAt(tSigPos);
TSigOptions.ValidationResult = ValidateTSig(data, tsigKeySelector, originalMac);
}
}
FinishParsing();
}
private ReturnCode ValidateTSig(byte[] resultData, DnsServer.SelectTsigKey tsigKeySelector, byte[] originalMac)
{
byte[] keyData;
if ((TSigOptions.Algorithm == TSigAlgorithm.Unknown) || (tsigKeySelector == null) || ((keyData = tsigKeySelector(TSigOptions.Algorithm, TSigOptions.Name)) == null))
{
return ReturnCode.BadKey;
}
else if (((TSigOptions.TimeSigned - TSigOptions.Fudge) > DateTime.Now) || ((TSigOptions.TimeSigned + TSigOptions.Fudge) < DateTime.Now))
{
return ReturnCode.BadTime;
}
else if ((TSigOptions.Mac == null) || (TSigOptions.Mac.Length == 0))
{
return ReturnCode.BadSig;
}
else
{
TSigOptions.KeyData = keyData;
// maxLength for the buffer to validate: Original (unsigned) dns message and encoded TSigOptions
// because of compression of keyname, the size of the signed message can not be used
int maxLength = TSigOptions.StartPosition + TSigOptions.MaximumLength;
if (originalMac != null)
{
// add length of mac on responses. MacSize not neccessary, this field is allready included in the size of the tsig options
maxLength += originalMac.Length;
}
byte[] validationBuffer = new byte[maxLength];
int currentPosition = 0;
// original mac if neccessary
if ((originalMac != null) && (originalMac.Length > 0))
{
EncodeUShort(validationBuffer, ref currentPosition, (ushort) originalMac.Length);
EncodeByteArray(validationBuffer, ref currentPosition, originalMac);
}
// original unsiged buffer
Buffer.BlockCopy(resultData, 0, validationBuffer, currentPosition, TSigOptions.StartPosition);
// update original transaction id and ar count in message
EncodeUShort(validationBuffer, currentPosition, TSigOptions.OriginalID);
EncodeUShort(validationBuffer, currentPosition + 10, (ushort) _additionalRecords.Count);
currentPosition += TSigOptions.StartPosition;
// TSig Variables
EncodeDomainName(validationBuffer, 0, ref currentPosition, TSigOptions.Name, false, null);
EncodeUShort(validationBuffer, ref currentPosition, (ushort) TSigOptions.RecordClass);
EncodeInt(validationBuffer, ref currentPosition, (ushort) TSigOptions.TimeToLive);
EncodeDomainName(validationBuffer, 0, ref currentPosition, TSigAlgorithmHelper.GetDomainName(TSigOptions.Algorithm), false, null);
TSigRecord.EncodeDateTime(validationBuffer, ref currentPosition, TSigOptions.TimeSigned);
EncodeUShort(validationBuffer, ref currentPosition, (ushort) TSigOptions.Fudge.TotalSeconds);
EncodeUShort(validationBuffer, ref currentPosition, (ushort) TSigOptions.Error);
EncodeUShort(validationBuffer, ref currentPosition, (ushort) TSigOptions.OtherData.Length);
EncodeByteArray(validationBuffer, ref currentPosition, TSigOptions.OtherData);
// Validate MAC
KeyedHashAlgorithm hashAlgorithm = TSigAlgorithmHelper.GetHashAlgorithm(TSigOptions.Algorithm);
hashAlgorithm.Key = keyData;
return (hashAlgorithm.ComputeHash(validationBuffer, 0, currentPosition).SequenceEqual(TSigOptions.Mac)) ? ReturnCode.NoError : ReturnCode.BadSig;
}
}
#endregion
#region Parsing
protected virtual void FinishParsing() {}
#region Methods for parsing answer
private static void ParseSection(byte[] resultData, ref int currentPosition, List<DnsRecordBase> sectionList, int recordCount)
{
for (int i = 0; i < recordCount; i++)
{
sectionList.Add(ParseRecord(resultData, ref currentPosition));
}
}
private static DnsRecordBase ParseRecord(byte[] resultData, ref int currentPosition)
{
int startPosition = currentPosition;
string name = ParseDomainName(resultData, ref currentPosition);
RecordType recordType = (RecordType) ParseUShort(resultData, ref currentPosition);
DnsRecordBase record = DnsRecordBase.Create(recordType, resultData, currentPosition + 6);
record.StartPosition = startPosition;
record.Name = name;
record.RecordType = recordType;
record.RecordClass = (RecordClass) ParseUShort(resultData, ref currentPosition);
record.TimeToLive = ParseInt(resultData, ref currentPosition);
record.RecordDataLength = ParseUShort(resultData, ref currentPosition);
if (record.RecordDataLength > 0)
{
record.ParseRecordData(resultData, currentPosition, record.RecordDataLength);
currentPosition += record.RecordDataLength;
}
return record;
}
private void ParseQuestions(byte[] resultData, ref int currentPosition, int recordCount)
{
for (int i = 0; i < recordCount; i++)
{
DnsQuestion question = new DnsQuestion { Name = ParseDomainName(resultData, ref currentPosition), RecordType = (RecordType) ParseUShort(resultData, ref currentPosition), RecordClass = (RecordClass) ParseUShort(resultData, ref currentPosition) };
Questions.Add(question);
}
}
#endregion
#region Helper methods for parsing records
internal static string ParseText(byte[] resultData, ref int currentPosition)
{
int length = resultData[currentPosition++];
return ParseText(resultData, ref currentPosition, length);
}
internal static string ParseText(byte[] resultData, ref int currentPosition, int length)
{
string res = Encoding.ASCII.GetString(resultData, currentPosition, length);
currentPosition += length;
return res;
}
internal static string ParseDomainName(byte[] resultData, ref int currentPosition)
{
int firstLabelLength;
string res = ParseDomainName(resultData, currentPosition, out firstLabelLength);
currentPosition += firstLabelLength;
return res;
}
internal static ushort ParseUShort(byte[] resultData, ref int currentPosition)
{
ushort res;
if (BitConverter.IsLittleEndian)
{
res = (ushort) ((resultData[currentPosition++] << 8) | resultData[currentPosition++]);
}
else
{
res = (ushort) (resultData[currentPosition++] | (resultData[currentPosition++] << 8));
}
return res;
}
internal static int ParseInt(byte[] resultData, ref int currentPosition)
{
int res;
if (BitConverter.IsLittleEndian)
{
res = ((resultData[currentPosition++] << 24) | (resultData[currentPosition++] << 16) | (resultData[currentPosition++] << 8) | resultData[currentPosition++]);
}
else
{
res = (resultData[currentPosition++] | (resultData[currentPosition++] << 8) | (resultData[currentPosition++] << 16) | (resultData[currentPosition++] << 24));
}
return res;
}
internal static uint ParseUInt(byte[] resultData, ref int currentPosition)
{
uint res;
if (BitConverter.IsLittleEndian)
{
res = (((uint) resultData[currentPosition++] << 24) | ((uint) resultData[currentPosition++] << 16) | ((uint) resultData[currentPosition++] << 8) | resultData[currentPosition++]);
}
else
{
res = (resultData[currentPosition++] | ((uint) resultData[currentPosition++] << 8) | ((uint) resultData[currentPosition++] << 16) | ((uint) resultData[currentPosition++] << 24));
}
return res;
}
internal static ulong ParseULong(byte[] resultData, ref int currentPosition)
{
ulong res;
if (BitConverter.IsLittleEndian)
{
res = ((ulong) ParseUInt(resultData, ref currentPosition) << 32) | ParseUInt(resultData, ref currentPosition);
}
else
{
res = ParseUInt(resultData, ref currentPosition) | ((ulong) ParseUInt(resultData, ref currentPosition) << 32);
}
return res;
}
private static string ParseDomainName(byte[] resultData, int currentPosition, out int firstLabelBytes)
{
StringBuilder sb = new StringBuilder(64, 255);
bool isInFirstLabel = true;
firstLabelBytes = 0;
while (true) // loop will be ended gracefully or when StringBuilder grows over 255 bytes
{
byte currentByte = resultData[currentPosition++];
if (currentByte == 0)
{
// end of domain, RFC1035
if (isInFirstLabel)
firstLabelBytes += 1;
break;
}
else if (currentByte >= 192)
{
// Pointer, RFC1035
if (isInFirstLabel)
{
firstLabelBytes += 2;
isInFirstLabel = false;
}
int pointer;
if (BitConverter.IsLittleEndian)
{
pointer = (ushort) (((currentByte - 192) << 8) | resultData[currentPosition++]);
}
else
{
pointer = (ushort) ((currentByte - 192) | (resultData[currentPosition++] << 8));
}
currentPosition = pointer;
}
else if (currentByte == 65)
{
// binary EDNS label, RFC2673, RFC3363, RFC3364
int length = resultData[currentPosition++];
if (isInFirstLabel)
firstLabelBytes += 1;
if (length == 0)
length = 256;
sb.Append(@"\[x");
string suffix = "/" + length + "]";
do
{
currentByte = resultData[currentPosition++];
if (isInFirstLabel)
firstLabelBytes += 1;
if (length < 8)
{
currentByte &= (byte) (0xff >> (8 - length));
}
sb.Append(currentByte.ToString("x2"));
length = length - 8;
} while (length > 0);
sb.Append(suffix);
}
else if (currentByte >= 64)
{
// extended dns label RFC 2671
throw new NotSupportedException("Unsupported extended dns label");
}
else
{
// append additional text part
if (isInFirstLabel)
firstLabelBytes += 1 + currentByte;
sb.Append(Encoding.ASCII.GetString(resultData, currentPosition, currentByte));
sb.Append(".");
currentPosition += currentByte;
}
}
return (sb.Length == 0) ? String.Empty : sb.ToString(0, sb.Length - 1);
}
internal static byte[] ParseByteData(byte[] resultData, ref int currentPosition, int length)
{
if (length == 0)
{
return new byte[] { };
}
else
{
byte[] res = new byte[length];
Buffer.BlockCopy(resultData, currentPosition, res, 0, length);
currentPosition += length;
return res;
}
}
#endregion
#endregion
#region Serializing
protected virtual void PrepareEncoding() {}
internal int Encode(bool addLengthPrefix, out byte[] messageData)
{
byte[] newTSigMac;
return Encode(addLengthPrefix, null, false, out messageData, out newTSigMac);
}
internal int Encode(bool addLengthPrefix, byte[] originalTsigMac, out byte[] messageData)
{
byte[] newTSigMac;
return Encode(addLengthPrefix, originalTsigMac, false, out messageData, out newTSigMac);
}
internal int Encode(bool addLengthPrefix, byte[] originalTsigMac, bool isSubSequentResponse, out byte[] messageData, out byte[] newTSigMac)
{
PrepareEncoding();
int offset = 0;
int messageOffset = offset;
int maxLength = addLengthPrefix ? 2 : 0;
originalTsigMac = originalTsigMac ?? new byte[] { };
if (TSigOptions != null)
{
if (!IsQuery)
{
offset += 2 + originalTsigMac.Length;
maxLength += 2 + originalTsigMac.Length;
}
maxLength += TSigOptions.MaximumLength;
}
#region Get Message Length
maxLength += 12;
maxLength += Questions.Sum(question => question.MaximumLength);
maxLength += AnswerRecords.Sum(record => record.MaximumLength);
maxLength += AuthorityRecords.Sum(record => record.MaximumLength);
maxLength += _additionalRecords.Sum(record => record.MaximumLength);
#endregion
messageData = new byte[maxLength];
int currentPosition = offset;
Dictionary<string, ushort> domainNames = new Dictionary<string, ushort>();
EncodeUShort(messageData, ref currentPosition, TransactionID);
EncodeUShort(messageData, ref currentPosition, Flags);
EncodeUShort(messageData, ref currentPosition, (ushort) Questions.Count);
EncodeUShort(messageData, ref currentPosition, (ushort) AnswerRecords.Count);
EncodeUShort(messageData, ref currentPosition, (ushort) AuthorityRecords.Count);
EncodeUShort(messageData, ref currentPosition, (ushort) _additionalRecords.Count);
foreach (DnsQuestion question in Questions)
{
question.Encode(messageData, offset, ref currentPosition, domainNames);
}
foreach (DnsRecordBase record in AnswerRecords)
{
record.Encode(messageData, offset, ref currentPosition, domainNames);
}
foreach (DnsRecordBase record in AuthorityRecords)
{
record.Encode(messageData, offset, ref currentPosition, domainNames);
}
foreach (DnsRecordBase record in _additionalRecords)
{
record.Encode(messageData, offset, ref currentPosition, domainNames);
}
if (TSigOptions == null)
{
newTSigMac = null;
}
else
{
if (!IsQuery)
{
EncodeUShort(messageData, messageOffset, (ushort) originalTsigMac.Length);
Buffer.BlockCopy(originalTsigMac, 0, messageData, messageOffset + 2, originalTsigMac.Length);
}
EncodeUShort(messageData, offset, TSigOptions.OriginalID);
int tsigVariablesPosition = currentPosition;
if (isSubSequentResponse)
{
TSigRecord.EncodeDateTime(messageData, ref tsigVariablesPosition, TSigOptions.TimeSigned);
EncodeUShort(messageData, ref tsigVariablesPosition, (ushort) TSigOptions.Fudge.TotalSeconds);
}
else
{
EncodeDomainName(messageData, offset, ref tsigVariablesPosition, TSigOptions.Name, false, null);
EncodeUShort(messageData, ref tsigVariablesPosition, (ushort) TSigOptions.RecordClass);
EncodeInt(messageData, ref tsigVariablesPosition, (ushort) TSigOptions.TimeToLive);
EncodeDomainName(messageData, offset, ref tsigVariablesPosition, TSigAlgorithmHelper.GetDomainName(TSigOptions.Algorithm), false, null);
TSigRecord.EncodeDateTime(messageData, ref tsigVariablesPosition, TSigOptions.TimeSigned);
EncodeUShort(messageData, ref tsigVariablesPosition, (ushort) TSigOptions.Fudge.TotalSeconds);
EncodeUShort(messageData, ref tsigVariablesPosition, (ushort) TSigOptions.Error);
EncodeUShort(messageData, ref tsigVariablesPosition, (ushort) TSigOptions.OtherData.Length);
EncodeByteArray(messageData, ref tsigVariablesPosition, TSigOptions.OtherData);
}
KeyedHashAlgorithm hashAlgorithm = TSigAlgorithmHelper.GetHashAlgorithm(TSigOptions.Algorithm);
if ((hashAlgorithm != null) && (TSigOptions.KeyData != null) && (TSigOptions.KeyData.Length > 0))
{
hashAlgorithm.Key = TSigOptions.KeyData;
newTSigMac = hashAlgorithm.ComputeHash(messageData, messageOffset, tsigVariablesPosition);
}
else
{
newTSigMac = new byte[] { };
}
EncodeUShort(messageData, offset, TransactionID);
EncodeUShort(messageData, offset + 10, (ushort) (_additionalRecords.Count + 1));
TSigOptions.Encode(messageData, offset, ref currentPosition, domainNames, newTSigMac);
if (!IsQuery)
{
Buffer.BlockCopy(messageData, offset, messageData, messageOffset, (currentPosition - offset));
currentPosition -= (2 + originalTsigMac.Length);
}
}
if (addLengthPrefix)
{
Buffer.BlockCopy(messageData, 0, messageData, 2, currentPosition);
EncodeUShort(messageData, 0, (ushort) (currentPosition));
currentPosition += 2;
}
return currentPosition;
}
internal static void EncodeUShort(byte[] buffer, int currentPosition, ushort value)
{
EncodeUShort(buffer, ref currentPosition, value);
}
internal static void EncodeUShort(byte[] buffer, ref int currentPosition, ushort value)
{
if (BitConverter.IsLittleEndian)
{
buffer[currentPosition++] = (byte) ((value >> 8) & 0xff);
buffer[currentPosition++] = (byte) (value & 0xff);
}
else
{
buffer[currentPosition++] = (byte) (value & 0xff);
buffer[currentPosition++] = (byte) ((value >> 8) & 0xff);
}
}
internal static void EncodeInt(byte[] buffer, ref int currentPosition, int value)
{
if (BitConverter.IsLittleEndian)
{
buffer[currentPosition++] = (byte) ((value >> 24) & 0xff);
buffer[currentPosition++] = (byte) ((value >> 16) & 0xff);
buffer[currentPosition++] = (byte) ((value >> 8) & 0xff);
buffer[currentPosition++] = (byte) (value & 0xff);
}
else
{
buffer[currentPosition++] = (byte) (value & 0xff);
buffer[currentPosition++] = (byte) ((value >> 8) & 0xff);
buffer[currentPosition++] = (byte) ((value >> 16) & 0xff);
buffer[currentPosition++] = (byte) ((value >> 24) & 0xff);
}
}
internal static void EncodeUInt(byte[] buffer, ref int currentPosition, uint value)
{
if (BitConverter.IsLittleEndian)
{
buffer[currentPosition++] = (byte) ((value >> 24) & 0xff);
buffer[currentPosition++] = (byte) ((value >> 16) & 0xff);
buffer[currentPosition++] = (byte) ((value >> 8) & 0xff);
buffer[currentPosition++] = (byte) (value & 0xff);
}
else
{
buffer[currentPosition++] = (byte) (value & 0xff);
buffer[currentPosition++] = (byte) ((value >> 8) & 0xff);
buffer[currentPosition++] = (byte) ((value >> 16) & 0xff);
buffer[currentPosition++] = (byte) ((value >> 24) & 0xff);
}
}
internal static void EncodeULong(byte[] buffer, ref int currentPosition, ulong value)
{
if (BitConverter.IsLittleEndian)
{
EncodeUInt(buffer, ref currentPosition, (uint) ((value >> 32) & 0xffffffff));
EncodeUInt(buffer, ref currentPosition, (uint) (value & 0xffffffff));
}
else
{
EncodeUInt(buffer, ref currentPosition, (uint) (value & 0xffffffff));
EncodeUInt(buffer, ref currentPosition, (uint) ((value >> 32) & 0xffffffff));
}
}
internal static void EncodeDomainName(byte[] messageData, int offset, ref int currentPosition, string name, bool isCompressionAllowed, Dictionary<string, ushort> domainNames)
{
if (String.IsNullOrEmpty(name) || (name == "."))
{
messageData[currentPosition++] = 0;
return;
}
ushort pointer;
if (isCompressionAllowed && domainNames.TryGetValue(name, out pointer))
{
EncodeUShort(messageData, ref currentPosition, pointer);
return;
}
int labelLength = name.IndexOf('.');
if (labelLength == -1)
labelLength = name.Length;
if (isCompressionAllowed)
domainNames[name] = (ushort) ((currentPosition | 0xc000) - offset);
messageData[currentPosition++] = (byte) labelLength;
EncodeByteArray(messageData, ref currentPosition, Encoding.ASCII.GetBytes(name.ToCharArray(0, labelLength)));
EncodeDomainName(messageData, offset, ref currentPosition, labelLength == name.Length ? "." : name.Substring(labelLength + 1), isCompressionAllowed, domainNames);
}
internal static void EncodeTextBlock(byte[] messageData, ref int currentPosition, string text)
{
byte[] textData = Encoding.ASCII.GetBytes(text);
for (int i = 0; i < textData.Length; i += 255)
{
int blockLength = Math.Min(255, (textData.Length - i));
messageData[currentPosition++] = (byte) blockLength;
Buffer.BlockCopy(textData, i, messageData, currentPosition, blockLength);
currentPosition += blockLength;
}
}
internal static void EncodeTextWithoutLength(byte[] messageData, ref int currentPosition, string text)
{
byte[] textData = Encoding.ASCII.GetBytes(text);
Buffer.BlockCopy(textData, 0, messageData, currentPosition, textData.Length);
currentPosition += textData.Length;
}
internal static void EncodeByteArray(byte[] messageData, ref int currentPosition, byte[] data)
{
if (data != null)
{
EncodeByteArray(messageData, ref currentPosition, data, data.Length);
}
}
internal static void EncodeByteArray(byte[] messageData, ref int currentPosition, byte[] data, int length)
{
if ((data != null) && (length > 0))
{
Buffer.BlockCopy(data, 0, messageData, currentPosition, length);
currentPosition += length;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Collections;
using System.ComponentModel;
namespace System.Data
{
/// <summary>
/// Represents a collection of constraints for a <see cref='System.Data.DataTable'/>.
/// </summary>
[DefaultEvent(nameof(CollectionChanged))]
public sealed class ConstraintCollection : InternalDataCollectionBase
{
private readonly DataTable _table;
private readonly ArrayList _list = new ArrayList();
private int _defaultNameIndex = 1;
private CollectionChangeEventHandler _onCollectionChanged;
private Constraint[] _delayLoadingConstraints;
private bool _fLoadForeignKeyConstraintsOnly = false;
/// <summary>
/// ConstraintCollection constructor. Used only by DataTable.
/// </summary>
internal ConstraintCollection(DataTable table)
{
_table = table;
}
/// <summary>
/// Gets the list of objects contained by the collection.
/// </summary>
protected override ArrayList List => _list;
/// <summary>
/// Gets the <see cref='System.Data.Constraint'/>
/// from the collection at the specified index.
/// </summary>
public Constraint this[int index]
{
get
{
if (index >= 0 && index < List.Count)
{
return (Constraint)List[index];
}
throw ExceptionBuilder.ConstraintOutOfRange(index);
}
}
/// <summary>
/// The DataTable with which this ConstraintCollection is associated
/// </summary>
internal DataTable Table => _table;
/// <summary>
/// Gets the <see cref='System.Data.Constraint'/> from the collection with the specified name.
/// </summary>
public Constraint this[string name]
{
get
{
int index = InternalIndexOf(name);
if (index == -2)
{
throw ExceptionBuilder.CaseInsensitiveNameConflict(name);
}
return (index < 0) ? null : (Constraint)List[index];
}
}
/// <summary>
/// Adds the constraint to the collection.
/// </summary>
public void Add(Constraint constraint) => Add(constraint, true);
// To add foreign key constraint without adding any unique constraint for internal use. Main purpose : Binary Remoting
internal void Add(Constraint constraint, bool addUniqueWhenAddingForeign)
{
if (constraint == null)
{
throw ExceptionBuilder.ArgumentNull(nameof(constraint));
}
// It is an error if we find an equivalent constraint already in collection
if (FindConstraint(constraint) != null)
{
throw ExceptionBuilder.DuplicateConstraint(FindConstraint(constraint).ConstraintName);
}
if (1 < _table.NestedParentRelations.Length)
{
if (!AutoGenerated(constraint))
{
throw ExceptionBuilder.CantAddConstraintToMultipleNestedTable(_table.TableName);
}
}
if (constraint is UniqueConstraint)
{
if (((UniqueConstraint)constraint)._bPrimaryKey)
{
if (Table._primaryKey != null)
{
throw ExceptionBuilder.AddPrimaryKeyConstraint();
}
}
AddUniqueConstraint((UniqueConstraint)constraint);
}
else if (constraint is ForeignKeyConstraint)
{
ForeignKeyConstraint fk = (ForeignKeyConstraint)constraint;
if (addUniqueWhenAddingForeign)
{
UniqueConstraint key = fk.RelatedTable.Constraints.FindKeyConstraint(fk.RelatedColumnsReference);
if (key == null)
{
if (constraint.ConstraintName.Length == 0)
constraint.ConstraintName = AssignName();
else
RegisterName(constraint.ConstraintName);
key = new UniqueConstraint(fk.RelatedColumnsReference);
fk.RelatedTable.Constraints.Add(key);
}
}
AddForeignKeyConstraint((ForeignKeyConstraint)constraint);
}
BaseAdd(constraint);
ArrayAdd(constraint);
OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, constraint));
if (constraint is UniqueConstraint)
{
if (((UniqueConstraint)constraint)._bPrimaryKey)
{
Table.PrimaryKey = ((UniqueConstraint)constraint).ColumnsReference;
}
}
}
/// <summary>
/// Constructs a new <see cref='System.Data.UniqueConstraint'/> using the
/// specified array of <see cref='System.Data.DataColumn'/>
/// objects and adds it to the collection.
/// </summary>
public Constraint Add(string name, DataColumn[] columns, bool primaryKey)
{
UniqueConstraint constraint = new UniqueConstraint(name, columns);
Add(constraint);
if (primaryKey)
Table.PrimaryKey = columns;
return constraint;
}
/// <summary>
/// Constructs a new <see cref='System.Data.UniqueConstraint'/> using the
/// specified <see cref='System.Data.DataColumn'/> and adds it to the collection.
/// </summary>
public Constraint Add(string name, DataColumn column, bool primaryKey)
{
UniqueConstraint constraint = new UniqueConstraint(name, column);
Add(constraint);
if (primaryKey)
Table.PrimaryKey = constraint.ColumnsReference;
return constraint;
}
/// <summary>
/// Constructs a new <see cref='System.Data.ForeignKeyConstraint'/>
/// with the
/// specified parent and child
/// columns and adds the constraint to the collection.
/// </summary>
public Constraint Add(string name, DataColumn primaryKeyColumn, DataColumn foreignKeyColumn)
{
ForeignKeyConstraint constraint = new ForeignKeyConstraint(name, primaryKeyColumn, foreignKeyColumn);
Add(constraint);
return constraint;
}
/// <summary>
/// Constructs a new <see cref='System.Data.ForeignKeyConstraint'/> with the specified parent columns and
/// child columns and adds the constraint to the collection.
/// </summary>
public Constraint Add(string name, DataColumn[] primaryKeyColumns, DataColumn[] foreignKeyColumns)
{
ForeignKeyConstraint constraint = new ForeignKeyConstraint(name, primaryKeyColumns, foreignKeyColumns);
Add(constraint);
return constraint;
}
public void AddRange(Constraint[] constraints)
{
if (_table.fInitInProgress)
{
_delayLoadingConstraints = constraints;
_fLoadForeignKeyConstraintsOnly = false;
return;
}
if (constraints != null)
{
foreach (Constraint constr in constraints)
{
if (constr != null)
{
Add(constr);
}
}
}
}
private void AddUniqueConstraint(UniqueConstraint constraint)
{
DataColumn[] columns = constraint.ColumnsReference;
for (int i = 0; i < columns.Length; i++)
{
if (columns[i].Table != _table)
{
throw ExceptionBuilder.ConstraintForeignTable();
}
}
constraint.ConstraintIndexInitialize();
if (!constraint.CanEnableConstraint())
{
constraint.ConstraintIndexClear();
throw ExceptionBuilder.UniqueConstraintViolation();
}
}
private void AddForeignKeyConstraint(ForeignKeyConstraint constraint)
{
if (!constraint.CanEnableConstraint())
{
throw ExceptionBuilder.ConstraintParentValues();
}
constraint.CheckCanAddToCollection(this);
}
private bool AutoGenerated(Constraint constraint)
{
ForeignKeyConstraint fk = (constraint as ForeignKeyConstraint);
if (null != fk)
{
return XmlTreeGen.AutoGenerated(fk, false);
}
else
{
UniqueConstraint unique = (UniqueConstraint)constraint;
return XmlTreeGen.AutoGenerated(unique);
}
}
/// <summary>
/// Occurs when the <see cref='System.Data.ConstraintCollection'/> is changed through additions or
/// removals.
/// </summary>
public event CollectionChangeEventHandler CollectionChanged
{
add
{
_onCollectionChanged += value;
}
remove
{
_onCollectionChanged -= value;
}
}
/// <summary>
/// Adds the constraint to the constraints array.
/// </summary>
private void ArrayAdd(Constraint constraint)
{
Debug.Assert(constraint != null, "Attempt to add null constraint to constraint array");
List.Add(constraint);
}
private void ArrayRemove(Constraint constraint)
{
List.Remove(constraint);
}
/// <summary>
/// Creates a new default name.
/// </summary>
internal string AssignName()
{
string newName = MakeName(_defaultNameIndex);
_defaultNameIndex++;
return newName;
}
/// <summary>
/// Does verification on the constraint and it's name.
/// An ArgumentNullException is thrown if this constraint is null. An ArgumentException is thrown if this constraint
/// already belongs to this collection, belongs to another collection.
/// A DuplicateNameException is thrown if this collection already has a constraint with the same
/// name (case insensitive).
/// </summary>
private void BaseAdd(Constraint constraint)
{
if (constraint == null)
throw ExceptionBuilder.ArgumentNull(nameof(constraint));
if (constraint.ConstraintName.Length == 0)
constraint.ConstraintName = AssignName();
else
RegisterName(constraint.ConstraintName);
constraint.InCollection = true;
}
/// <summary>
/// BaseGroupSwitch will intelligently remove and add tables from the collection.
/// </summary>
private void BaseGroupSwitch(Constraint[] oldArray, int oldLength, Constraint[] newArray, int newLength)
{
// We're doing a smart diff of oldArray and newArray to find out what
// should be removed. We'll pass through oldArray and see if it exists
// in newArray, and if not, do remove work. newBase is an opt. in case
// the arrays have similar prefixes.
int newBase = 0;
for (int oldCur = 0; oldCur < oldLength; oldCur++)
{
bool found = false;
for (int newCur = newBase; newCur < newLength; newCur++)
{
if (oldArray[oldCur] == newArray[newCur])
{
if (newBase == newCur)
{
newBase++;
}
found = true;
break;
}
}
if (!found)
{
// This means it's in oldArray and not newArray. Remove it.
BaseRemove(oldArray[oldCur]);
List.Remove(oldArray[oldCur]);
}
}
// Now, let's pass through news and those that don't belong, add them.
for (int newCur = 0; newCur < newLength; newCur++)
{
if (!newArray[newCur].InCollection)
BaseAdd(newArray[newCur]);
List.Add(newArray[newCur]);
}
}
/// <summary>
/// Does verification on the constraint and it's name.
/// An ArgumentNullException is thrown if this constraint is null. An ArgumentException is thrown
/// if this constraint doesn't belong to this collection or if this constraint is part of a relationship.
/// </summary>
private void BaseRemove(Constraint constraint)
{
if (constraint == null)
{
throw ExceptionBuilder.ArgumentNull(nameof(constraint));
}
if (constraint.Table != _table)
{
throw ExceptionBuilder.ConstraintRemoveFailed();
}
UnregisterName(constraint.ConstraintName);
constraint.InCollection = false;
if (constraint is UniqueConstraint)
{
for (int i = 0; i < Table.ChildRelations.Count; i++)
{
DataRelation rel = Table.ChildRelations[i];
if (rel.ParentKeyConstraint == constraint)
rel.SetParentKeyConstraint(null);
}
((UniqueConstraint)constraint).ConstraintIndexClear();
}
else if (constraint is ForeignKeyConstraint)
{
for (int i = 0; i < Table.ParentRelations.Count; i++)
{
DataRelation rel = Table.ParentRelations[i];
if (rel.ChildKeyConstraint == constraint)
rel.SetChildKeyConstraint(null);
}
}
}
/// <summary>
/// Indicates if a <see cref='System.Data.Constraint'/> can be removed.
/// </summary>
// PUBLIC because called by design-time... need to consider this.
public bool CanRemove(Constraint constraint)
{
return CanRemove(constraint, fThrowException: false);
}
internal bool CanRemove(Constraint constraint, bool fThrowException)
{
return constraint.CanBeRemovedFromCollection(this, fThrowException);
}
/// <summary>
/// Clears the collection of any <see cref='System.Data.Constraint'/>
/// objects.
/// </summary>
public void Clear()
{
if (_table != null)
{
_table.PrimaryKey = null;
for (int i = 0; i < _table.ParentRelations.Count; i++)
{
_table.ParentRelations[i].SetChildKeyConstraint(null);
}
for (int i = 0; i < _table.ChildRelations.Count; i++)
{
_table.ChildRelations[i].SetParentKeyConstraint(null);
}
}
if (_table.fInitInProgress && _delayLoadingConstraints != null)
{
_delayLoadingConstraints = null;
_fLoadForeignKeyConstraintsOnly = false;
}
int oldLength = List.Count;
Constraint[] constraints = new Constraint[List.Count];
List.CopyTo(constraints, 0);
try
{
// this will smartly add and remove the appropriate tables.
BaseGroupSwitch(constraints, oldLength, null, 0);
}
catch (Exception e) when (Common.ADP.IsCatchableOrSecurityExceptionType(e))
{
// something messed up. restore to original state.
BaseGroupSwitch(null, 0, constraints, oldLength);
List.Clear();
for (int i = 0; i < oldLength; i++)
{
List.Add(constraints[i]);
}
throw;
}
List.Clear();
OnCollectionChanged(s_refreshEventArgs);
}
/// <summary>
/// Indicates whether the <see cref='System.Data.Constraint'/>, specified by name, exists in the collection.
/// </summary>
public bool Contains(string name)
{
return (InternalIndexOf(name) >= 0);
}
internal bool Contains(string name, bool caseSensitive)
{
if (!caseSensitive)
return Contains(name);
int index = InternalIndexOf(name);
if (index < 0)
return false;
return (name == ((Constraint)List[index]).ConstraintName);
}
public void CopyTo(Constraint[] array, int index)
{
if (array == null)
throw ExceptionBuilder.ArgumentNull(nameof(array));
if (index < 0)
throw ExceptionBuilder.ArgumentOutOfRange(nameof(index));
if (array.Length - index < _list.Count)
throw ExceptionBuilder.InvalidOffsetLength();
for (int i = 0; i < _list.Count; ++i)
{
array[index + i] = (Constraint)_list[i];
}
}
/// <summary>
/// Returns a matching constraint object.
/// </summary>
internal Constraint FindConstraint(Constraint constraint)
{
int constraintCount = List.Count;
for (int i = 0; i < constraintCount; i++)
{
if (((Constraint)List[i]).Equals(constraint))
return (Constraint)List[i];
}
return null;
}
/// <summary>
/// Returns a matching constraint object.
/// </summary>
internal UniqueConstraint FindKeyConstraint(DataColumn[] columns)
{
int constraintCount = List.Count;
for (int i = 0; i < constraintCount; i++)
{
UniqueConstraint constraint = (List[i] as UniqueConstraint);
if ((null != constraint) && CompareArrays(constraint.Key.ColumnsReference, columns))
{
return constraint;
}
}
return null;
}
/// <summary>
/// Returns a matching constraint object.
/// </summary>
internal UniqueConstraint FindKeyConstraint(DataColumn column)
{
int constraintCount = List.Count;
for (int i = 0; i < constraintCount; i++)
{
UniqueConstraint constraint = (List[i] as UniqueConstraint);
if ((null != constraint) && (constraint.Key.ColumnsReference.Length == 1) && (constraint.Key.ColumnsReference[0] == column))
return constraint;
}
return null;
}
/// <summary>
/// Returns a matching constraint object.
/// </summary>
internal ForeignKeyConstraint FindForeignKeyConstraint(DataColumn[] parentColumns, DataColumn[] childColumns)
{
int constraintCount = List.Count;
for (int i = 0; i < constraintCount; i++)
{
ForeignKeyConstraint constraint = (List[i] as ForeignKeyConstraint);
if ((null != constraint) &&
CompareArrays(constraint.ParentKey.ColumnsReference, parentColumns) &&
CompareArrays(constraint.ChildKey.ColumnsReference, childColumns))
return constraint;
}
return null;
}
private static bool CompareArrays(DataColumn[] a1, DataColumn[] a2)
{
Debug.Assert(a1 != null && a2 != null, "Invalid Arguments");
if (a1.Length != a2.Length)
return false;
int i, j;
for (i = 0; i < a1.Length; i++)
{
bool check = false;
for (j = 0; j < a2.Length; j++)
{
if (a1[i] == a2[j])
{
check = true;
break;
}
}
if (!check)
{
return false;
}
}
return true;
}
/// <summary>
/// Returns the index of the specified <see cref='System.Data.Constraint'/> .
/// </summary>
public int IndexOf(Constraint constraint)
{
if (null != constraint)
{
int count = Count;
for (int i = 0; i < count; ++i)
{
if (constraint == (Constraint)List[i])
return i;
}
// didn't find the constraint
}
return -1;
}
/// <summary>
/// Returns the index of the <see cref='System.Data.Constraint'/>, specified by name.
/// </summary>
public int IndexOf(string constraintName)
{
int index = InternalIndexOf(constraintName);
return (index < 0) ? -1 : index;
}
// Return value:
// >= 0: find the match
// -1: No match
// -2: At least two matches with different cases
internal int InternalIndexOf(string constraintName)
{
int cachedI = -1;
if ((null != constraintName) && (0 < constraintName.Length))
{
int constraintCount = List.Count;
int result = 0;
for (int i = 0; i < constraintCount; i++)
{
Constraint constraint = (Constraint)List[i];
result = NamesEqual(constraint.ConstraintName, constraintName, false, _table.Locale);
if (result == 1)
return i;
if (result == -1)
cachedI = (cachedI == -1) ? i : -2;
}
}
return cachedI;
}
/// <summary>
/// Makes a default name with the given index. e.g. Constraint1, Constraint2, ... Constrainti
/// </summary>
private string MakeName(int index)
{
if (1 == index)
{
return "Constraint1";
}
return "Constraint" + index.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
/// <summary>
/// Raises the <see cref='System.Data.ConstraintCollection.CollectionChanged'/> event.
/// </summary>
private void OnCollectionChanged(CollectionChangeEventArgs ccevent)
{
_onCollectionChanged?.Invoke(this, ccevent);
}
/// <summary>
/// Registers this name as being used in the collection. Will throw an ArgumentException
/// if the name is already being used. Called by Add, All property, and Constraint.ConstraintName property.
/// if the name is equivalent to the next default name to hand out, we increment our defaultNameIndex.
/// </summary>
internal void RegisterName(string name)
{
Debug.Assert(name != null);
int constraintCount = List.Count;
for (int i = 0; i < constraintCount; i++)
{
if (NamesEqual(name, ((Constraint)List[i]).ConstraintName, true, _table.Locale) != 0)
{
throw ExceptionBuilder.DuplicateConstraintName(((Constraint)List[i]).ConstraintName);
}
}
if (NamesEqual(name, MakeName(_defaultNameIndex), true, _table.Locale) != 0)
{
_defaultNameIndex++;
}
}
/// <summary>
/// Removes the specified <see cref='System.Data.Constraint'/> from the collection.
/// </summary>
public void Remove(Constraint constraint)
{
if (constraint == null)
throw ExceptionBuilder.ArgumentNull(nameof(constraint));
// this will throw an exception if it can't be removed, otherwise indicates
// whether we need to remove it from the collection.
if (CanRemove(constraint, true))
{
// constraint can be removed
BaseRemove(constraint);
ArrayRemove(constraint);
if (constraint is UniqueConstraint && ((UniqueConstraint)constraint).IsPrimaryKey)
{
Table.PrimaryKey = null;
}
OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, constraint));
}
}
/// <summary>
/// Removes the constraint at the specified index from the collection.
/// </summary>
public void RemoveAt(int index)
{
Constraint c = this[index];
if (c == null)
throw ExceptionBuilder.ConstraintOutOfRange(index);
Remove(c);
}
/// <summary>
/// Removes the constraint, specified by name, from the collection.
/// </summary>
public void Remove(string name)
{
Constraint c = this[name];
if (c == null)
throw ExceptionBuilder.ConstraintNotInTheTable(name);
Remove(c);
}
/// <summary>
/// Unregisters this name as no longer being used in the collection. Called by Remove, All property, and
/// Constraint.ConstraintName property. If the name is equivalent to the last proposed default name, we walk backwards
/// to find the next proper default name to use.
/// </summary>
internal void UnregisterName(string name)
{
if (NamesEqual(name, MakeName(_defaultNameIndex - 1), true, _table.Locale) != 0)
{
do
{
_defaultNameIndex--;
} while (_defaultNameIndex > 1 &&
!Contains(MakeName(_defaultNameIndex - 1)));
}
}
internal void FinishInitConstraints()
{
if (_delayLoadingConstraints == null)
return;
int colCount;
DataColumn[] parents, childs;
for (int i = 0; i < _delayLoadingConstraints.Length; i++)
{
if (_delayLoadingConstraints[i] is UniqueConstraint)
{
if (_fLoadForeignKeyConstraintsOnly)
continue;
UniqueConstraint constr = (UniqueConstraint)_delayLoadingConstraints[i];
if (constr._columnNames == null)
{
Add(constr);
continue;
}
colCount = constr._columnNames.Length;
parents = new DataColumn[colCount];
for (int j = 0; j < colCount; j++)
parents[j] = _table.Columns[constr._columnNames[j]];
if (constr._bPrimaryKey)
{
if (_table._primaryKey != null)
{
throw ExceptionBuilder.AddPrimaryKeyConstraint();
}
else
{
Add(constr.ConstraintName, parents, true);
}
continue;
}
UniqueConstraint newConstraint = new UniqueConstraint(constr._constraintName, parents);
if (FindConstraint(newConstraint) == null)
Add(newConstraint);
}
else
{
ForeignKeyConstraint constr = (ForeignKeyConstraint)_delayLoadingConstraints[i];
if (constr._parentColumnNames == null || constr._childColumnNames == null)
{
Add(constr);
continue;
}
if (_table.DataSet == null)
{
_fLoadForeignKeyConstraintsOnly = true;
continue;
}
colCount = constr._parentColumnNames.Length;
parents = new DataColumn[colCount];
childs = new DataColumn[colCount];
for (int j = 0; j < colCount; j++)
{
if (constr._parentTableNamespace == null)
parents[j] = _table.DataSet.Tables[constr._parentTableName].Columns[constr._parentColumnNames[j]];
else
parents[j] = _table.DataSet.Tables[constr._parentTableName, constr._parentTableNamespace].Columns[constr._parentColumnNames[j]];
childs[j] = _table.Columns[constr._childColumnNames[j]];
}
ForeignKeyConstraint newConstraint = new ForeignKeyConstraint(constr._constraintName, parents, childs);
newConstraint.AcceptRejectRule = constr._acceptRejectRule;
newConstraint.DeleteRule = constr._deleteRule;
newConstraint.UpdateRule = constr._updateRule;
Add(newConstraint);
}
}
if (!_fLoadForeignKeyConstraintsOnly)
_delayLoadingConstraints = null;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Net;
using System.Reflection;
using Orleans.CodeGeneration;
using Orleans.GrainDirectory;
using Orleans.Runtime.Providers;
using Orleans.Serialization;
namespace Orleans.Runtime
{
internal class GrainTypeManager
{
private IDictionary<string, GrainTypeData> grainTypes;
private Dictionary<SiloAddress, GrainInterfaceMap> grainInterfaceMapsBySilo;
private Dictionary<int, List<SiloAddress>> supportedSilosByTypeCode;
private readonly Logger logger = LogManager.GetLogger("GrainTypeManager");
private readonly GrainInterfaceMap grainInterfaceMap;
private readonly Dictionary<int, InvokerData> invokers = new Dictionary<int, InvokerData>();
private readonly SiloAssemblyLoader loader;
private readonly SerializationManager serializationManager;
private readonly MultiClusterRegistrationStrategyManager multiClusterRegistrationStrategyManager;
private readonly PlacementStrategy defaultPlacementStrategy;
private Dictionary<int, Dictionary<ushort, List<SiloAddress>>> supportedSilosByInterface;
internal IReadOnlyDictionary<SiloAddress, GrainInterfaceMap> GrainInterfaceMapsBySilo
{
get { return grainInterfaceMapsBySilo; }
}
public IEnumerable<KeyValuePair<string, GrainTypeData>> GrainClassTypeData { get { return grainTypes; } }
public GrainInterfaceMap ClusterGrainInterfaceMap { get; private set; }
public GrainTypeManager(ILocalSiloDetails siloDetails, SiloAssemblyLoader loader, DefaultPlacementStrategy defaultPlacementStrategy, SerializationManager serializationManager, MultiClusterRegistrationStrategyManager multiClusterRegistrationStrategyManager)
{
var localTestMode = siloDetails.SiloAddress.Endpoint.Address.Equals(IPAddress.Loopback);
this.defaultPlacementStrategy = defaultPlacementStrategy.PlacementStrategy;
this.loader = loader;
this.serializationManager = serializationManager;
this.multiClusterRegistrationStrategyManager = multiClusterRegistrationStrategyManager;
grainInterfaceMap = new GrainInterfaceMap(localTestMode, this.defaultPlacementStrategy);
ClusterGrainInterfaceMap = grainInterfaceMap;
grainInterfaceMapsBySilo = new Dictionary<SiloAddress, GrainInterfaceMap>();
}
public void Start()
{
// loading application assemblies now occurs in four phases.
// 1. We scan the file system for assemblies meeting pre-determined criteria, specified in SiloAssemblyLoader.LoadApplicationAssemblies (called by the constructor).
// 2. We load those assemblies into memory. In the official distribution of Orleans, this is usually 4 assemblies.
// (no more assemblies should be loaded into memory, so now is a good time to log all types registered with the serialization manager)
this.serializationManager.LogRegisteredTypes();
// 3. We scan types in memory for GrainTypeData objects that describe grain classes and their corresponding grain state classes.
InitializeGrainClassData(loader);
// 4. We scan types in memory for grain method invoker objects.
InitializeInvokerMap(loader);
InitializeInterfaceMap();
}
public Dictionary<string, string> GetGrainInterfaceToClassMap()
{
return grainInterfaceMap.GetPrimaryImplementations();
}
internal bool TryGetPrimaryImplementation(string grainInterface, out string grainClass)
{
return grainInterfaceMap.TryGetPrimaryImplementation(grainInterface, out grainClass);
}
internal GrainTypeData this[string className]
{
get
{
string msg;
lock (this)
{
string grainType;
if (grainInterfaceMap.TryGetPrimaryImplementation(className, out grainType))
return grainTypes[grainType];
if (grainTypes.ContainsKey(className))
return grainTypes[className];
if (TypeUtils.IsGenericClass(className))
{
var templateName = TypeUtils.GetRawClassName(className);
if (grainInterfaceMap.TryGetPrimaryImplementation(templateName, out grainType))
templateName = grainType;
if (grainTypes.ContainsKey(templateName))
{
// Found the generic template class
try
{
// Instantiate the specific type from generic template
var genericGrainTypeData = (GenericGrainTypeData)grainTypes[templateName];
Type[] typeArgs = TypeUtils.GenericTypeArgsFromClassName(className);
var concreteTypeData = genericGrainTypeData.MakeGenericType(typeArgs);
// Add to lookup tables for next time
var grainClassName = concreteTypeData.GrainClass;
grainTypes.Add(grainClassName, concreteTypeData);
return concreteTypeData;
}
catch (Exception ex)
{
msg = "Cannot instantiate generic class " + className;
logger.Error(ErrorCode.Runtime_Error_100092, msg, ex);
throw new KeyNotFoundException(msg, ex);
}
}
}
}
msg = "Cannot find GrainTypeData for class " + className;
logger.Error(ErrorCode.Runtime_Error_100093, msg);
throw new TypeLoadException(msg);
}
}
internal void GetTypeInfo(int typeCode, out string grainClass, out PlacementStrategy placement, out MultiClusterRegistrationStrategy activationStrategy, string genericArguments = null)
{
if (!ClusterGrainInterfaceMap.TryGetTypeInfo(typeCode, out grainClass, out placement, out activationStrategy, genericArguments))
throw new OrleansException(String.Format("Unexpected: Cannot find an implementation class for grain interface {0}", typeCode));
}
internal void SetInterfaceMapsBySilo(Dictionary<SiloAddress, GrainInterfaceMap> value)
{
grainInterfaceMapsBySilo = value;
RebuildFullGrainInterfaceMap();
}
internal IReadOnlyList<SiloAddress> GetSupportedSilos(int typeCode)
{
return supportedSilosByTypeCode[typeCode];
}
internal IReadOnlyDictionary<ushort, IReadOnlyList<SiloAddress>> GetSupportedSilos(int typeCode, int ifaceId, IReadOnlyList<ushort> versions)
{
var result = new Dictionary<ushort, IReadOnlyList<SiloAddress>>();
foreach (var version in versions)
{
var silosWithTypeCode = supportedSilosByTypeCode[typeCode];
// We need to sort this so the list of silos returned will
// be the same accross all silos in the cluster
var silosWithCorrectVersion = supportedSilosByInterface[ifaceId][version]
.Intersect(silosWithTypeCode)
.OrderBy(addr => addr)
.ToList();
result[version] = silosWithCorrectVersion;
}
return result;
}
internal IReadOnlyList<ushort> GetAvailableVersions(int ifaceId)
{
return supportedSilosByInterface[ifaceId].Keys.ToList();
}
internal ushort GetLocalSupportedVersion(int ifaceId)
{
return grainInterfaceMap.GetInterfaceVersion(ifaceId);
}
private void InitializeGrainClassData(SiloAssemblyLoader loader)
{
grainTypes = loader.GetGrainClassTypes();
LogManager.GrainTypes = this.grainTypes.Keys.ToList();
}
private void InitializeInvokerMap(SiloAssemblyLoader loader)
{
IEnumerable<KeyValuePair<int, Type>> types = loader.GetGrainMethodInvokerTypes();
foreach (var i in types)
{
int ifaceId = i.Key;
Type type = i.Value;
AddInvokerClass(ifaceId, type);
}
}
private void InitializeInterfaceMap()
{
foreach (GrainTypeData grainType in grainTypes.Values)
AddToGrainInterfaceToClassMap(grainType.Type, grainType.RemoteInterfaceTypes, grainType.IsStatelessWorker);
}
private void AddToGrainInterfaceToClassMap(Type grainClass, IEnumerable<Type> grainInterfaces, bool isUnordered)
{
var placement = GrainTypeData.GetPlacementStrategy(grainClass, this.defaultPlacementStrategy);
var registrationStrategy = this.multiClusterRegistrationStrategyManager.GetMultiClusterRegistrationStrategy(grainClass);
foreach (var iface in grainInterfaces)
{
var isPrimaryImplementor = IsPrimaryImplementor(grainClass, iface);
grainInterfaceMap.AddEntry(iface, grainClass, placement, registrationStrategy, isPrimaryImplementor);
}
if (isUnordered)
grainInterfaceMap.AddToUnorderedList(grainClass);
}
private static bool IsPrimaryImplementor(Type grainClass, Type iface)
{
// If the class name exactly matches the interface name, it is considered the primary (default)
// implementation of the interface, e.g. IFooGrain -> FooGrain
return (iface.Name.Substring(1) == grainClass.Name);
}
public bool TryGetData(string name, out GrainTypeData result)
{
return grainTypes.TryGetValue(name, out result);
}
internal GrainInterfaceMap GetTypeCodeMap()
{
// the map is immutable at this point
return grainInterfaceMap;
}
private void AddInvokerClass(int interfaceId, Type invoker)
{
lock (invokers)
{
if (!invokers.ContainsKey(interfaceId))
invokers.Add(interfaceId, new InvokerData(invoker));
}
}
/// <summary>
/// Returns a list of all graintypes in the system.
/// </summary>
/// <returns></returns>
internal string[] GetGrainTypeList()
{
return grainTypes.Keys.ToArray();
}
internal IGrainMethodInvoker GetInvoker(int interfaceId, string genericGrainType = null)
{
try
{
InvokerData invokerData;
if (invokers.TryGetValue(interfaceId, out invokerData))
return invokerData.GetInvoker(genericGrainType);
}
catch (Exception ex)
{
throw new OrleansException(String.Format("Error finding invoker for interface ID: {0} (0x{0, 8:X8}). {1}", interfaceId, ex), ex);
}
Type type;
var interfaceName = grainInterfaceMap.TryGetServiceInterface(interfaceId, out type) ?
type.FullName : "*unavailable*";
throw new OrleansException(String.Format("Cannot find an invoker for interface {0} (ID={1},0x{1, 8:X8}).",
interfaceName, interfaceId));
}
private void RebuildFullGrainInterfaceMap()
{
var newClusterGrainInterfaceMap = new GrainInterfaceMap(false, this.defaultPlacementStrategy);
var newSupportedSilosByTypeCode = new Dictionary<int, List<SiloAddress>>();
var newSupportedSilosByInterface = new Dictionary<int, Dictionary<ushort, List<SiloAddress>>>();
foreach (var kvp in grainInterfaceMapsBySilo)
{
newClusterGrainInterfaceMap.AddMap(kvp.Value);
foreach (var supportedInterface in kvp.Value.SupportedInterfaces)
{
var ifaceId = supportedInterface.InterfaceId;
var version = supportedInterface.InterfaceVersion;
var supportedSilosByVersion = newSupportedSilosByInterface.GetValueOrAddNew(ifaceId);
var supportedSilosForVersion = supportedSilosByVersion.GetValueOrAddNew(version);
supportedSilosForVersion.Add(kvp.Key);
}
foreach (var grainClassData in kvp.Value.SupportedGrainClassData)
{
var grainType = grainClassData.GrainTypeCode;
var supportedSilos = newSupportedSilosByTypeCode.GetValueOrAddNew(grainType);
supportedSilos.Add(kvp.Key);
}
}
foreach (var silos in newSupportedSilosByTypeCode.Values)
{
// We need to sort this so the list of silos returned will
// be the same accross all silos in the cluster
silos.Sort();
}
ClusterGrainInterfaceMap = newClusterGrainInterfaceMap;
supportedSilosByTypeCode = newSupportedSilosByTypeCode;
supportedSilosByInterface = newSupportedSilosByInterface;
}
private class InvokerData
{
private readonly Type baseInvokerType;
private IGrainMethodInvoker invoker;
private readonly Dictionary<string, IGrainMethodInvoker> cachedGenericInvokers;
private readonly object cachedGenericInvokersLockObj;
public InvokerData(Type invokerType)
{
baseInvokerType = invokerType;
if (invokerType.GetTypeInfo().IsGenericType)
{
cachedGenericInvokers = new Dictionary<string, IGrainMethodInvoker>();
cachedGenericInvokersLockObj = new object(); ;
}
}
public IGrainMethodInvoker GetInvoker(string genericGrainType = null)
{
// if the grain class is non-generic
if (cachedGenericInvokersLockObj == null)
{
return invoker ?? (invoker = (IGrainMethodInvoker)Activator.CreateInstance(baseInvokerType));
}
else
{
lock (cachedGenericInvokersLockObj)
{
if (cachedGenericInvokers.ContainsKey(genericGrainType))
return cachedGenericInvokers[genericGrainType];
}
var typeArgs = TypeUtils.GenericTypeArgsFromArgsString(genericGrainType);
var concreteType = baseInvokerType.MakeGenericType(typeArgs);
var inv = (IGrainMethodInvoker)Activator.CreateInstance(concreteType);
lock (cachedGenericInvokersLockObj)
{
if (!cachedGenericInvokers.ContainsKey(genericGrainType))
cachedGenericInvokers[genericGrainType] = inv;
}
return inv;
}
}
}
}
}
| |
// 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.Net.Sockets;
using System.Net.Tests;
using Xunit;
namespace System.Net.NameResolution.PalTests
{
public class NameResolutionPalTests
{
static NameResolutionPalTests()
{
NameResolutionPal.EnsureSocketsAreInitialized();
}
[Fact]
public void HostName_NotNull()
{
Assert.NotNull(NameResolutionPal.GetHostName());
}
[Fact]
public void GetHostByName_LocalHost()
{
IPHostEntry hostEntry = NameResolutionPal.GetHostByName("localhost");
Assert.NotNull(hostEntry);
Assert.NotNull(hostEntry.HostName);
Assert.NotNull(hostEntry.AddressList);
Assert.NotNull(hostEntry.Aliases);
}
[Fact]
public void GetHostByName_HostName()
{
string hostName = NameResolutionPal.GetHostName();
Assert.NotNull(hostName);
IPHostEntry hostEntry = NameResolutionPal.GetHostByName(hostName);
Assert.NotNull(hostEntry);
Assert.NotNull(hostEntry.HostName);
Assert.NotNull(hostEntry.AddressList);
Assert.NotNull(hostEntry.Aliases);
}
[Fact]
public void GetHostByAddr_LocalHost()
{
Assert.NotNull(NameResolutionPal.GetHostByAddr(new IPAddress(0x0100007f)));
}
[Fact]
public void GetHostByName_LocalHost_GetHostByAddr()
{
IPHostEntry hostEntry1 = NameResolutionPal.GetHostByName("localhost");
Assert.NotNull(hostEntry1);
IPHostEntry hostEntry2 = NameResolutionPal.GetHostByAddr(hostEntry1.AddressList[0]);
Assert.NotNull(hostEntry2);
IPAddress[] list1 = hostEntry1.AddressList;
IPAddress[] list2 = hostEntry2.AddressList;
for (int i = 0; i < list1.Length; i++)
{
Assert.NotEqual(-1, Array.IndexOf(list2, list1[i]));
}
}
[Fact]
public void GetHostByName_HostName_GetHostByAddr()
{
IPHostEntry hostEntry1 = NameResolutionPal.GetHostByName(HttpTestServers.Http2Host);
Assert.NotNull(hostEntry1);
IPAddress[] list1 = hostEntry1.AddressList;
Assert.InRange(list1.Length, 1, Int32.MaxValue);
foreach (IPAddress addr1 in list1)
{
IPHostEntry hostEntry2 = NameResolutionPal.GetHostByAddr(addr1);
Assert.NotNull(hostEntry2);
IPAddress[] list2 = hostEntry2.AddressList;
Assert.InRange(list2.Length, 1, list1.Length);
foreach (IPAddress addr2 in list2)
{
Assert.NotEqual(-1, Array.IndexOf(list1, addr2));
}
}
}
[Fact]
public void TryGetAddrInfo_LocalHost()
{
IPHostEntry hostEntry;
int nativeErrorCode;
SocketError error = NameResolutionPal.TryGetAddrInfo("localhost", out hostEntry, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(hostEntry);
Assert.NotNull(hostEntry.HostName);
Assert.NotNull(hostEntry.AddressList);
Assert.NotNull(hostEntry.Aliases);
}
[Fact]
public void TryGetAddrInfo_HostName()
{
string hostName = NameResolutionPal.GetHostName();
Assert.NotNull(hostName);
IPHostEntry hostEntry;
int nativeErrorCode;
SocketError error = NameResolutionPal.TryGetAddrInfo(hostName, out hostEntry, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(hostEntry);
Assert.NotNull(hostEntry.HostName);
Assert.NotNull(hostEntry.AddressList);
Assert.NotNull(hostEntry.Aliases);
}
[Fact]
public void TryGetNameInfo_LocalHost_IPv4()
{
SocketError error;
int nativeErrorCode;
string name = NameResolutionPal.TryGetNameInfo(new IPAddress(new byte[] { 127, 0, 0, 1 }), out error, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(name);
}
[Fact]
public void TryGetNameInfo_LocalHost_IPv6()
{
SocketError error;
int nativeErrorCode;
string name = NameResolutionPal.TryGetNameInfo(new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }), out error, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(name);
}
[Fact]
public void TryGetAddrInfo_LocalHost_TryGetNameInfo()
{
IPHostEntry hostEntry;
int nativeErrorCode;
SocketError error = NameResolutionPal.TryGetAddrInfo("localhost", out hostEntry, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(hostEntry);
string name = NameResolutionPal.TryGetNameInfo(hostEntry.AddressList[0], out error, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(name);
}
[Fact]
public void TryGetAddrInfo_HostName_TryGetNameInfo()
{
string hostName = NameResolutionPal.GetHostName();
Assert.NotNull(hostName);
IPHostEntry hostEntry;
int nativeErrorCode;
SocketError error = NameResolutionPal.TryGetAddrInfo(hostName, out hostEntry, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(hostEntry);
string name = NameResolutionPal.TryGetNameInfo(hostEntry.AddressList[0], out error, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(name);
}
[Fact]
public void TryGetNameInfo_LocalHost_IPv4_TryGetAddrInfo()
{
SocketError error;
int nativeErrorCode;
string name = NameResolutionPal.TryGetNameInfo(new IPAddress(new byte[] { 127, 0, 0, 1 }), out error, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(name);
IPHostEntry hostEntry;
error = NameResolutionPal.TryGetAddrInfo(name, out hostEntry, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(hostEntry);
}
[Fact]
public void TryGetNameInfo_LocalHost_IPv6_TryGetAddrInfo()
{
SocketError error;
int nativeErrorCode;
string name = NameResolutionPal.TryGetNameInfo(new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }), out error, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(name);
IPHostEntry hostEntry;
error = NameResolutionPal.TryGetAddrInfo(name, out hostEntry, out nativeErrorCode);
Assert.Equal(SocketError.Success, error);
Assert.NotNull(hostEntry);
}
}
}
| |
using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
namespace Netron.Lithium
{
/// <summary>
/// Base class for shapes
/// </summary>
public class ShapeBase : Entity
{
#region Fields
/// <summary>
/// the rectangle on which any shape lives
/// </summary>
protected internal Rectangle rectangle;
/// <summary>
/// the backcolor of the shapes
/// </summary>
protected Color shapeColor = Color.SteelBlue;
/// <summary>
/// the brush corresponding to the backcolor
/// </summary>
protected Brush shapeBrush;
/// <summary>
/// the text on the shape
/// </summary>
protected string text = string.Empty;
/// <summary>
/// whether this shape if the root
/// </summary>
protected bool isRoot = false;
/// <summary>
/// the child nodes collection
/// </summary>
protected internal ShapeCollection childNodes;
/// <summary>
/// used to drag child nodes
/// </summary>
protected internal bool pickup = false;
/// <summary>
/// points to the unique parent of this shape, unless it's the root and then Null
/// </summary>
protected internal ShapeBase parentNode = null;
/// <summary>
/// whether the shape is expanded
/// If expanded, all the child nodes will have visible=true and vice versa
/// </summary>
protected internal bool expanded = false;
/// <summary>
/// this is the unique link to the parent unless this shape is the root
/// </summary>
protected internal Connection connection = null;
/// <summary>
/// used by the visiting pattern and tags whether this shape has been visited already
/// </summary>
protected internal bool visited = false;
/// <summary>
/// the level of the shape in the hierarchy
/// </summary>
protected internal int level = -1;
#endregion
#region Properties
/// <summary>
/// Gets or sets the child node collection of this shape
/// </summary>
[Browsable(false)]
public ShapeCollection ChildNodes
{
get{return childNodes;}
set{childNodes = value;}
}
/// <summary>
/// Gets or sets whether this is the root of the diagram
/// </summary>
[Browsable(false)]
public bool IsRoot
{
get{return isRoot;}
set{isRoot = value;}
}
/// <summary>
/// Gets the level of the shape in the hierarchy
/// </summary>
public int Level
{
get{return level;}
}
/// <summary>
/// Gets or sets the width of the shape
/// </summary>
[Browsable(true), Description("The width of the shape"), Category("Layout")]
[GraphData]
public int Width
{
get{return rectangle.Width;}
set{
Resize(value,Height);
site.DrawTree();
site.Invalidate();
}
}
/// <summary>
/// Gets or sets the height of the shape
/// </summary>
[Browsable(true), Description("The height of the shape"), Category("Layout")]
[GraphData]
public int Height
{
get{return this.rectangle.Height;}
set{
Resize(this.Width,value);
site.DrawTree();
site.Invalidate();
}
}
/// <summary>
/// Gets or sets the text of the shape
/// </summary>
[Browsable(true), Description("The text shown on the shape"), Category("Layout")]
[GraphData]
public string Text
{
get{return text;}
set{text = value;
Fit();
site.DrawTree();
site.Invalidate();
}
}
/// <summary>
/// the x-coordinate of the upper-left corner
/// </summary>
[Browsable(false), Description("The x-coordinate of the upper-left corner"), Category("Layout")]
[GraphData]
public int X
{
get{return rectangle.X;}
set{
Point p = new Point(value - rectangle.X, rectangle.Y);
this.Move(p);
site.Invalidate(); //note that 'this.Invalidate()' will not be enough
}
}
/// <summary>
/// the y-coordinate of the upper-left corner
/// </summary>
[Browsable(false), Description("The y-coordinate of the upper-left corner"), Category("Layout")]
[GraphData]
public int Y
{
get{return rectangle.Y;}
set{
Point p = new Point(rectangle.X, value - rectangle.Y);
this.Move(p);
site.Invalidate();
}
}
/// <summary>
/// The backcolor of the shape
/// </summary>
[Browsable(true), Description("The backcolor of the shape"), Category("Layout")]
[GraphData]
public Color ShapeColor
{
get{return shapeColor;}
set{shapeColor = value; SetBrush(); Invalidate();}
}
/// <summary>
/// Gets or sets whether the shape is visible
/// </summary>
[Browsable(false), GraphData]
public bool Visible
{
get{return visible;}
set{visible = value;}
}
/// <summary>
/// Gets or sets whether the shape is expanded/collapsed
/// </summary>
[Browsable(false), GraphData]
public bool Expanded
{
get{return expanded;}
set{expanded = value;}
}
/// <summary>
/// Gets the (unique) parent node of this shape
/// Null if this is the root
/// </summary>
[Browsable(false), GraphData]
public ShapeBase ParentNode
{
get{return parentNode;}
}
/// <summary>
/// Gets or sets the location of the shape;
/// </summary>
[Browsable(false)]
public Point Location
{
get{return new Point(this.rectangle.X,this.rectangle.Y);}
set{
//we use the move method but it requires the delta value, not an absolute position!
Point p = new Point(value.X-rectangle.X,value.Y-rectangle.Y);
//if you'd use this it would indeed move the shape but not the connector s of the shape
//this.rectangle.X = value.X; this.rectangle.Y = value.Y; Invalidate();
this.Move(p);
}
}
/// <summary>
/// Gets the left coordiante of the rectangle
/// </summary>
[Browsable(false)]
public int Left
{
get{return this.rectangle.Left;}
}
/// <summary>
/// Gets the right coordiante of the rectangle
/// </summary>
[Browsable(false)]
public int Right
{
get{return this.rectangle.Right;}
}
/// <summary>
/// Get the bottom coordinate of the shape
/// </summary>
[Browsable(false)]
public int Bottom
{
get{return this.rectangle.Bottom;}
}
/// <summary>
/// Gets the top coordinate of the rectangle
/// </summary>
[Browsable(false)]
public int Top
{
get{return this.rectangle.Top;}
}
#endregion
#region Constructor
/// <summary>
/// Default ctor
/// </summary>
public ShapeBase()
{
Init();
}
/// <summary>
/// Constructor with the site of the shape
/// </summary>
/// <param name="site">the graphcontrol instance to which the shape is attached</param>
public ShapeBase(LithiumControl site) : base(site)
{
Init();
}
#endregion
#region Methods
/// <summary>
/// Resizes the shape's rectangle in function of the containing text
/// </summary>
public void Fit()
{
Graphics g = Graphics.FromHwnd(site.Handle);
Size s = Size.Round(g.MeasureString(text,Font));
//if(childNodes.Count>0)
//rectangle.Width =s.Width +10 + this.childNodes.Count.ToString().Length*5 +5; //the last part is to addition for the '[child count]' part
//else
rectangle.Width =s.Width +10;
rectangle.Height = s.Height+8;
Invalidate();
}
/// <summary>
/// Expand the children, if any
/// </summary>
public void Expand()
{
expanded = true;
visible = true;
for(int k =0; k<childNodes.Count;k++)
{
childNodes[k].visible = true;
childNodes[k].connection.visible = true;
if(childNodes[k].expanded) childNodes[k].Expand();
}
}
/// <summary>
/// Collapses the children underneath this shape
/// </summary>
/// <param name="change">true to set the expanded field to true</param>
public void Collapse(bool change)
{
if(change) expanded = false;
for(int k =0; k<childNodes.Count;k++)
{
childNodes[k].visible = false;
childNodes[k].connection.visible = false;
if(childNodes[k].expanded) childNodes[k].Collapse(false);
}
}
/// <summary>
/// Adds a child to this shape
/// </summary>
/// <param name="text">the text of the newly created shape</param>
/// <returns>the create shape</returns>
public ShapeBase AddChild(string text)
{
SimpleRectangle shape = new SimpleRectangle(site);
shape.Location = new Point(Width/2+50,Height/2+50);
shape.Width = 50;
shape.Height = 25;
shape.Text = text;
shape.ShapeColor = Color.Linen;
shape.IsRoot = false;
shape.parentNode = this;
shape.Font = font;
shape.level = level+1;
shape.Fit(); //fit the child
//add to the collections
site.graphAbstract.Shapes.Add(shape);
this.childNodes.Add(shape);
//add a connection; From=child, To=parent
Connection con = new Connection(shape, this);
site.Connections.Add(con);
con.site = this.site;
con.visible = true;
shape.connection = con;
if(visible)
Expand();
else
{
shape.visible = false;
con.visible = false;
}
Fit(); //the cild count added at the end will enlarge the rectangle, so we have to fit
return shape;
}
/// <summary>
/// Summarizes the initialization used by the constructors
/// </summary>
private void Init()
{
rectangle = new Rectangle(0,0,100,70);
childNodes = new ShapeCollection();
SetBrush();
}
/// <summary>
/// Sets the brush corresponding to the backcolor
/// </summary>
protected void SetBrush()
{
if(isSelected)
shapeBrush = new SolidBrush(Color.YellowGreen);
else
shapeBrush = new SolidBrush(shapeColor);
}
/// <summary>
/// Overrides the abstract paint method
/// </summary>
/// <param name="g">a graphics object onto which to paint</param>
public override void Paint(System.Drawing.Graphics g)
{
return;
}
/// <summary>
/// Override the abstract Hit method
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
public override bool Hit(System.Drawing.Point p)
{
return false;
}
/// <summary>
/// Overrides the abstract Invalidate method
/// </summary>
public override void Invalidate()
{
site.Invalidate(rectangle);
}
/// <summary>
/// Moves the shape with the given shift
/// </summary>
/// <param name="p">represent a shift-vector, not the absolute position!</param>
public override void Move(Point p)
{
this.rectangle.X += p.X;
this.rectangle.Y += p.Y;
this.Invalidate();
}
/// <summary>
/// Resizes the shape
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
public virtual void Resize(int width, int height)
{
this.rectangle.Height = height;
this.rectangle.Width = width;
this.site.Invalidate();
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace DynThings.WebPortal.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
public class AndroidNativeUtility : SA.Common.Pattern.Singleton<AndroidNativeUtility> {
//Actions
public static event Action<AN_PackageCheckResult> OnPackageCheckResult = delegate{};
public static event Action<string> OnAndroidIdLoaded = delegate{};
public static event Action<string> InternalStoragePathLoaded = delegate{};
public static event Action<string> ExternalStoragePathLoaded = delegate{};
public static event Action<AN_Locale> LocaleInfoLoaded = delegate{};
public static event Action<string[]> ActionDevicePackagesListLoaded = delegate{};
public static event Action<AN_NetworkInfo> ActionNetworkInfoLoaded = delegate{};
public static event Action<AN_RefreshTokenResult> OnOAuthRefreshTokenLoaded = delegate {};
public static event Action<AN_AccessTokenResult> OnOAuthAccessTokenLoaded = delegate {};
public static event Action<AN_DeviceCodeResult> OnDeviceCodeLoaded = delegate {};
private string _redirectUrl = string.Empty;
private string _clientId = string.Empty;
private string _clientSecret = string.Empty;
//--------------------------------------
// Init
//--------------------------------------
void Awake() {
DontDestroyOnLoad(gameObject);
}
//--------------------------------------
// Public Methods
//--------------------------------------
public void GenerateRefreshToken(string redirectUrl, string clientId, string clientSecret) {
_redirectUrl = redirectUrl;
_clientId = clientId;
_clientSecret = clientSecret;
AndroidNative.GenerateRefreshToken (_redirectUrl, _clientId);
}
public void RefreshOAuthToken(string refreshToken, string clientId, string clientSecret) {
StartCoroutine(RefreshOAuthTokenRequest(clientId, clientSecret, refreshToken));
}
public void ObtainUserDeviceCode(string clientId) {
StartCoroutine (ObtainUserDeviceCodeRequest (clientId));
}
public void CheckIsPackageInstalled(string packageName) {
AndroidNative.isPackageInstalled(packageName);
}
public void StartApplication(string bundle) {
AndroidNative.runPackage(bundle);
}
public void StartApplication(string packageName, Dictionary<string, string> extras) {
StringBuilder builder = new StringBuilder();
foreach (KeyValuePair<string, string> extra in extras) {
builder.AppendFormat("{0}{1}{2}", extra.Key, AndroidNative.DATA_SPLITTER, extra.Value);
builder.Append(AndroidNative.DATA_SPLITTER2);
}
builder.Append(AndroidNative.DATA_EOF);
Debug.Log("[StartApplication] with Extras " + builder.ToString());
AndroidNative.LaunchApplication(packageName, builder.ToString());
}
public void LoadAndroidId() {
AndroidNative.LoadAndroidId();
}
public void GetInternalStoragePath() {
AndroidNative.GetInternalStoragePath();
}
public void GetExternalStoragePath() {
AndroidNative.GetExternalStoragePath();
}
public string GetExternalStoragePublicDirectory(AN_ExternalStorageType type) {
return AndroidNative.GetExternalStoragePublicDirectory(type.ToString());
}
public void LoadLocaleInfo() {
AndroidNative.LoadLocaleInfo();
}
public void LoadPackagesList() {
AndroidNative.LoadPackagesList();
}
public void LoadNetworkInfo() {
AndroidNative.LoadNetworkInfo();
}
//--------------------------------------
// Static Methods
//--------------------------------------
public static void OpenSettingsPage(string action) {
AndroidNative.OpenSettingsPage(action);
}
public static void ShowPreloader(string title, string message) {
AN_PoupsProxy.ShowPreloader(title, message, AndroidNativeSettings.Instance.DialogTheme);
}
public static void ShowPreloader(string title, string message, AndroidDialogTheme theme) {
AN_PoupsProxy.ShowPreloader(title, message, AndroidNativeSettings.Instance.DialogTheme);
}
public static void HidePreloader() {
AN_PoupsProxy.HidePreloader();
}
public static void OpenAppRatingPage(string url) {
AN_PoupsProxy.OpenAppRatePage(url);
}
public static void RedirectToGooglePlayRatingPage(string url) {
OpenAppRatingPage(url);
}
public static void HideCurrentPopup() {
AN_PoupsProxy.HideCurrentPopup();
}
public static int SDKLevel {
get {
#if UNITY_ANDROID
var clazz = AndroidJNI.FindClass("android.os.Build$VERSION");
var fieldID = AndroidJNI.GetStaticFieldID(clazz, "SDK_INT", "I");
var sdkLevel = AndroidJNI.GetStaticIntField(clazz, fieldID);
return sdkLevel;
#else
return 0;
#endif
}
}
public static void InvitePlusFriends() {
AndroidNative.InvitePlusFriends();
}
//--------------------------------------
// Event Handlers
//--------------------------------------
private void RefreshTokenCodeReceived(string data) {
Debug.Log (data);
string[] rawData = data.Split (new string[] { "|" }, StringSplitOptions.None);
int status = Int32.Parse (rawData [0]);
if (status == 1) {
StartCoroutine (GenerateRefreshTokenRequest (rawData [1], _clientId, _clientSecret, _redirectUrl));
} else {
AN_RefreshTokenResult result = new AN_RefreshTokenResult ("Request Authorization Code error");
OnOAuthRefreshTokenLoaded (result);
}
}
private IEnumerator GenerateRefreshTokenRequest(string code, string clientId, string clientSecret, string redirectUrl) {
WWWForm requestForm = new WWWForm ();
requestForm.AddField ("grant_type", "authorization_code");
requestForm.AddField ("code", code);
requestForm.AddField ("client_id", clientId);
requestForm.AddField ("client_secret", clientSecret);
requestForm.AddField ("redirect_uri", redirectUrl);
WWW response = new WWW ("https://accounts.google.com/o/oauth2/token", requestForm);
yield return response;
if (string.IsNullOrEmpty (response.error)) {
Dictionary<string, object> data = ANMiniJSON.Json.Deserialize (response.text) as Dictionary<string, object>;
string access_token = data.ContainsKey ("access_token") ? data ["access_token"].ToString () : string.Empty;
string refresh_token = data.ContainsKey ("refresh_token") ? data ["refresh_token"].ToString () : string.Empty;
string token_type = data.ContainsKey ("token_type") ? data ["token_type"].ToString () : string.Empty;
long expiresIn = data.ContainsKey ("expires_in") ? (long)data ["expires_in"] : 0L;
AN_RefreshTokenResult result = new AN_RefreshTokenResult (access_token, refresh_token, token_type, expiresIn);
OnOAuthRefreshTokenLoaded (result);
} else {
AN_RefreshTokenResult result = new AN_RefreshTokenResult (response.error);
OnOAuthRefreshTokenLoaded (result);
}
}
private IEnumerator RefreshOAuthTokenRequest(string clientId, string clientSecret, string refreshToken) {
WWWForm requestForm = new WWWForm ();
requestForm.AddField ("grant_type", "refresh_token");
requestForm.AddField ("client_id", clientId);
requestForm.AddField ("client_secret", clientSecret);
requestForm.AddField ("refresh_token", refreshToken);
WWW response = new WWW ("https://accounts.google.com/o/oauth2/token", requestForm);
yield return response;
if (string.IsNullOrEmpty (response.error)) {
Dictionary<string, object> data = ANMiniJSON.Json.Deserialize (response.text) as Dictionary<string, object>;
string access_token = data.ContainsKey ("access_token") ? data ["access_token"].ToString () : string.Empty;
string token_type = data.ContainsKey ("token_type") ? data ["token_type"].ToString () : string.Empty;
long expiresIn = data.ContainsKey ("expires_in") ? (long)data ["expires_in"] : 0L;
AN_AccessTokenResult result = new AN_AccessTokenResult (access_token, token_type, expiresIn);
OnOAuthAccessTokenLoaded (result);
} else {
AN_AccessTokenResult result = new AN_AccessTokenResult (response.error);
OnOAuthAccessTokenLoaded (result);
}
}
private IEnumerator ObtainUserDeviceCodeRequest(string clientId) {
WWWForm requestForm = new WWWForm ();
requestForm.AddField ("client_id", clientId);
requestForm.AddField ("scope", "email profile");
WWW response = new WWW ("https://accounts.google.com/o/oauth2/device/code", requestForm);
yield return response;
Debug.Log (response.text);
if (string.IsNullOrEmpty (response.error)) {
Dictionary<string, object> data = ANMiniJSON.Json.Deserialize (response.text) as Dictionary<string, object>;
string device_code = data.ContainsKey ("device_code") ? data ["device_code"].ToString () : string.Empty;
string user_code = data.ContainsKey ("user_code") ? data ["user_code"].ToString () : string.Empty;
string verification_url = data.ContainsKey ("verification_url") ? data ["verification_url"].ToString () : string.Empty;
long expires_in = data.ContainsKey ("expires_in") ? (long)data ["expires_in"] : 0L;
long interval = data.ContainsKey ("interval") ? (long)data ["interval"] : 0L;
AN_DeviceCodeResult result = new AN_DeviceCodeResult (device_code, user_code, verification_url, expires_in, interval);
OnDeviceCodeLoaded (result);
} else {
AN_DeviceCodeResult result = new AN_DeviceCodeResult (response.error);
OnDeviceCodeLoaded (result);
}
}
private void OnAndroidIdLoadedEvent(string id) {
OnAndroidIdLoaded(id);
}
private void OnPacakgeFound(string packageName) {
AN_PackageCheckResult result = new AN_PackageCheckResult(packageName);
OnPackageCheckResult(result);
}
private void OnPacakgeNotFound(string packageName) {
AN_PackageCheckResult result = new AN_PackageCheckResult(packageName, new SA.Common.Models.Error(0, "Pacakge not Found"));
OnPackageCheckResult(result);
}
private void OnExternalStoragePathLoaded(string path) {
ExternalStoragePathLoaded(path);
}
private void OnInternalStoragePathLoaded(string path) {
InternalStoragePathLoaded(path);
}
private void OnLocaleInfoLoaded(string data) {
string[] storeData;
storeData = data.Split(AndroidNative.DATA_SPLITTER [0]);
AN_Locale locale = new AN_Locale();
locale.CountryCode = storeData[0];
locale.DisplayCountry = storeData[1];
locale.LanguageCode = storeData[2];
locale.DisplayLanguage = storeData[3];
LocaleInfoLoaded(locale);
}
private void OnPackagesListLoaded(string data) {
string[] storeData;
storeData = data.Split(AndroidNative.DATA_SPLITTER [0]);
ActionDevicePackagesListLoaded(storeData);
}
private void OnNetworkInfoLoaded (string data) {
string[] storeData;
storeData = data.Split(AndroidNative.DATA_SPLITTER [0]);
AN_NetworkInfo info = new AN_NetworkInfo();
info.SubnetMask = storeData[0];
info.IpAddress = storeData[1];
info.MacAddress = storeData[2];
info.SSID = storeData[3];
info.BSSID = storeData[4];
info.LinkSpeed = System.Convert.ToInt32(storeData[5]);
info.NetworkId = System.Convert.ToInt32(storeData[6]);
ActionNetworkInfoLoaded(info);
}
}
| |
namespace PlayFab.Sockets.Models
{
using System;
using System.Collections.Generic;
using PlayFab;
using SharedModels;
[Serializable]
public class GetConnectionInfoRequest : PlayFabRequestCommon { }
[Serializable]
public class GetConnectionInfoResponse : PlayFabResultCommon
{
public string AccessToken = "";
public string Url = "";
}
[Serializable]
public class SubscribeRequest
{
public Topic Topic { get; set; }
}
[Serializable]
public class UnsubscribeRequest
{
public Topic Topic { get; set; }
}
[Serializable]
public class PlayFabNetworkMessage
{
public Event @event { get; set; }
public T ReadMessage<T>()
{
var json = PlayFab.PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer);
return json.DeserializeObject<T>(@event.payload);
}
}
[Serializable]
public class Topic
{
public EntityKey Entity { get; set; }
public EventFullName FullName { get; set; }
//public override string ToString()
//{
// return $"{EventNamespace}-{EventName}-{Entity}";
//}
public override bool Equals(object topic)
{
var internalTopic = topic as Topic;
if (internalTopic == null)
return false;
return internalTopic.FullName.Namespace == this.FullName.Namespace &&
internalTopic.FullName.Name == this.FullName.Name &&
internalTopic.Entity.Id == this.Entity.Id &&
internalTopic.Entity.Type == this.Entity.Type;
}
public override int GetHashCode()
{
return (this.Entity.Id +
this.Entity.Type +
this.FullName.Namespace +
this.FullName.Name).GetHashCode();
}
}
public class EntityKey
{
public string Type { get; set; }
public string Id { get; set; }
}
public class PubSubResponse
{
/// <summary>
/// HTTP Response Int
/// </summary>
public int code;
public object content;
}
public class PubSubJsonError
{
/// <summary>
/// HTTP Response Int
/// </summary>
public int code;
/// <summary>
/// HTTP Response Name
/// </summary>
public string status;
public string error;
/// <summary>
/// GenericErrorCodes Int
/// </summary>
/// won't be used, mainly for server side consistency
public int errorCode;
/// <summary>
/// GenericErrorCodes Name
/// </summary>
/// won't be used, mainly for server side consistency
public string errorMessage;
/// won't be used, mainly for server side consistency
public string errorHash;
// mapping of parameter name to error messages
public Dictionary<string, string[]> errorDetails = null;
}
public class PubSubJsonSuccess<TResponseType> where TResponseType : class
{
/// <summary>
/// HTTP Response Int
/// </summary>
public int code;
/// <summary>
/// HTTP Response Name
/// </summary>
public string status;
public TResponseType data;
}
public class PubSubServiceException : Exception
{
public string[] requestIds;
public PubSubServiceException(string message, string[] requestIds)
: base(message)
{
this.requestIds = requestIds;
}
}
[Serializable]
public enum ErrorStates
{
Ok = 0,
Retry30S = 30,
Retry5M = 300,
Retry10M = 600,
Retry15M = 900,
Cancelled = -1
}
public class ErrorStrings
{
public const string MissingConnectionInfo =
"Attempted to create a HubConnection without ConnectionInfo. Make sure that is called and completed first.";
public const string MustBeConnectedSubscribe = "You must be connected to subscribe";
public const string MustBeConnectedUnSubscribe = "You must be connected to subscribe";
}
public class Endpoints
{
public const string GetConnectionInfo = "/PubSub/GetConnectionInfo";
}
[Serializable]
public class Event
{
public const string CurrentSchemaVersion = "2.0.1";
/// <summary>
/// PlayStream event format version, following a semantic versioning scheme.
/// This covers only the format of the common event structure as defined here,
/// not the payload formats of specific events.
/// </summary>
public string schemaVersion { get; set; }
/// <summary>
/// Combination of a namespace and name, which fully specify the event type.
/// </summary>
public EventFullName fullName { get; set; }
/// <summary>
/// Globally unique identifier for the event. Assigned by PlayFab when first generated or received.
/// E.g. A0D1FE18136243E8BAE86BC76C5AD5EA
/// </summary>
public string id { get; set; }
/// <summary>
/// UTC time that the event was written to PlayStream.
/// For events originating outside of PlayFab, such as those posted to the WriteEvents API,
/// this is the server time when PlayFab received the event.
/// </summary>
public DateTime timestamp { get; set; }
/// <summary>
/// The primary entity associated with the event.
/// </summary>
public EntityKey entity { get; set; }
/// <summary>
/// Entity that initiated the event.
/// Matches the Owner entity when an entity updates a resource in its own profile.
/// </summary>
public EntityKey originator { get; set; }
/// <summary>
/// An optional field containing info about events originating outside of PlayFab.
/// </summary>
public OriginInfo originInfo { get; set; }
/// <summary>
/// Arbitrary data associated with the event.
/// The format of the string is indicated by PayloadContentType.
/// The schema of the payload data varies depending on the FullName of event and is not
/// necessarily known by PlayFab. It may contain arbitrary JSON with nested objects and arrays,
/// Base64 encoded Protocol Buffer binary serialized objects, etc.
/// </summary>
public string payload { get; set; }
/// <summary>
/// A property bag of lineage information about the primary entity associated with this event.
/// The keys are entity types e.g. namespace, title. The values are the corresponding Id's e.g. namespace Id, title Id.
/// </summary>
public EntityLineage entityLineage { get; set; }
/// <summary>
/// Media Type of the Payload
///
/// Examples:
/// 'JSON' (default)
/// 'Base64' (binary, e.g. Protocol Buffers)
/// </summary>
public PayloadContentType payloadContentType { get; set; }
public static string GenerateEventId()
{
return Guid.NewGuid().ToString("N");
}
}
public static class EventExtensions
{
public static Topic GetTopic(this Event @event)
{
return new Topic()
{
Entity = @event.entity,
FullName = @event.fullName
};
}
}
[Serializable]
public class EventFullName
{
/// <summary>
/// Namespace of the event, which scopes the meaning of the Name. The first part of the Namespace
/// is a standard namespace. For custom events this is always "custom". Optionally, this
/// top-level namespace may be followed by additional '.' delimited values to form a sub-categorization.
/// E.g. "com.playfab.events.files" or "org.example.schema1".
/// </summary>
public string Namespace { get; set; }
/// <summary>
/// Name of the event, unique within the Namespace, indicating the "type" or "meaning" of the event
/// as well as the format of its payload, if any. E.g. "file_updated"
/// </summary>
public string Name { get; set; }
/*
public EventFullName(string ns, string name)
{
Namespace = ns;
Name = name;
}*/
public override string ToString()
{
return $"{Namespace}.{Name}";
}
}
[Serializable]
public class OriginInfo
{
/// <summary>
/// An optional identifier assigned to events originating outside of PlayFab.
/// For example, a client might assign IDs to events locally, before it posts them to the WriteEvents API.
/// It is recommended that values of this property be globally unique, but uniqueness is not
/// enforced by PlayFab.
/// </summary>
public string Id { get; set; }
/// <summary>
/// An optional UTC timestamp assigned to events originating outside of PlayFab.
/// For example, a client might record timestamps for events locally, before it posts them to the WriteEvents API.
/// </summary>
public DateTime Timestamp { get; set; }
///// <summary>
///// Optional name/value pairs supplied by caller of the API which generated the event.
///// This can be used to capture details such as client version, flight, etc.
///// </summary>
////[StringDictionaryCountAndLength(5, 25, 25)]
//[ProtoMember(9)]
//public Dictionary<string, string> Tags { get; set; }
public OriginInfo() { }
public OriginInfo(string id, DateTime timestamp)
{
Id = id;
Timestamp = timestamp;
}
}
[Serializable]
public enum PayloadContentType
{
JSON,
Base64,
}
[Serializable]
public sealed class EntityLineage : Dictionary<string, string>
{
public EntityLineage(params EntityKey[] ancestors)
: base(ancestors.Length)
{
foreach (EntityKey ancestor in ancestors)
{
Add(ancestor.Type, ancestor.Id);
}
}
public EntityLineage() { }
}
}
| |
//
// MassStorageSource.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2008 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.Unix;
using Hyena;
using Hyena.Collections;
using Banshee.IO;
using Banshee.Dap;
using Banshee.Base;
using Banshee.ServiceStack;
using Banshee.Library;
using Banshee.Sources;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Hardware;
using Banshee.Playlists.Formats;
using Banshee.Playlist;
namespace Banshee.Dap.MassStorage
{
public class MassStorageSource : DapSource
{
private Banshee.Collection.Gui.ArtworkManager artwork_manager
= ServiceManager.Get<Banshee.Collection.Gui.ArtworkManager> ();
private MassStorageDevice ms_device;
private IVolume volume;
private IUsbDevice usb_device;
public override void DeviceInitialize (IDevice device)
{
base.DeviceInitialize (device);
volume = device as IVolume;
if (volume == null || (usb_device = volume.ResolveRootUsbDevice ()) == null) {
throw new InvalidDeviceException ();
}
ms_device = DeviceMapper.Map (this);
try {
if (!ms_device.LoadDeviceConfiguration ()) {
ms_device = null;
}
} catch {
ms_device = null;
}
if (!HasMediaCapabilities && ms_device == null) {
throw new InvalidDeviceException ();
}
// Ignore iPods, except ones with .is_audio_player files
if (MediaCapabilities != null && MediaCapabilities.IsType ("ipod")) {
if (ms_device != null && ms_device.HasIsAudioPlayerFile) {
Log.Information (
"Mass Storage Support Loading iPod",
"The USB mass storage audio player support is loading an iPod because it has an .is_audio_player file. " +
"If you aren't running Rockbox or don't know what you're doing, things might not behave as expected."
);
} else {
throw new InvalidDeviceException ();
}
}
Name = ms_device == null ? volume.Name : ms_device.Name;
mount_point = volume.MountPoint;
Initialize ();
if (ms_device != null) {
ms_device.SourceInitialize ();
}
AddDapProperties ();
// TODO differentiate between Audio Players and normal Disks, and include the size, eg "2GB Audio Player"?
//GenericName = Catalog.GetString ("Audio Player");
}
private void AddDapProperties ()
{
if (AudioFolders.Length > 0 && !String.IsNullOrEmpty (AudioFolders[0])) {
AddDapProperty (String.Format (
Catalog.GetPluralString ("Audio Folder", "Audio Folders", AudioFolders.Length), AudioFolders.Length),
System.String.Join ("\n", AudioFolders)
);
}
if (VideoFolders.Length > 0 && !String.IsNullOrEmpty (VideoFolders[0])) {
AddDapProperty (String.Format (
Catalog.GetPluralString ("Video Folder", "Video Folders", VideoFolders.Length), VideoFolders.Length),
System.String.Join ("\n", VideoFolders)
);
}
if (FolderDepth != -1) {
AddDapProperty (Catalog.GetString ("Required Folder Depth"), FolderDepth.ToString ());
}
AddYesNoDapProperty (Catalog.GetString ("Supports Playlists"), PlaylistTypes.Count > 0);
/*if (AcceptableMimeTypes.Length > 0) {
AddDapProperty (String.Format (
Catalog.GetPluralString ("Audio Format", "Audio Formats", PlaybackFormats.Length), PlaybackFormats.Length),
System.String.Join (", ", PlaybackFormats)
);
}*/
}
private DatabaseImportManager importer;
// WARNING: This will be called from a thread!
protected override void LoadFromDevice ()
{
importer = new DatabaseImportManager (this);
importer.KeepUserJobHidden = true;
importer.Threaded = false; // We are already threaded
importer.Finished += OnImportFinished;
foreach (string audio_folder in BaseDirectories) {
importer.Enqueue (audio_folder);
}
}
private void OnImportFinished (object o, EventArgs args)
{
importer.Finished -= OnImportFinished;
if (!CanSyncPlaylists) {
return;
}
Hyena.Data.Sqlite.HyenaSqliteCommand insert_cmd = new Hyena.Data.Sqlite.HyenaSqliteCommand (
"INSERT INTO CorePlaylistEntries (PlaylistID, TrackID) VALUES (?, ?)");
int [] psources = new int [] {DbId};
foreach (string playlist_path in PlaylistFiles) {
IPlaylistFormat loaded_playlist = PlaylistFileUtil.Load (playlist_path, new Uri (BaseDirectory));
if (loaded_playlist == null)
continue;
PlaylistSource playlist = new PlaylistSource (System.IO.Path.GetFileNameWithoutExtension (playlist_path), this);
playlist.Save ();
//Hyena.Data.Sqlite.HyenaSqliteCommand.LogAll = true;
foreach (Dictionary<string, object> element in loaded_playlist.Elements) {
string track_path = (element["uri"] as Uri).LocalPath;
int track_id = DatabaseTrackInfo.GetTrackIdForUri (new SafeUri (track_path), psources);
if (track_id == 0) {
Log.DebugFormat ("Failed to find track {0} in DAP library to load it into playlist {1}", track_path, playlist_path);
} else {
ServiceManager.DbConnection.Execute (insert_cmd, playlist.DbId, track_id);
}
}
//Hyena.Data.Sqlite.HyenaSqliteCommand.LogAll = false;
playlist.UpdateCounts ();
AddChildSource (playlist);
}
}
public override void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, BatchUserJob job)
{
if (track.PrimarySourceId == DbId) {
Banshee.IO.File.Copy (track.Uri, uri, false);
}
}
public override void Import ()
{
LibraryImportManager importer = new LibraryImportManager (true);
foreach (string audio_folder in BaseDirectories) {
importer.Enqueue (audio_folder);
}
}
public IVolume Volume {
get { return volume; }
}
public IUsbDevice UsbDevice {
get { return usb_device; }
}
private string mount_point;
public override string BaseDirectory {
get { return mount_point; }
}
protected override IDeviceMediaCapabilities MediaCapabilities {
get {
return ms_device ?? (
volume.Parent == null
? base.MediaCapabilities
: volume.Parent.MediaCapabilities ?? base.MediaCapabilities
);
}
}
#region Properties and Methods for Supporting Syncing of Playlists
private string playlists_path;
private string PlaylistsPath {
get {
if (playlists_path == null) {
if (MediaCapabilities == null || MediaCapabilities.PlaylistPath == null) {
playlists_path = WritePath;
} else {
playlists_path = System.IO.Path.Combine (WritePath, MediaCapabilities.PlaylistPath);
playlists_path = playlists_path.Replace ("%File", String.Empty);
}
if (!Directory.Exists (playlists_path)) {
Directory.Create (playlists_path);
}
}
return playlists_path;
}
}
private string [] playlist_formats;
private string [] PlaylistFormats {
get {
if (playlist_formats == null && MediaCapabilities != null) {
playlist_formats = MediaCapabilities.PlaylistFormats;
}
return playlist_formats;
}
set { playlist_formats = value; }
}
private List<PlaylistFormatDescription> playlist_types;
private IList<PlaylistFormatDescription> PlaylistTypes {
get {
if (playlist_types == null) {
playlist_types = new List<PlaylistFormatDescription> ();
if (PlaylistFormats != null) {
foreach (PlaylistFormatDescription desc in Banshee.Playlist.PlaylistFileUtil.ExportFormats) {
foreach (string mimetype in desc.MimeTypes) {
if (Array.IndexOf (PlaylistFormats, mimetype) != -1) {
playlist_types.Add (desc);
break;
}
}
}
}
}
SupportsPlaylists &= CanSyncPlaylists;
return playlist_types;
}
}
private IEnumerable<string> PlaylistFiles {
get {
foreach (string file_name in Directory.GetFiles (PlaylistsPath)) {
foreach (PlaylistFormatDescription desc in playlist_types) {
if (file_name.EndsWith (desc.FileExtension)) {
yield return file_name;
break;
}
}
}
}
}
private bool CanSyncPlaylists {
get {
return PlaylistsPath != null && playlist_types.Count > 0;
}
}
public override void SyncPlaylists ()
{
if (!CanSyncPlaylists) {
return;
}
foreach (string file_name in PlaylistFiles) {
Banshee.IO.File.Delete (new SafeUri (file_name));
}
// Add playlists from Banshee to the device
PlaylistFormatBase playlist_format = null;
List<Source> children = new List<Source> (Children);
foreach (Source child in children) {
PlaylistSource from = child as PlaylistSource;
if (from != null) {
from.Reload ();
if (playlist_format == null) {
playlist_format = Activator.CreateInstance (PlaylistTypes[0].Type) as PlaylistFormatBase;
}
SafeUri playlist_path = new SafeUri (System.IO.Path.Combine (
PlaylistsPath, String.Format ("{0}.{1}", from.Name, PlaylistTypes[0].FileExtension)));
System.IO.Stream stream = Banshee.IO.File.OpenWrite (playlist_path, true);
playlist_format.BaseUri = new Uri (BaseDirectory);
playlist_format.Save (stream, from);
stream.Close ();
}
}
}
#endregion
protected override string [] GetIconNames ()
{
string [] names = ms_device != null ? ms_device.GetIconNames () : null;
return names == null ? base.GetIconNames () : names;
}
public override long BytesUsed {
get { return BytesCapacity - volume.Available; }
}
public override long BytesCapacity {
get { return (long) volume.Capacity; }
}
private bool had_write_error = false;
public override bool IsReadOnly {
get { return volume.IsReadOnly || had_write_error; }
}
private string write_path = null;
public string WritePath {
get {
if (write_path == null) {
write_path = BaseDirectory;
// According to the HAL spec, the first folder listed in the audio_folders property
// is the folder to write files to.
if (AudioFolders.Length > 0) {
write_path = Banshee.Base.Paths.Combine (write_path, AudioFolders[0]);
}
}
return write_path;
}
set { write_path = value; }
}
private string write_path_video = null;
public string WritePathVideo {
get {
if (write_path_video == null) {
write_path_video = BaseDirectory;
// Some Devices May Have a Separate Video Directory
if (VideoFolders.Length > 0) {
write_path_video = Banshee.Base.Paths.Combine (write_path_video, VideoFolders[0]);
} else if (AudioFolders.Length > 0) {
write_path_video = Banshee.Base.Paths.Combine (write_path_video, AudioFolders[0]);
write_path_video = Banshee.Base.Paths.Combine (write_path_video, "Videos");
}
}
return write_path_video;
}
set { write_path_video = value; }
}
private string [] audio_folders;
protected string [] AudioFolders {
get {
if (audio_folders == null) {
audio_folders = HasMediaCapabilities ? MediaCapabilities.AudioFolders : new string[0];
}
return audio_folders;
}
set { audio_folders = value; }
}
private string [] video_folders;
protected string [] VideoFolders {
get {
if (video_folders == null) {
video_folders = HasMediaCapabilities ? MediaCapabilities.VideoFolders : new string[0];
}
return video_folders;
}
set { video_folders = value; }
}
protected IEnumerable<string> BaseDirectories {
get {
if (AudioFolders.Length == 0) {
yield return BaseDirectory;
} else {
foreach (string audio_folder in AudioFolders) {
yield return Paths.Combine (BaseDirectory, audio_folder);
}
}
}
}
private int folder_depth = -1;
protected int FolderDepth {
get {
if (folder_depth == -1) {
folder_depth = HasMediaCapabilities ? MediaCapabilities.FolderDepth : -1;
}
return folder_depth;
}
set { folder_depth = value; }
}
private int cover_art_size = -1;
protected int CoverArtSize {
get {
if (cover_art_size == -1) {
cover_art_size = HasMediaCapabilities ? MediaCapabilities.CoverArtSize : 0;
}
return cover_art_size;
}
set { cover_art_size = value; }
}
private string cover_art_file_name = null;
protected string CoverArtFileName {
get {
if (cover_art_file_name == null) {
cover_art_file_name = HasMediaCapabilities ? MediaCapabilities.CoverArtFileName : null;
}
return cover_art_file_name;
}
set { cover_art_file_name = value; }
}
private string cover_art_file_type = null;
protected string CoverArtFileType {
get {
if (cover_art_file_type == null) {
cover_art_file_type = HasMediaCapabilities ? MediaCapabilities.CoverArtFileType : null;
}
return cover_art_file_type;
}
set { cover_art_file_type = value; }
}
protected override void AddTrackToDevice (DatabaseTrackInfo track, SafeUri fromUri)
{
if (track.PrimarySourceId == DbId)
return;
SafeUri new_uri = new SafeUri (GetTrackPath (track, System.IO.Path.GetExtension (fromUri.LocalPath)));
// If it already is on the device but it's out of date, remove it
//if (File.Exists(new_uri) && File.GetLastWriteTime(track.Uri.LocalPath) > File.GetLastWriteTime(new_uri))
//RemoveTrack(new MassStorageTrackInfo(new SafeUri(new_uri)));
if (!File.Exists (new_uri)) {
Directory.Create (System.IO.Path.GetDirectoryName (new_uri.LocalPath));
File.Copy (fromUri, new_uri, false);
DatabaseTrackInfo copied_track = new DatabaseTrackInfo (track);
copied_track.PrimarySource = this;
copied_track.Uri = new_uri;
// Write the metadata in db to the file on the DAP if it has changed since file was modified
// to ensure that when we load it next time, it's data will match what's in the database
// and the MetadataHash will actually match. We do this by comparing the time
// stamps on files for last update of the db metadata vs the sync to file.
// The equals on the inequality below is necessary for podcasts who often have a sync and
// update time that are the same to the second, even though the album metadata has changed in the
// DB to the feedname instead of what is in the file. It should be noted that writing the metadata
// is a small fraction of the total copy time anyway.
if (track.LastSyncedStamp >= Hyena.DateTimeUtil.ToDateTime (track.FileModifiedStamp)) {
Log.DebugFormat ("Copying Metadata to File Since Sync time >= Updated Time");
Banshee.Streaming.StreamTagger.SaveToFile (copied_track);
}
copied_track.Save (false);
}
if (CoverArtSize > -1 && !String.IsNullOrEmpty (CoverArtFileType) &&
!String.IsNullOrEmpty (CoverArtFileName) && (FolderDepth == -1 || FolderDepth > 0)) {
SafeUri cover_uri = new SafeUri (System.IO.Path.Combine (System.IO.Path.GetDirectoryName (new_uri.LocalPath),
CoverArtFileName));
string coverart_id;
if (track.HasAttribute (TrackMediaAttributes.Podcast)) {
coverart_id = String.Format ("podcast-{0}", Banshee.Base.CoverArtSpec.EscapePart (track.AlbumTitle));
} else {
coverart_id = track.ArtworkId;
}
if (!File.Exists (cover_uri) && CoverArtSpec.CoverExists (coverart_id)) {
Gdk.Pixbuf pic = null;
if (CoverArtSize == 0) {
if (CoverArtFileType == "jpg" || CoverArtFileType == "jpeg") {
SafeUri local_cover_uri = new SafeUri (Banshee.Base.CoverArtSpec.GetPath (coverart_id));
Banshee.IO.File.Copy (local_cover_uri, cover_uri, false);
} else {
pic = artwork_manager.LookupPixbuf (coverart_id);
}
} else {
pic = artwork_manager.LookupScalePixbuf (coverart_id, CoverArtSize);
}
if (pic != null) {
try {
byte [] bytes = pic.SaveToBuffer (CoverArtFileType);
System.IO.Stream cover_art_file = File.OpenWrite (cover_uri, true);
cover_art_file.Write (bytes, 0, bytes.Length);
cover_art_file.Close ();
} catch (GLib.GException){
Log.DebugFormat ("Could not convert cover art to {0}, unsupported filetype?", CoverArtFileType);
} finally {
Banshee.Collection.Gui.ArtworkManager.DisposePixbuf (pic);
}
}
}
}
}
protected override bool DeleteTrack (DatabaseTrackInfo track)
{
try {
if (ms_device != null && !ms_device.DeleteTrackHook (track)) {
return false;
}
string track_file = System.IO.Path.GetFileName (track.Uri.LocalPath);
string track_dir = System.IO.Path.GetDirectoryName (track.Uri.LocalPath);
int files = 0;
// Count how many files remain in the track's directory,
// excluding self or cover art
foreach (string file in System.IO.Directory.GetFiles (track_dir)) {
string relative = System.IO.Path.GetFileName (file);
if (relative != track_file && relative != CoverArtFileName) {
files++;
}
}
// If we are the last track, go ahead and delete the artwork
// to ensure that the directory tree can get trimmed away too
if (files == 0 && CoverArtFileName != null) {
System.IO.File.Delete (Paths.Combine (track_dir, CoverArtFileName));
}
Banshee.IO.Utilities.DeleteFileTrimmingParentDirectories (track.Uri);
} catch (System.IO.FileNotFoundException) {
} catch (System.IO.DirectoryNotFoundException) {
}
return true;
}
protected override void Eject ()
{
base.Eject ();
if (volume.CanUnmount) {
volume.Unmount ();
}
if (volume.CanEject) {
volume.Eject ();
}
}
protected override bool CanHandleDeviceCommand (DeviceCommand command)
{
try {
SafeUri uri = new SafeUri (command.DeviceId);
return BaseDirectory.StartsWith (uri.LocalPath);
} catch {
return false;
}
}
private string GetTrackPath (TrackInfo track, string ext)
{
string file_path = null;
if (track.HasAttribute (TrackMediaAttributes.Podcast)) {
string album = FileNamePattern.Escape (track.DisplayAlbumTitle);
string title = FileNamePattern.Escape (track.DisplayTrackTitle);
file_path = System.IO.Path.Combine ("Podcasts", album);
file_path = System.IO.Path.Combine (file_path, title);
} else if (track.HasAttribute (TrackMediaAttributes.VideoStream)) {
string album = FileNamePattern.Escape (track.DisplayAlbumTitle);
string title = FileNamePattern.Escape (track.DisplayTrackTitle);
file_path = System.IO.Path.Combine (album, title);
} else if (ms_device == null || !ms_device.GetTrackPath (track, out file_path)) {
// If the folder_depth property exists, we have to put the files in a hiearchy of
// the exact given depth (not including the mount point/audio_folder).
if (FolderDepth != -1) {
int depth = FolderDepth;
string album_artist = FileNamePattern.Escape (track.DisplayAlbumArtistName);
string track_album = FileNamePattern.Escape (track.DisplayAlbumTitle);
string track_number = FileNamePattern.Escape (Convert.ToString (track.TrackNumber));
string track_title = FileNamePattern.Escape (track.DisplayTrackTitle);
if (depth == 0) {
// Artist - Album - 01 - Title
string track_artist = FileNamePattern.Escape (track.DisplayArtistName);
file_path = String.Format ("{0} - {1} - {2} - {3}", track_artist, track_album, track_number, track_title);
} else if (depth == 1) {
// Artist - Album/01 - Title
file_path = String.Format ("{0} - {1}", album_artist, track_album);
file_path = System.IO.Path.Combine (file_path, String.Format ("{0} - {1}", track_number, track_title));
} else if (depth == 2) {
// Artist/Album/01 - Title
file_path = album_artist;
file_path = System.IO.Path.Combine (file_path, track_album);
file_path = System.IO.Path.Combine (file_path, String.Format ("{0} - {1}", track_number, track_title));
} else {
// If the *required* depth is more than 2..go nuts!
for (int i = 0; i < depth - 2; i++) {
if (i == 0) {
file_path = album_artist.Substring (0, Math.Min (i+1, album_artist.Length)).Trim ();
} else {
file_path = System.IO.Path.Combine (file_path, album_artist.Substring (0, Math.Min (i+1, album_artist.Length)).Trim ());
}
}
// Finally add on the Artist/Album/01 - Track
file_path = System.IO.Path.Combine (file_path, album_artist);
file_path = System.IO.Path.Combine (file_path, track_album);
file_path = System.IO.Path.Combine (file_path, String.Format ("{0} - {1}", track_number, track_title));
}
} else {
file_path = FileNamePattern.CreateFromTrackInfo (track);
}
}
if (track.HasAttribute (TrackMediaAttributes.VideoStream)) {
file_path = System.IO.Path.Combine (WritePathVideo, file_path);
} else {
file_path = System.IO.Path.Combine (WritePath, file_path);
}
file_path += ext;
return file_path;
}
}
}
| |
// 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 Stream whose backing store is memory. Great
** for temporary storage without creating a temp file. Also
** lets users expose a byte[] as a stream.
**
**
===========================================================*/
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Permissions;
namespace System.IO {
// A MemoryStream represents a Stream in memory (ie, it has no backing store).
// This stream may reduce the need for temporary buffers and files in
// an application.
//
// There are two ways to create a MemoryStream. You can initialize one
// from an unsigned byte array, or you can create an empty one. Empty
// memory streams are resizable, while ones created with a byte array provide
// a stream "view" of the data.
[Serializable]
[ComVisible(true)]
public class MemoryStream : Stream
{
private byte[] _buffer; // Either allocated internally or externally.
private int _origin; // For user-provided arrays, start at this origin
private int _position; // read/write head.
[ContractPublicPropertyName("Length")]
private int _length; // Number of bytes within the memory stream
private int _capacity; // length of usable portion of buffer for stream
// Note that _capacity == _buffer.Length for non-user-provided byte[]'s
private bool _expandable; // User-provided buffers aren't expandable.
private bool _writable; // Can user write to this stream?
private bool _exposable; // Whether the array can be returned to the user.
private bool _isOpen; // Is this stream open or closed?
[NonSerialized]
private Task<int> _lastReadTask; // The last successful task returned from ReadAsync
private const int MemStreamMaxLength = Int32.MaxValue;
public MemoryStream()
: this(0) {
}
public MemoryStream(int capacity) {
if (capacity < 0) {
throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
}
Contract.EndContractBlock();
_buffer = capacity != 0 ? new byte[capacity] : EmptyArray<byte>.Value;
_capacity = capacity;
_expandable = true;
_writable = true;
_exposable = true;
_origin = 0; // Must be 0 for byte[]'s created by MemoryStream
_isOpen = true;
}
public MemoryStream(byte[] buffer)
: this(buffer, true) {
}
public MemoryStream(byte[] buffer, bool writable) {
if (buffer == null) throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
Contract.EndContractBlock();
_buffer = buffer;
_length = _capacity = buffer.Length;
_writable = writable;
_exposable = false;
_origin = 0;
_isOpen = true;
}
public MemoryStream(byte[] buffer, int index, int count)
: this(buffer, index, count, true, false) {
}
public MemoryStream(byte[] buffer, int index, int count, bool writable)
: this(buffer, index, count, writable, false) {
}
public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) {
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
_buffer = buffer;
_origin = _position = index;
_length = _capacity = index + count;
_writable = writable;
_exposable = publiclyVisible; // Can TryGetBuffer/GetBuffer return the array?
_expandable = false;
_isOpen = true;
}
public override bool CanRead {
[Pure]
get { return _isOpen; }
}
public override bool CanSeek {
[Pure]
get { return _isOpen; }
}
public override bool CanWrite {
[Pure]
get { return _writable; }
}
private void EnsureWriteable() {
if (!CanWrite) __Error.WriteNotSupported();
}
protected override void Dispose(bool disposing)
{
try {
if (disposing) {
_isOpen = false;
_writable = false;
_expandable = false;
// Don't set buffer to null - allow TryGetBuffer, GetBuffer & ToArray to work.
_lastReadTask = null;
}
}
finally {
// Call base.Close() to cleanup async IO resources
base.Dispose(disposing);
}
}
// returns a bool saying whether we allocated a new array.
private bool EnsureCapacity(int value) {
// Check for overflow
if (value < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
if (value > _capacity) {
int newCapacity = value;
if (newCapacity < 256)
newCapacity = 256;
// We are ok with this overflowing since the next statement will deal
// with the cases where _capacity*2 overflows.
if (newCapacity < _capacity * 2)
newCapacity = _capacity * 2;
// We want to expand the array up to Array.MaxArrayLengthOneDimensional
// And we want to give the user the value that they asked for
if ((uint)(_capacity * 2) > Array.MaxByteArrayLength)
newCapacity = value > Array.MaxByteArrayLength ? value : Array.MaxByteArrayLength;
Capacity = newCapacity;
return true;
}
return false;
}
public override void Flush() {
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public override Task FlushAsync(CancellationToken cancellationToken) {
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try {
Flush();
return Task.CompletedTask;
} catch(Exception ex) {
return Task.FromException(ex);
}
}
public virtual byte[] GetBuffer() {
if (!_exposable)
throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_MemStreamBuffer"));
return _buffer;
}
public virtual bool TryGetBuffer(out ArraySegment<byte> buffer) {
if (!_exposable) {
buffer = default(ArraySegment<byte>);
return false;
}
buffer = new ArraySegment<byte>(_buffer, offset:_origin, count:(_length - _origin));
return true;
}
// -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) ---------------
// PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer())
internal byte[] InternalGetBuffer() {
return _buffer;
}
// PERF: Get origin and length - used in ResourceWriter.
[FriendAccessAllowed]
internal void InternalGetOriginAndLength(out int origin, out int length)
{
if (!_isOpen) __Error.StreamIsClosed();
origin = _origin;
length = _length;
}
// PERF: True cursor position, we don't need _origin for direct access
internal int InternalGetPosition() {
if (!_isOpen) __Error.StreamIsClosed();
return _position;
}
// PERF: Takes out Int32 as fast as possible
internal int InternalReadInt32() {
if (!_isOpen)
__Error.StreamIsClosed();
int pos = (_position += 4); // use temp to avoid a race condition
if (pos > _length)
{
_position = _length;
__Error.EndOfFile();
}
return (int)(_buffer[pos-4] | _buffer[pos-3] << 8 | _buffer[pos-2] << 16 | _buffer[pos-1] << 24);
}
// PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes
internal int InternalEmulateRead(int count) {
if (!_isOpen) __Error.StreamIsClosed();
int n = _length - _position;
if (n > count) n = count;
if (n < 0) n = 0;
Contract.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
_position += n;
return n;
}
// Gets & sets the capacity (number of bytes allocated) for this stream.
// The capacity cannot be set to a value less than the current length
// of the stream.
//
public virtual int Capacity {
get {
if (!_isOpen) __Error.StreamIsClosed();
return _capacity - _origin;
}
set {
// Only update the capacity if the MS is expandable and the value is different than the current capacity.
// Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity
if (value < Length) throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
Contract.Ensures(_capacity - _origin == value);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
if (!_expandable && (value != Capacity)) __Error.MemoryStreamNotExpandable();
// MemoryStream has this invariant: _origin > 0 => !expandable (see ctors)
if (_expandable && value != _capacity) {
if (value > 0) {
byte[] newBuffer = new byte[value];
if (_length > 0) Buffer.InternalBlockCopy(_buffer, 0, newBuffer, 0, _length);
_buffer = newBuffer;
}
else {
_buffer = null;
}
_capacity = value;
}
}
}
public override long Length {
get {
if (!_isOpen) __Error.StreamIsClosed();
return _length - _origin;
}
}
public override long Position {
get {
if (!_isOpen) __Error.StreamIsClosed();
return _position - _origin;
}
set {
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.Ensures(Position == value);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
if (value > MemStreamMaxLength)
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
_position = _origin + (int)value;
}
}
public override int Read([In, Out] byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
int n = _length - _position;
if (n > count) n = count;
if (n <= 0)
return 0;
Contract.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
if (n <= 8)
{
int byteCount = n;
while (--byteCount >= 0)
buffer[offset + byteCount] = _buffer[_position + byteCount];
}
else
Buffer.InternalBlockCopy(_buffer, _position, buffer, offset, n);
_position += n;
return n;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Read(...)
// If cancellation was requested, bail early
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<int>(cancellationToken);
try
{
int n = Read(buffer, offset, count);
var t = _lastReadTask;
Contract.Assert(t == null || t.Status == TaskStatus.RanToCompletion,
"Expected that a stored last task completed successfully");
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n));
}
catch (OperationCanceledException oce)
{
return Task.FromCancellation<int>(oce);
}
catch (Exception exception)
{
return Task.FromException<int>(exception);
}
}
public override int ReadByte() {
if (!_isOpen) __Error.StreamIsClosed();
if (_position >= _length) return -1;
return _buffer[_position++];
}
public override void CopyTo(Stream destination, int bufferSize)
{
// Since we did not originally override this method, validate the arguments
// the same way Stream does for back-compat.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Read() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Read) when we are not sure.
if (GetType() != typeof(MemoryStream))
{
base.CopyTo(destination, bufferSize);
return;
}
int originalPosition = _position;
// Seek to the end of the MemoryStream.
int remaining = InternalEmulateRead(_length - originalPosition);
// If we were already at or past the end, there's no copying to do so just quit.
if (remaining > 0)
{
// Call Write() on the other Stream, using our internal buffer and avoiding any
// intermediary allocations.
destination.Write(_buffer, originalPosition, remaining);
}
}
public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) {
// This implementation offers beter performance compared to the base class version.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to ReadAsync() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into ReadAsync) when we are not sure.
if (this.GetType() != typeof(MemoryStream))
return base.CopyToAsync(destination, bufferSize, cancellationToken);
// If cancelled - return fast:
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
// Avoid copying data from this buffer into a temp buffer:
// (require that InternalEmulateRead does not throw,
// otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below)
Int32 pos = _position;
Int32 n = InternalEmulateRead(_length - _position);
// If destination is not a memory stream, write there asynchronously:
MemoryStream memStrDest = destination as MemoryStream;
if (memStrDest == null)
return destination.WriteAsync(_buffer, pos, n, cancellationToken);
try {
// If destination is a MemoryStream, CopyTo synchronously:
memStrDest.Write(_buffer, pos, n);
return Task.CompletedTask;
} catch(Exception ex) {
return Task.FromException(ex);
}
}
public override long Seek(long offset, SeekOrigin loc) {
if (!_isOpen) __Error.StreamIsClosed();
if (offset > MemStreamMaxLength)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
switch(loc) {
case SeekOrigin.Begin: {
int tempPosition = unchecked(_origin + (int)offset);
if (offset < 0 || tempPosition < _origin)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
_position = tempPosition;
break;
}
case SeekOrigin.Current: {
int tempPosition = unchecked(_position + (int)offset);
if (unchecked(_position + offset) < _origin || tempPosition < _origin)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
_position = tempPosition;
break;
}
case SeekOrigin.End: {
int tempPosition = unchecked(_length + (int)offset);
if ( unchecked(_length + offset) < _origin || tempPosition < _origin )
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
_position = tempPosition;
break;
}
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
}
Contract.Assert(_position >= 0, "_position >= 0");
return _position;
}
// Sets the length of the stream to a given value. The new
// value must be nonnegative and less than the space remaining in
// the array, Int32.MaxValue - origin
// Origin is 0 in all cases other than a MemoryStream created on
// top of an existing array and a specific starting offset was passed
// into the MemoryStream constructor. The upper bounds prevents any
// situations where a stream may be created on top of an array then
// the stream is made longer than the maximum possible length of the
// array (Int32.MaxValue).
//
public override void SetLength(long value) {
if (value < 0 || value > Int32.MaxValue) {
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
Contract.Ensures(_length - _origin == value);
Contract.EndContractBlock();
EnsureWriteable();
// Origin wasn't publicly exposed above.
Contract.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails.
if (value > (Int32.MaxValue - _origin)) {
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
int newLength = _origin + (int)value;
bool allocatedNewArray = EnsureCapacity(newLength);
if (!allocatedNewArray && newLength > _length)
Array.Clear(_buffer, _length, newLength - _length);
_length = newLength;
if (_position > newLength) _position = newLength;
}
public virtual byte[] ToArray() {
BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy.");
byte[] copy = new byte[_length - _origin];
Buffer.InternalBlockCopy(_buffer, _origin, copy, 0, _length - _origin);
return copy;
}
public override void Write(byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
EnsureWriteable();
int i = _position + count;
// Check for overflow
if (i < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
if (i > _length) {
bool mustZero = _position > _length;
if (i > _capacity) {
bool allocatedNewArray = EnsureCapacity(i);
if (allocatedNewArray)
mustZero = false;
}
if (mustZero)
Array.Clear(_buffer, _length, i - _length);
_length = i;
}
if ((count <= 8) && (buffer != _buffer))
{
int byteCount = count;
while (--byteCount >= 0)
_buffer[_position + byteCount] = buffer[offset + byteCount];
}
else
Buffer.InternalBlockCopy(buffer, offset, _buffer, _position, count);
_position = i;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Write(...)
// If cancellation is already requested, bail early
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Write(buffer, offset, count);
return Task.CompletedTask;
}
catch (OperationCanceledException oce)
{
return Task.FromCancellation<VoidTaskResult>(oce);
}
catch (Exception exception)
{
return Task.FromException(exception);
}
}
public override void WriteByte(byte value) {
if (!_isOpen) __Error.StreamIsClosed();
EnsureWriteable();
if (_position >= _length) {
int newLength = _position + 1;
bool mustZero = _position > _length;
if (newLength >= _capacity) {
bool allocatedNewArray = EnsureCapacity(newLength);
if (allocatedNewArray)
mustZero = false;
}
if (mustZero)
Array.Clear(_buffer, _length, _position - _length);
_length = newLength;
}
_buffer[_position++] = value;
}
// Writes this MemoryStream to another stream.
public virtual void WriteTo(Stream stream) {
if (stream==null)
throw new ArgumentNullException(nameof(stream), Environment.GetResourceString("ArgumentNull_Stream"));
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
stream.Write(_buffer, _origin, _length - _origin);
}
}
}
| |
// ==++==
//
// Copyright(c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
namespace System.Reflection
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_PropertyInfo))]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
#pragma warning restore 618
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class PropertyInfo : MemberInfo, _PropertyInfo
{
#region Constructor
protected PropertyInfo() { }
#endregion
#if !FEATURE_CORECLR
public static bool operator ==(PropertyInfo left, PropertyInfo right)
{
if (ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null ||
left is RuntimePropertyInfo || right is RuntimePropertyInfo)
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(PropertyInfo left, PropertyInfo right)
{
return !(left == right);
}
#endif // !FEATURE_CORECLR
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Property; } }
#endregion
#region Public Abstract\Virtual Members
public virtual object GetConstantValue()
{
throw new NotImplementedException();
}
public virtual object GetRawConstantValue()
{
throw new NotImplementedException();
}
public abstract Type PropertyType { get; }
public abstract void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture);
public abstract MethodInfo[] GetAccessors(bool nonPublic);
public abstract MethodInfo GetGetMethod(bool nonPublic);
public abstract MethodInfo GetSetMethod(bool nonPublic);
public abstract ParameterInfo[] GetIndexParameters();
public abstract PropertyAttributes Attributes { get; }
public abstract bool CanRead { get; }
public abstract bool CanWrite { get; }
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public Object GetValue(Object obj)
{
return GetValue(obj, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public virtual Object GetValue(Object obj,Object[] index)
{
return GetValue(obj, BindingFlags.Default, null, index, null);
}
public abstract Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture);
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public void SetValue(Object obj, Object value)
{
SetValue(obj, value, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public virtual void SetValue(Object obj, Object value, Object[] index)
{
SetValue(obj, value, BindingFlags.Default, null, index, null);
}
#endregion
#region Public Members
public virtual Type[] GetRequiredCustomModifiers() { return EmptyArray<Type>.Value; }
public virtual Type[] GetOptionalCustomModifiers() { return EmptyArray<Type>.Value; }
public MethodInfo[] GetAccessors() { return GetAccessors(false); }
public virtual MethodInfo GetMethod
{
get
{
return GetGetMethod(true);
}
}
public virtual MethodInfo SetMethod
{
get
{
return GetSetMethod(true);
}
}
public MethodInfo GetGetMethod() { return GetGetMethod(false); }
public MethodInfo GetSetMethod() { return GetSetMethod(false); }
public bool IsSpecialName { get { return(Attributes & PropertyAttributes.SpecialName) != 0; } }
#endregion
#if !FEATURE_CORECLR
Type _PropertyInfo.GetType()
{
return base.GetType();
}
void _PropertyInfo.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _PropertyInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _PropertyInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
// If you implement this method, make sure to include _PropertyInfo.Invoke in VM\DangerousAPIs.h and
// include _PropertyInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
void _PropertyInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
}
[Serializable]
internal unsafe sealed class RuntimePropertyInfo : PropertyInfo, ISerializable
{
#region Private Data Members
private int m_token;
private string m_name;
[System.Security.SecurityCritical]
private void* m_utf8name;
private PropertyAttributes m_flags;
private RuntimeTypeCache m_reflectedTypeCache;
private RuntimeMethodInfo m_getterMethod;
private RuntimeMethodInfo m_setterMethod;
private MethodInfo[] m_otherMethod;
private RuntimeType m_declaringType;
private BindingFlags m_bindingFlags;
private Signature m_signature;
private ParameterInfo[] m_parameters;
#endregion
#region Constructor
[System.Security.SecurityCritical] // auto-generated
internal RuntimePropertyInfo(
int tkProperty, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate)
{
Contract.Requires(declaredType != null);
Contract.Requires(reflectedTypeCache != null);
Contract.Assert(!reflectedTypeCache.IsGlobal);
MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport;
m_token = tkProperty;
m_reflectedTypeCache = reflectedTypeCache;
m_declaringType = declaredType;
ConstArray sig;
scope.GetPropertyProps(tkProperty, out m_utf8name, out m_flags, out sig);
RuntimeMethodInfo dummy;
Associates.AssignAssociates(scope, tkProperty, declaredType, reflectedTypeCache.GetRuntimeType(),
out dummy, out dummy, out dummy,
out m_getterMethod, out m_setterMethod, out m_otherMethod,
out isPrivate, out m_bindingFlags);
}
#endregion
#region Internal Members
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
RuntimePropertyInfo m = o as RuntimePropertyInfo;
if ((object)m == null)
return false;
return m.m_token == m_token &&
RuntimeTypeHandle.GetModule(m_declaringType).Equals(
RuntimeTypeHandle.GetModule(m.m_declaringType));
}
internal Signature Signature
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_signature == null)
{
PropertyAttributes flags;
ConstArray sig;
void* name;
GetRuntimeModule().MetadataImport.GetPropertyProps(
m_token, out name, out flags, out sig);
m_signature = new Signature(sig.Signature.ToPointer(), (int)sig.Length, m_declaringType);
}
return m_signature;
}
}
internal bool EqualsSig(RuntimePropertyInfo target)
{
//@Asymmetry - Legacy policy is to remove duplicate properties, including hidden properties.
// The comparison is done by name and by sig. The EqualsSig comparison is expensive
// but forutnetly it is only called when an inherited property is hidden by name or
// when an interfaces declare properies with the same signature.
// Note that we intentionally don't resolve generic arguments so that we don't treat
// signatures that only match in certain instantiations as duplicates. This has the
// down side of treating overriding and overriden properties as different properties
// in some cases. But PopulateProperties in rttype.cs should have taken care of that
// by comparing VTable slots.
//
// Class C1(Of T, Y)
// Property Prop1(ByVal t1 As T) As Integer
// Get
// ... ...
// End Get
// End Property
// Property Prop1(ByVal y1 As Y) As Integer
// Get
// ... ...
// End Get
// End Property
// End Class
//
Contract.Requires(Name.Equals(target.Name));
Contract.Requires(this != target);
Contract.Requires(this.ReflectedType == target.ReflectedType);
#if FEATURE_LEGACYNETCF
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
return Signature.CompareSigForAppCompat(this.Signature, this.m_declaringType,
target.Signature, target.m_declaringType);
#endif
return Signature.CompareSig(this.Signature, target.Signature);
}
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
#endregion
#if FEATURE_LEGACYNETCF
// BEGIN helper methods for Dev11 466969 quirk
internal bool HasMatchingAccessibility(RuntimePropertyInfo target)
{
Contract.Assert(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8);
bool match = true;
if (!IsMatchingAccessibility(this.GetGetMethod(true), target.GetGetMethod(true)))
{
match = false;
}
else if (!IsMatchingAccessibility(this.GetSetMethod(true), target.GetSetMethod(true)))
{
match = false;
}
return match;
}
private bool IsMatchingAccessibility(MethodInfo lhsInfo, MethodInfo rhsInfo)
{
if (lhsInfo != null && rhsInfo != null)
{
return lhsInfo.IsPublic == rhsInfo.IsPublic;
}
else
{
// don't be tempted to return false here! we only want to introduce
// the quirk behavior when we know that the accessibility is different.
// in all other cases return true so the code works as before.
return true;
}
}
// END helper methods for Dev11 466969 quirk
#endif
#region Object Overrides
public override String ToString()
{
return FormatNameAndSig(false);
}
private string FormatNameAndSig(bool serialization)
{
StringBuilder sbName = new StringBuilder(PropertyType.FormatTypeName(serialization));
sbName.Append(" ");
sbName.Append(Name);
RuntimeType[] arguments = Signature.Arguments;
if (arguments.Length > 0)
{
sbName.Append(" [");
sbName.Append(MethodBase.ConstructParameters(arguments, Signature.CallingConvention, serialization));
sbName.Append("]");
}
return sbName.ToString();
}
#endregion
#region ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return MemberTypes.Property; } }
public override String Name
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_name == null)
m_name = new Utf8String(m_utf8name).ToString();
return m_name;
}
}
public override Type DeclaringType
{
get
{
return m_declaringType;
}
}
public override Type ReflectedType
{
get
{
return ReflectedTypeInternal;
}
}
private RuntimeType ReflectedTypeInternal
{
get
{
return m_reflectedTypeCache.GetRuntimeType();
}
}
public override int MetadataToken { get { return m_token; } }
public override Module Module { get { return GetRuntimeModule(); } }
internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
#endregion
#region PropertyInfo Overrides
#region Non Dynamic
public override Type[] GetRequiredCustomModifiers()
{
return Signature.GetCustomModifiers(0, true);
}
public override Type[] GetOptionalCustomModifiers()
{
return Signature.GetCustomModifiers(0, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
internal object GetConstantValue(bool raw)
{
Object defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw);
if (defaultValue == DBNull.Value)
// Arg_EnumLitValueNotFound -> "Literal value was not found."
throw new InvalidOperationException(Environment.GetResourceString("Arg_EnumLitValueNotFound"));
return defaultValue;
}
public override object GetConstantValue() { return GetConstantValue(false); }
public override object GetRawConstantValue() { return GetConstantValue(true); }
public override MethodInfo[] GetAccessors(bool nonPublic)
{
List<MethodInfo> accessorList = new List<MethodInfo>();
if (Associates.IncludeAccessor(m_getterMethod, nonPublic))
accessorList.Add(m_getterMethod);
if (Associates.IncludeAccessor(m_setterMethod, nonPublic))
accessorList.Add(m_setterMethod);
if ((object)m_otherMethod != null)
{
for(int i = 0; i < m_otherMethod.Length; i ++)
{
if (Associates.IncludeAccessor(m_otherMethod[i] as MethodInfo, nonPublic))
accessorList.Add(m_otherMethod[i]);
}
}
return accessorList.ToArray();
}
public override Type PropertyType
{
get { return Signature.ReturnType; }
}
public override MethodInfo GetGetMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_getterMethod, nonPublic))
return null;
return m_getterMethod;
}
public override MethodInfo GetSetMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_setterMethod, nonPublic))
return null;
return m_setterMethod;
}
public override ParameterInfo[] GetIndexParameters()
{
ParameterInfo[] indexParams = GetIndexParametersNoCopy();
int numParams = indexParams.Length;
if (numParams == 0)
return indexParams;
ParameterInfo[] ret = new ParameterInfo[numParams];
Array.Copy(indexParams, ret, numParams);
return ret;
}
internal ParameterInfo[] GetIndexParametersNoCopy()
{
// @History - Logic ported from RTM
// No need to lock because we don't guarantee the uniqueness of ParameterInfo objects
if (m_parameters == null)
{
int numParams = 0;
ParameterInfo[] methParams = null;
// First try to get the Get method.
MethodInfo m = GetGetMethod(true);
if (m != null)
{
// There is a Get method so use it.
methParams = m.GetParametersNoCopy();
numParams = methParams.Length;
}
else
{
// If there is no Get method then use the Set method.
m = GetSetMethod(true);
if (m != null)
{
methParams = m.GetParametersNoCopy();
numParams = methParams.Length - 1;
}
}
// Now copy over the parameter info's and change their
// owning member info to the current property info.
ParameterInfo[] propParams = new ParameterInfo[numParams];
for (int i = 0; i < numParams; i++)
propParams[i] = new RuntimeParameterInfo((RuntimeParameterInfo)methParams[i], this);
m_parameters = propParams;
}
return m_parameters;
}
public override PropertyAttributes Attributes
{
get
{
return m_flags;
}
}
public override bool CanRead
{
get
{
return m_getterMethod != null;
}
}
public override bool CanWrite
{
get
{
return m_setterMethod != null;
}
}
#endregion
#region Dynamic
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValue(Object obj,Object[] index)
{
return GetValue(obj, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
null, index, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
{
MethodInfo m = GetGetMethod(true);
if (m == null)
throw new ArgumentException(System.Environment.GetResourceString("Arg_GetMethNotFnd"));
return m.Invoke(obj, invokeAttr, binder, index, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, Object[] index)
{
SetValue(obj,
value,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
null,
index,
null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
{
MethodInfo m = GetSetMethod(true);
if (m == null)
throw new ArgumentException(System.Environment.GetResourceString("Arg_SetMethNotFnd"));
Object[] args = null;
if (index != null)
{
args = new Object[index.Length + 1];
for(int i=0;i<index.Length;i++)
args[i] = index[i];
args[index.Length] = value;
}
else
{
args = new Object[1];
args[0] = value;
}
m.Invoke(obj, invokeAttr, binder, args, culture);
}
#endregion
#endregion
#region ISerializable Implementation
[System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
MemberInfoSerializationHolder.GetSerializationInfo(
info,
Name,
ReflectedTypeInternal,
ToString(),
SerializationToString(),
MemberTypes.Property,
null);
}
internal string SerializationToString()
{
return FormatNameAndSig(true);
}
#endregion
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Linq;
#if ASPNETWEBAPI
using System.Web.Http.Routing.Constraints;
#else
using System.Web.Mvc.Routing.Constraints;
using System.Web.Routing;
#endif
using Microsoft.TestCommon;
#if ASPNETWEBAPI
namespace System.Web.Http.Routing
#else
namespace System.Web.Mvc.Routing
#endif
{
public class InlineRouteTemplateParserTests
{
#if ASPNETWEBAPI
private static readonly RouteParameter OptionalParameter = RouteParameter.Optional;
#else
private static readonly UrlParameter OptionalParameter = UrlParameter.Optional;
#endif
[Fact]
public void ParseRouteTemplate_ChainedConstraintAndDefault()
{
var result = Act(@"hello/{param:int=111111}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.Equal("111111", result.Defaults["param"]);
Assert.IsType<IntRouteConstraint>(result.Constraints["param"]);
}
[Fact]
public void ParseRouteTemplate_ChainedConstraintWithArgumentsAndDefault()
{
var result = Act(@"hello/{param:regex(\d+)=111111}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.Equal("111111", result.Defaults["param"]);
Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\d+", ((RegexRouteConstraint)result.Constraints["param"]).Pattern);
}
[Fact]
public void ParseRouteTemplate_ChainedConstraintAndOptional()
{
var result = Act(@"hello/{param:int?}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.Equal(OptionalParameter, result.Defaults["param"]);
Assert.IsType<OptionalRouteConstraint>(result.Constraints["param"]);
var constraint = (OptionalRouteConstraint)result.Constraints["param"];
Assert.IsType<IntRouteConstraint>(constraint.InnerConstraint);
}
[Fact]
public void ParseRouteTemplate_ChainedConstraintWithArgumentsAndOptional()
{
var result = Act(@"hello/{param:regex(\d+)?}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.Equal(OptionalParameter, result.Defaults["param"]);
Assert.IsType<OptionalRouteConstraint>(result.Constraints["param"]);
var constraint = (OptionalRouteConstraint)result.Constraints["param"];
Assert.Equal(@"\d+", ((RegexRouteConstraint)constraint.InnerConstraint).Pattern);
}
[Fact]
public void ParseRouteTemplate_ChainedConstraints()
{
var result = Act(@"hello/{param:regex(\d+):regex(\w+)}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.IsType<CompoundRouteConstraint>(result.Constraints["param"]);
CompoundRouteConstraint constraint = (CompoundRouteConstraint)result.Constraints["param"];
Assert.Equal(@"\d+", ((RegexRouteConstraint)constraint.Constraints.ElementAt(0)).Pattern);
Assert.Equal(@"\w+", ((RegexRouteConstraint)constraint.Constraints.ElementAt(1)).Pattern);
}
[Fact]
public void ParseRouteTemplate_Constraint()
{
var result = Act(@"hello/{param:regex(\d+)}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\d+", ((RegexRouteConstraint)result.Constraints["param"]).Pattern);
}
[Fact]
public void ParseRouteTemplate_ConstraintsDefaultsAndOptionalsInMultipleSections()
{
var result = Act(@"some/url-{p1:alpha:length(3)=hello}/{p2=abc}/{p3?}");
Assert.Equal("some/url-{p1}/{p2}/{p3}", result.RouteUrl);
Assert.Equal("hello", result.Defaults["p1"]);
Assert.Equal("abc", result.Defaults["p2"]);
Assert.Equal(OptionalParameter, result.Defaults["p3"]);
Assert.IsType<CompoundRouteConstraint>(result.Constraints["p1"]);
CompoundRouteConstraint constraint = (CompoundRouteConstraint)result.Constraints["p1"];
Assert.IsType<AlphaRouteConstraint>(constraint.Constraints.ElementAt(0));
Assert.IsType<LengthRouteConstraint>(constraint.Constraints.ElementAt(1));
}
[Fact]
public void ParseRouteTemplate_NoTokens()
{
var result = Act("hello/world");
Assert.Equal("hello/world", result.RouteUrl);
}
[Fact]
public void ParseRouteTemplate_OptionalParam()
{
var result = Act("hello/{param?}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.Equal(OptionalParameter, result.Defaults["param"]);
}
[Fact]
public void ParseRouteTemplate_ParamDefault()
{
var result = Act("hello/{param=world}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.Equal("world", result.Defaults["param"]);
}
[Fact]
public void ParseRouteTemplate_RegexConstraintWithClosingBraceInPattern()
{
var result = Act(@"hello/{param:regex(\})}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\}", ((RegexRouteConstraint)result.Constraints["param"]).Pattern);
}
[Fact]
public void ParseRouteTemplate_RegexConstraintWithClosingParenInPattern()
{
var result = Act(@"hello/{param:regex(\))}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\)", ((RegexRouteConstraint)result.Constraints["param"]).Pattern);
}
[Fact]
public void ParseRouteTemplate_RegexConstraintWithColonInPattern()
{
var result = Act(@"hello/{param:regex(:)}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@":", ((RegexRouteConstraint)result.Constraints["param"]).Pattern);
}
[Fact]
public void ParseRouteTemplate_RegexConstraintWithCommaInPattern()
{
var result = Act(@"hello/{param:regex(\w,\w)}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\w,\w", ((RegexRouteConstraint)result.Constraints["param"]).Pattern);
}
[Fact]
public void ParseRouteTemplate_RegexConstraintWithEqualsSignInPattern()
{
var result = Act(@"hello/{param:regex(=)}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.DoesNotContain("param", result.Defaults.Keys);
Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"=", ((RegexRouteConstraint)result.Constraints["param"]).Pattern);
}
[Fact]
public void ParseRouteTemplate_RegexConstraintWithOpenBraceInPattern()
{
var result = Act(@"hello/{param:regex(\{)}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\{", ((RegexRouteConstraint)result.Constraints["param"]).Pattern);
}
[Fact]
public void ParseRouteTemplate_RegexConstraintWithOpenParenInPattern()
{
var result = Act(@"hello/{param:regex(\()}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\(", ((RegexRouteConstraint)result.Constraints["param"]).Pattern);
}
[Fact]
public void ParseRouteTemplate_RegexConstraintWithQuestionMarkInPattern()
{
var result = Act(@"hello/{param:regex(\?)}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.DoesNotContain("param", result.Defaults.Keys);
Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\?", ((RegexRouteConstraint)result.Constraints["param"]).Pattern);
}
private ParseResult Act(string template)
{
var result = new ParseResult();
#if ASPNETWEBAPI
result.Constraints = new HttpRouteValueDictionary();
result.Defaults = new HttpRouteValueDictionary();
#else
result.Constraints = new RouteValueDictionary();
result.Defaults = new RouteValueDictionary();
#endif
result.RouteUrl = InlineRouteTemplateParser.ParseRouteTemplate(template, result.Defaults, result.Constraints, new DefaultInlineConstraintResolver());
return result;
}
struct ParseResult
{
public string RouteUrl;
#if ASPNETWEBAPI
public HttpRouteValueDictionary Defaults;
public HttpRouteValueDictionary Constraints;
#else
public RouteValueDictionary Defaults;
public RouteValueDictionary Constraints;
#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.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Xunit;
namespace System.Security.Cryptography.EcDsa.Tests
{
public class ECDsaTests : ECDsaTestsBase
{
[Fact]
public void KeySizeProp()
{
using (ECDsa e = ECDsaFactory.Create())
{
e.KeySize = 384;
Assert.Equal(384, e.KeySize);
ECParameters p384 = e.ExportParameters(false);
Assert.True(p384.Curve.IsNamed);
p384.Validate();
e.KeySize = 521;
Assert.Equal(521, e.KeySize);
ECParameters p521 = e.ExportParameters(false);
Assert.True(p521.Curve.IsNamed);
p521.Validate();
// Ensure the key was regenerated
Assert.NotEqual(p384.Curve.Oid.FriendlyName, p521.Curve.Oid.FriendlyName);
}
}
[ActiveIssue(10206, Xunit.PlatformID.AnyUnix)]
[Theory, MemberData(nameof(TestNewCurves))]
public void TestRegenKeyExplicit(CurveDef curveDef)
{
ECParameters param, param2;
ECDsa ec, newEc;
using (ec = ECDsaFactory.Create(curveDef.Curve))
{
param = ec.ExportExplicitParameters(true);
Assert.NotEqual(null, param.D);
using (newEc = ECDsaFactory.Create())
{
newEc.ImportParameters(param);
// The curve name is not flowed on explicit export\import (by design) so this excercises logic
// that regenerates based on current curve values
newEc.GenerateKey(param.Curve);
param2 = newEc.ExportExplicitParameters(true);
// Only curve should match
ComparePrivateKey(param, param2, false);
ComparePublicKey(param.Q, param2.Q, false);
CompareCurve(param.Curve, param2.Curve);
// Specify same curve name
newEc.GenerateKey(curveDef.Curve);
Assert.Equal(curveDef.KeySize, newEc.KeySize);
param2 = newEc.ExportExplicitParameters(true);
// Only curve should match
ComparePrivateKey(param, param2, false);
ComparePublicKey(param.Q, param2.Q, false);
CompareCurve(param.Curve, param2.Curve);
// Specify different curve than current
if (param.Curve.IsPrime)
{
if (curveDef.Curve.Oid.FriendlyName != ECCurve.NamedCurves.nistP256.Oid.FriendlyName)
{
// Specify different curve (nistP256) by explicit value
newEc.GenerateKey(ECCurve.NamedCurves.nistP256);
Assert.Equal(256, newEc.KeySize);
param2 = newEc.ExportExplicitParameters(true);
// Keys should should not match
ComparePrivateKey(param, param2, false);
ComparePublicKey(param.Q, param2.Q, false);
// P,X,Y (and others) should not match
Assert.True(param2.Curve.IsPrime);
Assert.NotEqual(param.Curve.Prime, param2.Curve.Prime);
Assert.NotEqual(param.Curve.G.X, param2.Curve.G.X);
Assert.NotEqual(param.Curve.G.Y, param2.Curve.G.Y);
// Reset back to original
newEc.GenerateKey(param.Curve);
Assert.Equal(curveDef.KeySize, newEc.KeySize);
ECParameters copyOfParam1 = newEc.ExportExplicitParameters(true);
// Only curve should match
ComparePrivateKey(param, copyOfParam1, false);
ComparePublicKey(param.Q, copyOfParam1.Q, false);
CompareCurve(param.Curve, copyOfParam1.Curve);
// Set back to nistP256
newEc.GenerateKey(param2.Curve);
Assert.Equal(256, newEc.KeySize);
param2 = newEc.ExportExplicitParameters(true);
// Keys should should not match
ComparePrivateKey(param, param2, false);
ComparePublicKey(param.Q, param2.Q, false);
// P,X,Y (and others) should not match
Assert.True(param2.Curve.IsPrime);
Assert.NotEqual(param.Curve.Prime, param2.Curve.Prime);
Assert.NotEqual(param.Curve.G.X, param2.Curve.G.X);
Assert.NotEqual(param.Curve.G.Y, param2.Curve.G.Y);
}
}
else if (param.Curve.IsCharacteristic2)
{
if (curveDef.Curve.Oid.Value != ECDSA_Sect193r1_OID_VALUE)
{
if (ECDsaFactory.IsCurveValid(new Oid(ECDSA_Sect193r1_OID_VALUE)))
{
// Specify different curve by name
newEc.GenerateKey(ECCurve.CreateFromValue(ECDSA_Sect193r1_OID_VALUE));
Assert.Equal(193, newEc.KeySize);
param2 = newEc.ExportExplicitParameters(true);
// Keys should should not match
ComparePrivateKey(param, param2, false);
ComparePublicKey(param.Q, param2.Q, false);
// Polynomial,X,Y (and others) should not match
Assert.True(param2.Curve.IsCharacteristic2);
Assert.NotEqual(param.Curve.Polynomial, param2.Curve.Polynomial);
Assert.NotEqual(param.Curve.G.X, param2.Curve.G.X);
Assert.NotEqual(param.Curve.G.Y, param2.Curve.G.Y);
}
}
}
}
}
}
[ActiveIssue(10206, Xunit.PlatformID.AnyUnix)]
[Theory, MemberData(nameof(TestCurves))]
public void TestRegenKeyNamed(CurveDef curveDef)
{
ECParameters param, param2;
ECDsa ec;
using (ec = ECDsaFactory.Create(curveDef.Curve))
{
param = ec.ExportParameters(true);
Assert.NotEqual(param.D, null);
param.Validate();
ec.GenerateKey(param.Curve);
param2 = ec.ExportParameters(true);
param2.Validate();
// Only curve should match
ComparePrivateKey(param, param2, false);
ComparePublicKey(param.Q, param2.Q, false);
CompareCurve(param.Curve, param2.Curve);
}
}
[ActiveIssue(10206, Xunit.PlatformID.AnyUnix)]
[ConditionalFact(nameof(ECExplicitCurvesSupported))]
public void TestRegenKeyNistP256()
{
ECParameters param, param2;
ECDsa ec;
using (ec = ECDsaFactory.Create(256))
{
param = ec.ExportExplicitParameters(true);
Assert.NotEqual(param.D, null);
ec.GenerateKey(param.Curve);
param2 = ec.ExportExplicitParameters(true);
// Only curve should match
ComparePrivateKey(param, param2, false);
ComparePublicKey(param.Q, param2.Q, false);
CompareCurve(param.Curve, param2.Curve);
}
}
[Theory, MemberData(nameof(TestCurves))]
public void TestChangeFromNamedCurveToKeySize(CurveDef curveDef)
{
using (ECDsa ec = ECDsaFactory.Create(curveDef.Curve))
{
ECParameters param = ec.ExportParameters(false);
// Avoid comparing against same key as in curveDef
if (ec.KeySize != 384 && ec.KeySize != 521)
{
ec.KeySize = 384;
ECParameters param384 = ec.ExportParameters(false);
Assert.NotEqual(param.Curve.Oid.FriendlyName, param384.Curve.Oid.FriendlyName);
Assert.Equal(384, ec.KeySize);
ec.KeySize = 521;
ECParameters param521 = ec.ExportParameters(false);
Assert.NotEqual(param384.Curve.Oid.FriendlyName, param521.Curve.Oid.FriendlyName);
Assert.Equal(521, ec.KeySize);
}
}
}
[ConditionalFact(nameof(ECExplicitCurvesSupported))]
public void TestPositive256WithExplicitParameters()
{
using (ECDsa ecdsa = ECDsaFactory.Create())
{
ecdsa.ImportParameters(ECDsaTestData.GetNistP256ExplicitTestData());
Verify256(ecdsa, true);
}
}
[Fact]
public void TestNegative256WithRandomKey()
{
using (ECDsa ecdsa = ECDsaFactory.Create(ECCurve.NamedCurves.nistP256))
{
Verify256(ecdsa, false); // will not match because of randomness
}
}
[Theory, MemberData(nameof(AllImplementations))]
public void SignDataByteArray_NullData_ThrowsArgumentNullException(ECDsa ecdsa)
{
Assert.Throws<ArgumentNullException>("data",
() => ecdsa.SignData((byte[])null, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void SignDataByteArray_DefaultHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa)
{
Assert.Throws<ArgumentException>("hashAlgorithm",
() => ecdsa.SignData(new byte[0], default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void SignDataByteArraySpan_NullData_ThrowsArgumentNullException(ECDsa ecdsa)
{
Assert.Throws<ArgumentNullException>("data",
() => ecdsa.SignData(null, -1, -1, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void SignDataByteArraySpan_NegativeOffset_ThrowsArgumentOutOfRangeException(ECDsa ecdsa)
{
Assert.Throws<ArgumentOutOfRangeException>("offset",
() => ecdsa.SignData(new byte[0], -1, -1, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void SignDataByteArraySpan_OffsetGreaterThanCount_ThrowsArgumentOutOfRangeException(ECDsa ecdsa)
{
Assert.Throws<ArgumentOutOfRangeException>("offset",
() => ecdsa.SignData(new byte[0], 2, 1, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void SignDataByteArraySpan_NegativeCount_ThrowsArgumentOutOfRangeException(ECDsa ecdsa)
{
Assert.Throws<ArgumentOutOfRangeException>("count",
() => ecdsa.SignData(new byte[0], 0, -1, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void SignDataByteArraySpan_CountGreaterThanLengthMinusOffset_ThrowsArgumentOutOfRangeException(ECDsa ecdsa)
{
Assert.Throws<ArgumentOutOfRangeException>("count",
() => ecdsa.SignData(new byte[0], 0, 1, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void SignDataByteArraySpan_DefaultHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa)
{
Assert.Throws<ArgumentException>("hashAlgorithm",
() => ecdsa.SignData(new byte[0], 0, 0, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void SignDataByteArraySpan_EmptyHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa)
{
Assert.Throws<ArgumentException>("hashAlgorithm",
() => ecdsa.SignData(new byte[10], 0, 10, new HashAlgorithmName("")));
}
[Theory, MemberData(nameof(AllImplementations))]
public void SignDataStream_NullData_ThrowsArgumentNullException(ECDsa ecdsa)
{
Assert.Throws<ArgumentNullException>("data",
() => ecdsa.SignData((Stream)null, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void SignDataStream_DefaultHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa)
{
Assert.Throws<ArgumentException>("hashAlgorithm",
() => ecdsa.SignData(new MemoryStream(), default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void VerifyDataByteArray_NullData_ThrowsArgumentNullException(ECDsa ecdsa)
{
Assert.Throws<ArgumentNullException>("data",
() => ecdsa.VerifyData((byte[])null, null, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void VerifyDataByteArray_NullSignature_ThrowsArgumentNullException(ECDsa ecdsa)
{
Assert.Throws<ArgumentNullException>("signature",
() => ecdsa.VerifyData(new byte[0], null, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void VerifyDataByteArray_DefaultHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa)
{
Assert.Throws<ArgumentException>("hashAlgorithm",
() => ecdsa.VerifyData(new byte[0], new byte[0], default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void VerifyDataByteArraySpan_NullData_ThrowsArgumentNullException(ECDsa ecdsa)
{
Assert.Throws<ArgumentNullException>("data",
() => ecdsa.VerifyData((byte[])null, -1, -1, null, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void VerifyDataByteArraySpan_NegativeOffset_ThrowsArgumentOutOfRangeException(ECDsa ecdsa)
{
Assert.Throws<ArgumentOutOfRangeException>("offset",
() => ecdsa.VerifyData(new byte[0], -1, -1, null, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void VerifyDataByteArraySpan_OffsetGreaterThanCount_ThrowsArgumentOutOfRangeException(ECDsa ecdsa)
{
Assert.Throws<ArgumentOutOfRangeException>("offset",
() => ecdsa.VerifyData(new byte[0], 2, 1, null, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void VerifyDataByteArraySpan_NegativeCount_ThrowsArgumentOutOfRangeException(ECDsa ecdsa)
{
Assert.Throws<ArgumentOutOfRangeException>("count",
() => ecdsa.VerifyData(new byte[0], 0, -1, null, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void VerifyDataByteArraySpan_CountGreaterThanLengthMinusOffset_ThrowsArgumentOutOfRangeException(ECDsa ecdsa)
{
Assert.Throws<ArgumentOutOfRangeException>("count",
() => ecdsa.VerifyData(new byte[0], 0, 1, null, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void VerifyDataByteArraySpan_NullSignature_ThrowsArgumentNullException(ECDsa ecdsa)
{
Assert.Throws<ArgumentNullException>("signature",
() => ecdsa.VerifyData(new byte[0], 0, 0, null, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void VerifyDataByteArraySpan_EmptyHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa)
{
Assert.Throws<ArgumentException>("hashAlgorithm",
() => ecdsa.VerifyData(new byte[10], 0, 10, new byte[0], new HashAlgorithmName("")));
}
[Theory, MemberData(nameof(AllImplementations))]
public void VerifyDataStream_NullData_ThrowsArgumentNullException(ECDsa ecdsa)
{
Assert.Throws<ArgumentNullException>("data",
() => ecdsa.VerifyData((Stream)null, null, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void VerifyDataStream_NullSignature_ThrowsArgumentNullException(ECDsa ecdsa)
{
Assert.Throws<ArgumentNullException>("signature",
() => ecdsa.VerifyData(new MemoryStream(), null, default(HashAlgorithmName)));
}
[Theory, MemberData(nameof(AllImplementations))]
public void VerifyDataStream_DefaultHashAlgorithm_ThrowsArgumentException(ECDsa ecdsa)
{
Assert.Throws<ArgumentException>("hashAlgorithm",
() => ecdsa.VerifyData(new MemoryStream(), new byte[0], default(HashAlgorithmName)));
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static IEnumerable<object[]> AllImplementations()
{
return new[] {
new ECDsa[] { ECDsaFactory.Create() },
new ECDsa[] { new ECDsaStub() },
};
}
public static IEnumerable<object[]> RealImplementations()
{
return new[] {
new ECDsa[] { ECDsaFactory.Create() },
};
}
[Theory, MemberData(nameof(RealImplementations))]
public void SignHash_NullHash_ThrowsArgumentNullException(ECDsa ecdsa)
{
Assert.Throws<ArgumentNullException>(
"hash",
() => ecdsa.SignHash(null));
}
[Theory, MemberData(nameof(RealImplementations))]
public void VerifyHash_NullHash_ThrowsArgumentNullException(ECDsa ecdsa)
{
Assert.Throws<ArgumentNullException>(
"hash",
() => ecdsa.VerifyHash(null, null));
}
[Theory, MemberData(nameof(RealImplementations))]
public void VerifyHash_NullSignature_ThrowsArgumentNullException(ECDsa ecdsa)
{
Assert.Throws<ArgumentNullException>(
"signature",
() => ecdsa.VerifyHash(new byte[0], null));
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
[Theory, MemberData(nameof(RealImplementations))]
public void SignDataByteArray_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa)
{
Assert.Throws<CryptographicException>(
() => ecdsa.SignData(new byte[0], new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM")));
}
[Theory, MemberData(nameof(RealImplementations))]
public void SignDataByteArraySpan_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa)
{
Assert.Throws<CryptographicException>(
() => ecdsa.SignData(new byte[0], 0, 0, new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM")));
}
[Theory, MemberData(nameof(RealImplementations))]
public void SignDataStream_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa)
{
Assert.Throws<CryptographicException>(
() => ecdsa.SignData(new MemoryStream(), new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM")));
}
[Theory, MemberData(nameof(RealImplementations))]
public void VerifyDataByteArray_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa)
{
Assert.Throws<CryptographicException>(
() => ecdsa.VerifyData(new byte[0], new byte[0], new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM")));
}
[Theory, MemberData(nameof(RealImplementations))]
public void VerifyDataByteArraySpan_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa)
{
Assert.Throws<CryptographicException>(
() => ecdsa.VerifyData(new byte[0], 0, 0, new byte[0], new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM")));
}
[Theory, MemberData(nameof(RealImplementations))]
public void VerifyDataStream_UnsupportedHashAlgorithm_ThrowsCryptographicException(ECDsa ecdsa)
{
Assert.Throws<CryptographicException>(
() => ecdsa.VerifyData(new MemoryStream(), new byte[0], new HashAlgorithmName("NOT_A_REAL_HASH_ALGORITHM")));
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
[Theory, MemberData(nameof(RealImplementations))]
public void SignData_MaxOffset_ZeroLength_NoThrow(ECDsa ecdsa)
{
// Explicitly larger than Array.Empty
byte[] data = new byte[10];
byte[] signature = ecdsa.SignData(data, data.Length, 0, HashAlgorithmName.SHA256);
Assert.True(ecdsa.VerifyData(Array.Empty<byte>(), signature, HashAlgorithmName.SHA256));
}
[Theory, MemberData(nameof(RealImplementations))]
public void VerifyData_MaxOffset_ZeroLength_NoThrow(ECDsa ecdsa)
{
// Explicitly larger than Array.Empty
byte[] data = new byte[10];
byte[] signature = ecdsa.SignData(Array.Empty<byte>(), HashAlgorithmName.SHA256);
Assert.True(ecdsa.VerifyData(data, data.Length, 0, signature, HashAlgorithmName.SHA256));
}
[Theory, MemberData(nameof(RealImplementations))]
public void Roundtrip_WithOffset(ECDsa ecdsa)
{
byte[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
byte[] halfData = { 5, 6, 7, 8, 9 };
byte[] dataSignature = ecdsa.SignData(data, 5, data.Length - 5, HashAlgorithmName.SHA256);
byte[] halfDataSignature = ecdsa.SignData(halfData, HashAlgorithmName.SHA256);
// Cross-feed the VerifyData calls to prove that both offsets work
Assert.True(ecdsa.VerifyData(data, 5, data.Length - 5, halfDataSignature, HashAlgorithmName.SHA256));
Assert.True(ecdsa.VerifyData(halfData, dataSignature, HashAlgorithmName.SHA256));
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
[Theory]
[InlineData(256)]
[InlineData(384)]
[InlineData(521)]
public void CreateKey(int keySize)
{
using (ECDsa ecdsa = ECDsaFactory.Create())
{
// Step 1, don't throw here.
ecdsa.KeySize = keySize;
// Step 2, ensure the key was generated without throwing.
ecdsa.SignData(Array.Empty<byte>(), HashAlgorithmName.SHA256);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static IEnumerable<object[]> InteroperableSignatureConfigurations()
{
foreach (HashAlgorithmName hashAlgorithm in new[] {
HashAlgorithmName.MD5,
HashAlgorithmName.SHA1,
HashAlgorithmName.SHA256,
HashAlgorithmName.SHA384,
HashAlgorithmName.SHA512 })
{
yield return new object[] { ECDsaFactory.Create(), hashAlgorithm };
}
}
[Theory, MemberData(nameof(InteroperableSignatureConfigurations))]
public void SignVerify_InteroperableSameKeys_RoundTripsUnlessTampered(ECDsa ecdsa, HashAlgorithmName hashAlgorithm)
{
byte[] data = Encoding.UTF8.GetBytes("something to repeat and sign");
// large enough to make hashing work though multiple iterations and not a multiple of 4KB it uses.
byte[] dataArray = new byte[33333];
MemoryStream dataStream = new MemoryStream(dataArray, true);
while (dataStream.Position < dataArray.Length - data.Length)
{
dataStream.Write(data, 0, data.Length);
}
dataStream.Position = 0;
byte[] dataArray2 = new byte[dataArray.Length + 2];
dataArray.CopyTo(dataArray2, 1);
ArraySegment<byte> dataSpan = new ArraySegment<byte>(dataArray2, 1, dataArray.Length);
HashAlgorithm halg;
if (hashAlgorithm == HashAlgorithmName.MD5)
halg = MD5.Create();
else if (hashAlgorithm == HashAlgorithmName.SHA1)
halg = SHA1.Create();
else if (hashAlgorithm == HashAlgorithmName.SHA256)
halg = SHA256.Create();
else if (hashAlgorithm == HashAlgorithmName.SHA384)
halg = SHA384.Create();
else if (hashAlgorithm == HashAlgorithmName.SHA512)
halg = SHA512.Create();
else
throw new Exception("Hash algorithm not supported.");
List<byte[]> signatures = new List<byte[]>(6);
// Compute a signature using each of the SignData overloads. Then, verify it using each
// of the VerifyData overloads, and VerifyHash overloads.
//
// Then, verify that VerifyHash fails if the data is tampered with.
signatures.Add(ecdsa.SignData(dataArray, hashAlgorithm));
signatures.Add(ecdsa.SignData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, hashAlgorithm));
signatures.Add(ecdsa.SignData(dataStream, hashAlgorithm));
dataStream.Position = 0;
signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataArray)));
signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count)));
signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataStream)));
dataStream.Position = 0;
foreach (byte[] signature in signatures)
{
Assert.True(ecdsa.VerifyData(dataArray, signature, hashAlgorithm), "Verify 1");
Assert.True(ecdsa.VerifyData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, signature, hashAlgorithm), "Verify 2");
Assert.True(ecdsa.VerifyData(dataStream, signature, hashAlgorithm), "Verify 3");
Assert.True(dataStream.Position == dataArray.Length, "Check stream read 3A");
dataStream.Position = 0;
Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify 4");
Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count), signature), "Verify 5");
Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataStream), signature), "Verify 6");
Assert.True(dataStream.Position == dataArray.Length, "Check stream read 6A");
dataStream.Position = 0;
}
int distinctSignatures = signatures.Distinct(new ByteArrayComparer()).Count();
Assert.True(distinctSignatures == signatures.Count, "Signing should be randomized");
foreach (byte[] signature in signatures)
{
signature[signature.Length - 1] ^= 0xFF; // flip some bits
Assert.False(ecdsa.VerifyData(dataArray, signature, hashAlgorithm), "Verify Tampered 1");
Assert.False(ecdsa.VerifyData(dataSpan.Array, dataSpan.Offset, dataSpan.Count, signature, hashAlgorithm), "Verify Tampered 2");
Assert.False(ecdsa.VerifyData(dataStream, signature, hashAlgorithm), "Verify Tampered 3");
Assert.True(dataStream.Position == dataArray.Length, "Check stream read 3B");
dataStream.Position = 0;
Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify Tampered 4");
Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataSpan.Array, dataSpan.Offset, dataSpan.Count), signature), "Verify Tampered 5");
Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataStream), signature), "Verify Tampered 6");
Assert.True(dataStream.Position == dataArray.Length, "Check stream read 6B");
dataStream.Position = 0;
}
}
private class ByteArrayComparer : IEqualityComparer<byte[]>
{
public bool Equals(byte[] x, byte[] y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(byte[] obj)
{
int h = 5381;
foreach (byte b in obj)
{
h = ((h << 5) + h) ^ b.GetHashCode();
}
return h;
}
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.Sec;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
namespace Org.BouncyCastle.Security
{
public sealed class PrivateKeyFactory
{
private PrivateKeyFactory()
{
}
public static IAsymmetricKeyParameter CreateKey(
byte[] privateKeyInfoData)
{
return CreateKey(
PrivateKeyInfo.GetInstance(
Asn1Object.FromByteArray(privateKeyInfoData)));
}
public static IAsymmetricKeyParameter CreateKey(
Stream inStr)
{
return CreateKey(
PrivateKeyInfo.GetInstance(
Asn1Object.FromStream(inStr)));
}
public static IAsymmetricKeyParameter CreateKey(
PrivateKeyInfo keyInfo)
{
AlgorithmIdentifier algID = keyInfo.AlgorithmID;
DerObjectIdentifier algOid = algID.ObjectID;
// TODO See RSAUtil.isRsaOid in Java build
if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption)
|| algOid.Equals(X509ObjectIdentifiers.IdEARsa)
|| algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss)
|| algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
{
RsaPrivateKeyStructure keyStructure = new RsaPrivateKeyStructure(
Asn1Sequence.GetInstance(keyInfo.PrivateKey));
return new RsaPrivateCrtKeyParameters(
keyStructure.Modulus,
keyStructure.PublicExponent,
keyStructure.PrivateExponent,
keyStructure.Prime1,
keyStructure.Prime2,
keyStructure.Exponent1,
keyStructure.Exponent2,
keyStructure.Coefficient);
}
// TODO?
// else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
{
DHParameter para = new DHParameter(
Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
DerInteger derX = (DerInteger)keyInfo.PrivateKey;
IBigInteger lVal = para.L;
int l = lVal == null ? 0 : lVal.IntValue;
DHParameters dhParams = new DHParameters(para.P, para.G, null, l);
return new DHPrivateKeyParameters(derX.Value, dhParams, algOid);
}
else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
{
ElGamalParameter para = new ElGamalParameter(
Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
DerInteger derX = (DerInteger)keyInfo.PrivateKey;
return new ElGamalPrivateKeyParameters(
derX.Value,
new ElGamalParameters(para.P, para.G));
}
else if (algOid.Equals(X9ObjectIdentifiers.IdDsa))
{
DerInteger derX = (DerInteger) keyInfo.PrivateKey;
Asn1Encodable ae = algID.Parameters;
DsaParameters parameters = null;
if (ae != null)
{
DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
parameters = new DsaParameters(para.P, para.Q, para.G);
}
return new DsaPrivateKeyParameters(derX.Value, parameters);
}
else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
{
X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object());
X9ECParameters ecP;
if (para.IsNamedCurve)
{
ecP = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier) para.Parameters);
}
else
{
ecP = new X9ECParameters((Asn1Sequence) para.Parameters);
}
ECDomainParameters dParams = new ECDomainParameters(
ecP.Curve,
ecP.G,
ecP.N,
ecP.H,
ecP.GetSeed());
ECPrivateKeyStructure ec = new ECPrivateKeyStructure(
Asn1Sequence.GetInstance(keyInfo.PrivateKey));
return new ECPrivateKeyParameters(ec.GetKey(), dParams);
}
else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
{
Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
ECPrivateKeyStructure ec = new ECPrivateKeyStructure(
Asn1Sequence.GetInstance(keyInfo.PrivateKey));
ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);
if (ecP == null)
return null;
return new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet);
}
else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
{
Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
DerOctetString derX = (DerOctetString) keyInfo.PrivateKey;
byte[] keyEnc = derX.GetOctets();
byte[] keyBytes = new byte[keyEnc.Length];
for (int i = 0; i != keyEnc.Length; i++)
{
keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian
}
IBigInteger x = new BigInteger(1, keyBytes);
return new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet);
}
else
{
throw new SecurityUtilityException("algorithm identifier in key not recognised");
}
}
public static IAsymmetricKeyParameter DecryptKey(
char[] passPhrase,
EncryptedPrivateKeyInfo encInfo)
{
return CreateKey(PrivateKeyInfoFactory.CreatePrivateKeyInfo(passPhrase, encInfo));
}
public static IAsymmetricKeyParameter DecryptKey(
char[] passPhrase,
byte[] encryptedPrivateKeyInfoData)
{
return DecryptKey(passPhrase, Asn1Object.FromByteArray(encryptedPrivateKeyInfoData));
}
public static IAsymmetricKeyParameter DecryptKey(
char[] passPhrase,
Stream encryptedPrivateKeyInfoStream)
{
return DecryptKey(passPhrase, Asn1Object.FromStream(encryptedPrivateKeyInfoStream));
}
private static IAsymmetricKeyParameter DecryptKey(
char[] passPhrase,
Asn1Object asn1Object)
{
return DecryptKey(passPhrase, EncryptedPrivateKeyInfo.GetInstance(asn1Object));
}
public static byte[] EncryptKey(
DerObjectIdentifier algorithm,
char[] passPhrase,
byte[] salt,
int iterationCount,
AsymmetricKeyParameter key)
{
return EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
algorithm, passPhrase, salt, iterationCount, key).GetEncoded();
}
public static byte[] EncryptKey(
string algorithm,
char[] passPhrase,
byte[] salt,
int iterationCount,
AsymmetricKeyParameter key)
{
return EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
algorithm, passPhrase, salt, iterationCount, key).GetEncoded();
}
}
}
| |
// 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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Dynamic.Utils;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// Builder for read only collections.
/// </summary>
/// <typeparam name="T">The type of the collection element.</typeparam>
[Serializable]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
public sealed class ReadOnlyCollectionBuilder<T> : IList<T>, IList
{
private const int DefaultCapacity = 4;
private T[] _items;
private int _size;
private int _version;
/// <summary>
/// Constructs a <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
public ReadOnlyCollectionBuilder()
{
_items = Array.Empty<T>();
}
/// <summary>
/// Constructs a <see cref="ReadOnlyCollectionBuilder{T}"/> with a given initial capacity.
/// The contents are empty but builder will have reserved room for the given
/// number of elements before any reallocations are required.
/// </summary>
/// <param name="capacity">Initial capacity of the builder.</param>
public ReadOnlyCollectionBuilder(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity));
_items = new T[capacity];
}
/// <summary>
/// Constructs a <see cref="ReadOnlyCollectionBuilder{T}"/>, copying contents of the given collection.
/// </summary>
/// <param name="collection">The collection whose elements to copy to the builder.</param>
public ReadOnlyCollectionBuilder(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
ICollection<T> c = collection as ICollection<T>;
if (c != null)
{
int count = c.Count;
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
else
{
_size = 0;
_items = new T[DefaultCapacity];
using (IEnumerator<T> en = collection.GetEnumerator())
{
while (en.MoveNext())
{
Add(en.Current);
}
}
}
}
/// <summary>
/// Gets and sets the capacity of this <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
public int Capacity
{
get { return _items.Length; }
set
{
if (value < _size)
throw new ArgumentOutOfRangeException(nameof(value));
if (value != _items.Length)
{
if (value > 0)
{
T[] newItems = new T[value];
if (_size > 0)
{
Array.Copy(_items, 0, newItems, 0, _size);
}
_items = newItems;
}
else
{
_items = Array.Empty<T>();
}
}
}
}
/// <summary>
/// Returns number of elements in the <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
public int Count => _size;
#region IList<T> Members
/// <summary>
/// Returns the index of the first occurrence of a given value in the builder.
/// </summary>
/// <param name="item">An item to search for.</param>
/// <returns>The index of the first occurrence of an item.</returns>
public int IndexOf(T item)
{
return Array.IndexOf(_items, item, 0, _size);
}
/// <summary>
/// Inserts an item to the <see cref="ReadOnlyCollectionBuilder{T}"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which item should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
public void Insert(int index, T item)
{
if (index > _size)
throw new ArgumentOutOfRangeException(nameof(index));
if (_size == _items.Length)
{
EnsureCapacity(_size + 1);
}
if (index < _size)
{
Array.Copy(_items, index, _items, index + 1, _size - index);
}
_items[index] = item;
_size++;
_version++;
}
/// <summary>
/// Removes the <see cref="ReadOnlyCollectionBuilder{T}"/> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
public void RemoveAt(int index)
{
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException(nameof(index));
_size--;
if (index < _size)
{
Array.Copy(_items, index + 1, _items, index, _size - index);
}
_items[_size] = default(T);
_version++;
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <returns>The element at the specified index.</returns>
public T this[int index]
{
get
{
if (index >= _size)
throw new ArgumentOutOfRangeException(nameof(index));
return _items[index];
}
set
{
if (index >= _size)
throw new ArgumentOutOfRangeException(nameof(index));
_items[index] = value;
_version++;
}
}
#endregion
#region ICollection<T> Members
/// <summary>
/// Adds an item to the <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
public void Add(T item)
{
if (_size == _items.Length)
{
EnsureCapacity(_size + 1);
}
_items[_size++] = item;
_version++;
}
/// <summary>
/// Removes all items from the <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
public void Clear()
{
if (_size > 0)
{
Array.Clear(_items, 0, _size);
_size = 0;
}
_version++;
}
/// <summary>
/// Determines whether the <see cref="ReadOnlyCollectionBuilder{T}"/> contains a specific value
/// </summary>
/// <param name="item">the object to locate in the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
/// <returns>true if item is found in the <see cref="ReadOnlyCollectionBuilder{T}"/>; otherwise, false.</returns>
public bool Contains(T item)
{
if ((object)item == null)
{
for (int i = 0; i < _size; i++)
{
if ((object)_items[i] == null)
{
return true;
}
}
return false;
}
else
{
EqualityComparer<T> c = EqualityComparer<T>.Default;
for (int i = 0; i < _size; i++)
{
if (c.Equals(_items[i], item))
{
return true;
}
}
return false;
}
}
/// <summary>
/// Copies the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/> to an <see cref="Array"/>,
/// starting at particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
/// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
public void CopyTo(T[] array, int arrayIndex)
{
Array.Copy(_items, 0, array, arrayIndex, _size);
}
bool ICollection<T>.IsReadOnly => false;
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
/// <param name="item">The object to remove from the <see cref="ReadOnlyCollectionBuilder{T}"/>.</param>
/// <returns>true if item was successfully removed from the <see cref="ReadOnlyCollectionBuilder{T}"/>;
/// otherwise, false. This method also returns false if item is not found in the original <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </returns>
public bool Remove(T item)
{
int index = IndexOf(item);
if (index >= 0)
{
RemoveAt(index);
return true;
}
return false;
}
#endregion
#region IEnumerable<T> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.</returns>
public IEnumerator<T> GetEnumerator() => new Enumerator(this);
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
#region IList Members
bool IList.IsReadOnly => false;
int IList.Add(object value)
{
ValidateNullValue(value, nameof(value));
try
{
Add((T)value);
}
catch (InvalidCastException)
{
throw InvalidTypeException(value, nameof(value));
}
return Count - 1;
}
bool IList.Contains(object value)
{
if (IsCompatibleObject(value))
{
return Contains((T)value);
}
else return false;
}
int IList.IndexOf(object value)
{
if (IsCompatibleObject(value))
{
return IndexOf((T)value);
}
return -1;
}
void IList.Insert(int index, object value)
{
ValidateNullValue(value, nameof(value));
try
{
Insert(index, (T)value);
}
catch (InvalidCastException)
{
throw InvalidTypeException(value, nameof(value));
}
}
bool IList.IsFixedSize => false;
void IList.Remove(object value)
{
if (IsCompatibleObject(value))
{
Remove((T)value);
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
ValidateNullValue(value, nameof(value));
try
{
this[index] = (T)value;
}
catch (InvalidCastException)
{
throw InvalidTypeException(value, nameof(value));
}
}
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(nameof(array));
Array.Copy(_items, 0, array, index, _size);
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => this;
#endregion
/// <summary>
/// Reverses the order of the elements in the entire <see cref="ReadOnlyCollectionBuilder{T}"/>.
/// </summary>
public void Reverse()
{
Reverse(0, Count);
}
/// <summary>
/// Reverses the order of the elements in the specified range.
/// </summary>
/// <param name="index">The zero-based starting index of the range to reverse.</param>
/// <param name="count">The number of elements in the range to reverse.</param>
public void Reverse(int index, int count)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
Array.Reverse(_items, index, count);
_version++;
}
/// <summary>
/// Copies the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/> to a new array.
/// </summary>
/// <returns>An array containing copies of the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/>.</returns>
public T[] ToArray()
{
T[] array = new T[_size];
Array.Copy(_items, 0, array, 0, _size);
return array;
}
/// <summary>
/// Creates a <see cref="ReadOnlyCollection{T}"/> containing all of the elements of the <see cref="ReadOnlyCollectionBuilder{T}"/>,
/// avoiding copying the elements to the new array if possible. Resets the <see cref="ReadOnlyCollectionBuilder{T}"/> after the
/// <see cref="ReadOnlyCollection{T}"/> has been created.
/// </summary>
/// <returns>A new instance of <see cref="ReadOnlyCollection{T}"/>.</returns>
public ReadOnlyCollection<T> ToReadOnlyCollection()
{
// Can we use the stored array?
T[] items;
if (_size == _items.Length)
{
items = _items;
}
else
{
items = ToArray();
}
_items = Array.Empty<T>();
_size = 0;
_version++;
return new TrueReadOnlyCollection<T>(items);
}
private void EnsureCapacity(int min)
{
if (_items.Length < min)
{
int newCapacity = DefaultCapacity;
if (_items.Length > 0)
{
newCapacity = _items.Length * 2;
}
if (newCapacity < min)
{
newCapacity = min;
}
Capacity = newCapacity;
}
}
private static bool IsCompatibleObject(object value)
{
return ((value is T) || (value == null && default(T) == null));
}
private static void ValidateNullValue(object value, string argument)
{
if (value == null && !(default(T) == null))
{
throw new ArgumentException(Strings.InvalidNullValue(typeof(T)), argument);
}
}
private static Exception InvalidTypeException(object value, string argument)
{
return new ArgumentException(Strings.InvalidObjectType(value != null ? value.GetType() : (object)"null", typeof(T)), argument);
}
[Serializable]
private class Enumerator : IEnumerator<T>, IEnumerator
{
private readonly ReadOnlyCollectionBuilder<T> _builder;
private readonly int _version;
private int _index;
private T _current;
internal Enumerator(ReadOnlyCollectionBuilder<T> builder)
{
_builder = builder;
_version = builder._version;
_index = 0;
_current = default(T);
}
#region IEnumerator<T> Members
public T Current => _current;
#endregion
#region IDisposable Members
public void Dispose()
{
}
#endregion
#region IEnumerator Members
object IEnumerator.Current
{
get
{
if (_index == 0 || _index > _builder._size)
{
throw Error.EnumerationIsDone();
}
return _current;
}
}
public bool MoveNext()
{
if (_version == _builder._version)
{
if (_index < _builder._size)
{
_current = _builder._items[_index++];
return true;
}
else
{
_index = _builder._size + 1;
_current = default(T);
return false;
}
}
else
{
throw Error.CollectionModifiedWhileEnumerating();
}
}
#endregion
#region IEnumerator Members
void IEnumerator.Reset()
{
if (_version != _builder._version)
{
throw Error.CollectionModifiedWhileEnumerating();
}
_index = 0;
_current = default(T);
}
#endregion
}
}
}
| |
namespace Epi.Windows.MakeView.Dialogs.FieldDefinitionDialogs
{
partial class RelateFieldDefinition
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RelateFieldDefinition));
this.rdbAccessibleAlways = new System.Windows.Forms.RadioButton();
this.rdbAccessibleWithConditions = new System.Windows.Forms.RadioButton();
this.lblCondition = new System.Windows.Forms.Label();
this.txtCondition = new System.Windows.Forms.TextBox();
this.lblAvailableVariables = new System.Windows.Forms.Label();
this.cbxVariables = new System.Windows.Forms.ComboBox();
this.grpOperators = new System.Windows.Forms.GroupBox();
this.toolStrip4 = new System.Windows.Forms.ToolStrip();
this.btnAnd = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.btnOr = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.btnYes = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.btnNo = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.btnMissing = new System.Windows.Forms.ToolStripButton();
this.toolStrip3 = new System.Windows.Forms.ToolStrip();
this.btnPlus = new System.Windows.Forms.ToolStripButton();
this.btnMinus = new System.Windows.Forms.ToolStripButton();
this.btnTimes = new System.Windows.Forms.ToolStripButton();
this.btnDivide = new System.Windows.Forms.ToolStripButton();
this.btnEqual = new System.Windows.Forms.ToolStripButton();
this.btnLess = new System.Windows.Forms.ToolStripButton();
this.btnGreat = new System.Windows.Forms.ToolStripButton();
this.btnAmp = new System.Windows.Forms.ToolStripButton();
this.btnQuote = new System.Windows.Forms.ToolStripButton();
this.btnOpenParen = new System.Windows.Forms.ToolStripButton();
this.btnCloseParen = new System.Windows.Forms.ToolStripButton();
this.chkReturnToParent = new System.Windows.Forms.CheckBox();
this.chkNutstat = new System.Windows.Forms.CheckBox();
this.label2 = new System.Windows.Forms.Label();
this.cbxRelatedView = new System.Windows.Forms.ComboBox();
this.groupBox1.SuspendLayout();
this.grpOperators.SuspendLayout();
this.toolStrip4.SuspendLayout();
this.toolStrip3.SuspendLayout();
this.SuspendLayout();
//
// btnButtonFont
//
resources.ApplyResources(this.btnButtonFont, "btnButtonFont");
//
// txtPrompt
//
resources.ApplyResources(this.txtPrompt, "txtPrompt");
//
// txtFieldName
//
resources.ApplyResources(this.txtFieldName, "txtFieldName");
//
// btnCancel
//
resources.ApplyResources(this.btnCancel, "btnCancel");
//
// btnOk
//
resources.ApplyResources(this.btnOk, "btnOk");
//
// groupBox1
//
this.groupBox1.Controls.Add(this.chkNutstat);
this.groupBox1.Controls.Add(this.chkReturnToParent);
this.groupBox1.Controls.Add(this.grpOperators);
this.groupBox1.Controls.Add(this.cbxVariables);
this.groupBox1.Controls.Add(this.lblAvailableVariables);
this.groupBox1.Controls.Add(this.txtCondition);
this.groupBox1.Controls.Add(this.lblCondition);
this.groupBox1.Controls.Add(this.rdbAccessibleAlways);
this.groupBox1.Controls.Add(this.rdbAccessibleWithConditions);
resources.ApplyResources(this.groupBox1, "groupBox1");
this.groupBox1.Controls.SetChildIndex(this.btnFieldFont, 0);
this.groupBox1.Controls.SetChildIndex(this.rdbAccessibleWithConditions, 0);
this.groupBox1.Controls.SetChildIndex(this.btnPromptFont, 0);
this.groupBox1.Controls.SetChildIndex(this.rdbAccessibleAlways, 0);
this.groupBox1.Controls.SetChildIndex(this.lblCondition, 0);
this.groupBox1.Controls.SetChildIndex(this.txtCondition, 0);
this.groupBox1.Controls.SetChildIndex(this.lblAvailableVariables, 0);
this.groupBox1.Controls.SetChildIndex(this.cbxVariables, 0);
this.groupBox1.Controls.SetChildIndex(this.grpOperators, 0);
this.groupBox1.Controls.SetChildIndex(this.chkReturnToParent, 0);
this.groupBox1.Controls.SetChildIndex(this.chkNutstat, 0);
//
// btnPromptFont
//
resources.ApplyResources(this.btnPromptFont, "btnPromptFont");
//
// btnFieldFont
//
resources.ApplyResources(this.btnFieldFont, "btnFieldFont");
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
this.baseImageList.Images.SetKeyName(76, "");
this.baseImageList.Images.SetKeyName(77, "");
this.baseImageList.Images.SetKeyName(78, "");
this.baseImageList.Images.SetKeyName(79, "");
this.baseImageList.Images.SetKeyName(80, "");
this.baseImageList.Images.SetKeyName(81, "");
this.baseImageList.Images.SetKeyName(82, "");
this.baseImageList.Images.SetKeyName(83, "");
this.baseImageList.Images.SetKeyName(84, "");
this.baseImageList.Images.SetKeyName(85, "");
this.baseImageList.Images.SetKeyName(86, "");
//
// rdbAccessibleAlways
//
resources.ApplyResources(this.rdbAccessibleAlways, "rdbAccessibleAlways");
this.rdbAccessibleAlways.Checked = true;
this.rdbAccessibleAlways.Name = "rdbAccessibleAlways";
this.rdbAccessibleAlways.TabStop = true;
this.rdbAccessibleAlways.UseVisualStyleBackColor = true;
//
// rdbAccessibleWithConditions
//
resources.ApplyResources(this.rdbAccessibleWithConditions, "rdbAccessibleWithConditions");
this.rdbAccessibleWithConditions.Name = "rdbAccessibleWithConditions";
this.rdbAccessibleWithConditions.UseVisualStyleBackColor = true;
this.rdbAccessibleWithConditions.CheckedChanged += new System.EventHandler(this.rdbAccessibleWithConditions_CheckedChanged);
//
// lblCondition
//
resources.ApplyResources(this.lblCondition, "lblCondition");
this.lblCondition.Name = "lblCondition";
//
// txtCondition
//
resources.ApplyResources(this.txtCondition, "txtCondition");
this.txtCondition.Name = "txtCondition";
//
// lblAvailableVariables
//
resources.ApplyResources(this.lblAvailableVariables, "lblAvailableVariables");
this.lblAvailableVariables.Name = "lblAvailableVariables";
//
// cbxVariables
//
resources.ApplyResources(this.cbxVariables, "cbxVariables");
this.cbxVariables.FormattingEnabled = true;
this.cbxVariables.Name = "cbxVariables";
this.cbxVariables.SelectedIndexChanged += new System.EventHandler(this.cbxVariables_SelectedIndexChanged);
//
// grpOperators
//
this.grpOperators.Controls.Add(this.toolStrip4);
this.grpOperators.Controls.Add(this.toolStrip3);
resources.ApplyResources(this.grpOperators, "grpOperators");
this.grpOperators.Name = "grpOperators";
this.grpOperators.TabStop = false;
//
// toolStrip4
//
this.toolStrip4.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.toolStrip4.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btnAnd,
this.toolStripSeparator4,
this.btnOr,
this.toolStripSeparator5,
this.btnYes,
this.toolStripSeparator6,
this.btnNo,
this.toolStripSeparator7,
this.btnMissing});
resources.ApplyResources(this.toolStrip4, "toolStrip4");
this.toolStrip4.Name = "toolStrip4";
//
// btnAnd
//
this.btnAnd.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnAnd, "btnAnd");
this.btnAnd.Name = "btnAnd";
this.btnAnd.Click += new System.EventHandler(this.ClickHandler);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4");
//
// btnOr
//
this.btnOr.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnOr, "btnOr");
this.btnOr.Name = "btnOr";
this.btnOr.Click += new System.EventHandler(this.ClickHandler);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
resources.ApplyResources(this.toolStripSeparator5, "toolStripSeparator5");
//
// btnYes
//
this.btnYes.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnYes, "btnYes");
this.btnYes.Name = "btnYes";
this.btnYes.Click += new System.EventHandler(this.ClickHandler);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
resources.ApplyResources(this.toolStripSeparator6, "toolStripSeparator6");
//
// btnNo
//
this.btnNo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnNo, "btnNo");
this.btnNo.Name = "btnNo";
this.btnNo.Click += new System.EventHandler(this.ClickHandler);
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
resources.ApplyResources(this.toolStripSeparator7, "toolStripSeparator7");
//
// btnMissing
//
this.btnMissing.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnMissing, "btnMissing");
this.btnMissing.Name = "btnMissing";
this.btnMissing.Click += new System.EventHandler(this.ClickHandler);
//
// toolStrip3
//
this.toolStrip3.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.toolStrip3.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btnPlus,
this.btnMinus,
this.btnTimes,
this.btnDivide,
this.btnEqual,
this.btnLess,
this.btnGreat,
this.btnAmp,
this.btnQuote,
this.btnOpenParen,
this.btnCloseParen});
resources.ApplyResources(this.toolStrip3, "toolStrip3");
this.toolStrip3.Name = "toolStrip3";
//
// btnPlus
//
this.btnPlus.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnPlus, "btnPlus");
this.btnPlus.Name = "btnPlus";
this.btnPlus.Click += new System.EventHandler(this.ClickHandler);
//
// btnMinus
//
this.btnMinus.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnMinus, "btnMinus");
this.btnMinus.Name = "btnMinus";
this.btnMinus.Click += new System.EventHandler(this.ClickHandler);
//
// btnTimes
//
this.btnTimes.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnTimes, "btnTimes");
this.btnTimes.Name = "btnTimes";
this.btnTimes.Click += new System.EventHandler(this.ClickHandler);
//
// btnDivide
//
this.btnDivide.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnDivide, "btnDivide");
this.btnDivide.Name = "btnDivide";
this.btnDivide.Click += new System.EventHandler(this.ClickHandler);
//
// btnEqual
//
this.btnEqual.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnEqual, "btnEqual");
this.btnEqual.Name = "btnEqual";
this.btnEqual.Click += new System.EventHandler(this.ClickHandler);
//
// btnLess
//
this.btnLess.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnLess, "btnLess");
this.btnLess.Name = "btnLess";
this.btnLess.Click += new System.EventHandler(this.ClickHandler);
//
// btnGreat
//
this.btnGreat.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnGreat, "btnGreat");
this.btnGreat.Name = "btnGreat";
this.btnGreat.Click += new System.EventHandler(this.ClickHandler);
//
// btnAmp
//
this.btnAmp.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnAmp, "btnAmp");
this.btnAmp.Name = "btnAmp";
this.btnAmp.Click += new System.EventHandler(this.ClickHandler);
//
// btnQuote
//
this.btnQuote.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnQuote, "btnQuote");
this.btnQuote.Name = "btnQuote";
this.btnQuote.Click += new System.EventHandler(this.ClickHandler);
//
// btnOpenParen
//
this.btnOpenParen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnOpenParen, "btnOpenParen");
this.btnOpenParen.Name = "btnOpenParen";
this.btnOpenParen.Click += new System.EventHandler(this.ClickHandler);
//
// btnCloseParen
//
this.btnCloseParen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
resources.ApplyResources(this.btnCloseParen, "btnCloseParen");
this.btnCloseParen.Name = "btnCloseParen";
//
// chkReturnToParent
//
resources.ApplyResources(this.chkReturnToParent, "chkReturnToParent");
this.chkReturnToParent.Name = "chkReturnToParent";
this.chkReturnToParent.UseVisualStyleBackColor = true;
//
// chkNutstat
//
resources.ApplyResources(this.chkNutstat, "chkNutstat");
this.chkNutstat.Name = "chkNutstat";
this.chkNutstat.UseVisualStyleBackColor = true;
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.ImageList = this.baseImageList;
this.label2.Name = "label2";
//
// cbxRelatedView
//
this.cbxRelatedView.FormattingEnabled = true;
resources.ApplyResources(this.cbxRelatedView, "cbxRelatedView");
this.cbxRelatedView.Name = "cbxRelatedView";
//
// RelateFieldDefinition
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.cbxRelatedView);
this.Controls.Add(this.label2);
this.Name = "RelateFieldDefinition";
this.Controls.SetChildIndex(this.txtFieldName, 0);
this.Controls.SetChildIndex(this.btnOk, 0);
this.Controls.SetChildIndex(this.btnCancel, 0);
this.Controls.SetChildIndex(this.groupBox1, 0);
this.Controls.SetChildIndex(this.label2, 0);
this.Controls.SetChildIndex(this.cbxRelatedView, 0);
this.Controls.SetChildIndex(this.btnButtonFont, 0);
this.Controls.SetChildIndex(this.lblPrompt, 0);
this.Controls.SetChildIndex(this.txtPrompt, 0);
this.Controls.SetChildIndex(this.label1, 0);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.grpOperators.ResumeLayout(false);
this.grpOperators.PerformLayout();
this.toolStrip4.ResumeLayout(false);
this.toolStrip4.PerformLayout();
this.toolStrip3.ResumeLayout(false);
this.toolStrip3.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.RadioButton rdbAccessibleAlways;
private System.Windows.Forms.RadioButton rdbAccessibleWithConditions;
private System.Windows.Forms.ComboBox cbxVariables;
private System.Windows.Forms.Label lblAvailableVariables;
private System.Windows.Forms.TextBox txtCondition;
private System.Windows.Forms.Label lblCondition;
private System.Windows.Forms.GroupBox grpOperators;
private System.Windows.Forms.ToolStrip toolStrip4;
private System.Windows.Forms.ToolStripButton btnAnd;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripButton btnOr;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripButton btnYes;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripButton btnNo;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripButton btnMissing;
private System.Windows.Forms.ToolStrip toolStrip3;
private System.Windows.Forms.ToolStripButton btnPlus;
private System.Windows.Forms.ToolStripButton btnMinus;
private System.Windows.Forms.ToolStripButton btnTimes;
private System.Windows.Forms.ToolStripButton btnDivide;
private System.Windows.Forms.ToolStripButton btnEqual;
private System.Windows.Forms.ToolStripButton btnLess;
private System.Windows.Forms.ToolStripButton btnGreat;
private System.Windows.Forms.ToolStripButton btnAmp;
private System.Windows.Forms.ToolStripButton btnQuote;
private System.Windows.Forms.ToolStripButton btnOpenParen;
private System.Windows.Forms.ToolStripButton btnCloseParen;
private System.Windows.Forms.CheckBox chkNutstat;
private System.Windows.Forms.CheckBox chkReturnToParent;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox cbxRelatedView;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace NaughtyAttributes.Editor
{
[CanEditMultipleObjects]
[CustomEditor(typeof(UnityEngine.Object), true)]
public class InspectorEditor : UnityEditor.Editor
{
private SerializedProperty script;
private IEnumerable<FieldInfo> fields;
private HashSet<FieldInfo> groupedFields;
private Dictionary<string, List<FieldInfo>> groupedFieldsByGroupName;
private IEnumerable<FieldInfo> nonSerializedFields;
private IEnumerable<PropertyInfo> nativeProperties;
private IEnumerable<MethodInfo> methods;
private Dictionary<string, SerializedProperty> serializedPropertiesByFieldName;
private bool useDefaultInspector;
protected virtual void OnEnable()
{
this.script = this.serializedObject.FindProperty("m_Script");
// Cache serialized fields and order
this.fields = ReflectionUtility.GetAllFields(this.target, f => this.serializedObject.FindProperty(f.Name) != null).OrderByDescending(field=>
{
int order = 0;
var drawOrderAttr = field.GetCustomAttributes(typeof(DrawOrderAttribute), true).FirstOrDefault() as DrawOrderAttribute;
if (drawOrderAttr != null)
{
order = drawOrderAttr.Order;
}
return order;
});
// If there are no NaughtyAttributes use default inspector
if (this.fields.All(f => f.GetCustomAttributes(typeof(NaughtyAttribute), true).Length == 0))
{
this.useDefaultInspector = true;
}
else
{
this.useDefaultInspector = false;
// Cache grouped fields
this.groupedFields = new HashSet<FieldInfo>(this.fields.Where(f => f.GetCustomAttributes(typeof(GroupAttribute), true).Length > 0));
// Cache grouped fields by group name
this.groupedFieldsByGroupName = new Dictionary<string, List<FieldInfo>>();
foreach (var groupedField in this.groupedFields)
{
string groupName = (groupedField.GetCustomAttributes(typeof(GroupAttribute), true)[0] as GroupAttribute).Name;
if (this.groupedFieldsByGroupName.ContainsKey(groupName))
{
this.groupedFieldsByGroupName[groupName].Add(groupedField);
}
else
{
this.groupedFieldsByGroupName[groupName] = new List<FieldInfo>()
{
groupedField
};
}
}
// Cache serialized properties by field name
this.serializedPropertiesByFieldName = new Dictionary<string, SerializedProperty>();
foreach (var field in this.fields)
{
this.serializedPropertiesByFieldName[field.Name] = this.serializedObject.FindProperty(field.Name);
}
}
// Cache non-serialized fields
this.nonSerializedFields = ReflectionUtility.GetAllFields(
this.target, f => f.GetCustomAttributes(typeof(DrawerAttribute), true).Length > 0 && this.serializedObject.FindProperty(f.Name) == null);
// Cache the native properties
this.nativeProperties = ReflectionUtility.GetAllProperties(
this.target, p => p.GetCustomAttributes(typeof(DrawerAttribute), true).Length > 0);
// Cache methods with DrawerAttribute
this.methods = ReflectionUtility.GetAllMethods(
this.target, m => m.GetCustomAttributes(typeof(DrawerAttribute), true).Length > 0);
}
protected virtual void OnDisable()
{
PropertyDrawerDatabase.ClearCache();
}
public override void OnInspectorGUI()
{
if (this.useDefaultInspector)
{
this.DrawDefaultInspector();
}
else
{
this.serializedObject.Update();
if (this.script != null)
{
GUI.enabled = false;
EditorGUILayout.PropertyField(this.script);
GUI.enabled = true;
}
// Draw fields
HashSet<string> drawnGroups = new HashSet<string>();
foreach (var field in this.fields)
{
if (this.groupedFields.Contains(field))
{
// Draw grouped fields
string groupName = (field.GetCustomAttributes(typeof(GroupAttribute), true)[0] as GroupAttribute).Name;
if (!drawnGroups.Contains(groupName))
{
drawnGroups.Add(groupName);
PropertyGrouper grouper = this.GetPropertyGrouperForField(field);
if (grouper != null)
{
grouper.BeginGroup(groupName);
this.ValidateAndDrawFields(this.groupedFieldsByGroupName[groupName]);
grouper.EndGroup();
}
else
{
this.ValidateAndDrawFields(this.groupedFieldsByGroupName[groupName]);
}
}
}
else
{
// Draw non-grouped field
this.ValidateAndDrawField(field);
}
}
this.serializedObject.ApplyModifiedProperties();
}
// Draw non-serialized fields
foreach (var field in this.nonSerializedFields)
{
DrawerAttribute drawerAttribute = (DrawerAttribute)field.GetCustomAttributes(typeof(DrawerAttribute), true)[0];
FieldDrawer drawer = FieldDrawerDatabase.GetDrawerForAttribute(drawerAttribute.GetType());
if (drawer != null)
{
drawer.DrawField(this.target, field);
}
}
// Draw native properties
foreach (var property in this.nativeProperties)
{
DrawerAttribute drawerAttribute = (DrawerAttribute)property.GetCustomAttributes(typeof(DrawerAttribute), true)[0];
NativePropertyDrawer drawer = NativePropertyDrawerDatabase.GetDrawerForAttribute(drawerAttribute.GetType());
if (drawer != null)
{
drawer.DrawNativeProperty(this.target, property);
}
}
// Draw methods
foreach (var method in this.methods)
{
DrawerAttribute drawerAttribute = (DrawerAttribute)method.GetCustomAttributes(typeof(DrawerAttribute), true)[0];
MethodDrawer methodDrawer = MethodDrawerDatabase.GetDrawerForAttribute(drawerAttribute.GetType());
if (methodDrawer != null)
{
methodDrawer.DrawMethod(this.target, method);
}
}
}
private void ValidateAndDrawFields(IEnumerable<FieldInfo> fields)
{
foreach (var field in fields)
{
this.ValidateAndDrawField(field);
}
}
private void ValidateAndDrawField(FieldInfo field)
{
this.DrawField(field);
this.ValidateField(field);
this.ApplyFieldMeta(field);
}
private void ValidateField(FieldInfo field)
{
ValidatorAttribute[] validatorAttributes = (ValidatorAttribute[])field.GetCustomAttributes(typeof(ValidatorAttribute), true);
foreach (var attribute in validatorAttributes)
{
PropertyValidator validator = PropertyValidatorDatabase.GetValidatorForAttribute(attribute.GetType());
if (validator != null)
{
validator.ValidateProperty(this.serializedPropertiesByFieldName[field.Name]);
}
}
}
private void DrawField(FieldInfo field)
{
// Check if the field has draw conditions
PropertyDrawCondition drawCondition = this.GetPropertyDrawConditionForField(field);
if (drawCondition != null)
{
bool canDrawProperty = drawCondition.CanDrawProperty(this.serializedPropertiesByFieldName[field.Name]);
if (!canDrawProperty)
{
return;
}
}
// Check if the field has HideInInspectorAttribute
HideInInspector[] hideInInspectorAttributes = (HideInInspector[])field.GetCustomAttributes(typeof(HideInInspector), true);
if (hideInInspectorAttributes.Length > 0)
{
return;
}
// Draw the field
EditorGUI.BeginChangeCheck();
PropertyDrawer drawer = this.GetPropertyDrawerForField(field);
if (drawer != null)
{
drawer.DrawProperty(this.serializedPropertiesByFieldName[field.Name]);
}
else
{
EditorDrawUtility.DrawPropertyField(this.serializedPropertiesByFieldName[field.Name]);
}
if (EditorGUI.EndChangeCheck())
{
OnValueChangedAttribute[] onValueChangedAttributes = (OnValueChangedAttribute[])field.GetCustomAttributes(typeof(OnValueChangedAttribute), true);
foreach (var onValueChangedAttribute in onValueChangedAttributes)
{
PropertyMeta meta = PropertyMetaDatabase.GetMetaForAttribute(onValueChangedAttribute.GetType());
if (meta != null)
{
meta.ApplyPropertyMeta(this.serializedPropertiesByFieldName[field.Name], onValueChangedAttribute);
}
}
}
}
private void ApplyFieldMeta(FieldInfo field)
{
// Apply custom meta attributes
MetaAttribute[] metaAttributes = field
.GetCustomAttributes(typeof(MetaAttribute), true)
.Where(attr => attr.GetType() != typeof(OnValueChangedAttribute))
.Select(obj => obj as MetaAttribute)
.ToArray();
Array.Sort(metaAttributes, (x, y) =>
{
return x.Order - y.Order;
});
foreach (var metaAttribute in metaAttributes)
{
PropertyMeta meta = PropertyMetaDatabase.GetMetaForAttribute(metaAttribute.GetType());
if (meta != null)
{
meta.ApplyPropertyMeta(this.serializedPropertiesByFieldName[field.Name], metaAttribute);
}
}
}
private PropertyDrawer GetPropertyDrawerForField(FieldInfo field)
{
DrawerAttribute[] drawerAttributes = (DrawerAttribute[])field.GetCustomAttributes(typeof(DrawerAttribute), true);
if (drawerAttributes.Length > 0)
{
PropertyDrawer drawer = PropertyDrawerDatabase.GetDrawerForAttribute(drawerAttributes[0].GetType());
return drawer;
}
else
{
return null;
}
}
private PropertyGrouper GetPropertyGrouperForField(FieldInfo field)
{
GroupAttribute[] groupAttributes = (GroupAttribute[])field.GetCustomAttributes(typeof(GroupAttribute), true);
if (groupAttributes.Length > 0)
{
PropertyGrouper grouper = PropertyGrouperDatabase.GetGrouperForAttribute(groupAttributes[0].GetType());
return grouper;
}
else
{
return null;
}
}
private PropertyDrawCondition GetPropertyDrawConditionForField(FieldInfo field)
{
DrawConditionAttribute[] drawConditionAttributes = (DrawConditionAttribute[])field.GetCustomAttributes(typeof(DrawConditionAttribute), true);
if (drawConditionAttributes.Length > 0)
{
PropertyDrawCondition drawCondition = PropertyDrawConditionDatabase.GetDrawConditionForAttribute(drawConditionAttributes[0].GetType());
return drawCondition;
}
else
{
return null;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Signum.Utilities;
using Signum.Entities;
using Signum.Utilities.DataStructures;
using System.Reflection;
using Signum.Engine.Maps;
using System.Threading;
using Signum.Utilities.Reflection;
using Signum.Utilities.ExpressionTrees;
using Signum.Engine.Basics;
using Signum.Engine.DynamicQuery;
using Signum.Entities.Reflection;
using System.Linq.Expressions;
using Signum.Entities.Basics;
using Signum.Engine.Operations.Internal;
namespace Signum.Engine.Operations
{
public static class OperationLogic
{
[AutoExpressionField]
public static IQueryable<OperationLogEntity> OperationLogs(this Entity e) =>
As.Expression(() => Database.Query<OperationLogEntity>().Where(a => a.Target.Is(e)));
[AutoExpressionField]
public static OperationLogEntity PreviousOperationLog(this Entity e) =>
As.Expression(() => e.OperationLogs().Where(ol => ol.End.HasValue && e.SystemPeriod().Contains(ol.End.Value)).OrderBy(a => a.End!.Value).FirstOrDefault());
[AutoExpressionField]
public static IQueryable<OperationLogEntity> Logs(this OperationSymbol o) =>
As.Expression(() => Database.Query<OperationLogEntity>().Where(a => a.Operation == o));
static Polymorphic<Dictionary<OperationSymbol, IOperation>> operations = new Polymorphic<Dictionary<OperationSymbol, IOperation>>(PolymorphicMerger.InheritDictionaryInterfaces, typeof(IEntity));
static ResetLazy<Dictionary<OperationSymbol, List<Type>>> operationsFromKey = new ResetLazy<Dictionary<OperationSymbol, List<Type>>>(() =>
{
return (from t in operations.OverridenTypes
from d in operations.GetDefinition(t)!.Keys
group t by d into g
select KeyValuePair.Create(g.Key, g.ToList())).ToDictionary();
});
public static HashSet<OperationSymbol> RegisteredOperations
{
get { return operations.OverridenValues.SelectMany(a => a.Keys).ToHashSet(); }
}
static readonly Variable<ImmutableStack<Type>> allowedTypes = Statics.ThreadVariable<ImmutableStack<Type>>("saveOperationsAllowedTypes");
public static bool AllowSaveGlobally { get; set; }
public static bool IsSaveAllowedInContext(Type type)
{
var stack = allowedTypes.Value;
return (stack != null && stack.Contains(type));
}
public static IDisposable AllowSave<T>() where T : class, IEntity
{
return AllowSave(typeof(T));
}
public static IDisposable AllowSave(Type type)
{
allowedTypes.Value = (allowedTypes.Value ?? ImmutableStack<Type>.Empty).Push(type);
return new Disposable(() => allowedTypes.Value = allowedTypes.Value.Pop());
}
public static void AssertStarted(SchemaBuilder sb)
{
sb.AssertDefined(ReflectionTools.GetMethodInfo(() => Start(null!)));
}
public static void Start(SchemaBuilder sb)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
sb.Include<OperationLogEntity>()
.WithQuery(() => lo => new
{
Entity = lo,
lo.Id,
lo.Target,
lo.Operation,
lo.User,
lo.Start,
lo.End,
lo.Exception
});
SymbolLogic<OperationSymbol>.Start(sb, () => RegisteredOperations);
sb.Include<OperationSymbol>()
.WithQuery(() => os => new
{
Entity = os,
os.Id,
os.Key
});
QueryLogic.Expressions.Register((OperationSymbol o) => o.Logs(), () => OperationMessage.Logs.NiceToString());
QueryLogic.Expressions.Register((Entity o) => o.OperationLogs(), () => typeof(OperationLogEntity).NicePluralName());
sb.Schema.EntityEventsGlobal.Saving += EntityEventsGlobal_Saving;
sb.Schema.Table<OperationSymbol>().PreDeleteSqlSync += new Func<Entity, SqlPreCommand>(Operation_PreDeleteSqlSync);
sb.Schema.Table<TypeEntity>().PreDeleteSqlSync += new Func<Entity, SqlPreCommand>(Type_PreDeleteSqlSync);
sb.Schema.SchemaCompleted += OperationLogic_Initializing;
sb.Schema.SchemaCompleted += () => RegisterCurrentLogs(sb.Schema);
ExceptionLogic.DeleteLogs += ExceptionLogic_DeleteLogs;
}
}
private static void RegisterCurrentLogs(Schema schema)
{
var s = Schema.Current;
foreach (var t in s.Tables.Values.Where(t => t.SystemVersioned != null))
{
giRegisterExpression.GetInvoker(t.Type)();
}
}
static GenericInvoker<Action> giRegisterExpression =
new GenericInvoker<Action>(() => RegisterPreviousLog<Entity>());
public static void RegisterPreviousLog<T>()
where T : Entity
{
QueryLogic.Expressions.Register(
(T entity) => entity.PreviousOperationLog(),
() => OperationMessage.PreviousOperationLog.NiceToString());
}
public static void ExceptionLogic_DeleteLogs(DeleteLogParametersEmbedded parameters, StringBuilder sb, CancellationToken token)
{
var dateLimit = parameters.GetDateLimitDelete(typeof(OperationLogEntity).ToTypeEntity());
if (dateLimit != null)
Database.Query<OperationLogEntity>().Where(o => o.Start < dateLimit!.Value).UnsafeDeleteChunksLog(parameters, sb, token);
dateLimit = parameters.GetDateLimitDeleteWithExceptions(typeof(OperationLogEntity).ToTypeEntity());
if (dateLimit == null)
return;
Database.Query<OperationLogEntity>().Where(o => o.Start < dateLimit!.Value && o.Exception != null).UnsafeDeleteChunksLog(parameters, sb, token);
}
static void OperationLogic_Initializing()
{
try
{
var types = Schema.Current.Tables.Keys
.Where(t => EntityKindCache.GetAttribute(t) == null);
if (types.Any())
throw new InvalidOperationException($"{0} has not EntityTypeAttribute".FormatWith(types.Select(a => "'" + a.TypeName() + "'").CommaAnd()));
var errors = (from t in Schema.Current.Tables.Keys
let attr = EntityKindCache.GetAttribute(t)
where attr.RequiresSaveOperation && !HasSaveLike(t)
select attr.IsRequiresSaveOperationOverriden ?
"'{0}' has '{1}' set to true, but no operation for saving has been implemented.".FormatWith(t.TypeName(), nameof(attr.RequiresSaveOperation)) :
"'{0}' is 'EntityKind.{1}', but no operation for saving has been implemented.".FormatWith(t.TypeName(), attr.EntityKind)).ToList();
if (errors.Any())
throw new InvalidOperationException(errors.ToString("\r\n") + @"
Consider the following options:
* Implement an operation for saving using 'save' snippet or .WithSave() method.
* Change the EntityKind to a more appropiated one.
* Exceptionally, override the property EntityTypeAttribute.RequiresSaveOperation for your particular entity.");
}
catch (Exception e) when (StartParameters.IgnoredCodeErrors != null)
{
StartParameters.IgnoredCodeErrors.Add(e);
}
}
static SqlPreCommand Operation_PreDeleteSqlSync(Entity arg)
{
return Administrator.DeleteWhereScript((OperationLogEntity ol) => ol.Operation, (OperationSymbol)arg);
}
static SqlPreCommand Type_PreDeleteSqlSync(Entity arg)
{
var table = Schema.Current.Table<OperationLogEntity>();
var column = (IColumn)((FieldImplementedByAll)Schema.Current.Field((OperationLogEntity ol) => ol.Target)).ColumnType;
return Administrator.DeleteWhereScript(table, column, ((TypeEntity)arg).Id);
}
static void EntityEventsGlobal_Saving(Entity ident)
{
if (ident.IsGraphModified &&
EntityKindCache.RequiresSaveOperation(ident.GetType()) && !AllowSaveGlobally && !IsSaveAllowedInContext(ident.GetType()))
throw new InvalidOperationException("Saving '{0}' is controlled by the operations. Use using(OperationLogic.AllowSave<{0}>()) or execute {1}".FormatWith(
ident.GetType().Name,
operations.GetValue(ident.GetType()).Values
.Where(IsSaveLike)
.CommaOr(o => o.OperationSymbol.Key)));
}
#region Events
public static event SurroundOperationHandler? SurroundOperation;
public static event AllowOperationHandler? AllowOperation;
internal static IDisposable? OnSuroundOperation(IOperation operation, OperationLogEntity log, IEntity? entity, object?[]? args)
{
return Disposable.Combine(SurroundOperation, f => f(operation, log, (Entity?)entity, args));
}
internal static void SetExceptionData(Exception ex, OperationSymbol operationSymbol, IEntity? entity, object?[]? args)
{
ex.Data["operation"] = operationSymbol;
ex.Data["entity"] = entity;
if (args != null)
ex.Data["args"] = args;
}
public static bool OperationAllowed(OperationSymbol operationSymbol, Type entityType, bool inUserInterface)
{
if (AllowOperation != null)
return AllowOperation(operationSymbol, entityType, inUserInterface);
else
return true;
}
public static void AssertOperationAllowed(OperationSymbol operationSymbol, Type entityType, bool inUserInterface)
{
if (!OperationAllowed(operationSymbol, entityType, inUserInterface))
throw new UnauthorizedAccessException(OperationMessage.Operation01IsNotAuthorized.NiceToString().FormatWith(operationSymbol.NiceToString(), operationSymbol.Key) +
(inUserInterface ? " " + OperationMessage.InUserInterface.NiceToString() : ""));
}
#endregion
public static void Register(this IOperation operation, bool replace = false)
{
if (!operation.OverridenType.IsIEntity())
throw new InvalidOperationException("Type '{0}' has to implement at least {1}".FormatWith(operation.OverridenType.Name));
operation.AssertIsValid();
var dic = operations.GetOrAddDefinition(operation.OverridenType);
if (replace)
dic[operation.OperationSymbol] = operation;
else
dic.AddOrThrow(operation.OperationSymbol, operation, "Operation {0} has already been registered");
operations.ClearCache();
operationsFromKey.Reset();
}
private static bool HasSaveLike(Type entityType)
{
return TypeOperations(entityType).Any(IsSaveLike);
}
private static bool IsSaveLike(IOperation operation)
{
return operation is IExecuteOperation && ((IEntityOperation)operation).CanBeModified == true;
}
public static List<OperationInfo> ServiceGetOperationInfos(Type entityType)
{
try
{
return (from oper in TypeOperations(entityType)
where OperationAllowed(oper.OperationSymbol, entityType, true)
select ToOperationInfo(oper)).ToList();
}
catch(Exception e)
{
e.Data["EntityType"] = entityType.TypeName();
throw;
}
}
public static bool HasConstructOperations(Type entityType)
{
return TypeOperations(entityType).Any(o => o.OperationType == Entities.OperationType.Constructor);
}
public static List<OperationInfo> GetAllOperationInfos(Type entityType)
{
return TypeOperations(entityType).Select(o => ToOperationInfo(o)).ToList();
}
public static OperationInfo GetOperationInfo(Type type, OperationSymbol operationSymbol)
{
return ToOperationInfo(FindOperation(type, operationSymbol));
}
public static IEnumerable<OperationSymbol> AllSymbols()
{
return operationsFromKey.Value.Keys;
}
private static OperationInfo ToOperationInfo(IOperation oper)
{
return new OperationInfo(oper.OperationSymbol, oper.OperationType)
{
CanBeModified = (oper as IEntityOperation)?.CanBeModified,
Returns = oper.Returns,
ReturnType = oper.ReturnType,
HasStates = (oper as IGraphHasStatesOperation)?.HasFromStates,
HasCanExecute = (oper as IEntityOperation)?.HasCanExecute,
CanBeNew = (oper as IEntityOperation)?.CanBeNew,
BaseType = (oper as IEntityOperation)?.BaseType ?? (oper as IConstructorFromManyOperation)?.BaseType
};
}
public static Dictionary<OperationSymbol, string> ServiceCanExecute(Entity entity)
{
try
{
var entityType = entity.GetType();
return (from o in TypeOperations(entityType)
let eo = o as IEntityOperation
where eo != null && (eo.CanBeNew || !entity.IsNew) && OperationAllowed(o.OperationSymbol, entityType, true)
select KeyValuePair.Create(eo.OperationSymbol, eo.CanExecute(entity))).ToDictionary();
}
catch(Exception e)
{
e.Data["entity"] = entity.BaseToString();
throw;
}
}
#region Execute
public static T Execute<T>(this T entity, ExecuteSymbol<T> symbol, params object?[]? args)
where T : class, IEntity
{
var op = Find<IExecuteOperation>(entity.GetType(), symbol.Symbol).AssertEntity((Entity)(IEntity)entity);
op.Execute(entity, args);
return (T)(IEntity)entity;
}
public static Entity ServiceExecute(IEntity entity, OperationSymbol operationSymbol, params object?[]? args)
{
var op = Find<IExecuteOperation>(entity.GetType(), operationSymbol).AssertEntity((Entity)(IEntity)entity);
op.Execute(entity, args);
return (Entity)(IEntity)entity;
}
public static T ExecuteLite<T>(this Lite<T> lite, ExecuteSymbol<T> symbol, params object?[]? args)
where T : class, IEntity
{
T entity = lite.RetrieveAndForget();
var op = Find<IExecuteOperation>(lite.EntityType, symbol.Symbol).AssertLite();
op.Execute(entity, args);
return entity;
}
public static Entity ServiceExecuteLite(Lite<IEntity> lite, OperationSymbol operationSymbol, params object?[]? args)
{
Entity entity = (Entity)lite.RetrieveAndForget();
var op = Find<IExecuteOperation>(lite.EntityType, operationSymbol);
op.Execute(entity, args);
return entity;
}
public static string? CanExecute<T>(this T entity, IEntityOperationSymbolContainer<T> symbol)
where T : class, IEntity
{
var op = Find<IEntityOperation>(entity.GetType(), symbol.Symbol);
return op.CanExecute(entity);
}
public static string? ServiceCanExecute(Entity entity, OperationSymbol operationSymbol)
{
var op = Find<IEntityOperation>(entity.GetType(), operationSymbol);
return op.CanExecute(entity);
}
#endregion
#region Delete
public static void DeleteLite<T>(this Lite<T> lite, DeleteSymbol<T> symbol, params object?[]? args)
where T : class, IEntity
{
IEntity entity = lite.RetrieveAndForget();
var op = Find<IDeleteOperation>(lite.EntityType, symbol.Symbol).AssertLite();
op.Delete(entity, args);
}
public static void ServiceDelete(Lite<IEntity> lite, OperationSymbol operationSymbol, params object?[]? args)
{
IEntity entity = lite.RetrieveAndForget();
var op = Find<IDeleteOperation>(lite.EntityType, operationSymbol);
op.Delete(entity, args);
}
public static void Delete<T>(this T entity, DeleteSymbol<T> symbol, params object?[]? args)
where T : class, IEntity
{
var op = Find<IDeleteOperation>(entity.GetType(), symbol.Symbol).AssertEntity((Entity)(IEntity)entity);
op.Delete(entity, args);
}
public static void ServiceDelete(Entity entity, OperationSymbol operationSymbol, params object?[]? args)
{
var op = Find<IDeleteOperation>(entity.GetType(), operationSymbol).AssertEntity((Entity)(IEntity)entity);
op.Delete(entity, args);
}
#endregion
#region Construct
public static Entity ServiceConstruct(Type type, OperationSymbol operationSymbol, params object?[]? args)
{
var op = Find<IConstructOperation>(type, operationSymbol);
return (Entity)op.Construct(args);
}
public static T Construct<T>(ConstructSymbol<T>.Simple symbol, params object?[]? args)
where T : class, IEntity
{
var op = Find<IConstructOperation>(typeof(T), symbol.Symbol);
return (T)op.Construct(args);
}
#endregion
#region ConstructFrom
public static T ConstructFrom<F, T>(this F entity, ConstructSymbol<T>.From<F> symbol, params object?[]? args)
where T : class, IEntity
where F : class, IEntity
{
var op = Find<IConstructorFromOperation>(entity.GetType(), symbol.Symbol).AssertEntity((Entity)(object)entity);
return (T)op.Construct(entity, args);
}
public static Entity ServiceConstructFrom(IEntity entity, OperationSymbol operationSymbol, params object?[]? args)
{
var op = Find<IConstructorFromOperation>(entity.GetType(), operationSymbol).AssertEntity((Entity)(object)entity);
return (Entity)op.Construct(entity, args);
}
public static T ConstructFromLite<F, T>(this Lite<F> lite, ConstructSymbol<T>.From<F> symbol, params object?[]? args)
where T : class, IEntity
where F : class, IEntity
{
var op = Find<IConstructorFromOperation>(lite.EntityType, symbol.Symbol).AssertLite();
return (T)op.Construct(Database.RetrieveAndForget(lite), args);
}
public static Entity ServiceConstructFromLite(Lite<IEntity> lite, OperationSymbol operationSymbol, params object?[]? args)
{
var op = Find<IConstructorFromOperation>(lite.EntityType, operationSymbol);
return (Entity)op.Construct(Database.RetrieveAndForget(lite), args);
}
#endregion
#region ConstructFromMany
public static Entity ServiceConstructFromMany(IEnumerable<Lite<IEntity>> lites, Type type, OperationSymbol operationSymbol, params object?[]? args)
{
var onlyType = lites.Select(a => a.EntityType).Distinct().Only();
return (Entity)Find<IConstructorFromManyOperation>(onlyType ?? type, operationSymbol).Construct(lites, args);
}
public static T ConstructFromMany<F, T>(List<Lite<F>> lites, ConstructSymbol<T>.FromMany<F> symbol, params object?[]? args)
where T : class, IEntity
where F : class, IEntity
{
var onlyType = lites.Select(a => a.EntityType).Distinct().Only();
return (T)(IEntity)Find<IConstructorFromManyOperation>(onlyType ?? typeof(F), symbol.Symbol).Construct(lites.Cast<Lite<IEntity>>().ToList(), args);
}
#endregion
public static T Find<T>(Type type, OperationSymbol operationSymbol)
where T : IOperation
{
IOperation result = FindOperation(type, operationSymbol);
if (!(result is T))
throw new InvalidOperationException("Operation '{0}' is a {1} not a {2} use {3} instead".FormatWith(operationSymbol, result.GetType().TypeName(), typeof(T).TypeName(),
result is IExecuteOperation ? "Execute" :
result is IDeleteOperation ? "Delete" :
result is IConstructOperation ? "Construct" :
result is IConstructorFromOperation ? "ConstructFrom" :
result is IConstructorFromManyOperation ? "ConstructFromMany" : null));
return (T)result;
}
public static IOperation FindOperation(Type type, OperationSymbol operationSymbol)
{
IOperation? result = TryFindOperation(type, operationSymbol);
if (result == null)
throw new InvalidOperationException("Operation '{0}' not found for type {1}".FormatWith(operationSymbol, type));
return result;
}
public static IOperation? TryFindOperation(Type type, OperationSymbol operationSymbol)
{
return operations.TryGetValue(type.CleanType())?.TryGetC(operationSymbol);
}
public static Graph<T>.Construct FindConstruct<T>(ConstructSymbol<T>.Simple symbol)
where T : class, IEntity
{
return (Graph<T>.Construct)FindOperation(typeof(T), symbol.Symbol);
}
public static Graph<T>.ConstructFrom<F> FindConstructFrom<F, T>(ConstructSymbol<T>.From<F> symbol)
where T : class, IEntity
where F : class, IEntity
{
return (Graph<T>.ConstructFrom<F>)FindOperation(typeof(F), symbol.Symbol);
}
public static Graph<T>.ConstructFromMany<F> FindConstructFromMany<F, T>(ConstructSymbol<T>.FromMany<F> symbol)
where T : class, IEntity
where F : class, IEntity
{
return (Graph<T>.ConstructFromMany<F>)FindOperation(typeof(F), symbol.Symbol);
}
public static Graph<T>.Execute FindExecute<T>(ExecuteSymbol<T> symbol)
where T : class, IEntity
{
return (Graph<T>.Execute)FindOperation(typeof(T), symbol.Symbol);
}
public static Graph<T>.Delete FindDelete<T>(DeleteSymbol<T> symbol)
where T : class, IEntity
{
return (Graph<T>.Delete)FindOperation(typeof(T), symbol.Symbol);
}
static T AssertLite<T>(this T result)
where T : IEntityOperation
{
if (result.CanBeModified)
throw new InvalidOperationException("Operation {0} is not allowed for Lites".FormatWith(result.OperationSymbol));
return result;
}
static T AssertEntity<T>(this T result, Entity entity)
where T : IEntityOperation
{
if (!result.CanBeModified)
{
var list = GraphExplorer.FromRoot(entity).Where(a => a.Modified == ModifiedState.SelfModified);
if (list.Any())
throw new InvalidOperationException("Operation {0} needs a Lite or a clean entity, but the entity has changes:\r\n {1}"
.FormatWith(result.OperationSymbol, list.ToString("\r\n")));
}
return result;
}
public static IEnumerable<IOperation> TypeOperations(Type type)
{
var dic = operations.TryGetValue(type);
if (dic == null)
return Enumerable.Empty<IOperation>();
return dic.Values;
}
public static IEnumerable<IOperation> TypeOperationsAndConstructors(Type type)
{
var typeOperations = from t in TypeOperations(type)
where t.OperationType != Entities.OperationType.ConstructorFrom &&
t.OperationType != Entities.OperationType.ConstructorFromMany
select t;
var returnTypeOperations = from kvp in operationsFromKey.Value
select FindOperation(kvp.Value.FirstEx(), kvp.Key) into op
where op.OperationType == Entities.OperationType.ConstructorFrom &&
op.OperationType == Entities.OperationType.ConstructorFromMany
where op.ReturnType == type
select op;
return typeOperations.Concat(returnTypeOperations);
}
public static string? InState<T>(this T state, params T[] fromStates) where T : struct, Enum
{
if (!fromStates.Contains(state))
return OperationMessage.StateShouldBe0InsteadOf1.NiceToString().FormatWith(
fromStates.CommaOr(v => ((Enum)(object)v).NiceToString()),
((Enum)(object)state).NiceToString());
return null;
}
public static List<Type> FindTypes(OperationSymbol operation)
{
return operationsFromKey.Value
.TryGetC(operation)
.EmptyIfNull()
.ToList();
}
internal static IEnumerable<Graph<E, S>.IGraphOperation> GraphOperations<E, S>()
where E : Entity
{
return operations.OverridenValues.SelectMany(d => d.Values).OfType<Graph<E, S>.IGraphOperation>();
}
public static bool IsDefined(Type type, OperationSymbol operation)
{
return operations.TryGetValue(type)?.TryGetC(operation) != null;
}
public static OperationType OperationType(Type type, OperationSymbol operationSymbol)
{
return FindOperation(type, operationSymbol).OperationType;
}
public static Dictionary<OperationSymbol, string> GetContextualCanExecute(IEnumerable<Lite<IEntity>> lites, List<OperationSymbol> operationSymbols)
{
Dictionary<OperationSymbol, string> result = new Dictionary<OperationSymbol, string>();
using (ExecutionMode.Global())
{
foreach (var grLites in lites.GroupBy(a => a.EntityType))
{
var operations = operationSymbols.Select(opKey => FindOperation(grLites.Key, opKey)).ToList();
foreach (var grOperations in operations.GroupBy(a => a.GetType().GetGenericArguments().Let(arr => Tuple.Create(arr[0], arr[1]))))
{
var dic = giGetContextualGraphCanExecute.GetInvoker(grLites.Key, grOperations.Key.Item1, grOperations.Key.Item2)(grLites, grOperations);
if (result.IsEmpty())
result.AddRange(dic);
else
{
foreach (var kvp in dic)
{
result[kvp.Key] = "\r\n".Combine(result.TryGetC(kvp.Key), kvp.Value);
}
}
}
}
}
return result;
}
internal static GenericInvoker<Func<IEnumerable<Lite<IEntity>>, IEnumerable<IOperation>, Dictionary<OperationSymbol, string>>> giGetContextualGraphCanExecute =
new GenericInvoker<Func<IEnumerable<Lite<IEntity>>, IEnumerable<IOperation>, Dictionary<OperationSymbol, string>>>((lites, operations) => GetContextualGraphCanExecute<Entity, Entity, DayOfWeek>(lites, operations));
internal static Dictionary<OperationSymbol, string> GetContextualGraphCanExecute<T, E, S>(IEnumerable<Lite<IEntity>> lites, IEnumerable<IOperation> operations)
where E : Entity
//where S : struct (nullable enums)
where T : E
{
var getState = Graph<E, S>.GetState;
var states = lites.GroupsOf(200).SelectMany(list =>
Database.Query<T>().Where(e => list.Contains(e.ToLite())).Select(getState).Distinct()).Distinct().ToList();
return (from o in operations.Cast<Graph<E, S>.IGraphFromStatesOperation>()
let invalid = states.Where(s => !o.FromStates.Contains(s)).ToList()
where invalid.Any()
select KeyValuePair.Create(o.OperationSymbol,
OperationMessage.StateShouldBe0InsteadOf1.NiceToString().FormatWith(
o.FromStates.CommaOr(v => ((Enum)(object)v).NiceToString()),
invalid.CommaOr(v => ((Enum)(object)v).NiceToString())))).ToDictionary();
}
public static Func<OperationLogEntity, bool> LogOperation = (request) => true;
public static void SaveLog(this OperationLogEntity log)
{
if (!LogOperation(log))
return;
using (ExecutionMode.Global())
log.Save();
}
}
public static class FluentOperationInclude
{
public static FluentInclude<T> WithSave<T>(this FluentInclude<T> fi, ExecuteSymbol<T> saveOperation)
where T : Entity
{
new Graph<T>.Execute(saveOperation)
{
CanBeNew = true,
CanBeModified = true,
Execute = (e, _) => { }
}.Register();
return fi;
}
public static FluentInclude<T> WithDelete<T>(this FluentInclude<T> fi, DeleteSymbol<T> delete)
where T : Entity
{
new Graph<T>.Delete(delete)
{
Delete = (e, _) => e.Delete()
}.Register();
return fi;
}
public static FluentInclude<T> WithConstruct<T>(this FluentInclude<T> fi, ConstructSymbol<T>.Simple construct, Func<object?[]?, T> constructFunction)
where T : Entity
{
new Graph<T>.Construct(construct)
{
Construct = constructFunction
}.Register();
return fi;
}
public static FluentInclude<T> WithConstruct<T>(this FluentInclude<T> fi, ConstructSymbol<T>.Simple construct)
where T : Entity, new()
{
new Graph<T>.Construct(construct)
{
Construct = (_) => new T()
}.Register();
return fi;
}
}
public interface IOperation
{
OperationSymbol OperationSymbol { get; }
Type OverridenType { get; }
OperationType OperationType { get; }
bool Returns { get; }
Type? ReturnType { get; }
void AssertIsValid();
IEnumerable<Enum>? UntypedFromStates { get; }
IEnumerable<Enum>? UntypedToStates { get; }
Type? StateType { get; }
}
public interface IEntityOperation : IOperation
{
bool CanBeModified { get; }
bool CanBeNew { get; }
string? CanExecute(IEntity entity);
bool HasCanExecute { get; }
Type BaseType { get; }
}
public delegate IDisposable? SurroundOperationHandler(IOperation operation, OperationLogEntity log, Entity? entity, object?[]? args);
public delegate void OperationHandler(IOperation operation, Entity entity);
public delegate void ErrorOperationHandler(IOperation operation, Entity entity, Exception ex);
public delegate bool AllowOperationHandler(OperationSymbol operationSymbol, Type entityType, bool inUserInterface);
}
| |
/*
Copyright (c) 2006- DEVSENSE
Copyright (c) 2004-2006 Tomas Matousek, Ladislav Prosek, Vaclav Novak, and Martin Maly.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Reflection.Emit;
using System.Diagnostics;
using System.Collections.Generic;
using PHP.Core.AST;
using PHP.Core.Emit;
using PHP.Core.Parsers;
using PHP.Core.Reflection;
namespace PHP.Core.Compiler.AST
{
partial class NodeCompilers
{
#region JumpStmt
[NodeCompiler(typeof(JumpStmt), Singleton = true)]
sealed class JumpStmtCompiler : StatementCompiler<JumpStmt>
{
internal override Statement Analyze(JumpStmt node, Analyzer analyzer)
{
if (analyzer.IsThisCodeUnreachable())
{
analyzer.ReportUnreachableCode(node.Span);
return EmptyStmt.Unreachable;
}
if (node.Expression != null)
{
ExInfoFromParent sinfo = ExInfoFromParent.DefaultExInfo;
if (node.Type == JumpStmt.Types.Return
&& analyzer.CurrentRoutine != null && analyzer.CurrentRoutine.Signature.AliasReturn
&& node.Expression is VarLikeConstructUse)
{
sinfo.Access = AccessType.ReadRef;
}
node.Expression = node.Expression.Analyze(analyzer, sinfo).Literalize();
if (node.Type != JumpStmt.Types.Return && node.Expression.HasValue())
{
int level = Convert.ObjectToInteger(node.Expression.GetValue());
if (level > analyzer.LoopNestingLevel || level < 0)
{
analyzer.ErrorSink.Add(Errors.InvalidBreakLevelCount, analyzer.SourceUnit, node.Span, level);
}
}
}
else if (node.Type != JumpStmt.Types.Return && analyzer.LoopNestingLevel == 0)
{
analyzer.ErrorSink.Add(Errors.InvalidBreakLevelCount, analyzer.SourceUnit, node.Span, 1);
}
// code in the same block after return, break, continue is unreachable
analyzer.EnterUnreachableCode();
return node;
}
internal override void Emit(JumpStmt node, CodeGenerator codeGenerator)
{
Statistics.AST.AddNode("JumpStmt");
// marks a sequence point:
codeGenerator.MarkSequencePoint(node.Span);
switch (node.Type)
{
case JumpStmt.Types.Break:
// Emit simple break; - break the most inner loop
if (node.Expression == null)
{
codeGenerator.BranchingStack.EmitBreak();
}
else if (node.Expression.HasValue())
{
// We can get the number at compile time and generate the right branch
// instruction for break x; where x is Literal
codeGenerator.BranchingStack.EmitBreak(Convert.ObjectToInteger(node.Expression.GetValue()));
}
else
{
// In this case we emit the switch that decides where to branch at runtime.
codeGenerator.EmitConversion(node.Expression, PhpTypeCode.Integer);
codeGenerator.BranchingStack.EmitBreakRuntime();
}
break;
case JumpStmt.Types.Continue:
// Emit simple continue; - banch back to the condition of the most inner loop
if (node.Expression == null)
{
codeGenerator.BranchingStack.EmitContinue();
}
else if (node.Expression.HasValue())
{
// We can get the number at compile time and generate the right branch
// instruction for continue x; where x is Literal
codeGenerator.BranchingStack.EmitContinue(Convert.ObjectToInteger(node.Expression.GetValue()));
}
else
{
// In this case we emit the switch that decides where to branch at runtime.
codeGenerator.EmitConversion(node.Expression, PhpTypeCode.Integer);
codeGenerator.BranchingStack.EmitContinueRuntime();
}
break;
case JumpStmt.Types.Return:
if (codeGenerator.ReturnsPhpReference)
EmitReturnPhpReference(node.Expression, codeGenerator);
else
EmitReturnObject(node.Expression, codeGenerator);
break;
default:
throw null;
}
}
/// <summary>
/// Return value is not deeply copied since the deep copy takes place when the caller accesses the value.
/// </summary>
private void EmitReturnObject(Expression expr, CodeGenerator/*!*/ codeGenerator)
{
ILEmitter il = codeGenerator.IL;
PhpTypeCode result;
if (expr != null)
{
result = expr.Emit(codeGenerator);
// dereference return value:
if (result == PhpTypeCode.PhpReference)
{
il.Emit(OpCodes.Ldfld, Fields.PhpReference_Value);
}
else if (result == PhpTypeCode.PhpArray)
{
// <array>.InplaceCopyOnReturn = true;
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Call, Core.Emit.Properties.PhpArray_InplaceCopyOnReturn.GetSetMethod());
}
else
{
codeGenerator.EmitBoxing(result);
}
}
else
{
il.Emit(OpCodes.Ldnull);
}
codeGenerator.EmitReturnBranch();
}
private void EmitReturnPhpReference(Expression expr, CodeGenerator codeGenerator)
{
ILEmitter il = codeGenerator.IL;
PhpTypeCode result;
if (expr != null)
{
result = expr.Emit(codeGenerator);
if (result != PhpTypeCode.PhpReference)
{
// return value is "boxed" to PhpReference:
if (result != PhpTypeCode.Void)
{
codeGenerator.EmitBoxing(result);
// We can box the value without making a copy since the result of the return expression
// is not accessible after returnign from the routine as it is a value (not a reference).
il.Emit(OpCodes.Newobj, Constructors.PhpReference_Object);
}
else
{
il.Emit(OpCodes.Newobj, Constructors.PhpReference_Void);
}
}
}
else
{
il.Emit(OpCodes.Newobj, Constructors.PhpReference_Void);
}
codeGenerator.EmitReturnBranch();
}
}
#endregion
#region GotoStmt
[NodeCompiler(typeof(GotoStmt), Singleton = true)]
sealed class GotoStmtCompiler : StatementCompiler<GotoStmt>
{
internal override Statement Analyze(GotoStmt node, Analyzer analyzer)
{
//
// TODO: analyze reachability, restrict jumps inside blocks, ...
//
// goto x;
// // unreachable
// x:
//
if (analyzer.IsThisCodeUnreachable())
{
analyzer.ReportUnreachableCode(node.Span);
return EmptyStmt.Unreachable;
}
Dictionary<VariableName, Statement> labels = analyzer.CurrentLabels;
Statement stmt;
if (labels.TryGetValue(node.LabelName, out stmt))
{
LabelStmt label = stmt as LabelStmt;
if (label != null)
label.IsReferred = true;
}
else
{
// add a stub (this node):
labels.Add(node.LabelName, node);
}
return node;
}
internal override void Emit(GotoStmt node, CodeGenerator codeGenerator)
{
Debug.Assert(codeGenerator.CurrentLabels.ContainsKey(node.LabelName));
Debug.Assert(codeGenerator.CurrentLabels[node.LabelName] is LabelStmt);
// marks a sequence point:
codeGenerator.MarkSequencePoint(node.Span);
codeGenerator.IL.Emit(OpCodes.Br, ((LabelStmt)codeGenerator.CurrentLabels[node.LabelName]).Label);
}
}
#endregion
#region LabelStmt
[NodeCompiler(typeof(LabelStmt), Singleton = true)]
sealed class LabelStmtCompiler : StatementCompiler<LabelStmt>
{
internal override Statement Analyze(LabelStmt node, Analyzer analyzer)
{
Dictionary<VariableName, Statement> labels = analyzer.CurrentLabels;
Statement stmt;
if (labels.TryGetValue(node.Name, out stmt))
{
if (stmt is LabelStmt)
{
analyzer.ErrorSink.Add(Errors.LabelRedeclared, analyzer.SourceUnit, node.Span, node.Name);
analyzer.ErrorSink.Add(Errors.RelatedLocation, analyzer.SourceUnit, stmt.Span);
}
else
{
labels[node.Name] = node;
node.IsReferred = true;
}
}
else
{
labels.Add(node.Name, node);
}
return node;
}
internal override void Emit(LabelStmt node, CodeGenerator codeGenerator)
{
codeGenerator.IL.MarkLabel(node.Label);
}
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
using Plivo.Exception;
using Plivo.Utilities;
using dict = System.Collections.Generic.Dictionary<string, string>;
using list = System.Collections.Generic.List<string>;
namespace Plivo.XML
{
public abstract class PlivoElement
{
protected list Nestables { get; set; }
protected list ValidAttributes { get; set; }
protected XElement Element { get; set; }
protected dict Attributes { get; set; }
public PlivoElement(string body, dict attributes)
{
Element = new XElement(GetType().Name, HtmlEntity.Convert(body));
Attributes = attributes;
}
public PlivoElement(dict attributes)
{
Element = new XElement(GetType().Name);
Attributes = attributes;
}
public PlivoElement(string body)
{
Element = new XElement(GetType().Name, HtmlEntity.Convert(body));
}
public PlivoElement()
{
Element = new XElement(GetType().Name);
}
protected void addAttributes()
{
foreach (KeyValuePair<string, string> kvp in Attributes)
{
string key = kvp.Key;
string val = kvp.Value;
int posn = ValidAttributes.FindIndex(k => k == key);
if (posn >= 0)
Element.SetAttributeValue(key, _convert_values(val));
else
throw new PlivoXMLException($"Invalid attribute {key} for {GetType().Name}");
}
}
private string _convert_values(string value)
{
string val = "";
switch (value.ToLower())
{
case "true":
val = value.ToLower();
break;
case "false":
val = value.ToLower();
break;
case "get":
val = value.ToUpper();
break;
case "post":
val = value.ToUpper();
break;
case "man":
val = value.ToUpper();
break;
case "woman":
val = value.ToUpper();
break;
default:
val = value;
break;
}
return val;
}
public PlivoElement Add(PlivoElement element)
{
int posn = Nestables.FindIndex(n => n == element.GetType().Name);
if (posn >= 0)
{
if (element.GetType().Name == "Cont")
{
Element.Add(new XText(element.Element.Value));
return element;
}
Element.Add(element.Element);
return element;
}
else
throw new PlivoXMLException(
$"Element {element.GetType().Name} cannot be nested within {GetType().Name}");
}
public PlivoElement AddSpeak(string body, dict parameters = null)
{
if (parameters == null) {
parameters = new Dictionary<string, string>();
}
return Add(new Speak(body, parameters));
}
public PlivoElement AddBreak(dict parameters)
{
return Add(new Break(parameters));
}
public PlivoElement AddCont(string body)
{
return Add(new Cont(body));
}
public PlivoElement AddEmphasis(string body, dict parameters)
{
return Add(new Emphasis(body, parameters));
}
public PlivoElement AddLang(string body, dict parameters)
{
return Add(new Lang(body, parameters));
}
public PlivoElement AddP(string body)
{
return Add(new P(body));
}
public PlivoElement AddPhoneme(string body, dict parameters)
{
return Add(new Phoneme(body, parameters));
}
public PlivoElement AddProsody(string body, dict parameters)
{
return Add(new Prosody(body, parameters));
}
public PlivoElement AddS(string body)
{
return Add(new S(body));
}
public PlivoElement AddSayAs(string body, dict parameters)
{
return Add(new SayAs(body, parameters));
}
public PlivoElement AddSub(string body, dict parameters)
{
return Add(new Sub(body, parameters));
}
public PlivoElement AddW(string body, dict parameters)
{
return Add(new W(body, parameters));
}
public PlivoElement AddPlay(string body, dict parameters)
{
return Add(new Play(body, parameters));
}
public PlivoElement AddGetDigits(dict parameters)
{
return Add(new GetDigits("", parameters));
}
public PlivoElement AddGetInput(dict parameters)
{
return Add(new GetInput("", parameters));
}
public PlivoElement AddRecord(dict parameters)
{
return Add(new Record(parameters));
}
public PlivoElement AddDial(dict parameters)
{
return Add(new Dial(parameters));
}
public PlivoElement AddNumber(string body, dict parameters)
{
return Add(new Number(body, parameters));
}
public PlivoElement AddUser(string body, dict parameters)
{
return Add(new User(body, parameters));
}
public PlivoElement AddRedirect(string body, dict parameters)
{
return Add(new Redirect(body, parameters));
}
public PlivoElement AddWait(dict parameters)
{
return Add(new Wait(parameters));
}
public PlivoElement AddHangup(dict parameters)
{
return Add(new Hangup(parameters));
}
public PlivoElement AddPreAnswer()
{
return Add(new PreAnswer());
}
public PlivoElement AddConference(string body, dict parameters)
{
return Add(new Conference(body, parameters));
}
public PlivoElement AddMultiPartyCall(string body, dict parameters)
{
return Add(new MultiPartyCall(body, parameters));
}
public PlivoElement AddMessage(string body, dict parameters)
{
return Add(new Message(body, parameters));
}
public PlivoElement AddDTMF(string body, dict attributes)
{
return Add(new DTMF(body, attributes));
}
public override string ToString()
{
return SerializeToXML().ToString().Replace("&", "&");
}
protected XDocument SerializeToXML()
{
return new XDocument(new XDeclaration("1.0", "utf-8", "yes"), Element);
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Contact Point Address
///<para>SObject Name: ContactPointAddress</para>
///<para>Custom Object: False</para>
///</summary>
public class SfContactPointAddress : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "ContactPointAddress"; }
}
///<summary>
/// Contact Point Address ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Owner ID
/// <para>Name: OwnerId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "ownerId")]
public string OwnerId { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Name
/// <para>Name: Name</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Last Viewed Date
/// <para>Name: LastViewedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastViewedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastViewedDate { get; set; }
///<summary>
/// Last Referenced Date
/// <para>Name: LastReferencedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastReferencedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastReferencedDate { get; set; }
///<summary>
/// Parent ID
/// <para>Name: ParentId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "parentId")]
public string ParentId { get; set; }
///<summary>
/// Active from Date
/// <para>Name: ActiveFromDate</para>
/// <para>SF Type: date</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "activeFromDate")]
public DateTime? ActiveFromDate { get; set; }
///<summary>
/// Active to Date
/// <para>Name: ActiveToDate</para>
/// <para>SF Type: date</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "activeToDate")]
public DateTime? ActiveToDate { get; set; }
///<summary>
/// Best time to contact end time
/// <para>Name: BestTimeToContactEndTime</para>
/// <para>SF Type: time</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bestTimeToContactEndTime")]
public string BestTimeToContactEndTime { get; set; }
///<summary>
/// Best time to contact start time
/// <para>Name: BestTimeToContactStartTime</para>
/// <para>SF Type: time</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bestTimeToContactStartTime")]
public string BestTimeToContactStartTime { get; set; }
///<summary>
/// Best time to contact time zone
/// <para>Name: BestTimeToContactTimezone</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "bestTimeToContactTimezone")]
public string BestTimeToContactTimezone { get; set; }
///<summary>
/// Is Primary
/// <para>Name: IsPrimary</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isPrimary")]
public bool? IsPrimary { get; set; }
///<summary>
/// Contact Point Phone ID
/// <para>Name: ContactPointPhoneId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "contactPointPhoneId")]
public string ContactPointPhoneId { get; set; }
///<summary>
/// ReferenceTo: ContactPointPhone
/// <para>RelationshipName: ContactPointPhone</para>
///</summary>
[JsonProperty(PropertyName = "contactPointPhone")]
[Updateable(false), Createable(false)]
public SfContactPointPhone ContactPointPhone { get; set; }
///<summary>
/// Address Type
/// <para>Name: AddressType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "addressType")]
public string AddressType { get; set; }
///<summary>
/// Address
/// <para>Name: Street</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "street")]
public string Street { get; set; }
///<summary>
/// City
/// <para>Name: City</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "city")]
public string City { get; set; }
///<summary>
/// State/Province
/// <para>Name: State</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "state")]
public string State { get; set; }
///<summary>
/// Zip/Postal Code
/// <para>Name: PostalCode</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "postalCode")]
public string PostalCode { get; set; }
///<summary>
/// Country
/// <para>Name: Country</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "country")]
public string Country { get; set; }
///<summary>
/// Latitude
/// <para>Name: Latitude</para>
/// <para>SF Type: double</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "latitude")]
public double? Latitude { get; set; }
///<summary>
/// Longitude
/// <para>Name: Longitude</para>
/// <para>SF Type: double</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "longitude")]
public double? Longitude { get; set; }
///<summary>
/// Shipping Geocode Accuracy
/// <para>Name: GeocodeAccuracy</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "geocodeAccuracy")]
public string GeocodeAccuracy { get; set; }
///<summary>
/// Address
/// <para>Name: Address</para>
/// <para>SF Type: address</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "address")]
[Updateable(false), Createable(false)]
public Address Address { get; set; }
///<summary>
/// Is Default Address
/// <para>Name: IsDefault</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDefault")]
public bool? IsDefault { get; set; }
}
}
| |
///
/// Author: Ahmed Lacevic
/// Date: 12/1/2007
/// Desc: Reads a DBF file, outputs a CSV file!
///
/// Revision History:
/// -----------------------------------
/// Author:
/// Date:
/// Desc:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using SocialExplorer.IO.FastDBF;
namespace DBF2CSV
{
class Program
{
static void Main(string[] args)
{
if(args.Length < 2)
{
//print help
Console.WriteLine("\n\n");
Console.WriteLine("Welcome to Social Explorer DBF 2 CSV Utility");
Console.WriteLine("-------------------------------------------------");
Console.WriteLine("\nParameters:");
Console.WriteLine("1. input DBF file");
Console.WriteLine("2. output CSV file");
Console.WriteLine("\nOptional switches:");
Console.WriteLine("/F - format numbers so 5.5000 comes out as 5.5");
Console.WriteLine("/P - padded output, fixed width (/P trumps /F)");
Console.WriteLine("/Q - only output quotes when comma appears in data");
Console.WriteLine("/E encoding - character encoding");
Console.WriteLine("\n\nExample: dbf2csv \"in.dbf\" \"out.csv\" /P /Q /E Windows-1250");
}
else
{
//check if input DBF file exists...
if(!File.Exists(args[0]))
{
Console.WriteLine("Input file '" + args[0] + "' does not exist!");
return;
}
//create output csv file overwrite if already exists.
if(File.Exists(args[1]))
{
//ask to overwrite:
Console.WriteLine("Output CSV file '" + args[1] + "' already exists.");
Console.WriteLine("Would you like to overwrite it? Press 'Y' for yes: ");
if(Console.ReadKey().KeyChar.ToString().ToUpper() != "Y")
return;
}
Encoding encoding = Encoding.GetEncoding(1252);
bool bSwitchF = false;
bool bSwitchP = false;
bool bSwitchQ = false;
for(int i=0;i<args.Length;i++)
if(args[i] == "/F")
bSwitchF = true;
for (int i = 0; i < args.Length; i++)
if (args[i] == "/P")
bSwitchP = true;
for (int i = 0; i < args.Length; i++)
if (args[i] == "/Q")
bSwitchQ = true;
for (int i = 0; i < args.Length; i++)
if ((args[i] == "/E") && ((i + 1) < args.Length))
encoding = Encoding.GetEncoding(args[i + 1]);
//open DBF file and create CSV output file...
StreamWriter swcsv = new StreamWriter(args[1], false, encoding);
DbfFile dbf = new DbfFile(encoding);
dbf.Open(args[0], FileMode.Open);
//output column names
for (int i = 0; i < dbf.Header.ColumnCount; i++)
{
if(dbf.Header[i].ColumnType != DbfColumn.DbfColumnType.Binary &&
dbf.Header[i].ColumnType != DbfColumn.DbfColumnType.Memo)
swcsv.Write((i == 0 ? "": ",") + dbf.Header[i].Name);
else
Console.WriteLine("WARNING: Excluding Binary/Memo field '" + dbf.Header[i].Name + "'");
}
swcsv.WriteLine();
//output values for all but binary and memo...
DbfRecord orec = new DbfRecord(dbf.Header);
while(dbf.ReadNext(orec))
{
//output column values...
if (!orec.IsDeleted)
{
for (int i = 0; i < orec.ColumnCount; i++)
{
if(orec.Column(i).ColumnType == DbfColumn.DbfColumnType.Character)
{
//string values: trim, enclose in quotes and escape quotes with double quotes
string sval = orec[i];
if(!bSwitchP)
sval = orec[i].Trim();
if(!bSwitchQ || sval.IndexOf('"') > -1)
sval = ("\"" + sval.Replace("\"", "\"\"") + "\"");
swcsv.Write(sval);
}
else if(orec.Column(i).ColumnType == DbfColumn.DbfColumnType.Date)
swcsv.Write(orec.GetDateValue(i).ToString("MM-dd-yyyy"));
else
{
if (bSwitchP)
swcsv.Write(orec[i]);
else if(bSwitchF)
swcsv.Write(FormatNumber(orec[i].Trim()));
else
swcsv.Write(orec[i].Trim());
}
//end record with a linefeed or end column with a comma.
if(i < orec.ColumnCount-1)
swcsv.Write(",");
}
//write line...
swcsv.WriteLine();
}
}
//close files...
swcsv.Flush();
swcsv.Close();
dbf.Close();
}
}
/// <summary>
/// Removes leading and trailing zeros from a number (double or int) value represented as a string.
/// So for example if a '5.00' is passed this function would return '5'. If '00035.3420' is passed, '35.342' is returned.
/// etc.
/// </summary>
/// <param name="sDouble"></param>
/// <returns></returns>
public static string FormatNumber(string sNumber)
{
//an empty string is effectively a NULL number, not a zero or anything so just return it as empty.
if (sNumber == null || sNumber == "")
return "";
//if this is not a decimal number, remove leading zeros...
if (sNumber.IndexOf('.') == -1)
{
//this is a bit tricky here. we could get a number "00000", which is really "0",
sNumber = sNumber.TrimStart("0".ToCharArray());
//if nothing is left, that means we had a zero to start with! since TrimStart("000") will return "".
if (sNumber == "")
sNumber = "0";
return sNumber;
}
else
{
string svalFormatted = sNumber;
svalFormatted = svalFormatted.Trim().Trim("0".ToCharArray());
//if only a period is left behind remove it
if (svalFormatted != "" && svalFormatted[svalFormatted.Length - 1] == '.')
svalFormatted = svalFormatted.Substring(0, svalFormatted.Length - 1);
//if formatted number starts with a '.' then add a 0 in front!
if (svalFormatted.Length > 0 && svalFormatted[0] == '.')
svalFormatted = "0" + svalFormatted;
//if nothing is left, that means we had a zero to start with! Trim("0") removed all
//trailing and leading zeros and a period was left over which was then removed as well,
//so the string is empty!
if (svalFormatted == "")
svalFormatted = "0";
return svalFormatted;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace OpenTokService.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using AjaxControlToolkit.Design;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.IO;
using System.Web.UI.WebControls;
using System.Drawing;
namespace AjaxControlToolkit {
/// <summary>
/// AsyncFileUpload is an ASP.NET AJAX Control that allows you to asynchronously upload files to the server.
/// The file uploading results can be checked both on the server and client sides.
/// </summary>
[Designer(typeof(AsyncFileUploadDesigner))]
[RequiredScript(typeof(CommonToolkitScripts))]
[ClientScriptResource("Sys.Extended.UI.AsyncFileUpload", AjaxControlToolkit.Constants.AsyncFileUploadName)]
[ToolboxBitmap(typeof(ToolboxIcons.Accessor), AjaxControlToolkit.Constants.AsyncFileUploadName + AjaxControlToolkit.Constants.IconPostfix)]
public class AsyncFileUpload : ScriptControlBase {
public static class Constants {
public const string
FileUploadIDKey = "AsyncFileUploadID",
InternalErrorInvalidIFrame = "The ExtendedFileUpload control has encountered an error with the uploader in this page. Please refresh the page and try again.",
fileUploadGUID = "b3b89160-3224-476e-9076-70b500c816cf";
public static class Errors {
public const string
NoFiles = "No files are attached to the upload.",
FileNull = "The file attached is invalid.",
NoFileName = "The file attached has an invalid filename.",
InputStreamNull = "The file attached could not be read.",
EmptyContentLength = "The file attached is empty.";
}
public static class StatusMessages {
public const string UploadSuccessful = "The file uploaded successfully.";
}
}
HttpPostedFile _postedFile = null;
HtmlInputFile _inputFile = null;
string _lastError = String.Empty;
string _hiddenFieldID = String.Empty;
string _innerTBID = String.Empty;
bool _persistFile = false;
bool _failedValidation = false;
AsyncFileUploaderStyle _controlStyle = AsyncFileUploaderStyle.Traditional;
public AsyncFileUpload()
: base(true, HtmlTextWriterTag.Div) {
}
/// <summary>
/// Fires when the file is successfully uploaded.
/// </summary>
[Bindable(true)]
[Category("Server Events")]
public event EventHandler<AsyncFileUploadEventArgs> UploadedComplete;
/// <summary>
/// Fires when the uploaded file is corrupted.
/// </summary>
[Bindable(true)]
[Category("Server Events")]
public event EventHandler<AsyncFileUploadEventArgs> UploadedFileError;
bool IsDesignMode {
get { return (HttpContext.Current == null); }
}
HttpPostedFile CurrentFile {
get { return _persistFile ? PersistentStoreManager.Instance.GetFileFromSession(ClientID) : _postedFile; }
}
/// <summary>
/// The name of a javascript function executed on the client side if the file upload started.
/// </summary>
[DefaultValue("")]
[Category("Behavior")]
[ExtenderControlEvent]
[ClientPropertyName("uploadStarted")]
public string OnClientUploadStarted {
get { return (string)(ViewState["OnClientUploadStarted"] ?? String.Empty); }
set { ViewState["OnClientUploadStarted"] = value; }
}
/// <summary>
/// The name of a javascript function executed on the client side after a file is successfully uploaded.
/// </summary>
[DefaultValue("")]
[Category("Behavior")]
[ExtenderControlEvent]
[ClientPropertyName("uploadComplete")]
public string OnClientUploadComplete {
get { return (string)(ViewState["OnClientUploadComplete"] ?? String.Empty); }
set { ViewState["OnClientUploadComplete"] = value; }
}
/// <summary>
/// The name of a javascript function executed on the client side if the file upload failed.
/// </summary>
[DefaultValue("")]
[Category("Behavior")]
[ExtenderControlEvent]
[ClientPropertyName("uploadError")]
public string OnClientUploadError {
get { return (string)(ViewState["OnClientUploadError"] ?? String.Empty); }
set { ViewState["OnClientUploadError"] = value; }
}
/// <summary>
/// Uploaded file bytes
/// </summary>
[BrowsableAttribute(false)]
public byte[] FileBytes {
get {
PopulateObjectPriorToRender(ClientID);
var file = CurrentFile;
if(file != null) {
try {
return GetBytesFromStream(file.InputStream);
} catch { }
}
return null;
}
}
/// <summary>
/// ID of a control that is shown while the file is being uploaded.
/// </summary>
[Category("Behavior")]
[Description("ID of Throbber")]
[DefaultValue("")]
public string ThrobberID {
get { return (string)(ViewState["ThrobberID"] ?? string.Empty); }
set { ViewState["ThrobberID"] = value; }
}
/// <summary>
/// The control's background color on upload complete. The default value is Lime.
/// </summary>
[Category("Appearance")]
[TypeConverter(typeof(WebColorConverter))]
[Description("Control's background color on upload complete.")]
[DefaultValue(typeof(Color), "Lime")]
public Color CompleteBackColor {
get { return (Color)(ViewState["CompleteBackColor"] ?? Color.Lime); }
set { ViewState["CompleteBackColor"] = value; }
}
/// <summary>
/// The control's background color when uploading is in progress.
/// The default value is White.
/// </summary>
[Category("Appearance")]
[TypeConverter(typeof(WebColorConverter))]
[Description("Control's background color when uploading is in progress.")]
[DefaultValue(typeof(Color), "White")]
public Color UploadingBackColor {
get { return (Color)(ViewState["UploadingBackColor"] ?? Color.White); }
set { ViewState["UploadingBackColor"] = value; }
}
/// <summary>
/// The control's background color on an upload error.
/// The default value is Red.
/// </summary>
[Category("Appearance")]
[TypeConverter(typeof(WebColorConverter))]
[Description("Control's background color on upload error.")]
[DefaultValue(typeof(Color), "Red")]
public Color ErrorBackColor {
get { return (Color)(ViewState["ErrorBackColor"] ?? Color.Red); }
set { ViewState["ErrorBackColor"] = value; }
}
/// <summary>
/// The control's width (Unit).
/// The default value is 355px.
/// </summary>
[DefaultValue(typeof(Unit), "")]
[Category("Layout")]
public override Unit Width {
get { return base.Width; }
set { base.Width = value; }
}
/// <summary>
/// Whether validation is failed
/// </summary>
[BrowsableAttribute(false)]
public bool FailedValidation {
get { return _failedValidation; }
set { _failedValidation = value; }
}
/// <summary>
/// The control's appearance style (Traditional, Modern). The default value is Traditional.
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[BrowsableAttribute(true)]
[DefaultValue(AsyncFileUploaderStyle.Traditional)]
public AsyncFileUploaderStyle UploaderStyle {
get { return _controlStyle; }
set { _controlStyle = value; }
}
/// <summary>
/// A HttpPostedFile object that provides access to the uploaded file
/// </summary>
[BrowsableAttribute(false)]
public HttpPostedFile PostedFile {
get {
PopulateObjectPriorToRender(ClientID);
return CurrentFile;
}
}
/// <summary>
/// A bool value indicating whether the control contains a file
/// </summary>
[BrowsableAttribute(false)]
public bool HasFile {
get {
PopulateObjectPriorToRender(ClientID);
if(_persistFile) {
return PersistentStoreManager.Instance.FileExists(ClientID);
}
return (_postedFile != null);
}
}
/// <summary>
/// Gets the name of a file on the client that is uploaded using the control.
/// </summary>
[BrowsableAttribute(false)]
public string FileName {
get {
PopulateObjectPriorToRender(ClientID);
if(_persistFile) {
return Path.GetFileName(PersistentStoreManager.Instance.GetFileName(ClientID));
} else if(_postedFile != null) {
return Path.GetFileName(_postedFile.FileName);
}
return String.Empty;
}
}
/// <summary>
/// Gets the name of a file on the client that is uploaded using the control.
/// </summary>
[BrowsableAttribute(false)]
public string ContentType {
get {
PopulateObjectPriorToRender(ClientID);
if(_persistFile) {
return PersistentStoreManager.Instance.GetContentType(ClientID);
} else if(_postedFile != null) {
return _postedFile.ContentType;
}
return String.Empty;
}
}
/// <summary>
/// Gets a Stream object that points to an uploaded file to prepare for reading the content of the file.
/// </summary>
[BrowsableAttribute(false)]
public Stream FileContent {
get {
PopulateObjectPriorToRender(ClientID);
var file = CurrentFile;
if(file == null || file.InputStream == null)
return null;
return file.InputStream;
}
}
/// <summary>
/// Whether a file is being uploaded.
/// </summary>
[BrowsableAttribute(false)]
public bool IsUploading {
get { return (Page.Request.QueryString[Constants.FileUploadIDKey] != null); }
}
/// <summary>
/// Whether a file is stored in session.
/// The default value is false.
/// </summary>
[Bindable(true)]
[BrowsableAttribute(true)]
[DefaultValue(false)]
public bool PersistFile {
get { return _persistFile; }
set { _persistFile = value; }
}
/// <summary>
/// Clears all uploaded files of a current control from session.
/// </summary>
public void ClearAllFilesFromPersistedStore() {
PersistentStoreManager.Instance.ClearAllFilesFromSession(this.ClientID);
}
/// <summary>
/// Clears all uploaded files of current control from session
/// </summary>
public void ClearFileFromPersistedStore() {
PersistentStoreManager.Instance.RemoveFileFromSession(this.ClientID);
}
/// <summary>
/// Saves the content of an uploaded file.
/// </summary>
/// <param name="fileName" type="String">Uploaded file name</param>
public void SaveAs(string fileName) {
PopulateObjectPriorToRender(this.ClientID);
var file = CurrentFile;
file.SaveAs(fileName);
}
void PopulateObjectPriorToRender(string controlId) {
bool exists;
if(_persistFile)
exists = PersistentStoreManager.Instance.FileExists(controlId);
else
exists = (_postedFile != null);
if((!exists) && (this.Page != null && this.Page.Request.Files.Count != 0))
ReceivedFile(controlId);
}
protected virtual void OnUploadedFileError(AsyncFileUploadEventArgs e) {
if(UploadedFileError != null)
UploadedFileError(this, e);
}
protected virtual void OnUploadedComplete(AsyncFileUploadEventArgs e) {
if(UploadedComplete != null)
UploadedComplete(this, e);
}
void ReceivedFile(string sendingControlID) {
AsyncFileUploadEventArgs eventArgs = null;
_lastError = String.Empty;
if(this.Page.Request.Files.Count > 0) {
HttpPostedFile file = null;
if(sendingControlID == null || sendingControlID == String.Empty) {
file = this.Page.Request.Files[0];
} else {
foreach(string uploadedFile in this.Page.Request.Files) {
var fileToUse = uploadedFile;
var straggler = "$ctl02";
if(fileToUse.EndsWith(straggler))
fileToUse = fileToUse.Remove(fileToUse.Length - straggler.Length);
if(fileToUse.Replace("$", "_").EndsWith(sendingControlID)) {
file = this.Page.Request.Files[uploadedFile];
break;
}
}
}
if(file == null) {
_lastError = Constants.Errors.FileNull;
eventArgs = new AsyncFileUploadEventArgs(
AsyncFileUploadState.Failed,
Constants.Errors.FileNull,
String.Empty,
String.Empty
);
OnUploadedFileError(eventArgs);
} else if(file.FileName == String.Empty) {
_lastError = Constants.Errors.NoFileName;
eventArgs = new AsyncFileUploadEventArgs(
AsyncFileUploadState.Unknown,
Constants.Errors.NoFileName,
file.FileName,
file.ContentLength.ToString()
);
OnUploadedFileError(eventArgs);
} else if(file.InputStream == null) {
_lastError = Constants.Errors.NoFileName;
eventArgs = new AsyncFileUploadEventArgs(
AsyncFileUploadState.Failed,
Constants.Errors.NoFileName,
file.FileName,
file.ContentLength.ToString()
);
OnUploadedFileError(eventArgs);
} else if(file.ContentLength < 1) {
_lastError = Constants.Errors.EmptyContentLength;
eventArgs = new AsyncFileUploadEventArgs(
AsyncFileUploadState.Unknown,
Constants.Errors.EmptyContentLength,
file.FileName,
file.ContentLength.ToString()
);
OnUploadedFileError(eventArgs);
} else {
eventArgs = new AsyncFileUploadEventArgs(
AsyncFileUploadState.Success,
String.Empty,
file.FileName,
file.ContentLength.ToString()
);
if(_persistFile) {
GC.SuppressFinalize(file);
PersistentStoreManager.Instance.AddFileToSession(this.ClientID, file.FileName, file);
} else {
_postedFile = file;
}
OnUploadedComplete(eventArgs);
}
}
}
public byte[] GetBytesFromStream(Stream stream) {
var buffer = new byte[32768];
using(var ms = new MemoryStream()) {
stream.Seek(0, SeekOrigin.Begin);
while(true) {
int read = stream.Read(buffer, 0, buffer.Length);
if(read <= 0) {
return ms.ToArray();
}
ms.Write(buffer, 0, read);
}
}
}
protected override void OnPreRender(EventArgs e) {
base.OnPreRender(e);
string sendingControlID = this.Page.Request.QueryString[Constants.FileUploadIDKey];
if(sendingControlID == null || sendingControlID == this.ClientID) {
ReceivedFile(this.ClientID);
if(sendingControlID != null && sendingControlID.StartsWith(this.ClientID)) {
string result;
if(_lastError == String.Empty) {
var bytes = this.FileBytes;
if(bytes != null)
result = bytes.Length.ToString() + "------" + ContentType;
else
result = String.Empty;
} else {
result = "error------" + _lastError;
}
TextWriter output = Page.Response.Output;
output.Write("<div id='" + ClientID + "'>");
output.Write(result);
output.Write("</div>");
}
}
}
internal void CreateChilds() {
Controls.Clear();
CreateChildControls();
}
protected override void CreateChildControls() {
PersistentStoreManager.Instance.ExtendedFileUploadGUID = Constants.fileUploadGUID;
string sendingControlID = null;
if(!IsDesignMode)
sendingControlID = this.Page.Request.QueryString[Constants.FileUploadIDKey];
if(IsDesignMode || String.IsNullOrEmpty(sendingControlID)) {
this._hiddenFieldID = GenerateHtmlInputHiddenControl();
string lastFileName = String.Empty;
if(_persistFile) {
if(PersistentStoreManager.Instance.FileExists(this.ClientID))
lastFileName = PersistentStoreManager.Instance.GetFileName(this.ClientID);
} else if(_postedFile != null) {
lastFileName = _postedFile.FileName;
}
GenerateHtmlInputFileControl(lastFileName);
}
}
protected string GenerateHtmlInputHiddenControl() {
var field = new HiddenField();
Controls.Add(field);
return field.ClientID;
}
protected string GenerateHtmlInputFileControl(string lastFileName) {
var div = new HtmlGenericControl("div");
Controls.Add(div);
if(this.UploaderStyle == AsyncFileUploaderStyle.Modern) {
var bgImageUrl = ToolkitResourceManager.GetImageHref(AjaxControlToolkit.Constants.AsyncFileUploadImage, this);
var style = "background:url(" + bgImageUrl + ") no-repeat 100% 1px; height:24px; margin:0px; text-align:right;";
if(!Width.IsEmpty)
style += "min-width:" + Width.ToString() + ";width:" + Width.ToString() + " !important;";
else
style += "width:355px;";
div.Attributes.Add("style", style);
}
if(!(this.UploaderStyle == AsyncFileUploaderStyle.Modern && IsDesignMode)) {
_inputFile = new HtmlInputFile();
if(!this.Enabled)
_inputFile.Disabled = true;
div.Controls.Add(_inputFile);
_inputFile.Attributes.Add("id", _inputFile.Name.Replace("$", "_"));
if(this.UploaderStyle != AsyncFileUploaderStyle.Modern) {
if(BackColor != Color.Empty)
_inputFile.Style[HtmlTextWriterStyle.BackgroundColor] = ColorTranslator.ToHtml(BackColor);
if(!Width.IsEmpty)
_inputFile.Style[HtmlTextWriterStyle.Width] = Width.ToString();
else
_inputFile.Style[HtmlTextWriterStyle.Width] = "355px";
}
}
if(this.UploaderStyle == AsyncFileUploaderStyle.Modern) {
var style = "opacity:0.0; -moz-opacity: 0.0; filter: alpha(opacity=00); font-size:14px;";
if(!Width.IsEmpty)
style += "width:" + Width.ToString() + ";";
if(_inputFile != null)
_inputFile.Attributes.Add("style", style);
var textBox = new TextBox();
if(!IsDesignMode) {
var div1 = new HtmlGenericControl("div");
div.Controls.Add(div1);
style = "margin-top:-23px;text-align:left;";
div1.Attributes.Add("style", style);
div1.Attributes.Add("type", "text");
div1.Controls.Add(textBox);
style = "height:17px; font-size:12px; font-family:Tahoma;";
} else {
div.Controls.Add(textBox);
style = "height:23px; font-size:12px; font-family:Tahoma;";
}
if(!Width.IsEmpty && Width.ToString().IndexOf("px") > 0)
style += "width:" + (int.Parse(Width.ToString().Substring(0, Width.ToString().IndexOf("px"))) - 107).ToString() + "px;";
else
style += "width:248px;";
if(lastFileName != String.Empty || this._failedValidation) {
if((this.FileBytes != null && this.FileBytes.Length > 0) && (!this._failedValidation)) {
style += "background-color:#00FF00;";
} else {
this._failedValidation = false;
style += "background-color:#FF0000;";
}
textBox.Text = lastFileName;
} else if(BackColor != Color.Empty) {
style += "background-color:" + ColorTranslator.ToHtml(BackColor) + ";";
}
textBox.ReadOnly = true;
textBox.Attributes.Add("style", style);
this._innerTBID = textBox.ClientID;
} else if(IsDesignMode) {
Controls.Clear();
Controls.Add(_inputFile);
}
return div.ClientID;
}
protected override void DescribeComponent(ScriptComponentDescriptor descriptor) {
base.DescribeComponent(descriptor);
if(!IsDesignMode) {
if(this._hiddenFieldID != String.Empty) descriptor.AddElementProperty("hiddenField", this._hiddenFieldID);
if(this._innerTBID != String.Empty) descriptor.AddElementProperty("innerTB", this._innerTBID);
if(this._inputFile != null) descriptor.AddElementProperty("inputFile", this._inputFile.Name.Replace("$", "_"));
descriptor.AddProperty("postBackUrl", Page.Response.ApplyAppPathModifier(Page.Request.RawUrl));
descriptor.AddProperty("formName", Path.GetFileName(this.Page.Form.Name));
if(CompleteBackColor != Color.Empty)
descriptor.AddProperty("completeBackColor", ColorTranslator.ToHtml(CompleteBackColor));
if(ErrorBackColor != Color.Empty)
descriptor.AddProperty("errorBackColor", ColorTranslator.ToHtml(ErrorBackColor));
if(UploadingBackColor != Color.Empty)
descriptor.AddProperty("uploadingBackColor", ColorTranslator.ToHtml(UploadingBackColor));
if(ThrobberID != string.Empty) {
var control = this.FindControl(ThrobberID);
if(control != null)
descriptor.AddElementProperty("throbber", control.ClientID);
}
}
}
protected override Style CreateControlStyle() {
return new AsyncFileUploadStyleWrapper(ViewState);
}
sealed class AsyncFileUploadStyleWrapper : Style {
public AsyncFileUploadStyleWrapper(StateBag state)
: base(state) {
}
protected override void FillStyleAttributes(CssStyleCollection attributes, IUrlResolutionService urlResolver) {
base.FillStyleAttributes(attributes, urlResolver);
attributes.Remove(HtmlTextWriterStyle.BackgroundColor);
attributes.Remove(HtmlTextWriterStyle.Width);
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.SS.Formula.Functions
{
using System;
using NPOI.SS.Formula;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Util;
/**
* This class performs a D* calculation. It takes an {@link IDStarAlgorithm} object and
* uses it for calculating the result value. Iterating a database and Checking the
* entries against the Set of conditions is done here.
*/
public class DStarRunner : Function3Arg
{
private IDStarAlgorithm algorithm;
public DStarRunner(IDStarAlgorithm algorithm)
{
this.algorithm = algorithm;
}
public ValueEval Evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex)
{
if (args.Length == 3)
{
return Evaluate(srcRowIndex, srcColumnIndex, args[0], args[1], args[2]);
}
else
{
return ErrorEval.VALUE_INVALID;
}
}
public ValueEval Evaluate(int srcRowIndex, int srcColumnIndex,
ValueEval database, ValueEval filterColumn, ValueEval conditionDatabase)
{
// Input Processing and error Checks.
if (!(database is TwoDEval) || !(conditionDatabase is TwoDEval))
{
return ErrorEval.VALUE_INVALID;
}
TwoDEval db = (TwoDEval)database;
TwoDEval cdb = (TwoDEval)conditionDatabase;
int fc;
try
{
fc = GetColumnForName(filterColumn, db);
}
catch (EvaluationException)
{
return ErrorEval.VALUE_INVALID;
}
if (fc == -1)
{ // column not found
return ErrorEval.VALUE_INVALID;
}
// Reset algorithm.
algorithm.Reset();
// Iterate over all db entries.
for (int row = 1; row < db.Height; ++row)
{
bool matches = true;
try
{
matches = FullFillsConditions(db, row, cdb);
}
catch (EvaluationException)
{
return ErrorEval.VALUE_INVALID;
}
// Filter each entry.
if (matches)
{
try
{
ValueEval currentValueEval = solveReference(db.GetValue(row, fc));
// Pass the match to the algorithm and conditionally abort the search.
bool shouldContinue = algorithm.ProcessMatch(currentValueEval);
if (!shouldContinue)
{
break;
}
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
}
}
// Return the result of the algorithm.
return algorithm.Result;
}
private enum Operator
{
largerThan,
largerEqualThan,
smallerThan,
smallerEqualThan,
equal
}
/**
* Resolve reference(-chains) until we have a normal value.
*
* @param field a ValueEval which can be a RefEval.
* @return a ValueEval which is guaranteed not to be a RefEval
* @If a multi-sheet reference was found along the way.
*/
private static ValueEval solveReference(ValueEval field)
{
if (field is RefEval)
{
RefEval refEval = (RefEval)field;
if (refEval.NumberOfSheets > 1)
{
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
return solveReference(refEval.GetInnerValueEval(refEval.FirstSheetIndex));
}
else
{
return field;
}
}
/**
* Returns the first column index that matches the given name. The name can either be
* a string or an integer, when it's an integer, then the respective column
* (1 based index) is returned.
* @param nameValueEval
* @param db
* @return the first column index that matches the given name (or int)
* @
*/
private static int GetColumnForTag(ValueEval nameValueEval, TwoDEval db)
{
int resultColumn = -1;
// Numbers as column indicator are allowed, check that.
if (nameValueEval is NumericValueEval)
{
double doubleResultColumn = ((NumericValueEval)nameValueEval).NumberValue;
resultColumn = (int)doubleResultColumn;
// Floating comparisions are usually not possible, but should work for 0.0.
if (doubleResultColumn - resultColumn != 0.0)
throw new EvaluationException(ErrorEval.VALUE_INVALID);
resultColumn -= 1; // Numbers are 1-based not 0-based.
}
else
{
resultColumn = GetColumnForName(nameValueEval, db);
}
return resultColumn;
}
private static int GetColumnForName(ValueEval nameValueEval, TwoDEval db)
{
String name = GetStringFromValueEval(nameValueEval);
return GetColumnForString(db, name);
}
/**
* For a given database returns the column number for a column heading.
*
* @param db Database.
* @param name Column heading.
* @return Corresponding column number.
* @If it's not possible to turn all headings into strings.
*/
private static int GetColumnForString(TwoDEval db, String name)
{
int resultColumn = -1;
for (int column = 0; column < db.Width; ++column)
{
ValueEval columnNameValueEval = db.GetValue(0, column);
String columnName = GetStringFromValueEval(columnNameValueEval);
if (name.Equals(columnName))
{
resultColumn = column;
break;
}
}
return resultColumn;
}
/**
* Checks a row in a database against a condition database.
*
* @param db Database.
* @param row The row in the database to Check.
* @param cdb The condition database to use for Checking.
* @return Whether the row matches the conditions.
* @If references could not be Resolved or comparison
* operators and operands didn't match.
*/
private static bool FullFillsConditions(TwoDEval db, int row, TwoDEval cdb)
{
// Only one row must match to accept the input, so rows are ORed.
// Each row is made up of cells where each cell is a condition,
// all have to match, so they are ANDed.
for (int conditionRow = 1; conditionRow < cdb.Height; ++conditionRow)
{
bool matches = true;
for (int column = 0; column < cdb.Width; ++column)
{ // columns are ANDed
// Whether the condition column matches a database column, if not it's a
// special column that accepts formulas.
bool columnCondition = true;
ValueEval condition = null;
try
{
// The condition to Apply.
condition = solveReference(cdb.GetValue(conditionRow, column));
}
catch (Exception)
{
// It might be a special formula, then it is ok if it fails.
columnCondition = false;
}
// If the condition is empty it matches.
if (condition is BlankEval)
continue;
// The column in the DB to apply the condition to.
ValueEval targetHeader = solveReference(cdb.GetValue(0, column));
targetHeader = solveReference(targetHeader);
if (!(targetHeader is StringValueEval))
columnCondition = false;
else if (GetColumnForName(targetHeader, db) == -1)
// No column found, it's again a special column that accepts formulas.
columnCondition = false;
if (columnCondition == true)
{ // normal column condition
// Should not throw, Checked above.
ValueEval target = db.GetValue(
row, GetColumnForName(targetHeader, db));
// Must be a string.
String conditionString = GetStringFromValueEval(condition);
if (!testNormalCondition(target, conditionString))
{
matches = false;
break;
}
}
else
{ // It's a special formula condition.
throw new NotImplementedException(
"D* function with formula conditions");
}
}
if (matches == true)
{
return true;
}
}
return false;
}
/**
* Test a value against a simple (< > <= >= = starts-with) condition string.
*
* @param value The value to Check.
* @param condition The condition to check for.
* @return Whether the condition holds.
* @If comparison operator and operands don't match.
*/
private static bool testNormalCondition(ValueEval value, String condition)
{
if(condition.StartsWith("<")) { // It's a </<= condition.
String number = condition.Substring(1);
if(number.StartsWith("=")) {
number = number.Substring(1);
return testNumericCondition(value, Operator.smallerEqualThan, number);
} else {
return testNumericCondition(value, Operator.smallerThan, number);
}
}
else if(condition.StartsWith(">")) { // It's a >/>= condition.
String number = condition.Substring(1);
if(number.StartsWith("=")) {
number = number.Substring(1);
return testNumericCondition(value, Operator.largerEqualThan, number);
} else {
return testNumericCondition(value, Operator.largerThan, number);
}
}
else if(condition.StartsWith("=")) { // It's a = condition.
String stringOrNumber = condition.Substring(1);
// Distinguish between string and number.
bool itsANumber = false;
try {
Int32.Parse(stringOrNumber);
itsANumber = true;
} catch (FormatException) { // It's not an int.
try {
Double.Parse(stringOrNumber);
itsANumber = true;
} catch (FormatException) { // It's a string.
itsANumber = false;
}
}
if(itsANumber) {
return testNumericCondition(value, Operator.equal, stringOrNumber);
} else { // It's a string.
String valueString = GetStringFromValueEval(value);
return stringOrNumber.Equals(valueString);
}
} else { // It's a text starts-with condition.
String valueString = GetStringFromValueEval(value);
return valueString.StartsWith(condition);
}
}
/**
* Test whether a value matches a numeric condition.
* @param valueEval Value to Check.
* @param op Comparator to use.
* @param condition Value to check against.
* @return whether the condition holds.
* @If it's impossible to turn the condition into a number.
*/
private static bool testNumericCondition(
ValueEval valueEval, Operator op, String condition)
{
// Construct double from ValueEval.
if (!(valueEval is NumericValueEval))
return false;
double value = ((NumericValueEval)valueEval).NumberValue;
// Construct double from condition.
double conditionValue = 0.0;
try
{
int intValue = Int32.Parse(condition);
conditionValue = intValue;
}
catch (FormatException)
{ // It's not an int.
try
{
conditionValue = Double.Parse(condition);
}
catch (FormatException)
{ // It's not a double.
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
}
int result = NumberComparer.Compare(value, conditionValue);
switch (op)
{
case Operator.largerThan:
return result > 0;
case Operator.largerEqualThan:
return result >= 0;
case Operator.smallerThan:
return result < 0;
case Operator.smallerEqualThan:
return result <= 0;
case Operator.equal:
return result == 0;
}
return false; // Can not be reached.
}
/**
* Takes a ValueEval and tries to retrieve a String value from it.
* It tries to resolve references if there are any.
*
* @param value ValueEval to retrieve the string from.
* @return String corresponding to the given ValueEval.
* @If it's not possible to retrieve a String value.
*/
private static String GetStringFromValueEval(ValueEval value)
{
value = solveReference(value);
if (value is BlankEval)
return "";
if (!(value is StringValueEval))
throw new EvaluationException(ErrorEval.VALUE_INVALID);
return ((StringValueEval)value).StringValue;
}
}
}
| |
// 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: This Class defines behaviors specific to a writing system.
// A writing system is the collection of scripts and
// orthographic rules required to represent a language as text.
//
//
////////////////////////////////////////////////////////////////////////////
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Text;
namespace System.Globalization
{
public partial class TextInfo : ICloneable, IDeserializationCallback
{
////--------------------------------------------------------------------//
//// Internal Information //
////--------------------------------------------------------------------//
private enum Tristate : byte
{
NotInitialized,
True,
False,
}
////
//// Variables.
////
private String _listSeparator;
private bool _isReadOnly = false;
//// _cultureName is the name of the creating culture. Note that we consider this authoratative,
//// if the culture's textinfo changes when deserializing, then behavior may change.
//// (ala Whidbey behavior). This is the only string Arrowhead needs to serialize.
//// _cultureData is the data that backs this class.
//// _textInfoName is the actual name of the textInfo (from cultureData.STEXTINFO)
//// this can be the same as _cultureName on Silverlight since the OS knows
//// how to do the sorting. However in the desktop, when we call the sorting dll, it doesn't
//// know how to resolve custom locle names to sort ids so we have to have alredy resolved this.
////
private readonly String _cultureName; // Name of the culture that created this text info
private CultureData _cultureData; // Data record for the culture that made us, not for this textinfo
private String _textInfoName; // Name of the text info we're using (ie: _cultureData.STEXTINFO)
private Tristate _isAsciiCasingSameAsInvariant = Tristate.NotInitialized;
// Invariant text info
internal static TextInfo Invariant
{
get
{
if (s_Invariant == null)
s_Invariant = new TextInfo(CultureData.Invariant);
return s_Invariant;
}
}
internal volatile static TextInfo s_Invariant;
void IDeserializationCallback.OnDeserialization(Object sender)
{
throw new PlatformNotSupportedException();
}
//
// Internal ordinal comparison functions
//
internal static int GetHashCodeOrdinalIgnoreCase(String s)
{
// This is the same as an case insensitive hash for Invariant
// (not necessarily true for sorting, but OK for casing & then we apply normal hash code rules)
return (Invariant.GetCaseInsensitiveHashCode(s));
}
// Currently we don't have native functions to do this, so we do it the hard way
internal static int IndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
{
if (count > source.Length || count < 0 || startIndex < 0 || startIndex > source.Length - count)
{
return -1;
}
return CultureInfo.InvariantCulture.CompareInfo.IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
// Currently we don't have native functions to do this, so we do it the hard way
internal static int LastIndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
{
if (count > source.Length || count < 0 || startIndex < 0 || startIndex > source.Length - 1 || (startIndex - count + 1 < 0))
{
return -1;
}
return CultureInfo.InvariantCulture.CompareInfo.LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
////////////////////////////////////////////////////////////////////////
//
// CodePage
//
// Returns the number of the code page used by this writing system.
// The type parameter can be any of the following values:
// ANSICodePage
// OEMCodePage
// MACCodePage
//
////////////////////////////////////////////////////////////////////////
public virtual int ANSICodePage
{
get
{
return (_cultureData.IDEFAULTANSICODEPAGE);
}
}
public virtual int OEMCodePage
{
get
{
return (_cultureData.IDEFAULTOEMCODEPAGE);
}
}
public virtual int MacCodePage
{
get
{
return (_cultureData.IDEFAULTMACCODEPAGE);
}
}
public virtual int EBCDICCodePage
{
get
{
return (_cultureData.IDEFAULTEBCDICCODEPAGE);
}
}
public int LCID
{
get
{
// Just use the LCID from our text info name
return CultureInfo.GetCultureInfo(_textInfoName).LCID;
}
}
//////////////////////////////////////////////////////////////////////////
////
//// CultureName
////
//// The name of the culture associated with the current TextInfo.
////
//////////////////////////////////////////////////////////////////////////
public string CultureName
{
get
{
return _textInfoName;
}
}
////////////////////////////////////////////////////////////////////////
//
// IsReadOnly
//
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
public bool IsReadOnly
{
get { return (_isReadOnly); }
}
//////////////////////////////////////////////////////////////////////////
////
//// Clone
////
//// Is the implementation of ICloneable.
////
//////////////////////////////////////////////////////////////////////////
public virtual object Clone()
{
object o = MemberwiseClone();
((TextInfo)o).SetReadOnlyState(false);
return (o);
}
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
//
// Create a cloned readonly instance or return the input one if it is
// readonly.
//
////////////////////////////////////////////////////////////////////////
public static TextInfo ReadOnly(TextInfo textInfo)
{
if (textInfo == null) { throw new ArgumentNullException(nameof(textInfo)); }
if (textInfo.IsReadOnly) { return (textInfo); }
TextInfo clonedTextInfo = (TextInfo)(textInfo.MemberwiseClone());
clonedTextInfo.SetReadOnlyState(true);
return (clonedTextInfo);
}
private void VerifyWritable()
{
if (_isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
internal void SetReadOnlyState(bool readOnly)
{
_isReadOnly = readOnly;
}
////////////////////////////////////////////////////////////////////////
//
// ListSeparator
//
// Returns the string used to separate items in a list.
//
////////////////////////////////////////////////////////////////////////
public virtual String ListSeparator
{
get
{
if (_listSeparator == null)
{
_listSeparator = _cultureData.SLIST;
}
return (_listSeparator);
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String);
}
VerifyWritable();
_listSeparator = value;
}
}
////////////////////////////////////////////////////////////////////////
//
// ToLower
//
// Converts the character or string to lower case. Certain locales
// have different casing semantics from the file systems in Win32.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual char ToLower(char c)
{
if (IsAscii(c) && IsAsciiCasingSameAsInvariant)
{
return ToLowerAsciiInvariant(c);
}
return (ChangeCase(c, toUpper: false));
}
public unsafe virtual String ToLower(String str)
{
if (str == null) { throw new ArgumentNullException(nameof(str)); }
return ChangeCase(str, toUpper: false);
}
private static Char ToLowerAsciiInvariant(Char c)
{
if ((uint)(c - 'A') <= (uint)('Z' - 'A'))
{
c = (Char)(c | 0x20);
}
return c;
}
////////////////////////////////////////////////////////////////////////
//
// ToUpper
//
// Converts the character or string to upper case. Certain locales
// have different casing semantics from the file systems in Win32.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual char ToUpper(char c)
{
if (IsAscii(c) && IsAsciiCasingSameAsInvariant)
{
return ToUpperAsciiInvariant(c);
}
return (ChangeCase(c, toUpper: true));
}
public unsafe virtual String ToUpper(String str)
{
if (str == null) { throw new ArgumentNullException(nameof(str)); }
return ChangeCase(str, toUpper: true);
}
internal static Char ToUpperAsciiInvariant(Char c)
{
if ((uint)(c - 'a') <= (uint)('z' - 'a'))
{
c = (Char)(c & ~0x20);
}
return c;
}
private static bool IsAscii(Char c)
{
return c < 0x80;
}
private bool IsAsciiCasingSameAsInvariant
{
get
{
if (_isAsciiCasingSameAsInvariant == Tristate.NotInitialized)
{
_isAsciiCasingSameAsInvariant = CultureInfo.GetCultureInfo(_textInfoName).CompareInfo.Compare("abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
CompareOptions.IgnoreCase) == 0 ? Tristate.True : Tristate.False;
}
return _isAsciiCasingSameAsInvariant == Tristate.True;
}
}
// IsRightToLeft
//
// Returns true if the dominant direction of text and UI such as the relative position of buttons and scroll bars
//
public bool IsRightToLeft
{
get
{
return _cultureData.IsRightToLeft;
}
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same CultureInfo as the current instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object obj)
{
TextInfo that = obj as TextInfo;
if (that != null)
{
return this.CultureName.Equals(that.CultureName);
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CultureInfo. The hash code is guaranteed to be the same for CultureInfo A
// and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.CultureName.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// TextInfo.
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return ("TextInfo - " + _cultureData.CultureName);
}
//
// Titlecasing:
// -----------
// Titlecasing refers to a casing practice wherein the first letter of a word is an uppercase letter
// and the rest of the letters are lowercase. The choice of which words to titlecase in headings
// and titles is dependent on language and local conventions. For example, "The Merry Wives of Windor"
// is the appropriate titlecasing of that play's name in English, with the word "of" not titlecased.
// In German, however, the title is "Die lustigen Weiber von Windsor," and both "lustigen" and "von"
// are not titlecased. In French even fewer words are titlecased: "Les joyeuses commeres de Windsor."
//
// Moreover, the determination of what actually constitutes a word is language dependent, and this can
// influence which letter or letters of a "word" are uppercased when titlecasing strings. For example
// "l'arbre" is considered two words in French, whereas "can't" is considered one word in English.
//
public unsafe String ToTitleCase(String str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
if (str.Length == 0)
{
return (str);
}
StringBuilder result = new StringBuilder();
string lowercaseData = null;
// Store if the current culture is Dutch (special case)
bool isDutchCulture = CultureName.StartsWith("nl-", StringComparison.OrdinalIgnoreCase);
for (int i = 0; i < str.Length; i++)
{
UnicodeCategory charType;
int charLen;
charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen);
if (Char.CheckLetter(charType))
{
// Special case to check for Dutch specific titlecasing with "IJ" characters
// at the beginning of a word
if (isDutchCulture && i < str.Length - 1 && (str[i] == 'i' || str[i] == 'I') && (str[i + 1] == 'j' || str[i + 1] == 'J'))
{
result.Append("IJ");
i += 2;
}
else
{
// Do the titlecasing for the first character of the word.
i = AddTitlecaseLetter(ref result, ref str, i, charLen) + 1;
}
//
// Convert the characters until the end of the this word
// to lowercase.
//
int lowercaseStart = i;
//
// Use hasLowerCase flag to prevent from lowercasing acronyms (like "URT", "USA", etc)
// This is in line with Word 2000 behavior of titlecasing.
//
bool hasLowerCase = (charType == UnicodeCategory.LowercaseLetter);
// Use a loop to find all of the other letters following this letter.
while (i < str.Length)
{
charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen);
if (IsLetterCategory(charType))
{
if (charType == UnicodeCategory.LowercaseLetter)
{
hasLowerCase = true;
}
i += charLen;
}
else if (str[i] == '\'')
{
i++;
if (hasLowerCase)
{
if (lowercaseData == null)
{
lowercaseData = this.ToLower(str);
}
result.Append(lowercaseData, lowercaseStart, i - lowercaseStart);
}
else
{
result.Append(str, lowercaseStart, i - lowercaseStart);
}
lowercaseStart = i;
hasLowerCase = true;
}
else if (!IsWordSeparator(charType))
{
// This category is considered to be part of the word.
// This is any category that is marked as false in wordSeprator array.
i += charLen;
}
else
{
// A word separator. Break out of the loop.
break;
}
}
int count = i - lowercaseStart;
if (count > 0)
{
if (hasLowerCase)
{
if (lowercaseData == null)
{
lowercaseData = this.ToLower(str);
}
result.Append(lowercaseData, lowercaseStart, count);
}
else
{
result.Append(str, lowercaseStart, count);
}
}
if (i < str.Length)
{
// not a letter, just append it
i = AddNonLetter(ref result, ref str, i, charLen);
}
}
else
{
// not a letter, just append it
i = AddNonLetter(ref result, ref str, i, charLen);
}
}
return (result.ToString());
}
private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
{
Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
if (charLen == 2)
{
// Surrogate pair
result.Append(input[inputIndex++]);
result.Append(input[inputIndex]);
}
else
{
result.Append(input[inputIndex]);
}
return inputIndex;
}
private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
{
Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
// for surrogate pairs do a simple ToUpper operation on the substring
if (charLen == 2)
{
// Surrogate pair
result.Append(ToUpper(input.Substring(inputIndex, charLen)));
inputIndex++;
}
else
{
switch (input[inputIndex])
{
//
// For AppCompat, the Titlecase Case Mapping data from NDP 2.0 is used below.
case (char)0x01C4: // DZ with Caron -> Dz with Caron
case (char)0x01C5: // Dz with Caron -> Dz with Caron
case (char)0x01C6: // dz with Caron -> Dz with Caron
result.Append((char)0x01C5);
break;
case (char)0x01C7: // LJ -> Lj
case (char)0x01C8: // Lj -> Lj
case (char)0x01C9: // lj -> Lj
result.Append((char)0x01C8);
break;
case (char)0x01CA: // NJ -> Nj
case (char)0x01CB: // Nj -> Nj
case (char)0x01CC: // nj -> Nj
result.Append((char)0x01CB);
break;
case (char)0x01F1: // DZ -> Dz
case (char)0x01F2: // Dz -> Dz
case (char)0x01F3: // dz -> Dz
result.Append((char)0x01F2);
break;
default:
result.Append(ToUpper(input[inputIndex]));
break;
}
}
return inputIndex;
}
//
// Used in ToTitleCase():
// When we find a starting letter, the following array decides if a category should be
// considered as word seprator or not.
//
private const int c_wordSeparatorMask =
/* false */ (0 << 0) | // UppercaseLetter = 0,
/* false */ (0 << 1) | // LowercaseLetter = 1,
/* false */ (0 << 2) | // TitlecaseLetter = 2,
/* false */ (0 << 3) | // ModifierLetter = 3,
/* false */ (0 << 4) | // OtherLetter = 4,
/* false */ (0 << 5) | // NonSpacingMark = 5,
/* false */ (0 << 6) | // SpacingCombiningMark = 6,
/* false */ (0 << 7) | // EnclosingMark = 7,
/* false */ (0 << 8) | // DecimalDigitNumber = 8,
/* false */ (0 << 9) | // LetterNumber = 9,
/* false */ (0 << 10) | // OtherNumber = 10,
/* true */ (1 << 11) | // SpaceSeparator = 11,
/* true */ (1 << 12) | // LineSeparator = 12,
/* true */ (1 << 13) | // ParagraphSeparator = 13,
/* true */ (1 << 14) | // Control = 14,
/* true */ (1 << 15) | // Format = 15,
/* false */ (0 << 16) | // Surrogate = 16,
/* false */ (0 << 17) | // PrivateUse = 17,
/* true */ (1 << 18) | // ConnectorPunctuation = 18,
/* true */ (1 << 19) | // DashPunctuation = 19,
/* true */ (1 << 20) | // OpenPunctuation = 20,
/* true */ (1 << 21) | // ClosePunctuation = 21,
/* true */ (1 << 22) | // InitialQuotePunctuation = 22,
/* true */ (1 << 23) | // FinalQuotePunctuation = 23,
/* true */ (1 << 24) | // OtherPunctuation = 24,
/* true */ (1 << 25) | // MathSymbol = 25,
/* true */ (1 << 26) | // CurrencySymbol = 26,
/* true */ (1 << 27) | // ModifierSymbol = 27,
/* true */ (1 << 28) | // OtherSymbol = 28,
/* false */ (0 << 29); // OtherNotAssigned = 29;
private static bool IsWordSeparator(UnicodeCategory category)
{
return (c_wordSeparatorMask & (1 << (int)category)) != 0;
}
private static bool IsLetterCategory(UnicodeCategory uc)
{
return (uc == UnicodeCategory.UppercaseLetter
|| uc == UnicodeCategory.LowercaseLetter
|| uc == UnicodeCategory.TitlecaseLetter
|| uc == UnicodeCategory.ModifierLetter
|| uc == UnicodeCategory.OtherLetter);
}
//
// Get case-insensitive hash code for the specified string.
//
internal unsafe int GetCaseInsensitiveHashCode(String str)
{
// Validate inputs
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
// This code assumes that ASCII casing is safe for whatever context is passed in.
// this is true today, because we only ever call these methods on Invariant. It would be ideal to refactor
// these methods so they were correct by construction and we could only ever use Invariant.
uint hash = 5381;
uint c;
// Note: We assume that str contains only ASCII characters until
// we hit a non-ASCII character to optimize the common case.
for (int i = 0; i < str.Length; i++)
{
c = str[i];
if (c >= 0x80)
{
return GetCaseInsensitiveHashCodeSlow(str);
}
// If we have a lowercase character, ANDing off 0x20
// will make it an uppercase character.
if ((c - 'a') <= ('z' - 'a'))
{
c = (uint)((int)c & ~0x20);
}
hash = ((hash << 5) + hash) ^ c;
}
return (int)hash;
}
private unsafe int GetCaseInsensitiveHashCodeSlow(String str)
{
Debug.Assert(str != null);
string upper = ToUpper(str);
uint hash = 5381;
uint c;
for (int i = 0; i < upper.Length; i++)
{
c = upper[i];
hash = ((hash << 5) + hash) ^ c;
}
return (int)hash;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Dbg = System.Management.Automation;
using System.Management.Automation.Internal;
using System.Security.Cryptography.X509Certificates;
using System.ComponentModel;
using DWORD = System.UInt32;
namespace System.Management.Automation
{
internal static class Win32Errors
{
internal const DWORD NO_ERROR = 0;
internal const DWORD E_FAIL = 0x80004005;
internal const DWORD TRUST_E_NOSIGNATURE = 0x800b0100;
internal const DWORD TRUST_E_BAD_DIGEST = 0x80096010;
internal const DWORD TRUST_E_PROVIDER_UNKNOWN = 0x800b0001;
internal const DWORD TRUST_E_SUBJECT_FORM_UNKNOWN = 0x800B0003;
internal const DWORD CERT_E_UNTRUSTEDROOT = 0x800b0109;
internal const DWORD TRUST_E_EXPLICIT_DISTRUST = 0x800B0111;
internal const DWORD CRYPT_E_BAD_MSG = 0x8009200d;
internal const DWORD NTE_BAD_ALGID = 0x80090008;
}
/// <summary>
/// Defines the valid status flags that a signature
/// on a file may have.
/// </summary>
public enum SignatureStatus
{
/// <summary>
/// The file has a valid signature. This means only that
/// the signature is syntactically valid. It does not
/// imply trust in any way.
/// </summary>
Valid,
/// <summary>
/// The file has an invalid signature.
/// </summary>
UnknownError,
/// <summary>
/// The file has no signature.
/// </summary>
NotSigned,
/// <summary>
/// The hash of the file does not match the hash stored
/// along with the signature.
/// </summary>
HashMismatch,
/// <summary>
/// The certificate was signed by a publisher not trusted
/// on the system.
/// </summary>
NotTrusted,
/// <summary>
/// The specified file format is not supported by the system
/// for signing operations. This usually means that the
/// system does not know how to sign or verify the file
/// type requested.
/// </summary>
NotSupportedFileFormat,
/// <summary>
/// The signature cannot be verified because it is incompatible
/// with the current system.
/// </summary>
Incompatible
};
/// <summary>
/// Defines the valid types of signatures.
/// </summary>
public enum SignatureType
{
/// <summary>
/// The file is not signed.
/// </summary>
None = 0,
/// <summary>
/// The signature is an Authenticode signature embedded into the file itself.
/// </summary>
Authenticode = 1,
/// <summary>
/// The signature is a catalog signature.
/// </summary>
Catalog = 2
};
/// <summary>
/// Represents a digital signature on a signed
/// file.
/// </summary>
public sealed class Signature
{
private string _path;
private SignatureStatus _status = SignatureStatus.UnknownError;
private DWORD _win32Error;
private X509Certificate2 _signerCert;
private string _statusMessage = string.Empty;
private X509Certificate2 _timeStamperCert;
// private DateTime signedOn = new DateTime(0);
// Three states:
// - True: we can rely on the catalog API to check catalog signature.
// - False: we cannot rely on the catalog API, either because it doesn't exist in the OS (win7),
// or it's not working properly (OneCore SKUs or dev environment where powershell might
// be updated/refreshed).
// - Null: it's not determined yet whether catalog API can be relied on or not.
internal static bool? CatalogApiAvailable = null;
/// <summary>
/// Gets the X509 certificate of the publisher that
/// signed the file.
/// </summary>
public X509Certificate2 SignerCertificate
{
get
{
return _signerCert;
}
}
/// <summary>
/// Gets the X509 certificate of the authority that
/// time-stamped the file.
/// </summary>
public X509Certificate2 TimeStamperCertificate
{
get
{
return _timeStamperCert;
}
}
/// <summary>
/// Gets the status of the signature on the file.
/// </summary>
public SignatureStatus Status
{
get
{
return _status;
}
}
/// <summary>
/// Gets the message corresponding to the status of the
/// signature on the file.
/// </summary>
public string StatusMessage
{
get
{
return _statusMessage;
}
}
/// <summary>
/// Gets the path of the file to which this signature
/// applies.
/// </summary>
public string Path
{
get
{
return _path;
}
}
/// <summary>
/// Returns the signature type of the signature.
/// </summary>
public SignatureType SignatureType { get; internal set; }
/// <summary>
/// True if the item is signed as part of an operating system release.
/// </summary>
public bool IsOSBinary { get; internal set; }
/// <summary>
/// Constructor for class Signature
///
/// Call this to create a validated time-stamped signature object.
/// </summary>
/// <param name="filePath">This signature is found in this file.</param>
/// <param name="error">Win32 error code.</param>
/// <param name="signer">Cert of the signer.</param>
/// <param name="timestamper">Cert of the time stamper.</param>
/// <returns>Constructed object.</returns>
internal Signature(string filePath,
DWORD error,
X509Certificate2 signer,
X509Certificate2 timestamper)
{
Utils.CheckArgForNullOrEmpty(filePath, "filePath");
Utils.CheckArgForNull(signer, "signer");
Utils.CheckArgForNull(timestamper, "timestamper");
Init(filePath, signer, error, timestamper);
}
/// <summary>
/// Constructor for class Signature
///
/// Call this to create a validated signature object.
/// </summary>
/// <param name="filePath">This signature is found in this file.</param>
/// <param name="signer">Cert of the signer.</param>
/// <returns>Constructed object.</returns>
internal Signature(string filePath,
X509Certificate2 signer)
{
Utils.CheckArgForNullOrEmpty(filePath, "filePath");
Utils.CheckArgForNull(signer, "signer");
Init(filePath, signer, 0, null);
}
/// <summary>
/// Constructor for class Signature
///
/// Call this ctor when creating an invalid signature object.
/// </summary>
/// <param name="filePath">This signature is found in this file.</param>
/// <param name="error">Win32 error code.</param>
/// <param name="signer">Cert of the signer.</param>
/// <returns>Constructed object.</returns>
internal Signature(string filePath,
DWORD error,
X509Certificate2 signer)
{
Utils.CheckArgForNullOrEmpty(filePath, "filePath");
Utils.CheckArgForNull(signer, "signer");
Init(filePath, signer, error, null);
}
/// <summary>
/// Constructor for class Signature
///
/// Call this ctor when creating an invalid signature object.
/// </summary>
/// <param name="filePath">This signature is found in this file.</param>
/// <param name="error">Win32 error code.</param>
/// <returns>Constructed object.</returns>
internal Signature(string filePath, DWORD error)
{
Utils.CheckArgForNullOrEmpty(filePath, "filePath");
Init(filePath, null, error, null);
}
private void Init(string filePath,
X509Certificate2 signer,
DWORD error,
X509Certificate2 timestamper)
{
_path = filePath;
_win32Error = error;
_signerCert = signer;
_timeStamperCert = timestamper;
SignatureType = SignatureType.None;
SignatureStatus isc =
GetSignatureStatusFromWin32Error(error);
_status = isc;
_statusMessage = GetSignatureStatusMessage(isc,
error,
filePath);
}
private static SignatureStatus GetSignatureStatusFromWin32Error(DWORD error)
{
SignatureStatus isc = SignatureStatus.UnknownError;
switch (error)
{
case Win32Errors.NO_ERROR:
isc = SignatureStatus.Valid;
break;
case Win32Errors.NTE_BAD_ALGID:
isc = SignatureStatus.Incompatible;
break;
case Win32Errors.TRUST_E_NOSIGNATURE:
isc = SignatureStatus.NotSigned;
break;
case Win32Errors.TRUST_E_BAD_DIGEST:
case Win32Errors.CRYPT_E_BAD_MSG:
isc = SignatureStatus.HashMismatch;
break;
case Win32Errors.TRUST_E_PROVIDER_UNKNOWN:
isc = SignatureStatus.NotSupportedFileFormat;
break;
case Win32Errors.TRUST_E_EXPLICIT_DISTRUST:
isc = SignatureStatus.NotTrusted;
break;
}
return isc;
}
private static string GetSignatureStatusMessage(SignatureStatus status,
DWORD error,
string filePath)
{
string message = null;
string resourceString = null;
string arg = null;
switch (status)
{
case SignatureStatus.Valid:
resourceString = MshSignature.MshSignature_Valid;
break;
case SignatureStatus.UnknownError:
int intError = SecuritySupport.GetIntFromDWORD(error);
Win32Exception e = new Win32Exception(intError);
message = e.Message;
break;
case SignatureStatus.Incompatible:
if (error == Win32Errors.NTE_BAD_ALGID)
{
resourceString = MshSignature.MshSignature_Incompatible_HashAlgorithm;
}
else
{
resourceString = MshSignature.MshSignature_Incompatible;
}
arg = filePath;
break;
case SignatureStatus.NotSigned:
resourceString = MshSignature.MshSignature_NotSigned;
arg = filePath;
break;
case SignatureStatus.HashMismatch:
resourceString = MshSignature.MshSignature_HashMismatch;
arg = filePath;
break;
case SignatureStatus.NotTrusted:
resourceString = MshSignature.MshSignature_NotTrusted;
arg = filePath;
break;
case SignatureStatus.NotSupportedFileFormat:
resourceString = MshSignature.MshSignature_NotSupportedFileFormat;
arg = System.IO.Path.GetExtension(filePath);
if (string.IsNullOrEmpty(arg))
{
resourceString = MshSignature.MshSignature_NotSupportedFileFormat_NoExtension;
arg = null;
}
break;
}
if (message == null)
{
if (arg == null)
{
message = resourceString;
}
else
{
message = StringUtil.Format(resourceString, arg);
}
}
return message;
}
};
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\EnvironmentQuery\Tests\EnvQueryTest_Dot.h:22
namespace UnrealEngine
{
[ManageType("ManageEnvQueryTest_Dot")]
public partial class ManageEnvQueryTest_Dot : UEnvQueryTest_Dot, IManageWrapper
{
public ManageEnvQueryTest_Dot(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Dot_UpdateNodeVersion(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Dot_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Dot_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Dot_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Dot_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Dot_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Dot_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Dot_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Dot_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Dot_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Dot_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Dot_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Dot_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Dot_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Dot_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UEnvQueryTest_Dot_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
public override void UpdateNodeVersion()
=> E__Supper__UEnvQueryTest_Dot_UpdateNodeVersion(this);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__UEnvQueryTest_Dot_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__UEnvQueryTest_Dot_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__UEnvQueryTest_Dot_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__UEnvQueryTest_Dot_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__UEnvQueryTest_Dot_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__UEnvQueryTest_Dot_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__UEnvQueryTest_Dot_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__UEnvQueryTest_Dot_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__UEnvQueryTest_Dot_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__UEnvQueryTest_Dot_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__UEnvQueryTest_Dot_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__UEnvQueryTest_Dot_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__UEnvQueryTest_Dot_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__UEnvQueryTest_Dot_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__UEnvQueryTest_Dot_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageEnvQueryTest_Dot self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageEnvQueryTest_Dot(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageEnvQueryTest_Dot>(PtrDesc);
}
}
}
| |
namespace android.view.inputmethod
{
[global::MonoJavaBridge.JavaClass()]
public partial class EditorInfo : java.lang.Object, android.text.InputType, android.os.Parcelable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static EditorInfo()
{
InitJNI();
}
protected EditorInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _dump10112;
public virtual void dump(android.util.Printer arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.inputmethod.EditorInfo._dump10112, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.inputmethod.EditorInfo.staticClass, global::android.view.inputmethod.EditorInfo._dump10112, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _writeToParcel10113;
public virtual void writeToParcel(android.os.Parcel arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.inputmethod.EditorInfo._writeToParcel10113, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.inputmethod.EditorInfo.staticClass, global::android.view.inputmethod.EditorInfo._writeToParcel10113, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _describeContents10114;
public virtual int describeContents()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.inputmethod.EditorInfo._describeContents10114);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.inputmethod.EditorInfo.staticClass, global::android.view.inputmethod.EditorInfo._describeContents10114);
}
internal static global::MonoJavaBridge.MethodId _EditorInfo10115;
public EditorInfo() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.inputmethod.EditorInfo.staticClass, global::android.view.inputmethod.EditorInfo._EditorInfo10115);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.FieldId _inputType10116;
public int inputType
{
get
{
return default(int);
}
set
{
}
}
public static int IME_MASK_ACTION
{
get
{
return 255;
}
}
public static int IME_ACTION_UNSPECIFIED
{
get
{
return 0;
}
}
public static int IME_ACTION_NONE
{
get
{
return 1;
}
}
public static int IME_ACTION_GO
{
get
{
return 2;
}
}
public static int IME_ACTION_SEARCH
{
get
{
return 3;
}
}
public static int IME_ACTION_SEND
{
get
{
return 4;
}
}
public static int IME_ACTION_NEXT
{
get
{
return 5;
}
}
public static int IME_ACTION_DONE
{
get
{
return 6;
}
}
public static int IME_FLAG_NO_EXTRACT_UI
{
get
{
return 268435456;
}
}
public static int IME_FLAG_NO_ACCESSORY_ACTION
{
get
{
return 536870912;
}
}
public static int IME_FLAG_NO_ENTER_ACTION
{
get
{
return 1073741824;
}
}
public static int IME_NULL
{
get
{
return 0;
}
}
internal static global::MonoJavaBridge.FieldId _imeOptions10117;
public int imeOptions
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _privateImeOptions10118;
public global::java.lang.String privateImeOptions
{
get
{
return default(global::java.lang.String);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _actionLabel10119;
public global::java.lang.CharSequence actionLabel
{
get
{
return default(global::java.lang.CharSequence);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _actionId10120;
public int actionId
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _initialSelStart10121;
public int initialSelStart
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _initialSelEnd10122;
public int initialSelEnd
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _initialCapsMode10123;
public int initialCapsMode
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _hintText10124;
public global::java.lang.CharSequence hintText
{
get
{
return default(global::java.lang.CharSequence);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _label10125;
public global::java.lang.CharSequence label
{
get
{
return default(global::java.lang.CharSequence);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _packageName10126;
public global::java.lang.String packageName
{
get
{
return default(global::java.lang.String);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _fieldId10127;
public int fieldId
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _fieldName10128;
public global::java.lang.String fieldName
{
get
{
return default(global::java.lang.String);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _extras10129;
public global::android.os.Bundle extras
{
get
{
return default(global::android.os.Bundle);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _CREATOR10130;
public static global::android.os.Parcelable_Creator CREATOR
{
get
{
return default(global::android.os.Parcelable_Creator);
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.inputmethod.EditorInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/inputmethod/EditorInfo"));
global::android.view.inputmethod.EditorInfo._dump10112 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.EditorInfo.staticClass, "dump", "(Landroid/util/Printer;Ljava/lang/String;)V");
global::android.view.inputmethod.EditorInfo._writeToParcel10113 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.EditorInfo.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V");
global::android.view.inputmethod.EditorInfo._describeContents10114 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.EditorInfo.staticClass, "describeContents", "()I");
global::android.view.inputmethod.EditorInfo._EditorInfo10115 = @__env.GetMethodIDNoThrow(global::android.view.inputmethod.EditorInfo.staticClass, "<init>", "()V");
}
}
}
| |
// 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.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
// NOTE:
// Currently the managed handler is opt-in on both Windows and Unix, due to still being a nascent implementation
// that's missing features, robustness, perf, etc. One opts into it currently by setting an environment variable,
// which makes it a bit difficult to test. There are two straightforward ways to test it:
// - This file contains test classes that derive from the other test classes in the project that create
// HttpClient{Handler} instances, and in the ctor sets the env var and in Dispose removes the env var.
// That has the effect of running all of those same tests again, but with the managed handler enabled.
// - By setting the env var prior to running tests, every test will implicitly use the managed handler,
// at which point the tests in this file are duplicative and can be commented out.
// For now parallelism is disabled because we use an env var to turn on the managed handler, and the env var
// impacts any tests running concurrently in the process. We can remove this restriction in the future once
// plans around the ManagedHandler are better understood.
[assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly, DisableTestParallelization = true, MaxParallelThreads = 1)]
namespace System.Net.Http.Functional.Tests
{
public sealed class ManagedHandler_HttpClientTest : HttpClientTest, IDisposable
{
public ManagedHandler_HttpClientTest() => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
public sealed class ManagedHandler_DiagnosticsTest : DiagnosticsTest, IDisposable
{
public ManagedHandler_DiagnosticsTest() => ManagedHandlerTestHelpers.SetEnvVar();
public new void Dispose()
{
ManagedHandlerTestHelpers.RemoveEnvVar();
base.Dispose();
}
}
// TODO #21452: Tests on this class fail when the associated condition is enabled.
//public sealed class ManagedHandler_HttpClientEKUTest : HttpClientEKUTest, IDisposable
//{
// public ManagedHandler_HttpClientEKUTest() => ManagedHandlerTestHelpers.SetEnvVar();
// public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
//}
public sealed class ManagedHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test : HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test, IDisposable
{
public ManagedHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test() => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
public sealed class ManagedHandler_HttpClientHandler_ClientCertificates_Test : HttpClientHandler_ClientCertificates_Test, IDisposable
{
public ManagedHandler_HttpClientHandler_ClientCertificates_Test(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
public new void Dispose()
{
ManagedHandlerTestHelpers.RemoveEnvVar();
base.Dispose();
}
}
public sealed class ManagedHandler_HttpClientHandler_DefaultProxyCredentials_Test : HttpClientHandler_DefaultProxyCredentials_Test, IDisposable
{
public ManagedHandler_HttpClientHandler_DefaultProxyCredentials_Test() => ManagedHandlerTestHelpers.SetEnvVar();
public new void Dispose()
{
ManagedHandlerTestHelpers.RemoveEnvVar();
base.Dispose();
}
}
public sealed class ManagedHandler_HttpClientHandler_MaxConnectionsPerServer_Test : HttpClientHandler_MaxConnectionsPerServer_Test, IDisposable
{
public ManagedHandler_HttpClientHandler_MaxConnectionsPerServer_Test() => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
public sealed class ManagedHandler_HttpClientHandler_ServerCertificates_Test : HttpClientHandler_ServerCertificates_Test, IDisposable
{
public ManagedHandler_HttpClientHandler_ServerCertificates_Test() => ManagedHandlerTestHelpers.SetEnvVar();
public new void Dispose()
{
ManagedHandlerTestHelpers.RemoveEnvVar();
base.Dispose();
}
}
public sealed class ManagedHandler_PostScenarioTest : PostScenarioTest, IDisposable
{
public ManagedHandler_PostScenarioTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
public sealed class ManagedHandler_ResponseStreamTest : ResponseStreamTest, IDisposable
{
public ManagedHandler_ResponseStreamTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
public sealed class ManagedHandler_HttpClientHandler_SslProtocols_Test : HttpClientHandler_SslProtocols_Test, IDisposable
{
public ManagedHandler_HttpClientHandler_SslProtocols_Test() => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
public sealed class ManagedHandler_SchSendAuxRecordHttpTest : SchSendAuxRecordHttpTest, IDisposable
{
public ManagedHandler_SchSendAuxRecordHttpTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
public sealed class ManagedHandler_HttpClientMiniStress : HttpClientMiniStress, IDisposable
{
public ManagedHandler_HttpClientMiniStress() => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
// TODO #21452:
//public sealed class ManagedHandler_DefaultCredentialsTest : DefaultCredentialsTest, IDisposable
//{
// public ManagedHandler_DefaultCredentialsTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
// public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
//}
public sealed class ManagedHandler_HttpClientHandlerTest : HttpClientHandlerTest, IDisposable
{
public ManagedHandler_HttpClientHandlerTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
public new void Dispose()
{
ManagedHandlerTestHelpers.RemoveEnvVar();
base.Dispose();
}
}
// TODO #21452: Socket's don't support canceling individual operations, so ReadStream on NetworkStream
// isn't cancelable once the operation has started. We either need to wrap the operation with one that's
// "cancelable", meaning that the underlying operation will still be running even though we've returned "canceled",
// or we need to just recognize that cancellation in such situations can be left up to the caller to do the
// same thing if it's really important.
//public sealed class ManagedHandler_CancellationTest : CancellationTest, IDisposable
//{
// public ManagedHandler_CancellationTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
// public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
//}
// TODO #21452: The managed handler doesn't currently track how much data was written for the response headers.
//public sealed class ManagedHandler_HttpClientHandler_MaxResponseHeadersLength_Test : HttpClientHandler_MaxResponseHeadersLength_Test, IDisposable
//{
// public ManagedHandler_HttpClientHandler_MaxResponseHeadersLength_Test() => ManagedHandlerTestHelpers.SetEnvVar();
// public new void Dispose()
// {
// ManagedHandlerTestHelpers.RemoveEnvVar();
// base.Dispose();
// }
//}
public sealed class ManagedHandler_HttpClientHandler_ConnectionPooling_Test : IDisposable
{
public ManagedHandler_HttpClientHandler_ConnectionPooling_Test() => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
// TODO: Currently the subsequent tests sometimes fail/hang with WinHttpHandler / CurlHandler.
// In theory they should pass with any handler that does appropriate connection pooling.
// We should understand why they sometimes fail there and ideally move them to be
// used by all handlers this test project tests.
[Fact]
public async Task MultipleIterativeRequests_SameConnectionReused()
{
using (var client = new HttpClient())
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
var ep = (IPEndPoint)listener.LocalEndPoint;
var uri = new Uri($"http://{ep.Address}:{ep.Port}/");
string responseBody =
"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Content-Length: 0\r\n" +
"\r\n";
Task<string> firstRequest = client.GetStringAsync(uri);
using (Socket server = await listener.AcceptAsync())
using (var serverStream = new NetworkStream(server, ownsSocket: false))
using (var serverReader = new StreamReader(serverStream))
using (var serverWriter = new StreamWriter(serverStream))
{
await serverReader.ReadLineAsync(); // GET line
await serverReader.ReadLineAsync(); // blank line
await serverWriter.WriteAsync(responseBody);
await serverWriter.FlushAsync();
await firstRequest;
Task<Socket> secondAccept = listener.AcceptAsync(); // shouldn't complete
Task<string> additionalRequest = client.GetStringAsync(uri);
await serverReader.ReadLineAsync(); // GET line
await serverReader.ReadLineAsync(); // blank line
await serverWriter.WriteAsync(responseBody);
await serverWriter.FlushAsync();
await additionalRequest;
Assert.False(secondAccept.IsCompleted, $"Second accept should never complete");
}
}
}
[OuterLoop("Incurs a delay")]
[Fact]
public async Task ServerDisconnectsAfterInitialRequest_SubsequentRequestUsesDifferentConnection()
{
using (var client = new HttpClient())
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(100);
var ep = (IPEndPoint)listener.LocalEndPoint;
var uri = new Uri($"http://{ep.Address}:{ep.Port}/");
string responseBody =
"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Content-Length: 0\r\n" +
"\r\n";
// Make multiple requests iteratively.
for (int i = 0; i < 2; i++)
{
Task<string> request = client.GetStringAsync(uri);
using (Socket server = await listener.AcceptAsync())
using (var serverStream = new NetworkStream(server, ownsSocket: false))
using (var serverReader = new StreamReader(serverStream))
using (var serverWriter = new StreamWriter(serverStream))
{
await serverReader.ReadLineAsync(); // GET line
await serverReader.ReadLineAsync(); // blank line
await server.SendAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(responseBody)), SocketFlags.None);
await request;
server.Shutdown(SocketShutdown.Both);
if (i == 0)
{
await Task.Delay(2000); // give client time to see the closing before next connect
}
}
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Concurrent;
using System.Globalization;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.Serialization;
using System.IO;
using System.Diagnostics.CodeAnalysis;
using Microsoft.PowerShell.Commands.Internal.Format;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Security.Permissions;
namespace System.Management.Automation.Runspaces
{
/// <summary>
/// This exception is used by Formattable constructor to indicate errors
/// occured during construction time.
/// </summary>
[Serializable]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "FormatTable")]
public class FormatTableLoadException : RuntimeException
{
private Collection<string> _errors;
#region Constructors
/// <summary>
/// This is the default constructor.
/// </summary>
public FormatTableLoadException() : base()
{
SetDefaultErrorRecord();
}
/// <summary>
/// This constructor takes a localized error message.
/// </summary>
/// <param name="message">
/// A localized error message.
/// </param>
public FormatTableLoadException(string message) : base(message)
{
SetDefaultErrorRecord();
}
/// <summary>
/// This constructor takes a localized message and an inner exception.
/// </summary>
/// <param name="message">
/// Localized error message.
/// </param>
/// <param name="innerException">
/// Inner exception.
/// </param>
public FormatTableLoadException(string message, Exception innerException)
: base(message, innerException)
{
SetDefaultErrorRecord();
}
/// <summary>
/// This constructor takes a collection of errors occurred during construction
/// time.
/// </summary>
/// <param name="loadErrors">
/// The errors that occured
/// </param>
internal FormatTableLoadException(ConcurrentBag<string> loadErrors) :
base(StringUtil.Format(FormatAndOutXmlLoadingStrings.FormatTableLoadErrors))
{
_errors = new Collection<string>(loadErrors.ToArray());
SetDefaultErrorRecord();
}
/// <summary>
/// This constructor is required by serialization.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected FormatTableLoadException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info == null)
{
throw new PSArgumentNullException("info");
}
int errorCount = info.GetInt32("ErrorCount");
if (errorCount > 0)
{
_errors = new Collection<string>();
for (int index = 0; index < errorCount; index++)
{
string key = string.Format(CultureInfo.InvariantCulture, "Error{0}", index);
_errors.Add(info.GetString(key));
}
}
}
#endregion Constructors
/// <summary>
/// Serializes the exception data.
/// </summary>
/// <param name="info">Serialization information.</param>
/// <param name="context">Streaming context.</param>
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new PSArgumentNullException("info");
}
base.GetObjectData(info, context);
// If there are simple fields, serialize them with info.AddValue
if (_errors != null)
{
int errorCount = _errors.Count;
info.AddValue("ErrorCount", errorCount);
for (int index = 0; index < errorCount; index++)
{
string key = string.Format(CultureInfo.InvariantCulture, "Error{0}", index);
info.AddValue(key, _errors[index]);
}
}
}
/// <summary>
/// Set the default ErrorRecord.
/// </summary>
protected void SetDefaultErrorRecord()
{
SetErrorCategory(ErrorCategory.InvalidData);
SetErrorId(typeof(FormatTableLoadException).FullName);
}
/// <summary>
/// The specific Formattable load errors.
/// </summary>
public Collection<string> Errors
{
get
{
return _errors;
}
}
}
/// <summary>
/// A class that keeps the information from format.ps1xml files in a cache table.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "FormatTable")]
public sealed class FormatTable
{
#region Private Data
private TypeInfoDataBaseManager _formatDBMgr;
#endregion
#region Constructor
/// <summary>
/// Default Constructor.
/// </summary>
internal FormatTable()
{
_formatDBMgr = new TypeInfoDataBaseManager();
}
/// <summary>
/// Constructor that creates a FormatTable from a set of format files.
/// </summary>
/// <param name="formatFiles">
/// Format files to load for format information.
/// </param>
/// <exception cref="ArgumentException">
/// 1. Path {0} is not fully qualified. Specify a fully qualified type file path.
/// </exception>
/// <exception cref="FormatTableLoadException">
/// 1. There were errors loading Formattable. Look in the Errors property to
/// get detailed error messages.
/// </exception>
public FormatTable(IEnumerable<string> formatFiles) : this(formatFiles, null, null)
{
}
/// <summary>
/// Append the formatData to the list of formatting configurations, and update the
/// entire formatting database.
/// </summary>
/// <param name="formatData">
/// The formatData is of type 'ExtendedTypeDefinition'. It defines the View configuration
/// including TableControl, ListControl, and WideControl.
/// </param>
/// <exception cref="FormatTableLoadException">
/// 1. There were errors loading Formattable. Look in the Errors property to
/// get detailed error messages.
/// </exception>
public void AppendFormatData(IEnumerable<ExtendedTypeDefinition> formatData)
{
if (formatData == null)
throw PSTraceSource.NewArgumentNullException("formatData");
_formatDBMgr.AddFormatData(formatData, false);
}
/// <summary>
/// Prepend the formatData to the list of formatting configurations, and update the
/// entire formatting database.
/// </summary>
/// <param name="formatData">
/// The formatData is of type 'ExtendedTypeDefinition'. It defines the View configuration
/// including TableControl, ListControl, and WideControl.
/// </param>
/// <exception cref="FormatTableLoadException">
/// 1. There were errors loading Formattable. Look in the Errors property to
/// get detailed error messages.
/// </exception>
public void PrependFormatData(IEnumerable<ExtendedTypeDefinition> formatData)
{
if (formatData == null)
throw PSTraceSource.NewArgumentNullException("formatData");
_formatDBMgr.AddFormatData(formatData, true);
}
/// <summary>
/// Constructor that creates a FormatTable from a set of format files.
/// </summary>
/// <param name="formatFiles">
/// Format files to load for format information.
/// </param>
/// <param name="authorizationManager">
/// Authorization manager to perform signature checks before reading ps1xml files (or null of no checks are needed)
/// </param>
/// <param name="host">
/// Host passed to <paramref name="authorizationManager"/>. Can be null if no interactive questions should be asked.
/// </param>
/// <exception cref="ArgumentException">
/// 1. Path {0} is not fully qualified. Specify a fully qualified type file path.
/// </exception>
/// <exception cref="FormatTableLoadException">
/// 1. There were errors loading Formattable. Look in the Errors property to
/// get detailed error messages.
/// </exception>
internal FormatTable(IEnumerable<string> formatFiles, AuthorizationManager authorizationManager, PSHost host)
{
if (formatFiles == null)
{
throw PSTraceSource.NewArgumentNullException("formatFiles");
}
_formatDBMgr = new TypeInfoDataBaseManager(formatFiles, true, authorizationManager, host);
}
#endregion
#region Internal Methods / Properties
internal TypeInfoDataBaseManager FormatDBManager
{
get { return _formatDBMgr; }
}
/// <summary>
/// Adds the <paramref name="formatFile"/> to the current FormatTable's file list.
/// The FormatTable will not reflect the change until Update is called.
/// </summary>
/// <param name="formatFile"></param>
/// <param name="shouldPrepend">
/// if true, <paramref name="formatFile"/> is prepended to the current FormatTable's file list.
/// if false, it will be appended.
/// </param>
internal void Add(string formatFile, bool shouldPrepend)
{
_formatDBMgr.Add(formatFile, shouldPrepend);
}
/// <summary>
/// Removes the <paramref name="formatFile"/> from the current FormatTable's file list.
/// The FormatTable will not reflect the change until Update is called.
/// </summary>
/// <param name="formatFile"></param>
internal void Remove(string formatFile)
{
_formatDBMgr.Remove(formatFile);
}
#endregion
#region static methods
/// <summary>
/// Returns a format table instance with all default
/// format files loaded.
/// </summary>
/// <returns></returns>
public static FormatTable LoadDefaultFormatFiles()
{
string psHome = Utils.DefaultPowerShellAppBase;
List<string> defaultFormatFiles = new List<string>();
if (!string.IsNullOrEmpty(psHome))
{
defaultFormatFiles.AddRange(Platform.FormatFileNames.Select(file => Path.Combine(psHome, file)));
}
return new FormatTable(defaultFormatFiles);
}
#endregion static methods
}
}
| |
using System;
using System.Threading.Tasks;
using System.Web;
using System.Net;
using System.Text;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.ComponentModel;
using SteamBot.SteamGroups;
using SteamKit2;
using SteamTrade;
using SteamKit2.Internal;
namespace SteamBot
{
public class Bot
{
public string BotControlClass;
// If the bot is logged in fully or not. This is only set
// when it is.
public bool IsLoggedIn = false;
// The bot's display name. Changing this does not mean that
// the bot's name will change.
public string DisplayName { get; private set; }
// The response to all chat messages sent to it.
public string ChatResponse;
// A list of SteamIDs that this bot recognizes as admins.
public ulong[] Admins;
public SteamFriends SteamFriends;
public SteamClient SteamClient;
public SteamTrading SteamTrade;
public SteamUser SteamUser;
public SteamGameCoordinator SteamGameCoordinator;
// The current trade; if the bot is not in a trade, this is
// null.
public Trade CurrentTrade;
public bool IsDebugMode = false;
// The log for the bot. This logs with the bot's display name.
public Log log;
public delegate UserHandler UserHandlerCreator(Bot bot, SteamID id);
public UserHandlerCreator CreateHandler;
Dictionary<ulong, UserHandler> userHandlers = new Dictionary<ulong, UserHandler>();
List<SteamID> friends = new List<SteamID>();
// List of Steam groups the bot is in.
private readonly List<SteamID> groups = new List<SteamID>();
// The maximum amount of time the bot will trade for.
public int MaximumTradeTime { get; private set; }
// The maximum amount of time the bot will wait in between
// trade actions.
public int MaximiumActionGap { get; private set; }
//The current game that the bot is playing, for posterity.
public int CurrentGame = 0;
// The Steam Web API key.
public string apiKey;
// The prefix put in the front of the bot's display name.
string DisplayNamePrefix;
// Log level to use for this bot
Log.LogLevel LogLevel;
// The number, in milliseconds, between polls for the trade.
int TradePollingInterval;
public string MyLoginKey;
string sessionId;
string token;
bool isprocess;
public bool IsRunning = false;
public string AuthCode { get; set; }
SteamUser.LogOnDetails logOnDetails;
TradeManager tradeManager;
private Task<Inventory> myInventoryTask;
public Inventory MyInventory
{
get
{
myInventoryTask.Wait();
return myInventoryTask.Result;
}
}
private BackgroundWorker backgroundWorker;
public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false)
{
logOnDetails = new SteamUser.LogOnDetails
{
Username = config.Username,
Password = config.Password
};
DisplayName = config.DisplayName;
ChatResponse = config.ChatResponse;
MaximumTradeTime = config.MaximumTradeTime;
MaximiumActionGap = config.MaximumActionGap;
DisplayNamePrefix = config.DisplayNamePrefix;
TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
Admins = config.Admins;
this.apiKey = apiKey;
this.isprocess = process;
try
{
LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
}
catch (ArgumentException)
{
Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'");
LogLevel = Log.LogLevel.Info;
}
log = new Log (config.LogFile, this.DisplayName, LogLevel);
CreateHandler = handlerCreator;
BotControlClass = config.BotControlClass;
// Hacking around https
ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;
log.Debug ("Initializing Steam Bot...");
SteamClient = new SteamClient();
SteamTrade = SteamClient.GetHandler<SteamTrading>();
SteamUser = SteamClient.GetHandler<SteamUser>();
SteamFriends = SteamClient.GetHandler<SteamFriends>();
SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>();
backgroundWorker = new BackgroundWorker { WorkerSupportsCancellation = true };
backgroundWorker.DoWork += BackgroundWorkerOnDoWork;
backgroundWorker.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
backgroundWorker.RunWorkerAsync();
}
/// <summary>
/// Occurs when the bot needs the SteamGuard authentication code.
/// </summary>
/// <remarks>
/// Return the code in <see cref="SteamGuardRequiredEventArgs.SteamGuard"/>
/// </remarks>
public event EventHandler<SteamGuardRequiredEventArgs> OnSteamGuardRequired;
/// <summary>
/// Starts the callback thread and connects to Steam via SteamKit2.
/// </summary>
/// <remarks>
/// THIS NEVER RETURNS.
/// </remarks>
/// <returns><c>true</c>. See remarks</returns>
public bool StartBot()
{
IsRunning = true;
log.Info("Connecting...");
if (!backgroundWorker.IsBusy)
// background worker is not running
backgroundWorker.RunWorkerAsync();
SteamClient.Connect();
log.Success("Done Loading Bot!");
return true; // never get here
}
/// <summary>
/// Disconnect from the Steam network and stop the callback
/// thread.
/// </summary>
public void StopBot()
{
IsRunning = false;
log.Debug("Trying to shut down bot thread.");
SteamClient.Disconnect();
backgroundWorker.CancelAsync();
}
/// <summary>
/// Creates a new trade with the given partner.
/// </summary>
/// <returns>
/// <c>true</c>, if trade was opened,
/// <c>false</c> if there is another trade that must be closed first.
/// </returns>
public bool OpenTrade (SteamID other)
{
if (CurrentTrade != null)
return false;
SteamTrade.Trade(other);
return true;
}
/// <summary>
/// Closes the current active trade.
/// </summary>
public void CloseTrade()
{
if (CurrentTrade == null)
return;
UnsubscribeTrade (GetUserHandler (CurrentTrade.OtherSID), CurrentTrade);
tradeManager.StopTrade ();
CurrentTrade = null;
}
void OnTradeTimeout(object sender, EventArgs args)
{
// ignore event params and just null out the trade.
GetUserHandler (CurrentTrade.OtherSID).OnTradeTimeout();
}
public void HandleBotCommand(string command)
{
try
{
GetUserHandler(SteamClient.SteamID).OnBotCommand(command);
}
catch (ObjectDisposedException e)
{
// Writing to console because odds are the error was caused by a disposed log.
Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e));
if (!this.IsRunning)
{
Console.WriteLine("The Bot is no longer running and could not write to the log. Try Starting this bot first.");
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e));
}
}
bool HandleTradeSessionStart (SteamID other)
{
if (CurrentTrade != null)
return false;
try
{
tradeManager.InitializeTrade(SteamUser.SteamID, other);
CurrentTrade = tradeManager.CreateTrade (SteamUser.SteamID, other);
CurrentTrade.OnClose += CloseTrade;
SubscribeTrade(CurrentTrade, GetUserHandler(other));
tradeManager.StartTradeThread(CurrentTrade);
return true;
}
catch (SteamTrade.Exceptions.InventoryFetchException ie)
{
// we shouldn't get here because the inv checks are also
// done in the TradeProposedCallback handler.
string response = String.Empty;
if (ie.FailingSteamId.ConvertToUInt64() == other.ConvertToUInt64())
{
response = "Trade failed. Could not correctly fetch your backpack. Either the inventory is inaccessible or your backpack is private.";
}
else
{
response = "Trade failed. Could not correctly fetch my backpack.";
}
SteamFriends.SendChatMessage(other,
EChatEntryType.ChatMsg,
response);
log.Info ("Bot sent other: " + response);
CurrentTrade = null;
return false;
}
}
public void SetGamePlaying(int id)
{
var gamePlaying = new SteamKit2.ClientMsgProtobuf<CMsgClientGamesPlayed>(EMsg.ClientGamesPlayed);
if (id != 0)
gamePlaying.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed
{
game_id = new GameID(id),
});
SteamClient.Send(gamePlaying);
CurrentGame = id;
}
void HandleSteamMessage (CallbackMsg msg)
{
log.Debug(msg.ToString());
#region Login
msg.Handle<SteamClient.ConnectedCallback> (callback =>
{
log.Debug ("Connection Callback: " + callback.Result);
if (callback.Result == EResult.OK)
{
UserLogOn();
}
else
{
log.Error ("Failed to connect to Steam Community, trying again...");
SteamClient.Connect ();
}
});
msg.Handle<SteamUser.LoggedOnCallback> (callback =>
{
log.Debug ("Logged On Callback: " + callback.Result);
if (callback.Result == EResult.OK)
{
MyLoginKey = callback.WebAPIUserNonce;
}
else
{
log.Error ("Login Error: " + callback.Result);
}
if (callback.Result == EResult.AccountLogonDenied)
{
log.Interface ("This account is SteamGuard enabled. Enter the code via the `auth' command.");
// try to get the steamguard auth code from the event callback
var eva = new SteamGuardRequiredEventArgs();
FireOnSteamGuardRequired(eva);
if (!String.IsNullOrEmpty(eva.SteamGuard))
logOnDetails.AuthCode = eva.SteamGuard;
else
logOnDetails.AuthCode = Console.ReadLine();
}
if (callback.Result == EResult.InvalidLoginAuthCode)
{
log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command.");
logOnDetails.AuthCode = Console.ReadLine();
}
});
msg.Handle<SteamUser.LoginKeyCallback> (callback =>
{
while (true)
{
bool authd = SteamWeb.Authenticate(callback, SteamClient, out sessionId, out token, MyLoginKey);
if (authd)
{
log.Success ("User Authenticated!");
tradeManager = new TradeManager(apiKey, sessionId, token);
tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximiumActionGap, TradePollingInterval);
tradeManager.OnTimeout += OnTradeTimeout;
break;
}
else
{
log.Warn ("Authentication failed, retrying in 2s...");
Thread.Sleep (2000);
}
}
if (Trade.CurrentSchema == null)
{
log.Info ("Downloading Schema...");
Trade.CurrentSchema = Schema.FetchSchema (apiKey);
log.Success ("Schema Downloaded!");
}
SteamFriends.SetPersonaName (DisplayNamePrefix+DisplayName);
SteamFriends.SetPersonaState (EPersonaState.Online);
log.Success ("Steam Bot Logged In Completely!");
IsLoggedIn = true;
GetUserHandler(SteamClient.SteamID).OnLoginCompleted();
});
// handle a special JobCallback differently than the others
if (msg.IsType<SteamClient.JobCallback<SteamUser.UpdateMachineAuthCallback>>())
{
msg.Handle<SteamClient.JobCallback<SteamUser.UpdateMachineAuthCallback>>(
jobCallback => OnUpdateMachineAuthCallback(jobCallback.Callback, jobCallback.JobID)
);
}
#endregion
#region Friends
msg.Handle<SteamFriends.FriendsListCallback>(callback =>
{
foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
{
if (friend.SteamID.AccountType == EAccountType.Clan)
{
if (!groups.Contains(friend.SteamID))
{
groups.Add(friend.SteamID);
if (friend.Relationship == EFriendRelationship.RequestRecipient)
{
if (GetUserHandler(friend.SteamID).OnGroupAdd())
{
AcceptGroupInvite(friend.SteamID);
}
else
{
DeclineGroupInvite(friend.SteamID);
}
}
}
else
{
if (friend.Relationship == EFriendRelationship.None)
{
groups.Remove(friend.SteamID);
}
}
}
else if (friend.SteamID.AccountType != EAccountType.Clan)
{
if (!friends.Contains(friend.SteamID))
{
friends.Add(friend.SteamID);
if (friend.Relationship == EFriendRelationship.RequestRecipient &&
GetUserHandler(friend.SteamID).OnFriendAdd())
{
SteamFriends.AddFriend(friend.SteamID);
}
}
else
{
if (friend.Relationship == EFriendRelationship.None)
{
friends.Remove(friend.SteamID);
GetUserHandler(friend.SteamID).OnFriendRemove();
}
}
}
}
});
msg.Handle<SteamFriends.FriendMsgCallback> (callback =>
{
EChatEntryType type = callback.EntryType;
if (callback.EntryType == EChatEntryType.ChatMsg)
{
log.Info (String.Format ("Chat Message from {0}: {1}",
SteamFriends.GetFriendPersonaName (callback.Sender),
callback.Message
));
GetUserHandler(callback.Sender).OnMessage(callback.Message, type);
}
});
#endregion
#region Group Chat
msg.Handle<SteamFriends.ChatMsgCallback>(callback =>
{
GetUserHandler(callback.ChatterID).OnChatRoomMessage(callback.ChatRoomID, callback.ChatterID, callback.Message);
});
#endregion
#region Trading
msg.Handle<SteamTrading.SessionStartCallback> (callback =>
{
bool started = HandleTradeSessionStart (callback.OtherClient);
if (!started)
log.Error ("Could not start the trade session.");
else
log.Debug ("SteamTrading.SessionStartCallback handled successfully. Trade Opened.");
});
msg.Handle<SteamTrading.TradeProposedCallback> (callback =>
{
try
{
tradeManager.InitializeTrade(SteamUser.SteamID, callback.OtherClient);
}
catch (WebException we)
{
SteamFriends.SendChatMessage(callback.OtherClient,
EChatEntryType.ChatMsg,
"Trade error: " + we.Message);
SteamTrade.RespondToTrade(callback.TradeID, false);
return;
}
catch (Exception)
{
SteamFriends.SendChatMessage(callback.OtherClient,
EChatEntryType.ChatMsg,
"Trade declined. Could not correctly fetch your backpack.");
SteamTrade.RespondToTrade(callback.TradeID, false);
return;
}
//if (tradeManager.OtherInventory.IsPrivate)
//{
// SteamFriends.SendChatMessage(callback.OtherClient,
// EChatEntryType.ChatMsg,
// "Trade declined. Your backpack cannot be private.");
// SteamTrade.RespondToTrade (callback.TradeID, false);
// return;
//}
if (CurrentTrade == null && GetUserHandler (callback.OtherClient).OnTradeRequest ())
SteamTrade.RespondToTrade (callback.TradeID, true);
else
SteamTrade.RespondToTrade (callback.TradeID, false);
});
msg.Handle<SteamTrading.TradeResultCallback> (callback =>
{
if (callback.Response == EEconTradeResponse.Accepted)
{
log.Debug ("Trade Status: " + callback.Response);
log.Info ("Trade Accepted!");
GetUserHandler(callback.OtherClient).OnTradeRequestReply(true, callback.Response.ToString());
}
else
{
log.Warn ("Trade failed: " + callback.Response);
CloseTrade ();
GetUserHandler(callback.OtherClient).OnTradeRequestReply(false, callback.Response.ToString());
}
});
#endregion
#region Disconnect
msg.Handle<SteamUser.LoggedOffCallback> (callback =>
{
IsLoggedIn = false;
log.Warn ("Logged Off: " + callback.Result);
});
msg.Handle<SteamClient.DisconnectedCallback> (callback =>
{
IsLoggedIn = false;
CloseTrade ();
log.Warn ("Disconnected from Steam Network!");
SteamClient.Connect ();
});
#endregion
}
void UserLogOn()
{
// get sentry file which has the machine hw info saved
// from when a steam guard code was entered
Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles"));
FileInfo fi = new FileInfo(System.IO.Path.Combine("sentryfiles",String.Format("{0}.sentryfile", logOnDetails.Username)));
if (fi.Exists && fi.Length > 0)
logOnDetails.SentryFileHash = SHAHash(File.ReadAllBytes(fi.FullName));
else
logOnDetails.SentryFileHash = null;
SteamUser.LogOn(logOnDetails);
}
UserHandler GetUserHandler (SteamID sid)
{
if (!userHandlers.ContainsKey (sid))
{
userHandlers [sid.ConvertToUInt64 ()] = CreateHandler (this, sid);
}
return userHandlers [sid.ConvertToUInt64 ()];
}
static byte [] SHAHash (byte[] input)
{
SHA1Managed sha = new SHA1Managed();
byte[] output = sha.ComputeHash( input );
sha.Clear();
return output;
}
void OnUpdateMachineAuthCallback (SteamUser.UpdateMachineAuthCallback machineAuth, JobID jobId)
{
byte[] hash = SHAHash (machineAuth.Data);
Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles"));
File.WriteAllBytes (System.IO.Path.Combine("sentryfiles", String.Format("{0}.sentryfile", logOnDetails.Username)), machineAuth.Data);
var authResponse = new SteamUser.MachineAuthDetails
{
BytesWritten = machineAuth.BytesToWrite,
FileName = machineAuth.FileName,
FileSize = machineAuth.BytesToWrite,
Offset = machineAuth.Offset,
SentryFileHash = hash, // should be the sha1 hash of the sentry file we just wrote
OneTimePassword = machineAuth.OneTimePassword, // not sure on this one yet, since we've had no examples of steam using OTPs
LastError = 0, // result from win32 GetLastError
Result = EResult.OK, // if everything went okay, otherwise ~who knows~
JobID = jobId, // so we respond to the correct server job
};
// send off our response
SteamUser.SendMachineAuthResponse (authResponse);
}
/// <summary>
/// Gets the bot's inventory and stores it in MyInventory.
/// </summary>
/// <example> This sample shows how to find items in the bot's inventory from a user handler.
/// <code>
/// Bot.GetInventory(); // Get the inventory first
/// foreach (var item in Bot.MyInventory.Items)
/// {
/// if (item.Defindex == 5021)
/// {
/// // Bot has a key in its inventory
/// }
/// }
/// </code>
/// </example>
public void GetInventory()
{
myInventoryTask = Task.Factory.StartNew(() => Inventory.FetchInventory(SteamUser.SteamID, apiKey));
}
/// <summary>
/// Subscribes all listeners of this to the trade.
/// </summary>
public void SubscribeTrade (Trade trade, UserHandler handler)
{
trade.OnSuccess += handler.OnTradeSuccess;
trade.OnClose += handler.OnTradeClose;
trade.OnError += handler.OnTradeError;
//trade.OnTimeout += OnTradeTimeout;
trade.OnAfterInit += handler.OnTradeInit;
trade.OnUserAddItem += handler.OnTradeAddItem;
trade.OnUserRemoveItem += handler.OnTradeRemoveItem;
trade.OnMessage += handler.OnTradeMessage;
trade.OnUserSetReady += handler.OnTradeReadyHandler;
trade.OnUserAccept += handler.OnTradeAcceptHandler;
}
/// <summary>
/// Unsubscribes all listeners of this from the current trade.
/// </summary>
public void UnsubscribeTrade (UserHandler handler, Trade trade)
{
trade.OnSuccess -= handler.OnTradeSuccess;
trade.OnClose -= handler.OnTradeClose;
trade.OnError -= handler.OnTradeError;
//Trade.OnTimeout -= OnTradeTimeout;
trade.OnAfterInit -= handler.OnTradeInit;
trade.OnUserAddItem -= handler.OnTradeAddItem;
trade.OnUserRemoveItem -= handler.OnTradeRemoveItem;
trade.OnMessage -= handler.OnTradeMessage;
trade.OnUserSetReady -= handler.OnTradeReadyHandler;
trade.OnUserAccept -= handler.OnTradeAcceptHandler;
}
#region Background Worker Methods
private void BackgroundWorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
{
if (runWorkerCompletedEventArgs.Error != null)
{
Exception ex = runWorkerCompletedEventArgs.Error;
var s = string.Format("Unhandled exceptions in bot {0} callback thread: {1} {2}",
DisplayName,
Environment.NewLine,
ex);
log.Error(s);
log.Info("This bot died. Stopping it..");
//backgroundWorker.RunWorkerAsync();
//Thread.Sleep(10000);
StopBot();
//StartBot();
}
log.Dispose();
}
private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
CallbackMsg msg;
while (!backgroundWorker.CancellationPending)
{
try
{
msg = SteamClient.WaitForCallback(true);
HandleSteamMessage(msg);
}
catch (WebException e)
{
log.Error("URI: " + (e.Response != null && e.Response.ResponseUri != null ? e.Response.ResponseUri.ToString() : "unknown") + " >> " + e.ToString());
System.Threading.Thread.Sleep(45000);//Steam is down, retry in 45 seconds.
}
catch (Exception e)
{
log.Error(e.ToString());
log.Warn("Restarting bot...");
}
}
}
#endregion Background Worker Methods
private void FireOnSteamGuardRequired(SteamGuardRequiredEventArgs e)
{
// Set to null in case this is another attempt
this.AuthCode = null;
EventHandler<SteamGuardRequiredEventArgs> handler = OnSteamGuardRequired;
if (handler != null)
handler(this, e);
else
{
while (true)
{
if (this.AuthCode != null)
{
e.SteamGuard = this.AuthCode;
break;
}
Thread.Sleep(5);
}
}
}
#region Group Methods
/// <summary>
/// Accepts the invite to a Steam Group
/// </summary>
/// <param name="group">SteamID of the group to accept the invite from.</param>
private void AcceptGroupInvite(SteamID group)
{
var AcceptInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite);
AcceptInvite.Body.GroupID = group.ConvertToUInt64();
AcceptInvite.Body.AcceptInvite = true;
this.SteamClient.Send(AcceptInvite);
}
/// <summary>
/// Declines the invite to a Steam Group
/// </summary>
/// <param name="group">SteamID of the group to decline the invite from.</param>
private void DeclineGroupInvite(SteamID group)
{
var DeclineInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite);
DeclineInvite.Body.GroupID = group.ConvertToUInt64();
DeclineInvite.Body.AcceptInvite = false;
this.SteamClient.Send(DeclineInvite);
}
/// <summary>
/// Invites a use to the specified Steam Group
/// </summary>
/// <param name="user">SteamID of the user to invite.</param>
/// <param name="groupId">SteamID of the group to invite the user to.</param>
public void InviteUserToGroup(SteamID user, SteamID groupId)
{
var InviteUser = new ClientMsg<CMsgInviteUserToGroup>((int)EMsg.ClientInviteUserToClan);
InviteUser.Body.GroupID = groupId.ConvertToUInt64();
InviteUser.Body.Invitee = user.ConvertToUInt64();
InviteUser.Body.UnknownInfo = true;
this.SteamClient.Send(InviteUser);
}
#endregion
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the 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.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using log4net;
namespace OpenSim.Region.ClientStack.LindenUDP
{
public class LLImageManager
{
private sealed class J2KImageComparer : IComparer<J2KImage>
{
public int Compare(J2KImage x, J2KImage y)
{
return x.Priority.CompareTo(y.Priority);
}
}
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_shuttingdown;
private AssetBase m_missingImage;
private LLClientView m_client; //Client we're assigned to
private IAssetCache m_assetCache; //Asset Cache
private IJ2KDecoder m_j2kDecodeModule; //Our J2K module
private C5.IntervalHeap<J2KImage> m_priorityQueue = new C5.IntervalHeap<J2KImage>(10, new J2KImageComparer());
private object m_syncRoot = new object();
public LLClientView Client { get { return m_client; } }
public AssetBase MissingImage { get { return m_missingImage; } }
public LLImageManager(LLClientView client, IAssetCache pAssetCache,
IJ2KDecoder pJ2kDecodeModule)
{
m_client = client;
m_assetCache = pAssetCache;
/*if (pAssetCache != null)
m_missingImage = pAssetCache.GetAsset(UUID.Parse("5748decc-f629-461c-9a36-a35a221fe21f"), AssetRequestInfo.InternalRequest());
if (m_missingImage == null)
m_log.Error("[ClientView] - Couldn't set missing image asset, falling back to missing image packet. This is known to crash the client");
*/
m_j2kDecodeModule = pJ2kDecodeModule;
}
/// <summary>
/// Handles an incoming texture request or update to an existing texture request
/// </summary>
/// <param name="newRequest"></param>
public void EnqueueReq(TextureRequestArgs newRequest)
{
//Make sure we're not shutting down..
if (!m_shuttingdown)
{
J2KImage imgrequest;
// Do a linear search for this texture download
lock (m_syncRoot)
m_priorityQueue.Find(delegate(J2KImage img) { return img.TextureID == newRequest.RequestedAssetID; }, out imgrequest);
if (imgrequest != null)
{
if (newRequest.DiscardLevel == -1 && newRequest.Priority == 0f)
{
//m_log.Debug("[TEX]: (CAN) ID=" + newRequest.RequestedAssetID);
try
{
lock (m_syncRoot)
m_priorityQueue.Delete(imgrequest.PriorityQueueHandle);
}
catch (Exception) { }
}
else
{
//m_log.DebugFormat("[TEX]: (UPD) ID={0}: D={1}, S={2}, P={3}",
// newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);
//Check the packet sequence to make sure this isn't older than
//one we've already received
if (newRequest.requestSequence > imgrequest.LastSequence)
{
//Update the sequence number of the last RequestImage packet
imgrequest.LastSequence = newRequest.requestSequence;
//Update the requested discard level
imgrequest.DiscardLevel = newRequest.DiscardLevel;
//Update the requested packet number
imgrequest.StartPacket = Math.Max(1, newRequest.PacketNumber);
//Update the requested priority
imgrequest.Priority = newRequest.Priority;
UpdateImageInQueue(imgrequest);
//Run an update
//imgrequest.RunUpdate();
}
}
}
else
{
if (newRequest.DiscardLevel == -1 && newRequest.Priority == 0f)
{
//m_log.DebugFormat("[TEX]: (IGN) ID={0}: D={1}, S={2}, P={3}",
// newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);
}
else
{
//m_log.DebugFormat("[TEX]: (NEW) ID={0}: D={1}, S={2}, P={3}",
// newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);
imgrequest = new J2KImage(this);
imgrequest.J2KDecoder = m_j2kDecodeModule;
imgrequest.AssetService = m_assetCache;
imgrequest.AgentID = m_client.AgentId;
imgrequest.DiscardLevel = newRequest.DiscardLevel;
imgrequest.StartPacket = Math.Max(1, newRequest.PacketNumber);
imgrequest.Priority = newRequest.Priority;
imgrequest.TextureID = newRequest.RequestedAssetID;
imgrequest.Priority = newRequest.Priority;
//Add this download to the priority queue
AddImageToQueue(imgrequest);
//Run an update
//imgrequest.RunUpdate();
}
}
}
}
public bool ProcessImageQueue(int packetsToSend)
{
int packetsSent = 0;
while (packetsSent < packetsToSend)
{
J2KImage image = GetHighestPriorityImage();
// If null was returned, the texture priority queue is currently empty
if (image == null)
return false;
image.CheckDoFirstUpdate();
if (image.IsDecoded)
{
int sent;
bool imageDone = image.SendPackets(m_client, packetsToSend - packetsSent, out sent);
packetsSent += sent;
// If the send is complete, destroy any knowledge of this transfer
if (imageDone)
RemoveImageFromQueue(image);
}
else
{
// TODO: This is a limitation of how LLImageManager is currently
// written. Undecoded textures should not be going into the priority
// queue, because a high priority undecoded texture will clog up the
// pipeline for a client
return true;
}
}
return m_priorityQueue.Count > 0;
}
/// <summary>
/// Faux destructor
/// </summary>
public void Close()
{
m_shuttingdown = true;
}
#region Priority Queue Helpers
J2KImage GetHighestPriorityImage()
{
J2KImage image = null;
lock (m_syncRoot)
{
if (m_priorityQueue.Count > 0)
{
try { image = m_priorityQueue.FindMax(); }
catch (Exception) { }
}
}
return image;
}
void AddImageToQueue(J2KImage image)
{
image.PriorityQueueHandle = null;
lock (m_syncRoot)
try { m_priorityQueue.Add(ref image.PriorityQueueHandle, image); }
catch (Exception) { }
}
void RemoveImageFromQueue(J2KImage image)
{
lock (m_syncRoot)
try { m_priorityQueue.Delete(image.PriorityQueueHandle); }
catch (Exception) { }
}
void UpdateImageInQueue(J2KImage image)
{
lock (m_syncRoot)
{
try { m_priorityQueue.Replace(image.PriorityQueueHandle, image); }
catch (Exception)
{
image.PriorityQueueHandle = null;
m_priorityQueue.Add(ref image.PriorityQueueHandle, image);
}
}
}
#endregion Priority Queue Helpers
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// This editor helper class makes it easy to create and show a context menu.
/// It ensures that it's possible to add multiple items with the same name.
/// </summary>
public static class NGUIContextMenu
{
[MenuItem("Help/NGUI Documentation (v.3.9.6)")]
static void ShowHelp0 (MenuCommand command) { NGUIHelp.Show(); }
[MenuItem("Help/NGUI Support Forum")]
static void ShowHelp01 (MenuCommand command) { Application.OpenURL("http://www.tasharen.com/forum/index.php?board=1.0"); }
[MenuItem("CONTEXT/UIWidget/Copy Widget")]
static void CopyStyle (MenuCommand command) { NGUISettings.CopyWidget(command.context as UIWidget); }
[MenuItem("CONTEXT/UIWidget/Paste Widget Values")]
static void PasteStyle (MenuCommand command) { NGUISettings.PasteWidget(command.context as UIWidget, true); }
[MenuItem("CONTEXT/UIWidget/Paste Widget Style")]
static void PasteStyle2 (MenuCommand command) { NGUISettings.PasteWidget(command.context as UIWidget, false); }
[MenuItem("CONTEXT/UIWidget/Help")]
static void ShowHelp1 (MenuCommand command) { NGUIHelp.Show(command.context); }
[MenuItem("CONTEXT/UIButton/Help")]
static void ShowHelp2 (MenuCommand command) { NGUIHelp.Show(typeof(UIButton)); }
[MenuItem("CONTEXT/UIToggle/Help")]
static void ShowHelp3 (MenuCommand command) { NGUIHelp.Show(typeof(UIToggle)); }
[MenuItem("CONTEXT/UIRoot/Help")]
static void ShowHelp4 (MenuCommand command) { NGUIHelp.Show(typeof(UIRoot)); }
[MenuItem("CONTEXT/UICamera/Help")]
static void ShowHelp5 (MenuCommand command) { NGUIHelp.Show(typeof(UICamera)); }
[MenuItem("CONTEXT/UIAnchor/Help")]
static void ShowHelp6 (MenuCommand command) { NGUIHelp.Show(typeof(UIAnchor)); }
[MenuItem("CONTEXT/UIStretch/Help")]
static void ShowHelp7 (MenuCommand command) { NGUIHelp.Show(typeof(UIStretch)); }
[MenuItem("CONTEXT/UISlider/Help")]
static void ShowHelp8 (MenuCommand command) { NGUIHelp.Show(typeof(UISlider)); }
[MenuItem("CONTEXT/UI2DSprite/Help")]
static void ShowHelp9 (MenuCommand command) { NGUIHelp.Show(typeof(UI2DSprite)); }
[MenuItem("CONTEXT/UIScrollBar/Help")]
static void ShowHelp10 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollBar)); }
[MenuItem("CONTEXT/UIProgressBar/Help")]
static void ShowHelp11 (MenuCommand command) { NGUIHelp.Show(typeof(UIProgressBar)); }
[MenuItem("CONTEXT/UIPopupList/Help")]
static void ShowHelp12 (MenuCommand command) { NGUIHelp.Show(typeof(UIPopupList)); }
[MenuItem("CONTEXT/UIInput/Help")]
static void ShowHelp13 (MenuCommand command) { NGUIHelp.Show(typeof(UIInput)); }
[MenuItem("CONTEXT/UIKeyBinding/Help")]
static void ShowHelp14 (MenuCommand command) { NGUIHelp.Show(typeof(UIKeyBinding)); }
[MenuItem("CONTEXT/UIGrid/Help")]
static void ShowHelp15 (MenuCommand command) { NGUIHelp.Show(typeof(UIGrid)); }
[MenuItem("CONTEXT/UITable/Help")]
static void ShowHelp16 (MenuCommand command) { NGUIHelp.Show(typeof(UITable)); }
[MenuItem("CONTEXT/UIPlayTween/Help")]
static void ShowHelp17 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayTween)); }
[MenuItem("CONTEXT/UIPlayAnimation/Help")]
static void ShowHelp18 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayAnimation)); }
[MenuItem("CONTEXT/UIPlaySound/Help")]
static void ShowHelp19 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlaySound)); }
[MenuItem("CONTEXT/UIScrollView/Help")]
static void ShowHelp20 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollView)); }
[MenuItem("CONTEXT/UIDragScrollView/Help")]
static void ShowHelp21 (MenuCommand command) { NGUIHelp.Show(typeof(UIDragScrollView)); }
[MenuItem("CONTEXT/UICenterOnChild/Help")]
static void ShowHelp22 (MenuCommand command) { NGUIHelp.Show(typeof(UICenterOnChild)); }
[MenuItem("CONTEXT/UICenterOnClick/Help")]
static void ShowHelp23 (MenuCommand command) { NGUIHelp.Show(typeof(UICenterOnClick)); }
[MenuItem("CONTEXT/UITweener/Help")]
[MenuItem("CONTEXT/UIPlayTween/Help")]
static void ShowHelp24 (MenuCommand command) { NGUIHelp.Show(typeof(UITweener)); }
[MenuItem("CONTEXT/ActiveAnimation/Help")]
[MenuItem("CONTEXT/UIPlayAnimation/Help")]
static void ShowHelp25 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayAnimation)); }
[MenuItem("CONTEXT/UIScrollView/Help")]
[MenuItem("CONTEXT/UIDragScrollView/Help")]
static void ShowHelp26 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollView)); }
[MenuItem("CONTEXT/UIPanel/Help")]
static void ShowHelp27 (MenuCommand command) { NGUIHelp.Show(typeof(UIPanel)); }
[MenuItem("CONTEXT/UILocalize/Help")]
static void ShowHelp28 (MenuCommand command) { NGUIHelp.Show(typeof(UILocalize)); }
[MenuItem("CONTEXT/Localization/Help")]
static void ShowHelp29 (MenuCommand command) { NGUIHelp.Show(typeof(Localization)); }
[MenuItem("CONTEXT/UIKeyNavigation/Help")]
static void ShowHelp30 (MenuCommand command) { NGUIHelp.Show(typeof(UIKeyNavigation)); }
[MenuItem("CONTEXT/PropertyBinding/Help")]
static void ShowHelp31 (MenuCommand command) { NGUIHelp.Show(typeof(PropertyBinding)); }
public delegate UIWidget AddFunc (GameObject go);
static List<string> mEntries = new List<string>();
static GenericMenu mMenu;
/// <summary>
/// Clear the context menu list.
/// </summary>
static public void Clear ()
{
mEntries.Clear();
mMenu = null;
}
/// <summary>
/// Add a new context menu entry.
/// </summary>
static public void AddItem (string item, bool isChecked, GenericMenu.MenuFunction2 callback, object param)
{
if (callback != null)
{
if (mMenu == null) mMenu = new GenericMenu();
int count = 0;
for (int i = 0; i < mEntries.Count; ++i)
{
string str = mEntries[i];
if (str == item) ++count;
}
mEntries.Add(item);
if (count > 0) item += " [" + count + "]";
mMenu.AddItem(new GUIContent(item), isChecked, callback, param);
}
else AddDisabledItem(item);
}
/// <summary>
/// Wrapper function called by the menu that in turn calls the correct callback.
/// </summary>
static public void AddChild (object obj)
{
AddFunc func = obj as AddFunc;
UIWidget widget = func(Selection.activeGameObject);
if (widget != null) Selection.activeGameObject = widget.gameObject;
}
/// <summary>
/// Add a new context menu entry.
/// </summary>
static public void AddChildWidget (string item, bool isChecked, AddFunc callback)
{
if (callback != null)
{
if (mMenu == null) mMenu = new GenericMenu();
int count = 0;
for (int i = 0; i < mEntries.Count; ++i)
{
string str = mEntries[i];
if (str == item) ++count;
}
mEntries.Add(item);
if (count > 0) item += " [" + count + "]";
mMenu.AddItem(new GUIContent(item), isChecked, AddChild, callback);
}
else AddDisabledItem(item);
}
/// <summary>
/// Wrapper function called by the menu that in turn calls the correct callback.
/// </summary>
static public void AddSibling (object obj)
{
AddFunc func = obj as AddFunc;
UIWidget widget = func(Selection.activeTransform.parent.gameObject);
if (widget != null) Selection.activeGameObject = widget.gameObject;
}
/// <summary>
/// Add a new context menu entry.
/// </summary>
static public void AddSiblingWidget (string item, bool isChecked, AddFunc callback)
{
if (callback != null)
{
if (mMenu == null) mMenu = new GenericMenu();
int count = 0;
for (int i = 0; i < mEntries.Count; ++i)
{
string str = mEntries[i];
if (str == item) ++count;
}
mEntries.Add(item);
if (count > 0) item += " [" + count + "]";
mMenu.AddItem(new GUIContent(item), isChecked, AddSibling, callback);
}
else AddDisabledItem(item);
}
/// <summary>
/// Add commonly NGUI context menu options.
/// </summary>
static public void AddCommonItems (GameObject target)
{
if (target != null)
{
UIWidget widget = target.GetComponent<UIWidget>();
string myName = string.Format("Selected {0}", (widget != null) ? NGUITools.GetTypeName(widget) : "Object");
AddItem(myName + "/Bring to Front", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.BringForward(Selection.gameObjects[i]);
},
null);
AddItem(myName + "/Push to Back", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.PushBack(Selection.gameObjects[i]);
},
null);
AddItem(myName + "/Nudge Forward", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.AdjustDepth(Selection.gameObjects[i], 1);
},
null);
AddItem(myName + "/Nudge Back", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.AdjustDepth(Selection.gameObjects[i], -1);
},
null);
if (widget != null)
{
NGUIContextMenu.AddSeparator(myName + "/");
AddItem(myName + "/Make Pixel-Perfect", false, OnMakePixelPerfect, Selection.activeTransform);
if (target.GetComponent<BoxCollider>() != null)
{
AddItem(myName + "/Reset Collider Size", false, OnBoxCollider, target);
}
}
NGUIContextMenu.AddSeparator(myName + "/");
AddItem(myName + "/Delete", false, OnDelete, target);
NGUIContextMenu.AddSeparator("");
if (Selection.activeTransform.parent != null && widget != null)
{
AddChildWidget("Create/Sprite/Child", false, NGUISettings.AddSprite);
AddChildWidget("Create/Label/Child", false, NGUISettings.AddLabel);
AddChildWidget("Create/Invisible Widget/Child", false, NGUISettings.AddWidget);
AddChildWidget("Create/Simple Texture/Child", false, NGUISettings.AddTexture);
AddChildWidget("Create/Unity 2D Sprite/Child", false, NGUISettings.Add2DSprite);
AddSiblingWidget("Create/Sprite/Sibling", false, NGUISettings.AddSprite);
AddSiblingWidget("Create/Label/Sibling", false, NGUISettings.AddLabel);
AddSiblingWidget("Create/Invisible Widget/Sibling", false, NGUISettings.AddWidget);
AddSiblingWidget("Create/Simple Texture/Sibling", false, NGUISettings.AddTexture);
AddSiblingWidget("Create/Unity 2D Sprite/Sibling", false, NGUISettings.Add2DSprite);
}
else
{
AddChildWidget("Create/Sprite", false, NGUISettings.AddSprite);
AddChildWidget("Create/Label", false, NGUISettings.AddLabel);
AddChildWidget("Create/Invisible Widget", false, NGUISettings.AddWidget);
AddChildWidget("Create/Simple Texture", false, NGUISettings.AddTexture);
AddChildWidget("Create/Unity 2D Sprite", false, NGUISettings.Add2DSprite);
}
NGUIContextMenu.AddSeparator("Create/");
AddItem("Create/Panel", false, AddPanel, target);
AddItem("Create/Scroll View", false, AddScrollView, target);
AddItem("Create/Grid", false, AddChild<UIGrid>, target);
AddItem("Create/Table", false, AddChild<UITable>, target);
AddItem("Create/Anchor (Legacy)", false, AddChild<UIAnchor>, target);
if (target.GetComponent<UIPanel>() != null)
{
if (target.GetComponent<UIScrollView>() == null)
{
AddItem("Attach/Scroll View", false, Attach, typeof(UIScrollView));
NGUIContextMenu.AddSeparator("Attach/");
}
}
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
else if (target.collider == null && target.GetComponent<Collider2D>() == null)
#else
else if (target.GetComponent<Collider>() == null && target.GetComponent<Collider2D>() == null)
#endif
{
AddItem("Attach/Box Collider", false, AttachCollider, null);
NGUIContextMenu.AddSeparator("Attach/");
}
bool header = false;
UIScrollView scrollView = NGUITools.FindInParents<UIScrollView>(target);
if (scrollView != null)
{
if (scrollView.GetComponentInChildren<UICenterOnChild>() == null)
{
AddItem("Attach/Center Scroll View on Child", false, Attach, typeof(UICenterOnChild));
header = true;
}
}
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
if (target.collider != null || target.GetComponent<Collider2D>() != null)
#else
if (target.GetComponent<Collider>() != null || target.GetComponent<Collider2D>() != null)
#endif
{
if (scrollView != null)
{
if (target.GetComponent<UIDragScrollView>() == null)
{
AddItem("Attach/Drag Scroll View", false, Attach, typeof(UIDragScrollView));
header = true;
}
if (target.GetComponent<UICenterOnClick>() == null && NGUITools.FindInParents<UICenterOnChild>(target) != null)
{
AddItem("Attach/Center Scroll View on Click", false, Attach, typeof(UICenterOnClick));
header = true;
}
}
if (header) NGUIContextMenu.AddSeparator("Attach/");
AddItem("Attach/Button Script", false, Attach, typeof(UIButton));
AddItem("Attach/Toggle Script", false, Attach, typeof(UIToggle));
AddItem("Attach/Slider Script", false, Attach, typeof(UISlider));
AddItem("Attach/Scroll Bar Script", false, Attach, typeof(UIScrollBar));
AddItem("Attach/Progress Bar Script", false, Attach, typeof(UISlider));
AddItem("Attach/Popup List Script", false, Attach, typeof(UIPopupList));
AddItem("Attach/Input Field Script", false, Attach, typeof(UIInput));
NGUIContextMenu.AddSeparator("Attach/");
if (target.GetComponent<UIDragResize>() == null)
AddItem("Attach/Drag Resize Script", false, Attach, typeof(UIDragResize));
if (target.GetComponent<UIDragScrollView>() == null)
{
for (int i = 0; i < UIPanel.list.Count; ++i)
{
UIPanel pan = UIPanel.list[i];
if (pan.clipping == UIDrawCall.Clipping.None) continue;
UIScrollView dr = pan.GetComponent<UIScrollView>();
if (dr == null) continue;
AddItem("Attach/Drag Scroll View", false, delegate(object obj)
{ target.AddComponent<UIDragScrollView>().scrollView = dr; }, null);
header = true;
break;
}
}
AddItem("Attach/Key Binding Script", false, Attach, typeof(UIKeyBinding));
if (target.GetComponent<UIKeyNavigation>() == null)
AddItem("Attach/Key Navigation Script", false, Attach, typeof(UIKeyNavigation));
NGUIContextMenu.AddSeparator("Attach/");
AddItem("Attach/Play Tween Script", false, Attach, typeof(UIPlayTween));
AddItem("Attach/Play Animation Script", false, Attach, typeof(UIPlayAnimation));
AddItem("Attach/Play Sound Script", false, Attach, typeof(UIPlaySound));
}
AddItem("Attach/Property Binding", false, Attach, typeof(PropertyBinding));
if (target.GetComponent<UILocalize>() == null)
AddItem("Attach/Localization Script", false, Attach, typeof(UILocalize));
if (widget != null)
{
AddMissingItem<TweenAlpha>(target, "Tween/Alpha");
AddMissingItem<TweenColor>(target, "Tween/Color");
AddMissingItem<TweenWidth>(target, "Tween/Width");
AddMissingItem<TweenHeight>(target, "Tween/Height");
}
else if (target.GetComponent<UIPanel>() != null)
{
AddMissingItem<TweenAlpha>(target, "Tween/Alpha");
}
NGUIContextMenu.AddSeparator("Tween/");
AddMissingItem<TweenPosition>(target, "Tween/Position");
AddMissingItem<TweenRotation>(target, "Tween/Rotation");
AddMissingItem<TweenScale>(target, "Tween/Scale");
AddMissingItem<TweenTransform>(target, "Tween/Transform");
if (target.GetComponent<AudioSource>() != null)
AddMissingItem<TweenVolume>(target, "Tween/Volume");
if (target.GetComponent<Camera>() != null)
{
AddMissingItem<TweenFOV>(target, "Tween/Field of View");
AddMissingItem<TweenOrthoSize>(target, "Tween/Orthographic Size");
}
}
}
/// <summary>
/// Helper function that adds a widget collider to the specified object.
/// </summary>
static void AttachCollider (object obj)
{
if (Selection.activeGameObject != null)
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.AddWidgetCollider(Selection.gameObjects[i]);
}
/// <summary>
/// Helper function that adds the specified type to all selected game objects. Used with the menu options above.
/// </summary>
static void Attach (object obj)
{
if (Selection.activeGameObject == null) return;
System.Type type = (System.Type)obj;
for (int i = 0; i < Selection.gameObjects.Length; ++i)
{
GameObject go = Selection.gameObjects[i];
if (go.GetComponent(type) != null) continue;
#if !UNITY_3_5
Component cmp = go.AddComponent(type);
Undo.RegisterCreatedObjectUndo(cmp, "Attach " + type);
#endif
}
}
/// <summary>
/// Helper function.
/// </summary>
static void AddMissingItem<T> (GameObject target, string name) where T : MonoBehaviour
{
if (target.GetComponent<T>() == null)
AddItem(name, false, Attach, typeof(T));
}
/// <summary>
/// Helper function for menu creation.
/// </summary>
static void AddChild<T> (object obj) where T : MonoBehaviour
{
GameObject go = obj as GameObject;
T t = NGUITools.AddChild<T>(go);
Selection.activeGameObject = t.gameObject;
}
/// <summary>
/// Helper function for menu creation.
/// </summary>
static void AddPanel (object obj)
{
GameObject go = obj as GameObject;
if (go.GetComponent<UIWidget>() != null) go = go.transform.parent.gameObject;
UIPanel panel = NGUISettings.AddPanel(go);
Selection.activeGameObject = panel.gameObject;
}
/// <summary>
/// Helper function for menu creation.
/// </summary>
static void AddScrollView (object obj)
{
GameObject go = obj as GameObject;
if (go.GetComponent<UIWidget>() != null) go = go.transform.parent.gameObject;
UIPanel panel = NGUISettings.AddPanel(go);
panel.clipping = UIDrawCall.Clipping.SoftClip;
panel.gameObject.AddComponent<UIScrollView>();
panel.name = "Scroll View";
Selection.activeGameObject = panel.gameObject;
}
/// <summary>
/// Add help options based on the components present on the specified game object.
/// </summary>
static public void AddHelp (GameObject go, bool addSeparator)
{
MonoBehaviour[] comps = Selection.activeGameObject.GetComponents<MonoBehaviour>();
bool addedSomething = false;
for (int i = 0; i < comps.Length; ++i)
{
System.Type type = comps[i].GetType();
string url = NGUIHelp.GetHelpURL(type);
if (url != null)
{
if (addSeparator)
{
addSeparator = false;
AddSeparator("");
}
AddItem("Help/" + type, false, delegate(object obj) { Application.OpenURL(url); }, null);
addedSomething = true;
}
}
if (addedSomething) AddSeparator("Help/");
AddItem("Help/All Topics", false, delegate(object obj) { NGUIHelp.Show(); }, null);
}
static void OnHelp (object obj) { NGUIHelp.Show(obj); }
static void OnMakePixelPerfect (object obj) { NGUITools.MakePixelPerfect(obj as Transform); }
static void OnBoxCollider (object obj) { NGUITools.AddWidgetCollider(obj as GameObject); }
static void OnDelete (object obj)
{
GameObject go = obj as GameObject;
Selection.activeGameObject = go.transform.parent.gameObject;
Undo.DestroyObjectImmediate(go);
}
/// <summary>
/// Add a new disabled context menu entry.
/// </summary>
static public void AddDisabledItem (string item)
{
if (mMenu == null) mMenu = new GenericMenu();
mMenu.AddDisabledItem(new GUIContent(item));
}
/// <summary>
/// Add a separator to the menu.
/// </summary>
static public void AddSeparator (string path)
{
if (mMenu == null) mMenu = new GenericMenu();
// For some weird reason adding separators on OSX causes the entire menu to be disabled. Wtf?
if (Application.platform != RuntimePlatform.OSXEditor)
mMenu.AddSeparator(path);
}
/// <summary>
/// Show the context menu with all the added items.
/// </summary>
static public void Show ()
{
if (mMenu != null)
{
mMenu.ShowAsContext();
mMenu = null;
mEntries.Clear();
}
}
}
| |
#region License
/*
* HttpBase.cs
*
* The MIT License
*
* Copyright (c) 2012-2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Threading;
using WebSocketSharp.Net;
namespace WebSocketSharp
{
internal abstract class HttpBase
{
#region Private Fields
private NameValueCollection _headers;
private const int _headersMaxLength = 8192;
private Version _version;
#endregion
#region Internal Fields
internal byte[] EntityBodyData;
#endregion
#region Protected Fields
protected const string CrLf = "\r\n";
#endregion
#region Protected Constructors
protected HttpBase (Version version, NameValueCollection headers)
{
_version = version;
_headers = headers;
}
#endregion
#region Public Properties
public string EntityBody {
get {
if (EntityBodyData == null || EntityBodyData.LongLength == 0)
return String.Empty;
Encoding enc = null;
var contentType = _headers["Content-Type"];
if (contentType != null && contentType.Length > 0)
enc = HttpUtility.GetEncoding (contentType);
return (enc ?? Encoding.UTF8).GetString (EntityBodyData);
}
}
public NameValueCollection Headers {
get {
return _headers;
}
}
public Version ProtocolVersion {
get {
return _version;
}
}
#endregion
#region Private Methods
private static byte[] readEntityBody (Stream stream, string length)
{
long len;
if (!Int64.TryParse (length, out len))
throw new ArgumentException ("Cannot be parsed.", "length");
if (len < 0)
throw new ArgumentOutOfRangeException ("length", "Less than zero.");
return len > 1024
? stream.ReadBytes (len, 1024)
: len > 0
? stream.ReadBytes ((int) len)
: null;
}
private static string[] readHeaders (Stream stream, int maxLength)
{
var buff = new List<byte> ();
var cnt = 0;
Action<int> add = i => {
if (i == -1)
throw new EndOfStreamException ("The header cannot be read from the data source.");
buff.Add ((byte) i);
cnt++;
};
var read = false;
while (cnt < maxLength) {
if (stream.ReadByte ().EqualsWith ('\r', add) &&
stream.ReadByte ().EqualsWith ('\n', add) &&
stream.ReadByte ().EqualsWith ('\r', add) &&
stream.ReadByte ().EqualsWith ('\n', add)) {
read = true;
break;
}
}
if (!read)
throw new WebSocketException ("The length of header part is greater than the max length.");
return Encoding.UTF8.GetString (buff.ToArray ())
.Replace (CrLf + " ", " ")
.Replace (CrLf + "\t", " ")
.Split (new[] { CrLf }, StringSplitOptions.RemoveEmptyEntries);
}
#endregion
#region Protected Methods
protected static T Read<T> (Stream stream, Func<string[], T> parser, int millisecondsTimeout)
where T : HttpBase
{
var timeout = false;
var timer = new Timer (
state => {
timeout = true;
stream.Close ();
},
null,
millisecondsTimeout,
-1);
T http = null;
Exception exception = null;
try {
http = parser (readHeaders (stream, _headersMaxLength));
var contentLen = http.Headers["Content-Length"];
if (contentLen != null && contentLen.Length > 0)
http.EntityBodyData = readEntityBody (stream, contentLen);
}
catch (Exception ex) {
exception = ex;
}
finally {
timer.Change (-1, -1);
timer.Dispose ();
}
var msg = timeout
? "A timeout has occurred while reading an HTTP request/response."
: exception != null
? "An exception has occurred while reading an HTTP request/response."
: null;
if (msg != null)
throw new WebSocketException (msg, exception);
return http;
}
#endregion
#region Public Methods
public byte[] ToByteArray ()
{
return Encoding.UTF8.GetBytes (ToString ());
}
#endregion
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
namespace SquabPie.Mono.Cecil.Cil {
public enum FlowControl {
Branch,
Break,
Call,
Cond_Branch,
Meta,
Next,
Phi,
Return,
Throw,
}
public enum OpCodeType {
Annotation,
Macro,
Nternal,
Objmodel,
Prefix,
Primitive,
}
public enum OperandType {
InlineBrTarget,
InlineField,
InlineI,
InlineI8,
InlineMethod,
InlineNone,
InlinePhi,
InlineR,
InlineSig,
InlineString,
InlineSwitch,
InlineTok,
InlineType,
InlineVar,
InlineArg,
ShortInlineBrTarget,
ShortInlineI,
ShortInlineR,
ShortInlineVar,
ShortInlineArg,
}
public enum StackBehaviour {
Pop0,
Pop1,
Pop1_pop1,
Popi,
Popi_pop1,
Popi_popi,
Popi_popi8,
Popi_popi_popi,
Popi_popr4,
Popi_popr8,
Popref,
Popref_pop1,
Popref_popi,
Popref_popi_popi,
Popref_popi_popi8,
Popref_popi_popr4,
Popref_popi_popr8,
Popref_popi_popref,
PopAll,
Push0,
Push1,
Push1_push1,
Pushi,
Pushi8,
Pushr4,
Pushr8,
Pushref,
Varpop,
Varpush,
}
public struct OpCode : IEquatable<OpCode> {
readonly byte op1;
readonly byte op2;
readonly byte code;
readonly byte flow_control;
readonly byte opcode_type;
readonly byte operand_type;
readonly byte stack_behavior_pop;
readonly byte stack_behavior_push;
public string Name {
get { return OpCodeNames.names [(int) Code]; }
}
public int Size {
get { return op1 == 0xff ? 1 : 2; }
}
public byte Op1 {
get { return op1; }
}
public byte Op2 {
get { return op2; }
}
public short Value {
get { return op1 == 0xff ? op2 : (short) ((op1 << 8) | op2); }
}
public Code Code {
get { return (Code) code; }
}
public FlowControl FlowControl {
get { return (FlowControl) flow_control; }
}
public OpCodeType OpCodeType {
get { return (OpCodeType) opcode_type; }
}
public OperandType OperandType {
get { return (OperandType) operand_type; }
}
public StackBehaviour StackBehaviourPop {
get { return (StackBehaviour) stack_behavior_pop; }
}
public StackBehaviour StackBehaviourPush {
get { return (StackBehaviour) stack_behavior_push; }
}
internal OpCode (int x, int y)
{
this.op1 = (byte) ((x >> 0) & 0xff);
this.op2 = (byte) ((x >> 8) & 0xff);
this.code = (byte) ((x >> 16) & 0xff);
this.flow_control = (byte) ((x >> 24) & 0xff);
this.opcode_type = (byte) ((y >> 0) & 0xff);
this.operand_type = (byte) ((y >> 8) & 0xff);
this.stack_behavior_pop = (byte) ((y >> 16) & 0xff);
this.stack_behavior_push = (byte) ((y >> 24) & 0xff);
if (op1 == 0xff)
OpCodes.OneByteOpCode [op2] = this;
else
OpCodes.TwoBytesOpCode [op2] = this;
}
public override int GetHashCode ()
{
return Value;
}
public override bool Equals (object obj)
{
if (!(obj is OpCode))
return false;
var opcode = (OpCode) obj;
return op1 == opcode.op1 && op2 == opcode.op2;
}
public bool Equals (OpCode opcode)
{
return op1 == opcode.op1 && op2 == opcode.op2;
}
public static bool operator == (OpCode one, OpCode other)
{
return one.op1 == other.op1 && one.op2 == other.op2;
}
public static bool operator != (OpCode one, OpCode other)
{
return one.op1 != other.op1 || one.op2 != other.op2;
}
public override string ToString ()
{
return Name;
}
}
static class OpCodeNames {
internal static readonly string [] names;
static OpCodeNames ()
{
var table = new byte [] {
3, 110, 111, 112,
5, 98, 114, 101, 97, 107,
7, 108, 100, 97, 114, 103, 46, 48,
7, 108, 100, 97, 114, 103, 46, 49,
7, 108, 100, 97, 114, 103, 46, 50,
7, 108, 100, 97, 114, 103, 46, 51,
7, 108, 100, 108, 111, 99, 46, 48,
7, 108, 100, 108, 111, 99, 46, 49,
7, 108, 100, 108, 111, 99, 46, 50,
7, 108, 100, 108, 111, 99, 46, 51,
7, 115, 116, 108, 111, 99, 46, 48,
7, 115, 116, 108, 111, 99, 46, 49,
7, 115, 116, 108, 111, 99, 46, 50,
7, 115, 116, 108, 111, 99, 46, 51,
7, 108, 100, 97, 114, 103, 46, 115,
8, 108, 100, 97, 114, 103, 97, 46, 115,
7, 115, 116, 97, 114, 103, 46, 115,
7, 108, 100, 108, 111, 99, 46, 115,
8, 108, 100, 108, 111, 99, 97, 46, 115,
7, 115, 116, 108, 111, 99, 46, 115,
6, 108, 100, 110, 117, 108, 108,
9, 108, 100, 99, 46, 105, 52, 46, 109, 49,
8, 108, 100, 99, 46, 105, 52, 46, 48,
8, 108, 100, 99, 46, 105, 52, 46, 49,
8, 108, 100, 99, 46, 105, 52, 46, 50,
8, 108, 100, 99, 46, 105, 52, 46, 51,
8, 108, 100, 99, 46, 105, 52, 46, 52,
8, 108, 100, 99, 46, 105, 52, 46, 53,
8, 108, 100, 99, 46, 105, 52, 46, 54,
8, 108, 100, 99, 46, 105, 52, 46, 55,
8, 108, 100, 99, 46, 105, 52, 46, 56,
8, 108, 100, 99, 46, 105, 52, 46, 115,
6, 108, 100, 99, 46, 105, 52,
6, 108, 100, 99, 46, 105, 56,
6, 108, 100, 99, 46, 114, 52,
6, 108, 100, 99, 46, 114, 56,
3, 100, 117, 112,
3, 112, 111, 112,
3, 106, 109, 112,
4, 99, 97, 108, 108,
5, 99, 97, 108, 108, 105,
3, 114, 101, 116,
4, 98, 114, 46, 115,
9, 98, 114, 102, 97, 108, 115, 101, 46, 115,
8, 98, 114, 116, 114, 117, 101, 46, 115,
5, 98, 101, 113, 46, 115,
5, 98, 103, 101, 46, 115,
5, 98, 103, 116, 46, 115,
5, 98, 108, 101, 46, 115,
5, 98, 108, 116, 46, 115,
8, 98, 110, 101, 46, 117, 110, 46, 115,
8, 98, 103, 101, 46, 117, 110, 46, 115,
8, 98, 103, 116, 46, 117, 110, 46, 115,
8, 98, 108, 101, 46, 117, 110, 46, 115,
8, 98, 108, 116, 46, 117, 110, 46, 115,
2, 98, 114,
7, 98, 114, 102, 97, 108, 115, 101,
6, 98, 114, 116, 114, 117, 101,
3, 98, 101, 113,
3, 98, 103, 101,
3, 98, 103, 116,
3, 98, 108, 101,
3, 98, 108, 116,
6, 98, 110, 101, 46, 117, 110,
6, 98, 103, 101, 46, 117, 110,
6, 98, 103, 116, 46, 117, 110,
6, 98, 108, 101, 46, 117, 110,
6, 98, 108, 116, 46, 117, 110,
6, 115, 119, 105, 116, 99, 104,
8, 108, 100, 105, 110, 100, 46, 105, 49,
8, 108, 100, 105, 110, 100, 46, 117, 49,
8, 108, 100, 105, 110, 100, 46, 105, 50,
8, 108, 100, 105, 110, 100, 46, 117, 50,
8, 108, 100, 105, 110, 100, 46, 105, 52,
8, 108, 100, 105, 110, 100, 46, 117, 52,
8, 108, 100, 105, 110, 100, 46, 105, 56,
7, 108, 100, 105, 110, 100, 46, 105,
8, 108, 100, 105, 110, 100, 46, 114, 52,
8, 108, 100, 105, 110, 100, 46, 114, 56,
9, 108, 100, 105, 110, 100, 46, 114, 101, 102,
9, 115, 116, 105, 110, 100, 46, 114, 101, 102,
8, 115, 116, 105, 110, 100, 46, 105, 49,
8, 115, 116, 105, 110, 100, 46, 105, 50,
8, 115, 116, 105, 110, 100, 46, 105, 52,
8, 115, 116, 105, 110, 100, 46, 105, 56,
8, 115, 116, 105, 110, 100, 46, 114, 52,
8, 115, 116, 105, 110, 100, 46, 114, 56,
3, 97, 100, 100,
3, 115, 117, 98,
3, 109, 117, 108,
3, 100, 105, 118,
6, 100, 105, 118, 46, 117, 110,
3, 114, 101, 109,
6, 114, 101, 109, 46, 117, 110,
3, 97, 110, 100,
2, 111, 114,
3, 120, 111, 114,
3, 115, 104, 108,
3, 115, 104, 114,
6, 115, 104, 114, 46, 117, 110,
3, 110, 101, 103,
3, 110, 111, 116,
7, 99, 111, 110, 118, 46, 105, 49,
7, 99, 111, 110, 118, 46, 105, 50,
7, 99, 111, 110, 118, 46, 105, 52,
7, 99, 111, 110, 118, 46, 105, 56,
7, 99, 111, 110, 118, 46, 114, 52,
7, 99, 111, 110, 118, 46, 114, 56,
7, 99, 111, 110, 118, 46, 117, 52,
7, 99, 111, 110, 118, 46, 117, 56,
8, 99, 97, 108, 108, 118, 105, 114, 116,
5, 99, 112, 111, 98, 106,
5, 108, 100, 111, 98, 106,
5, 108, 100, 115, 116, 114,
6, 110, 101, 119, 111, 98, 106,
9, 99, 97, 115, 116, 99, 108, 97, 115, 115,
6, 105, 115, 105, 110, 115, 116,
9, 99, 111, 110, 118, 46, 114, 46, 117, 110,
5, 117, 110, 98, 111, 120,
5, 116, 104, 114, 111, 119,
5, 108, 100, 102, 108, 100,
6, 108, 100, 102, 108, 100, 97,
5, 115, 116, 102, 108, 100,
6, 108, 100, 115, 102, 108, 100,
7, 108, 100, 115, 102, 108, 100, 97,
6, 115, 116, 115, 102, 108, 100,
5, 115, 116, 111, 98, 106,
14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 49, 46, 117, 110,
14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 50, 46, 117, 110,
14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 52, 46, 117, 110,
14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 56, 46, 117, 110,
14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 49, 46, 117, 110,
14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 50, 46, 117, 110,
14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 52, 46, 117, 110,
14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 56, 46, 117, 110,
13, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 46, 117, 110,
13, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 46, 117, 110,
3, 98, 111, 120,
6, 110, 101, 119, 97, 114, 114,
5, 108, 100, 108, 101, 110,
7, 108, 100, 101, 108, 101, 109, 97,
9, 108, 100, 101, 108, 101, 109, 46, 105, 49,
9, 108, 100, 101, 108, 101, 109, 46, 117, 49,
9, 108, 100, 101, 108, 101, 109, 46, 105, 50,
9, 108, 100, 101, 108, 101, 109, 46, 117, 50,
9, 108, 100, 101, 108, 101, 109, 46, 105, 52,
9, 108, 100, 101, 108, 101, 109, 46, 117, 52,
9, 108, 100, 101, 108, 101, 109, 46, 105, 56,
8, 108, 100, 101, 108, 101, 109, 46, 105,
9, 108, 100, 101, 108, 101, 109, 46, 114, 52,
9, 108, 100, 101, 108, 101, 109, 46, 114, 56,
10, 108, 100, 101, 108, 101, 109, 46, 114, 101, 102,
8, 115, 116, 101, 108, 101, 109, 46, 105,
9, 115, 116, 101, 108, 101, 109, 46, 105, 49,
9, 115, 116, 101, 108, 101, 109, 46, 105, 50,
9, 115, 116, 101, 108, 101, 109, 46, 105, 52,
9, 115, 116, 101, 108, 101, 109, 46, 105, 56,
9, 115, 116, 101, 108, 101, 109, 46, 114, 52,
9, 115, 116, 101, 108, 101, 109, 46, 114, 56,
10, 115, 116, 101, 108, 101, 109, 46, 114, 101, 102,
10, 108, 100, 101, 108, 101, 109, 46, 97, 110, 121,
10, 115, 116, 101, 108, 101, 109, 46, 97, 110, 121,
9, 117, 110, 98, 111, 120, 46, 97, 110, 121,
11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 49,
11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 49,
11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 50,
11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 50,
11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 52,
11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 52,
11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 56,
11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 56,
9, 114, 101, 102, 97, 110, 121, 118, 97, 108,
8, 99, 107, 102, 105, 110, 105, 116, 101,
8, 109, 107, 114, 101, 102, 97, 110, 121,
7, 108, 100, 116, 111, 107, 101, 110,
7, 99, 111, 110, 118, 46, 117, 50,
7, 99, 111, 110, 118, 46, 117, 49,
6, 99, 111, 110, 118, 46, 105,
10, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105,
10, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117,
7, 97, 100, 100, 46, 111, 118, 102,
10, 97, 100, 100, 46, 111, 118, 102, 46, 117, 110,
7, 109, 117, 108, 46, 111, 118, 102,
10, 109, 117, 108, 46, 111, 118, 102, 46, 117, 110,
7, 115, 117, 98, 46, 111, 118, 102,
10, 115, 117, 98, 46, 111, 118, 102, 46, 117, 110,
10, 101, 110, 100, 102, 105, 110, 97, 108, 108, 121,
5, 108, 101, 97, 118, 101,
7, 108, 101, 97, 118, 101, 46, 115,
7, 115, 116, 105, 110, 100, 46, 105,
6, 99, 111, 110, 118, 46, 117,
7, 97, 114, 103, 108, 105, 115, 116,
3, 99, 101, 113,
3, 99, 103, 116,
6, 99, 103, 116, 46, 117, 110,
3, 99, 108, 116,
6, 99, 108, 116, 46, 117, 110,
5, 108, 100, 102, 116, 110,
9, 108, 100, 118, 105, 114, 116, 102, 116, 110,
5, 108, 100, 97, 114, 103,
6, 108, 100, 97, 114, 103, 97,
5, 115, 116, 97, 114, 103,
5, 108, 100, 108, 111, 99,
6, 108, 100, 108, 111, 99, 97,
5, 115, 116, 108, 111, 99,
8, 108, 111, 99, 97, 108, 108, 111, 99,
9, 101, 110, 100, 102, 105, 108, 116, 101, 114,
10, 117, 110, 97, 108, 105, 103, 110, 101, 100, 46,
9, 118, 111, 108, 97, 116, 105, 108, 101, 46,
5, 116, 97, 105, 108, 46,
7, 105, 110, 105, 116, 111, 98, 106,
12, 99, 111, 110, 115, 116, 114, 97, 105, 110, 101, 100, 46,
5, 99, 112, 98, 108, 107,
7, 105, 110, 105, 116, 98, 108, 107,
3, 110, 111, 46,
7, 114, 101, 116, 104, 114, 111, 119,
6, 115, 105, 122, 101, 111, 102,
10, 114, 101, 102, 97, 110, 121, 116, 121, 112, 101,
9, 114, 101, 97, 100, 111, 110, 108, 121, 46,
};
names = new string [219];
for (int i = 0, p = 0; i < names.Length; i++) {
var buffer = new char [table [p++]];
for (int j = 0; j < buffer.Length; j++)
buffer [j] = (char) table [p++];
names [i] = new string (buffer);
}
}
}
}
| |
// Visual Studio Shared Project
// 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.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.Win32.SafeHandles;
namespace Microsoft.VisualStudioTools.Project {
internal static class NativeMethods {
// IIDS
public static readonly Guid IID_IUnknown = new Guid("{00000000-0000-0000-C000-000000000046}");
public const int ERROR_FILE_NOT_FOUND = 2;
public const int
CLSCTX_INPROC_SERVER = 0x1;
public const int
S_FALSE = 0x00000001,
S_OK = 0x00000000,
IDOK = 1,
IDCANCEL = 2,
IDABORT = 3,
IDRETRY = 4,
IDIGNORE = 5,
IDYES = 6,
IDNO = 7,
IDCLOSE = 8,
IDHELP = 9,
IDTRYAGAIN = 10,
IDCONTINUE = 11,
OLECMDERR_E_NOTSUPPORTED = unchecked((int)0x80040100),
OLECMDERR_E_UNKNOWNGROUP = unchecked((int)0x80040104),
UNDO_E_CLIENTABORT = unchecked((int)0x80044001),
E_OUTOFMEMORY = unchecked((int)0x8007000E),
E_INVALIDARG = unchecked((int)0x80070057),
E_FAIL = unchecked((int)0x80004005),
E_NOINTERFACE = unchecked((int)0x80004002),
E_POINTER = unchecked((int)0x80004003),
E_NOTIMPL = unchecked((int)0x80004001),
E_UNEXPECTED = unchecked((int)0x8000FFFF),
E_HANDLE = unchecked((int)0x80070006),
E_ABORT = unchecked((int)0x80004004),
E_ACCESSDENIED = unchecked((int)0x80070005),
E_PENDING = unchecked((int)0x8000000A);
public const int
OLECLOSE_SAVEIFDIRTY = 0,
OLECLOSE_NOSAVE = 1,
OLECLOSE_PROMPTSAVE = 2;
public const int
OLEIVERB_PRIMARY = 0,
OLEIVERB_SHOW = -1,
OLEIVERB_OPEN = -2,
OLEIVERB_HIDE = -3,
OLEIVERB_UIACTIVATE = -4,
OLEIVERB_INPLACEACTIVATE = -5,
OLEIVERB_DISCARDUNDOSTATE = -6,
OLEIVERB_PROPERTIES = -7;
public const int
OFN_READONLY = unchecked((int)0x00000001),
OFN_OVERWRITEPROMPT = unchecked((int)0x00000002),
OFN_HIDEREADONLY = unchecked((int)0x00000004),
OFN_NOCHANGEDIR = unchecked((int)0x00000008),
OFN_SHOWHELP = unchecked((int)0x00000010),
OFN_ENABLEHOOK = unchecked((int)0x00000020),
OFN_ENABLETEMPLATE = unchecked((int)0x00000040),
OFN_ENABLETEMPLATEHANDLE = unchecked((int)0x00000080),
OFN_NOVALIDATE = unchecked((int)0x00000100),
OFN_ALLOWMULTISELECT = unchecked((int)0x00000200),
OFN_EXTENSIONDIFFERENT = unchecked((int)0x00000400),
OFN_PATHMUSTEXIST = unchecked((int)0x00000800),
OFN_FILEMUSTEXIST = unchecked((int)0x00001000),
OFN_CREATEPROMPT = unchecked((int)0x00002000),
OFN_SHAREAWARE = unchecked((int)0x00004000),
OFN_NOREADONLYRETURN = unchecked((int)0x00008000),
OFN_NOTESTFILECREATE = unchecked((int)0x00010000),
OFN_NONETWORKBUTTON = unchecked((int)0x00020000),
OFN_NOLONGNAMES = unchecked((int)0x00040000),
OFN_EXPLORER = unchecked((int)0x00080000),
OFN_NODEREFERENCELINKS = unchecked((int)0x00100000),
OFN_LONGNAMES = unchecked((int)0x00200000),
OFN_ENABLEINCLUDENOTIFY = unchecked((int)0x00400000),
OFN_ENABLESIZING = unchecked((int)0x00800000),
OFN_USESHELLITEM = unchecked((int)0x01000000),
OFN_DONTADDTORECENT = unchecked((int)0x02000000),
OFN_FORCESHOWHIDDEN = unchecked((int)0x10000000);
// for READONLYSTATUS
public const int
ROSTATUS_NotReadOnly = 0x0,
ROSTATUS_ReadOnly = 0x1,
ROSTATUS_Unknown = unchecked((int)0xFFFFFFFF);
public const int
IEI_DoNotLoadDocData = 0x10000000;
public const int
CB_SETDROPPEDWIDTH = 0x0160,
GWL_STYLE = (-16),
GWL_EXSTYLE = (-20),
DWL_MSGRESULT = 0,
SW_SHOWNORMAL = 1,
HTMENU = 5,
WS_POPUP = unchecked((int)0x80000000),
WS_CHILD = 0x40000000,
WS_MINIMIZE = 0x20000000,
WS_VISIBLE = 0x10000000,
WS_DISABLED = 0x08000000,
WS_CLIPSIBLINGS = 0x04000000,
WS_CLIPCHILDREN = 0x02000000,
WS_MAXIMIZE = 0x01000000,
WS_CAPTION = 0x00C00000,
WS_BORDER = 0x00800000,
WS_DLGFRAME = 0x00400000,
WS_VSCROLL = 0x00200000,
WS_HSCROLL = 0x00100000,
WS_SYSMENU = 0x00080000,
WS_THICKFRAME = 0x00040000,
WS_TABSTOP = 0x00010000,
WS_MINIMIZEBOX = 0x00020000,
WS_MAXIMIZEBOX = 0x00010000,
WS_EX_DLGMODALFRAME = 0x00000001,
WS_EX_MDICHILD = 0x00000040,
WS_EX_TOOLWINDOW = 0x00000080,
WS_EX_CLIENTEDGE = 0x00000200,
WS_EX_CONTEXTHELP = 0x00000400,
WS_EX_RIGHT = 0x00001000,
WS_EX_LEFT = 0x00000000,
WS_EX_RTLREADING = 0x00002000,
WS_EX_LEFTSCROLLBAR = 0x00004000,
WS_EX_CONTROLPARENT = 0x00010000,
WS_EX_STATICEDGE = 0x00020000,
WS_EX_APPWINDOW = 0x00040000,
WS_EX_LAYERED = 0x00080000,
WS_EX_TOPMOST = 0x00000008,
WS_EX_NOPARENTNOTIFY = 0x00000004,
LVM_SETEXTENDEDLISTVIEWSTYLE = (0x1000 + 54),
LVS_EX_LABELTIP = 0x00004000,
// winuser.h
WH_JOURNALPLAYBACK = 1,
WH_GETMESSAGE = 3,
WH_MOUSE = 7,
WSF_VISIBLE = 0x0001,
WM_NULL = 0x0000,
WM_CREATE = 0x0001,
WM_DELETEITEM = 0x002D,
WM_DESTROY = 0x0002,
WM_MOVE = 0x0003,
WM_SIZE = 0x0005,
WM_ACTIVATE = 0x0006,
WA_INACTIVE = 0,
WA_ACTIVE = 1,
WA_CLICKACTIVE = 2,
WM_SETFOCUS = 0x0007,
WM_KILLFOCUS = 0x0008,
WM_ENABLE = 0x000A,
WM_SETREDRAW = 0x000B,
WM_SETTEXT = 0x000C,
WM_GETTEXT = 0x000D,
WM_GETTEXTLENGTH = 0x000E,
WM_PAINT = 0x000F,
WM_CLOSE = 0x0010,
WM_QUERYENDSESSION = 0x0011,
WM_QUIT = 0x0012,
WM_QUERYOPEN = 0x0013,
WM_ERASEBKGND = 0x0014,
WM_SYSCOLORCHANGE = 0x0015,
WM_ENDSESSION = 0x0016,
WM_SHOWWINDOW = 0x0018,
WM_WININICHANGE = 0x001A,
WM_SETTINGCHANGE = 0x001A,
WM_DEVMODECHANGE = 0x001B,
WM_ACTIVATEAPP = 0x001C,
WM_FONTCHANGE = 0x001D,
WM_TIMECHANGE = 0x001E,
WM_CANCELMODE = 0x001F,
WM_SETCURSOR = 0x0020,
WM_MOUSEACTIVATE = 0x0021,
WM_CHILDACTIVATE = 0x0022,
WM_QUEUESYNC = 0x0023,
WM_GETMINMAXINFO = 0x0024,
WM_PAINTICON = 0x0026,
WM_ICONERASEBKGND = 0x0027,
WM_NEXTDLGCTL = 0x0028,
WM_SPOOLERSTATUS = 0x002A,
WM_DRAWITEM = 0x002B,
WM_MEASUREITEM = 0x002C,
WM_VKEYTOITEM = 0x002E,
WM_CHARTOITEM = 0x002F,
WM_SETFONT = 0x0030,
WM_GETFONT = 0x0031,
WM_SETHOTKEY = 0x0032,
WM_GETHOTKEY = 0x0033,
WM_QUERYDRAGICON = 0x0037,
WM_COMPAREITEM = 0x0039,
WM_GETOBJECT = 0x003D,
WM_COMPACTING = 0x0041,
WM_COMMNOTIFY = 0x0044,
WM_WINDOWPOSCHANGING = 0x0046,
WM_WINDOWPOSCHANGED = 0x0047,
WM_POWER = 0x0048,
WM_COPYDATA = 0x004A,
WM_CANCELJOURNAL = 0x004B,
WM_NOTIFY = 0x004E,
WM_INPUTLANGCHANGEREQUEST = 0x0050,
WM_INPUTLANGCHANGE = 0x0051,
WM_TCARD = 0x0052,
WM_HELP = 0x0053,
WM_USERCHANGED = 0x0054,
WM_NOTIFYFORMAT = 0x0055,
WM_CONTEXTMENU = 0x007B,
WM_STYLECHANGING = 0x007C,
WM_STYLECHANGED = 0x007D,
WM_DISPLAYCHANGE = 0x007E,
WM_GETICON = 0x007F,
WM_SETICON = 0x0080,
WM_NCCREATE = 0x0081,
WM_NCDESTROY = 0x0082,
WM_NCCALCSIZE = 0x0083,
WM_NCHITTEST = 0x0084,
WM_NCPAINT = 0x0085,
WM_NCACTIVATE = 0x0086,
WM_GETDLGCODE = 0x0087,
WM_NCMOUSEMOVE = 0x00A0,
WM_NCLBUTTONDOWN = 0x00A1,
WM_NCLBUTTONUP = 0x00A2,
WM_NCLBUTTONDBLCLK = 0x00A3,
WM_NCRBUTTONDOWN = 0x00A4,
WM_NCRBUTTONUP = 0x00A5,
WM_NCRBUTTONDBLCLK = 0x00A6,
WM_NCMBUTTONDOWN = 0x00A7,
WM_NCMBUTTONUP = 0x00A8,
WM_NCMBUTTONDBLCLK = 0x00A9,
WM_NCXBUTTONDOWN = 0x00AB,
WM_NCXBUTTONUP = 0x00AC,
WM_NCXBUTTONDBLCLK = 0x00AD,
WM_KEYFIRST = 0x0100,
WM_KEYDOWN = 0x0100,
WM_KEYUP = 0x0101,
WM_CHAR = 0x0102,
WM_DEADCHAR = 0x0103,
WM_CTLCOLOR = 0x0019,
WM_SYSKEYDOWN = 0x0104,
WM_SYSKEYUP = 0x0105,
WM_SYSCHAR = 0x0106,
WM_SYSDEADCHAR = 0x0107,
WM_KEYLAST = 0x0108,
WM_IME_STARTCOMPOSITION = 0x010D,
WM_IME_ENDCOMPOSITION = 0x010E,
WM_IME_COMPOSITION = 0x010F,
WM_IME_KEYLAST = 0x010F,
WM_INITDIALOG = 0x0110,
WM_COMMAND = 0x0111,
WM_SYSCOMMAND = 0x0112,
WM_TIMER = 0x0113,
WM_HSCROLL = 0x0114,
WM_VSCROLL = 0x0115,
WM_INITMENU = 0x0116,
WM_INITMENUPOPUP = 0x0117,
WM_MENUSELECT = 0x011F,
WM_MENUCHAR = 0x0120,
WM_ENTERIDLE = 0x0121,
WM_CHANGEUISTATE = 0x0127,
WM_UPDATEUISTATE = 0x0128,
WM_QUERYUISTATE = 0x0129,
WM_CTLCOLORMSGBOX = 0x0132,
WM_CTLCOLOREDIT = 0x0133,
WM_CTLCOLORLISTBOX = 0x0134,
WM_CTLCOLORBTN = 0x0135,
WM_CTLCOLORDLG = 0x0136,
WM_CTLCOLORSCROLLBAR = 0x0137,
WM_CTLCOLORSTATIC = 0x0138,
WM_MOUSEFIRST = 0x0200,
WM_MOUSEMOVE = 0x0200,
WM_LBUTTONDOWN = 0x0201,
WM_LBUTTONUP = 0x0202,
WM_LBUTTONDBLCLK = 0x0203,
WM_RBUTTONDOWN = 0x0204,
WM_RBUTTONUP = 0x0205,
WM_RBUTTONDBLCLK = 0x0206,
WM_MBUTTONDOWN = 0x0207,
WM_MBUTTONUP = 0x0208,
WM_MBUTTONDBLCLK = 0x0209,
WM_XBUTTONDOWN = 0x020B,
WM_XBUTTONUP = 0x020C,
WM_XBUTTONDBLCLK = 0x020D,
WM_MOUSEWHEEL = 0x020A,
WM_MOUSELAST = 0x020A,
WM_PARENTNOTIFY = 0x0210,
WM_ENTERMENULOOP = 0x0211,
WM_EXITMENULOOP = 0x0212,
WM_NEXTMENU = 0x0213,
WM_SIZING = 0x0214,
WM_CAPTURECHANGED = 0x0215,
WM_MOVING = 0x0216,
WM_POWERBROADCAST = 0x0218,
WM_DEVICECHANGE = 0x0219,
WM_IME_SETCONTEXT = 0x0281,
WM_IME_NOTIFY = 0x0282,
WM_IME_CONTROL = 0x0283,
WM_IME_COMPOSITIONFULL = 0x0284,
WM_IME_SELECT = 0x0285,
WM_IME_CHAR = 0x0286,
WM_IME_KEYDOWN = 0x0290,
WM_IME_KEYUP = 0x0291,
WM_MDICREATE = 0x0220,
WM_MDIDESTROY = 0x0221,
WM_MDIACTIVATE = 0x0222,
WM_MDIRESTORE = 0x0223,
WM_MDINEXT = 0x0224,
WM_MDIMAXIMIZE = 0x0225,
WM_MDITILE = 0x0226,
WM_MDICASCADE = 0x0227,
WM_MDIICONARRANGE = 0x0228,
WM_MDIGETACTIVE = 0x0229,
WM_MDISETMENU = 0x0230,
WM_ENTERSIZEMOVE = 0x0231,
WM_EXITSIZEMOVE = 0x0232,
WM_DROPFILES = 0x0233,
WM_MDIREFRESHMENU = 0x0234,
WM_MOUSEHOVER = 0x02A1,
WM_MOUSELEAVE = 0x02A3,
WM_CUT = 0x0300,
WM_COPY = 0x0301,
WM_PASTE = 0x0302,
WM_CLEAR = 0x0303,
WM_UNDO = 0x0304,
WM_RENDERFORMAT = 0x0305,
WM_RENDERALLFORMATS = 0x0306,
WM_DESTROYCLIPBOARD = 0x0307,
WM_DRAWCLIPBOARD = 0x0308,
WM_PAINTCLIPBOARD = 0x0309,
WM_VSCROLLCLIPBOARD = 0x030A,
WM_SIZECLIPBOARD = 0x030B,
WM_ASKCBFORMATNAME = 0x030C,
WM_CHANGECBCHAIN = 0x030D,
WM_HSCROLLCLIPBOARD = 0x030E,
WM_QUERYNEWPALETTE = 0x030F,
WM_PALETTEISCHANGING = 0x0310,
WM_PALETTECHANGED = 0x0311,
WM_HOTKEY = 0x0312,
WM_PRINT = 0x0317,
WM_PRINTCLIENT = 0x0318,
WM_HANDHELDFIRST = 0x0358,
WM_HANDHELDLAST = 0x035F,
WM_AFXFIRST = 0x0360,
WM_AFXLAST = 0x037F,
WM_PENWINFIRST = 0x0380,
WM_PENWINLAST = 0x038F,
WM_APP = unchecked((int)0x8000),
WM_USER = 0x0400,
WM_REFLECT =
WM_USER + 0x1C00,
WS_OVERLAPPED = 0x00000000,
WPF_SETMINPOSITION = 0x0001,
WM_CHOOSEFONT_GETLOGFONT = (0x0400 + 1),
WHEEL_DELTA = 120,
DWLP_MSGRESULT = 0,
PSNRET_NOERROR = 0,
PSNRET_INVALID = 1,
PSNRET_INVALID_NOCHANGEPAGE = 2,
EM_SETCUEBANNER = 0x1501;
public const int
PSN_APPLY = ((0 - 200) - 2),
PSN_KILLACTIVE = ((0 - 200) - 1),
PSN_RESET = ((0 - 200) - 3),
PSN_SETACTIVE = ((0 - 200) - 0);
public const int
GMEM_MOVEABLE = 0x0002,
GMEM_ZEROINIT = 0x0040,
GMEM_DDESHARE = 0x2000;
public const int
SWP_NOACTIVATE = 0x0010,
SWP_NOZORDER = 0x0004,
SWP_NOSIZE = 0x0001,
SWP_NOMOVE = 0x0002,
SWP_FRAMECHANGED = 0x0020;
public const int
TVM_SETINSERTMARK = (0x1100 + 26),
TVM_GETEDITCONTROL = (0x1100 + 15);
public const int
FILE_ATTRIBUTE_READONLY = 0x00000001,
FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
public const int
PSP_DEFAULT = 0x00000000,
PSP_DLGINDIRECT = 0x00000001,
PSP_USEHICON = 0x00000002,
PSP_USEICONID = 0x00000004,
PSP_USETITLE = 0x00000008,
PSP_RTLREADING = 0x00000010,
PSP_HASHELP = 0x00000020,
PSP_USEREFPARENT = 0x00000040,
PSP_USECALLBACK = 0x00000080,
PSP_PREMATURE = 0x00000400,
PSP_HIDEHEADER = 0x00000800,
PSP_USEHEADERTITLE = 0x00001000,
PSP_USEHEADERSUBTITLE = 0x00002000;
public const int
PSH_DEFAULT = 0x00000000,
PSH_PROPTITLE = 0x00000001,
PSH_USEHICON = 0x00000002,
PSH_USEICONID = 0x00000004,
PSH_PROPSHEETPAGE = 0x00000008,
PSH_WIZARDHASFINISH = 0x00000010,
PSH_WIZARD = 0x00000020,
PSH_USEPSTARTPAGE = 0x00000040,
PSH_NOAPPLYNOW = 0x00000080,
PSH_USECALLBACK = 0x00000100,
PSH_HASHELP = 0x00000200,
PSH_MODELESS = 0x00000400,
PSH_RTLREADING = 0x00000800,
PSH_WIZARDCONTEXTHELP = 0x00001000,
PSH_WATERMARK = 0x00008000,
PSH_USEHBMWATERMARK = 0x00010000, // user pass in a hbmWatermark instead of pszbmWatermark
PSH_USEHPLWATERMARK = 0x00020000, //
PSH_STRETCHWATERMARK = 0x00040000, // stretchwatermark also applies for the header
PSH_HEADER = 0x00080000,
PSH_USEHBMHEADER = 0x00100000,
PSH_USEPAGELANG = 0x00200000, // use frame dialog template matched to page
PSH_WIZARD_LITE = 0x00400000,
PSH_NOCONTEXTHELP = 0x02000000;
public const int
PSBTN_BACK = 0,
PSBTN_NEXT = 1,
PSBTN_FINISH = 2,
PSBTN_OK = 3,
PSBTN_APPLYNOW = 4,
PSBTN_CANCEL = 5,
PSBTN_HELP = 6,
PSBTN_MAX = 6;
public const int
TRANSPARENT = 1,
OPAQUE = 2,
FW_BOLD = 700;
[StructLayout(LayoutKind.Sequential)]
public struct NMHDR {
public IntPtr hwndFrom;
public int idFrom;
public int code;
}
/// <devdoc>
/// Please use this "approved" method to compare file names.
/// </devdoc>
public static bool IsSamePath(string file1, string file2)
{
if (file1 == null || file1.Length == 0)
{
return (file2 == null || file2.Length == 0);
}
Uri uri1 = null;
Uri uri2 = null;
try
{
if (!Uri.TryCreate(file1, UriKind.Absolute, out uri1) || !Uri.TryCreate(file2, UriKind.Absolute, out uri2))
{
return false;
}
if (uri1 != null && uri1.IsFile && uri2 != null && uri2.IsFile)
{
return 0 == String.Compare(uri1.LocalPath, uri2.LocalPath, StringComparison.OrdinalIgnoreCase);
}
return file1 == file2;
}
catch (UriFormatException e)
{
Trace.WriteLine("Exception " + e.Message);
}
return false;
}
/// <devdoc>
/// Helper class for setting the text parameters to OLECMDTEXT structures.
/// </devdoc>
public static class OLECMDTEXT {
public static void SetText(IntPtr pCmdTextInt, string text) {
Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT pCmdText = (Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT)Marshal.PtrToStructure(pCmdTextInt, typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT));
char[] menuText = text.ToCharArray();
// Get the offset to the rgsz param. This is where we will stuff our text
//
IntPtr offset = Marshal.OffsetOf(typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT), "rgwz");
IntPtr offsetToCwActual = Marshal.OffsetOf(typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT), "cwActual");
// The max chars we copy is our string, or one less than the buffer size,
// since we need a null at the end.
//
int maxChars = Math.Min((int)pCmdText.cwBuf - 1, menuText.Length);
Marshal.Copy(menuText, 0, (IntPtr)((long)pCmdTextInt + (long)offset), maxChars);
// append a null character
Marshal.WriteInt16((IntPtr)((long)pCmdTextInt + (long)offset + maxChars * 2), 0);
// write out the length
// +1 for the null char
Marshal.WriteInt32((IntPtr)((long)pCmdTextInt + (long)offsetToCwActual), maxChars + 1);
}
/// <summary>
/// Gets the flags of the OLECMDTEXT structure
/// </summary>
/// <param name="pCmdTextInt">The structure to read.</param>
/// <returns>The value of the flags.</returns>
public static OLECMDTEXTF GetFlags(IntPtr pCmdTextInt) {
Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT pCmdText = (Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT)Marshal.PtrToStructure(pCmdTextInt, typeof(Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT));
if ((pCmdText.cmdtextf & (int)OLECMDTEXTF.OLECMDTEXTF_NAME) != 0)
return OLECMDTEXTF.OLECMDTEXTF_NAME;
if ((pCmdText.cmdtextf & (int)OLECMDTEXTF.OLECMDTEXTF_STATUS) != 0)
return OLECMDTEXTF.OLECMDTEXTF_STATUS;
return OLECMDTEXTF.OLECMDTEXTF_NONE;
}
/// <summary>
/// Flags for the OLE command text
/// </summary>
public enum OLECMDTEXTF {
/// <summary>No flag</summary>
OLECMDTEXTF_NONE = 0,
/// <summary>The name of the command is required.</summary>
OLECMDTEXTF_NAME = 1,
/// <summary>A description of the status is required.</summary>
OLECMDTEXTF_STATUS = 2
}
}
/// <devdoc>
/// OLECMDF enums for IOleCommandTarget
/// </devdoc>
public enum tagOLECMDF {
OLECMDF_SUPPORTED = 1,
OLECMDF_ENABLED = 2,
OLECMDF_LATCHED = 4,
OLECMDF_NINCHED = 8,
OLECMDF_INVISIBLE = 16
}
[DllImport("user32", CallingConvention = CallingConvention.Winapi)]
public static extern IntPtr GetParent(IntPtr hWnd);
[DllImport("user32", CallingConvention = CallingConvention.Winapi)]
public static extern bool GetClientRect(IntPtr hWnd, out User32RECT lpRect);
[DllImport("user32", CallingConvention = CallingConvention.Winapi)]
public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[DllImport("user32", CallingConvention = CallingConvention.Winapi)]
public static extern IntPtr SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode)]
public static extern IntPtr SendMessageW(IntPtr hWnd, uint msg, IntPtr wParam, string lParam);
[DllImport("user32", CallingConvention = CallingConvention.Winapi)]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32", CallingConvention = CallingConvention.Winapi)]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
public static void SetErrorDescription(string description, params object[] args) {
ICreateErrorInfo errInfo;
ErrorHandler.ThrowOnFailure(CreateErrorInfo(out errInfo));
errInfo.SetDescription(String.Format(description, args));
var guidNull = Guid.Empty;
errInfo.SetGUID(ref guidNull);
errInfo.SetHelpFile(null);
errInfo.SetHelpContext(0);
errInfo.SetSource("");
IErrorInfo errorInfo = errInfo as IErrorInfo;
SetErrorInfo(0, errorInfo);
}
[DllImport("oleaut32")]
static extern int CreateErrorInfo(out ICreateErrorInfo errInfo);
[DllImport("oleaut32")]
static extern int SetErrorInfo(uint dwReserved, IErrorInfo perrinfo);
[ComImport(), Guid("9BDA66AE-CA28-4e22-AA27-8A7218A0E3FA"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IEventHandler {
// converts the underlying codefunction into an event handler for the given event
// if the given event is NULL, then the function will handle no events
[PreserveSig]
int AddHandler(string bstrEventName);
[PreserveSig]
int RemoveHandler(string bstrEventName);
IVsEnumBSTR GetHandledEvents();
bool HandlesEvent(string bstrEventName);
}
[ComImport(), Guid("A55CCBCC-7031-432d-B30A-A68DE7BDAD75"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IParameterKind {
void SetParameterPassingMode(PARAMETER_PASSING_MODE ParamPassingMode);
void SetParameterArrayDimensions(int uDimensions);
int GetParameterArrayCount();
int GetParameterArrayDimensions(int uIndex);
int GetParameterPassingMode();
}
public enum PARAMETER_PASSING_MODE {
cmParameterTypeIn = 1,
cmParameterTypeOut = 2,
cmParameterTypeInOut = 3
}
[
ComImport, ComVisible(true), Guid("3E596484-D2E4-461a-A876-254C4F097EBB"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)
]
public interface IMethodXML {
// Generate XML describing the contents of this function's body.
void GetXML(ref string pbstrXML);
// Parse the incoming XML with respect to the CodeModel XML schema and
// use the result to regenerate the body of the function.
/// <include file='doc\NativeMethods.uex' path='docs/doc[@for="IMethodXML.SetXML"]/*' />
[PreserveSig]
int SetXML(string pszXML);
// This is really a textpoint
[PreserveSig]
int GetBodyPoint([MarshalAs(UnmanagedType.Interface)]out object bodyPoint);
}
[ComImport(), Guid("EA1A87AD-7BC5-4349-B3BE-CADC301F17A3"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVBFileCodeModelEvents {
[PreserveSig]
int StartEdit();
[PreserveSig]
int EndEdit();
}
///--------------------------------------------------------------------------
/// ICodeClassBase:
///--------------------------------------------------------------------------
[GuidAttribute("23BBD58A-7C59-449b-A93C-43E59EFC080C")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport()]
public interface ICodeClassBase {
[PreserveSig()]
int GetBaseName(out string pBaseName);
}
public const ushort CF_HDROP = 15; // winuser.h
public const uint MK_CONTROL = 0x0008; //winuser.h
public const uint MK_SHIFT = 0x0004;
public const int MAX_PATH = 260; // windef.h
public const int MAX_FOLDER_PATH = MAX_PATH - 12; // folders need to allow 8.3 filenames, so MAX_PATH - 12
/// <summary>
/// Specifies options for a bitmap image associated with a task item.
/// </summary>
public enum VSTASKBITMAP {
BMP_COMPILE = -1,
BMP_SQUIGGLE = -2,
BMP_COMMENT = -3,
BMP_SHORTCUT = -4,
BMP_USER = -5
};
public const int ILD_NORMAL = 0x0000,
ILD_TRANSPARENT = 0x0001,
ILD_MASK = 0x0010,
ILD_ROP = 0x0040;
/// <summary>
/// Defines the values that are not supported by the System.Environment.SpecialFolder enumeration
/// </summary>
[ComVisible(true)]
public enum ExtendedSpecialFolder {
/// <summary>
/// Identical to CSIDL_COMMON_STARTUP
/// </summary>
CommonStartup = 0x0018,
/// <summary>
/// Identical to CSIDL_WINDOWS
/// </summary>
Windows = 0x0024,
}
// APIS
/// <summary>
/// Changes the parent window of the specified child window.
/// </summary>
/// <param name="hWnd">Handle to the child window.</param>
/// <param name="hWndParent">Handle to the new parent window. If this parameter is NULL, the desktop window becomes the new parent window.</param>
/// <returns>A handle to the previous parent window indicates success. NULL indicates failure.</returns>
[DllImport("User32", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent);
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern bool DestroyIcon(IntPtr handle);
[DllImport("user32.dll", EntryPoint = "IsDialogMessageA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool IsDialogMessageA(IntPtr hDlg, ref MSG msg);
[DllImport("kernel32", EntryPoint = "GetBinaryTypeW", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)]
private static extern bool _GetBinaryType(string lpApplicationName, out GetBinaryTypeResult lpBinaryType);
private enum GetBinaryTypeResult : uint {
SCS_32BIT_BINARY = 0,
SCS_DOS_BINARY = 1,
SCS_WOW_BINARY = 2,
SCS_PIF_BINARY = 3,
SCS_POSIX_BINARY = 4,
SCS_OS216_BINARY = 5,
SCS_64BIT_BINARY = 6
}
public static ProcessorArchitecture GetBinaryType(string path) {
GetBinaryTypeResult result;
if (_GetBinaryType(path, out result)) {
switch (result) {
case GetBinaryTypeResult.SCS_32BIT_BINARY:
return ProcessorArchitecture.X86;
case GetBinaryTypeResult.SCS_64BIT_BINARY:
return ProcessorArchitecture.Amd64;
case GetBinaryTypeResult.SCS_DOS_BINARY:
case GetBinaryTypeResult.SCS_WOW_BINARY:
case GetBinaryTypeResult.SCS_PIF_BINARY:
case GetBinaryTypeResult.SCS_POSIX_BINARY:
case GetBinaryTypeResult.SCS_OS216_BINARY:
default:
break;
}
}
return ProcessorArchitecture.None;
}
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
[DllImport("ADVAPI32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool LogonUser(
[In] string lpszUsername,
[In] string lpszDomain,
[In] string lpszPassword,
[In] LogonType dwLogonType,
[In] LogonProvider dwLogonProvider,
[In, Out] ref IntPtr hToken
);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr handle);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern uint GetFinalPathNameByHandle(
SafeHandle hFile,
[Out]StringBuilder lpszFilePath,
uint cchFilePath,
uint dwFlags
);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern SafeFileHandle CreateFile(
string lpFileName,
FileDesiredAccess dwDesiredAccess,
FileShareFlags dwShareMode,
IntPtr lpSecurityAttributes,
FileCreationDisposition dwCreationDisposition,
FileFlagsAndAttributes dwFlagsAndAttributes,
IntPtr hTemplateFile
);
[Flags]
public enum FileDesiredAccess : uint {
FILE_LIST_DIRECTORY = 1
}
[Flags]
public enum FileShareFlags : uint {
FILE_SHARE_READ = 0x00000001,
FILE_SHARE_WRITE = 0x00000002,
FILE_SHARE_DELETE = 0x00000004
}
[Flags]
public enum FileCreationDisposition : uint {
OPEN_EXISTING = 3
}
[Flags]
public enum FileFlagsAndAttributes : uint {
FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
}
public static IntPtr INVALID_FILE_HANDLE = new IntPtr(-1);
public static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
public enum LogonType {
LOGON32_LOGON_INTERACTIVE = 2,
LOGON32_LOGON_NETWORK,
LOGON32_LOGON_BATCH,
LOGON32_LOGON_SERVICE = 5,
LOGON32_LOGON_UNLOCK = 7,
LOGON32_LOGON_NETWORK_CLEARTEXT,
LOGON32_LOGON_NEW_CREDENTIALS
}
public enum LogonProvider {
LOGON32_PROVIDER_DEFAULT = 0,
LOGON32_PROVIDER_WINNT35,
LOGON32_PROVIDER_WINNT40,
LOGON32_PROVIDER_WINNT50
}
[DllImport("msi.dll", CharSet = CharSet.Unicode)]
internal static extern MsiInstallState MsiGetComponentPath(string szProduct, string szComponent, [Out]StringBuilder lpPathBuf, ref uint pcchBuf);
/// <summary>
/// Buffer for lpProductBuf must be 39 characters long.
/// </summary>
/// <param name="szComponent"></param>
/// <param name="lpProductBuf"></param>
/// <returns></returns>
[DllImport("msi.dll", CharSet = CharSet.Unicode)]
internal static extern uint MsiGetProductCode(string szComponent, [Out]StringBuilder lpProductBuf);
internal enum MsiInstallState {
NotUsed = -7, // component disabled
BadConfig = -6, // configuration data corrupt
Incomplete = -5, // installation suspended or in progress
SourceAbsent = -4, // run from source, source is unavailable
MoreData = -3, // return buffer overflow
InvalidArg = -2, // invalid function argument
Unknown = -1, // unrecognized product or feature
Broken = 0, // broken
Advertised = 1, // advertised feature
Removed = 1, // component being removed (action state, not settable)
Absent = 2, // uninstalled (or action state absent but clients remain)
Local = 3, // installed on local drive
Source = 4, // run from source, CD or net
Default = 5 // use default, local or source
}
[DllImport("user32", CallingConvention = CallingConvention.Winapi)]
public static extern bool AllowSetForegroundWindow(int dwProcessId);
[DllImport("mpr", CharSet = CharSet.Unicode)]
public static extern uint WNetAddConnection3(IntPtr handle, ref _NETRESOURCE lpNetResource, string lpPassword, string lpUsername, uint dwFlags);
public const int CONNECT_INTERACTIVE = 0x08;
public const int CONNECT_PROMPT = 0x10;
public const int RESOURCETYPE_DISK = 1;
public struct _NETRESOURCE {
public uint dwScope;
public uint dwType;
public uint dwDisplayType;
public uint dwUsage;
public string lpLocalName;
public string lpRemoteName;
public string lpComment;
public string lpProvider;
}
[DllImport(ExternDll.Kernel32, EntryPoint = "GetFinalPathNameByHandleW", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int GetFinalPathNameByHandle(SafeFileHandle handle, [In, Out] StringBuilder path, int bufLen, int flags);
[DllImport(ExternDll.Kernel32, EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeFileHandle CreateFile(
string lpFileName,
int dwDesiredAccess,
[MarshalAs(UnmanagedType.U4)] FileShare dwShareMode,
IntPtr SecurityAttributes,
[MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition,
int dwFlagsAndAttributes,
IntPtr hTemplateFile);
/// <summary>
/// Given a directory, actual or symbolic, return the actual directory path.
/// </summary>
/// <param name="symlink">DirectoryInfo object for the suspected symlink.</param>
/// <returns>A string of the actual path.</returns>
internal static string GetAbsolutePathToDirectory(string symlink) {
const int FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
const int DEVICE_QUERY_ACCESS = 0;
using (SafeFileHandle directoryHandle = CreateFile(
symlink,
DEVICE_QUERY_ACCESS,
FileShare.Write,
System.IntPtr.Zero,
FileMode.Open,
FILE_FLAG_BACKUP_SEMANTICS,
System.IntPtr.Zero)) {
if (directoryHandle.IsInvalid) {
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
StringBuilder path = new StringBuilder(512);
int pathSize = GetFinalPathNameByHandle(directoryHandle, path, path.Capacity, 0);
if (pathSize < 0) {
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
// UNC Paths will start with \\?\. Remove this if present as this isn't really expected on a path.
var pathString = path.ToString();
return pathString.StartsWith(@"\\?\") ? pathString.Substring(4) : pathString;
}
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool FindNextFile(IntPtr hFindFile, out WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool FindClose(IntPtr hFindFile);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool DeleteFile(string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool RemoveDirectory(string lpPathName);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool MoveFile(String src, String dst);
}
internal class CredUI {
private const string advapi32Dll = "advapi32.dll";
private const string credUIDll = "credui.dll";
public const int
ERROR_INVALID_FLAGS = 1004, // Invalid flags.
ERROR_NOT_FOUND = 1168, // Element not found.
ERROR_NO_SUCH_LOGON_SESSION = 1312, // A specified logon session does not exist. It may already have been terminated.
ERROR_LOGON_FAILURE = 1326; // Logon failure: unknown user name or bad password.
[Flags]
public enum CREDUI_FLAGS : uint {
INCORRECT_PASSWORD = 0x1,
DO_NOT_PERSIST = 0x2,
REQUEST_ADMINISTRATOR = 0x4,
EXCLUDE_CERTIFICATES = 0x8,
REQUIRE_CERTIFICATE = 0x10,
SHOW_SAVE_CHECK_BOX = 0x40,
ALWAYS_SHOW_UI = 0x80,
REQUIRE_SMARTCARD = 0x100,
PASSWORD_ONLY_OK = 0x200,
VALIDATE_USERNAME = 0x400,
COMPLETE_USERNAME = 0x800,
PERSIST = 0x1000,
SERVER_CREDENTIAL = 0x4000,
EXPECT_CONFIRMATION = 0x20000,
GENERIC_CREDENTIALS = 0x40000,
USERNAME_TARGET_CREDENTIALS = 0x80000,
KEEP_USERNAME = 0x100000,
}
[StructLayout(LayoutKind.Sequential)]
public class CREDUI_INFO {
public int cbSize;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
public IntPtr hwndParentCERParent;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszMessageText;
[MarshalAs(UnmanagedType.LPWStr)]
public string pszCaptionText;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
public IntPtr hbmBannerCERHandle;
}
public enum CredUIReturnCodes : uint {
NO_ERROR = 0,
ERROR_CANCELLED = 1223,
ERROR_NO_SUCH_LOGON_SESSION = 1312,
ERROR_NOT_FOUND = 1168,
ERROR_INVALID_ACCOUNT_NAME = 1315,
ERROR_INSUFFICIENT_BUFFER = 122,
ERROR_INVALID_PARAMETER = 87,
ERROR_INVALID_FLAGS = 1004,
}
// Copied from wincred.h
public const uint
// Values of the Credential Type field.
CRED_TYPE_GENERIC = 1,
CRED_TYPE_DOMAIN_PASSWORD = 2,
CRED_TYPE_DOMAIN_CERTIFICATE = 3,
CRED_TYPE_DOMAIN_VISIBLE_PASSWORD = 4,
CRED_TYPE_MAXIMUM = 5, // Maximum supported cred type
CRED_TYPE_MAXIMUM_EX = (CRED_TYPE_MAXIMUM + 1000), // Allow new applications to run on old OSes
// String limits
CRED_MAX_CREDENTIAL_BLOB_SIZE = 512, // Maximum size of the CredBlob field (in bytes)
CRED_MAX_STRING_LENGTH = 256, // Maximum length of the various credential string fields (in characters)
CRED_MAX_USERNAME_LENGTH = (256 + 1 + 256), // Maximum length of the UserName field. The worst case is <User>@<DnsDomain>
CRED_MAX_GENERIC_TARGET_NAME_LENGTH = 32767, // Maximum length of the TargetName field for CRED_TYPE_GENERIC (in characters)
CRED_MAX_DOMAIN_TARGET_NAME_LENGTH = (256 + 1 + 80), // Maximum length of the TargetName field for CRED_TYPE_DOMAIN_* (in characters). Largest one is <DfsRoot>\<DfsShare>
CRED_MAX_VALUE_SIZE = 256, // Maximum size of the Credential Attribute Value field (in bytes)
CRED_MAX_ATTRIBUTES = 64, // Maximum number of attributes per credential
CREDUI_MAX_MESSAGE_LENGTH = 32767,
CREDUI_MAX_CAPTION_LENGTH = 128,
CREDUI_MAX_GENERIC_TARGET_LENGTH = CRED_MAX_GENERIC_TARGET_NAME_LENGTH,
CREDUI_MAX_DOMAIN_TARGET_LENGTH = CRED_MAX_DOMAIN_TARGET_NAME_LENGTH,
CREDUI_MAX_USERNAME_LENGTH = CRED_MAX_USERNAME_LENGTH,
CREDUI_MAX_PASSWORD_LENGTH = (CRED_MAX_CREDENTIAL_BLOB_SIZE / 2);
internal enum CRED_PERSIST : uint {
NONE = 0,
SESSION = 1,
LOCAL_MACHINE = 2,
ENTERPRISE = 3,
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct NativeCredential {
public uint flags;
public uint type;
public string targetName;
public string comment;
public int lastWritten_lowDateTime;
public int lastWritten_highDateTime;
public uint credentialBlobSize;
public IntPtr credentialBlob;
public uint persist;
public uint attributeCount;
public IntPtr attributes;
public string targetAlias;
public string userName;
};
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport(advapi32Dll, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CredReadW")]
public static extern bool
CredRead(
[MarshalAs(UnmanagedType.LPWStr)]
string targetName,
[MarshalAs(UnmanagedType.U4)]
uint type,
[MarshalAs(UnmanagedType.U4)]
uint flags,
out IntPtr credential
);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport(advapi32Dll, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CredWriteW")]
public static extern bool
CredWrite(
ref NativeCredential Credential,
[MarshalAs(UnmanagedType.U4)]
uint flags
);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport(advapi32Dll, SetLastError = true)]
public static extern bool
CredFree(
IntPtr buffer
);
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport(credUIDll, EntryPoint = "CredUIPromptForCredentialsW", CharSet = CharSet.Unicode)]
public static extern CredUIReturnCodes CredUIPromptForCredentials(
CREDUI_INFO pUiInfo, // Optional (one can pass null here)
[MarshalAs(UnmanagedType.LPWStr)]
string targetName,
IntPtr Reserved, // Must be 0 (IntPtr.Zero)
int iError,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder pszUserName,
[MarshalAs(UnmanagedType.U4)]
uint ulUserNameMaxChars,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder pszPassword,
[MarshalAs(UnmanagedType.U4)]
uint ulPasswordMaxChars,
ref int pfSave,
CREDUI_FLAGS dwFlags);
/// <returns>
/// Win32 system errors:
/// NO_ERROR
/// ERROR_INVALID_ACCOUNT_NAME
/// ERROR_INSUFFICIENT_BUFFER
/// ERROR_INVALID_PARAMETER
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[DllImport(credUIDll, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CredUIParseUserNameW")]
public static extern CredUIReturnCodes CredUIParseUserName(
[MarshalAs(UnmanagedType.LPWStr)]
string strUserName,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder strUser,
[MarshalAs(UnmanagedType.U4)]
uint iUserMaxChars,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder strDomain,
[MarshalAs(UnmanagedType.U4)]
uint iDomainMaxChars
);
}
struct User32RECT {
public int left;
public int top;
public int right;
public int bottom;
public int Width {
get {
return right - left;
}
}
public int Height {
get {
return bottom - top;
}
}
}
[Guid("22F03340-547D-101B-8E65-08002B2BD119")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface ICreateErrorInfo {
int SetGUID(
ref Guid rguid
);
int SetSource(string szSource);
int SetDescription(string szDescription);
int SetHelpFile(string szHelpFile);
int SetHelpContext(uint dwHelpContext);
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct WIN32_FIND_DATA {
public uint dwFileAttributes;
public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;
public uint nFileSizeHigh;
public uint nFileSizeLow;
public uint dwReserved0;
public uint dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;
}
}
| |
#pragma warning disable 1587
#region Header
///
/// JsonWriter.cs
/// Stream-like facility to output JSON text.
///
/// The authors disclaim copyright to this source code. For more details, see
/// the COPYING file included with this distribution.
///
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace Json.LitJson
{
internal enum Condition
{
InArray,
InObject,
NotAProperty,
Property,
Value
}
internal class WriterContext
{
public int Count;
public bool InArray;
public bool InObject;
public bool ExpectingValue;
public int Padding;
}
public class JsonWriter
{
#region Fields
private static NumberFormatInfo number_format;
private WriterContext context;
private Stack<WriterContext> ctx_stack;
private bool has_reached_end;
private char[] hex_seq;
private int indentation;
private int indent_value;
private StringBuilder inst_string_builder;
private bool pretty_print;
private bool validate;
private TextWriter writer;
#endregion
#region Properties
public int IndentValue {
get { return indent_value; }
set {
indentation = (indentation / indent_value) * value;
indent_value = value;
}
}
public bool PrettyPrint {
get { return pretty_print; }
set { pretty_print = value; }
}
public TextWriter TextWriter {
get { return writer; }
}
public bool Validate {
get { return validate; }
set { validate = value; }
}
#endregion
#region Constructors
static JsonWriter ()
{
number_format = NumberFormatInfo.InvariantInfo;
}
public JsonWriter ()
{
inst_string_builder = new StringBuilder ();
writer = new StringWriter (inst_string_builder);
Init ();
}
public JsonWriter (StringBuilder sb) :
this (new StringWriter (sb))
{
}
public JsonWriter (TextWriter writer)
{
if (writer == null)
throw new ArgumentNullException ("writer");
this.writer = writer;
Init ();
}
#endregion
#region Private Methods
private void DoValidation (Condition cond)
{
if (! context.ExpectingValue)
context.Count++;
if (! validate)
return;
if (has_reached_end)
throw new JsonException (
"A complete JSON symbol has already been written");
switch (cond) {
case Condition.InArray:
if (! context.InArray)
throw new JsonException (
"Can't close an array here");
break;
case Condition.InObject:
if (! context.InObject || context.ExpectingValue)
throw new JsonException (
"Can't close an object here");
break;
case Condition.NotAProperty:
if (context.InObject && ! context.ExpectingValue)
throw new JsonException (
"Expected a property");
break;
case Condition.Property:
if (! context.InObject || context.ExpectingValue)
throw new JsonException (
"Can't add a property here");
break;
case Condition.Value:
if (! context.InArray &&
(! context.InObject || ! context.ExpectingValue))
throw new JsonException (
"Can't add a value here");
break;
}
}
private void Init ()
{
has_reached_end = false;
hex_seq = new char[4];
indentation = 0;
indent_value = 4;
pretty_print = false;
validate = true;
ctx_stack = new Stack<WriterContext> ();
context = new WriterContext ();
ctx_stack.Push (context);
}
private static void IntToHex (int n, char[] hex)
{
int num;
for (int i = 0; i < 4; i++) {
num = n % 16;
if (num < 10)
hex[3 - i] = (char) ('0' + num);
else
hex[3 - i] = (char) ('A' + (num - 10));
n >>= 4;
}
}
private void Indent ()
{
if (pretty_print)
indentation += indent_value;
}
private void Put (string str)
{
if (pretty_print && ! context.ExpectingValue)
for (int i = 0; i < indentation; i++)
writer.Write (' ');
writer.Write (str);
}
private void PutNewline ()
{
PutNewline (true);
}
private void PutNewline (bool add_comma)
{
if (add_comma && ! context.ExpectingValue &&
context.Count > 1)
writer.Write (',');
if (pretty_print && ! context.ExpectingValue)
writer.Write ("\r\n");
}
private void PutString (string str)
{
Put (String.Empty);
writer.Write ('"');
int n = str.Length;
for (int i = 0; i < n; i++)
{
char c = str[i];
switch (c) {
case '\n':
writer.Write ("\\n");
continue;
case '\r':
writer.Write ("\\r");
continue;
case '\t':
writer.Write ("\\t");
continue;
case '"':
case '\\':
writer.Write ('\\');
writer.Write (c);
continue;
case '\f':
writer.Write ("\\f");
continue;
case '\b':
writer.Write ("\\b");
continue;
}
if ((int) c >= 32 && (int) c <= 126) {
writer.Write (c);
continue;
}
if (c < ' ' || (c >= '\u0080' && c < '\u00a0'))
{
// Turn into a \uXXXX sequence
IntToHex((int)c, hex_seq);
writer.Write("\\u");
writer.Write(hex_seq);
}
else
{
writer.Write(c);
}
}
writer.Write ('"');
}
private void Unindent ()
{
if (pretty_print)
indentation -= indent_value;
}
#endregion
public override string ToString ()
{
if (inst_string_builder == null)
return String.Empty;
return inst_string_builder.ToString ();
}
public void Reset ()
{
has_reached_end = false;
ctx_stack.Clear ();
context = new WriterContext ();
ctx_stack.Push (context);
if (inst_string_builder != null)
inst_string_builder.Remove (0, inst_string_builder.Length);
}
public void Write (bool boolean)
{
DoValidation (Condition.Value);
PutNewline ();
Put (boolean ? "true" : "false");
context.ExpectingValue = false;
}
public void Write (decimal number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write (double number)
{
DoValidation (Condition.Value);
PutNewline ();
string str = Convert.ToString (number, number_format);
Put (str);
if (str.IndexOf ('.') == -1 &&
str.IndexOf ('E') == -1)
writer.Write (".0");
context.ExpectingValue = false;
}
public void Write (int number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write (long number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number));
context.ExpectingValue = false;
}
public void Write (string str)
{
DoValidation (Condition.Value);
PutNewline ();
if (str == null)
Put ("null");
else
PutString (str);
context.ExpectingValue = false;
}
public void Write (ulong number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write(DateTime date)
{
DoValidation(Condition.Value);
PutNewline();
Put(ConvertToUnixEpochMilliSeconds(date).ToString(CultureInfo.InvariantCulture));
context.ExpectingValue = false;
}
private static readonly DateTime EPOCH_START = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static int ConvertToUnixEpochSeconds(DateTime dateTime)
{
return (int)ConvertToUnixEpochMilliSeconds(dateTime);
}
public static double ConvertToUnixEpochMilliSeconds(DateTime dateTime)
{
var ts = new TimeSpan(dateTime.ToUniversalTime().Ticks - EPOCH_START.Ticks);
double milli = Math.Round(ts.TotalMilliseconds, 0) / 1000.0;
return milli;
}
public void WriteArrayEnd ()
{
DoValidation (Condition.InArray);
PutNewline (false);
ctx_stack.Pop ();
if (ctx_stack.Count == 1)
has_reached_end = true;
else {
context = ctx_stack.Peek ();
context.ExpectingValue = false;
}
Unindent ();
Put ("]");
}
public void WriteArrayStart ()
{
DoValidation (Condition.NotAProperty);
PutNewline ();
Put ("[");
context = new WriterContext ();
context.InArray = true;
ctx_stack.Push (context);
Indent ();
}
public void WriteObjectEnd ()
{
DoValidation (Condition.InObject);
PutNewline (false);
ctx_stack.Pop ();
if (ctx_stack.Count == 1)
has_reached_end = true;
else {
context = ctx_stack.Peek ();
context.ExpectingValue = false;
}
Unindent ();
Put ("}");
}
public void WriteObjectStart ()
{
DoValidation (Condition.NotAProperty);
PutNewline ();
Put ("{");
context = new WriterContext ();
context.InObject = true;
ctx_stack.Push (context);
Indent ();
}
public void WritePropertyName (string property_name)
{
DoValidation (Condition.Property);
PutNewline ();
PutString (property_name);
if (pretty_print) {
if (property_name.Length > context.Padding)
context.Padding = property_name.Length;
for (int i = context.Padding - property_name.Length;
i >= 0; i--)
writer.Write (' ');
writer.Write (": ");
} else
writer.Write (':');
context.ExpectingValue = true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Orchard.Caching;
using Orchard.ContentManagement;
using Orchard.Environment.Extensions.Models;
using Orchard.FileSystems.WebSite;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.Utility.Extensions;
namespace Orchard.Environment.Extensions.Folders {
public class ExtensionHarvester : IExtensionHarvester {
private const string NameSection = "name";
private const string PathSection = "path";
private const string DescriptionSection = "description";
private const string VersionSection = "version";
private const string OrchardVersionSection = "orchardversion";
private const string AuthorSection = "author";
private const string WebsiteSection = "website";
private const string TagsSection = "tags";
private const string AntiForgerySection = "antiforgery";
private const string ZonesSection = "zones";
private const string BaseThemeSection = "basetheme";
private const string DependenciesSection = "dependencies";
private const string CategorySection = "category";
private const string FeatureDescriptionSection = "featuredescription";
private const string FeatureNameSection = "featurename";
private const string PrioritySection = "priority";
private const string FeaturesSection = "features";
private const string SessionStateSection = "sessionstate";
private const string LifecycleStatusSection = "lifecyclestatus";
private readonly ICacheManager _cacheManager;
private readonly IWebSiteFolder _webSiteFolder;
private readonly ICriticalErrorProvider _criticalErrorProvider;
public ExtensionHarvester(ICacheManager cacheManager, IWebSiteFolder webSiteFolder, ICriticalErrorProvider criticalErrorProvider) {
_cacheManager = cacheManager;
_webSiteFolder = webSiteFolder;
_criticalErrorProvider = criticalErrorProvider;
Logger = NullLogger.Instance;
T = NullLocalizer.Instance;
}
public Localizer T { get; set; }
public ILogger Logger { get; set; }
public bool DisableMonitoring { get; set; }
public IEnumerable<ExtensionDescriptor> HarvestExtensions(IEnumerable<string> paths, string extensionType, string manifestName, bool manifestIsOptional) {
return paths
.SelectMany(path => HarvestExtensions(path, extensionType, manifestName, manifestIsOptional))
.ToList();
}
private IEnumerable<ExtensionDescriptor> HarvestExtensions(string path, string extensionType, string manifestName, bool manifestIsOptional) {
string key = string.Format("{0}-{1}-{2}", path, manifestName, extensionType);
return _cacheManager.Get(key, ctx => {
if (!DisableMonitoring) {
Logger.Debug("Monitoring virtual path \"{0}\"", path);
ctx.Monitor(_webSiteFolder.WhenPathChanges(path));
}
return AvailableExtensionsInFolder(path, extensionType, manifestName, manifestIsOptional).ToReadOnlyCollection();
});
}
private List<ExtensionDescriptor> AvailableExtensionsInFolder(string path, string extensionType, string manifestName, bool manifestIsOptional) {
Logger.Information("Start looking for extensions in '{0}'...", path);
var subfolderPaths = _webSiteFolder.ListDirectories(path);
var localList = new List<ExtensionDescriptor>();
foreach (var subfolderPath in subfolderPaths) {
var extensionId = Path.GetFileName(subfolderPath.TrimEnd('/', '\\'));
var manifestPath = Path.Combine(subfolderPath, manifestName);
try {
var descriptor = GetExtensionDescriptor(path, extensionId, extensionType, manifestPath, manifestIsOptional);
if (descriptor == null)
continue;
if (descriptor.Path != null && !descriptor.Path.IsValidUrlSegment()) {
Logger.Error("The module '{0}' could not be loaded because it has an invalid Path ({1}). It was ignored. The Path if specified must be a valid URL segment. The best bet is to stick with letters and numbers with no spaces.",
extensionId,
descriptor.Path);
_criticalErrorProvider.RegisterErrorMessage(T("The extension '{0}' could not be loaded because it has an invalid Path ({1}). It was ignored. The Path if specified must be a valid URL segment. The best bet is to stick with letters and numbers with no spaces.",
extensionId,
descriptor.Path));
continue;
}
if (descriptor.Path == null) {
descriptor.Path = descriptor.Name.IsValidUrlSegment()
? descriptor.Name
: descriptor.Id;
}
localList.Add(descriptor);
}
catch (Exception ex) {
// Ignore invalid module manifests
Logger.Error(ex, "The module '{0}' could not be loaded. It was ignored.", extensionId);
_criticalErrorProvider.RegisterErrorMessage(T("The extension '{0}' manifest could not be loaded. It was ignored.", extensionId));
}
}
Logger.Information("Done looking for extensions in '{0}': {1}", path, string.Join(", ", localList.Select(d => d.Id)));
return localList;
}
public static ExtensionDescriptor GetDescriptorForExtension(string locationPath, string extensionId, string extensionType, string manifestText) {
Dictionary<string, string> manifest = ParseManifest(manifestText);
var extensionDescriptor = new ExtensionDescriptor {
Location = locationPath,
Id = extensionId,
ExtensionType = extensionType,
Name = GetValue(manifest, NameSection) ?? extensionId,
Path = GetValue(manifest, PathSection),
Description = GetValue(manifest, DescriptionSection),
Version = GetValue(manifest, VersionSection),
OrchardVersion = GetValue(manifest, OrchardVersionSection),
Author = GetValue(manifest, AuthorSection),
WebSite = GetValue(manifest, WebsiteSection),
Tags = GetValue(manifest, TagsSection),
AntiForgery = GetValue(manifest, AntiForgerySection),
Zones = GetValue(manifest, ZonesSection),
BaseTheme = GetValue(manifest, BaseThemeSection),
SessionState = GetValue(manifest, SessionStateSection),
LifecycleStatus = GetValue(manifest, LifecycleStatusSection, LifecycleStatus.Production)
};
extensionDescriptor.Features = GetFeaturesForExtension(manifest, extensionDescriptor);
return extensionDescriptor;
}
private ExtensionDescriptor GetExtensionDescriptor(string locationPath, string extensionId, string extensionType, string manifestPath, bool manifestIsOptional) {
return _cacheManager.Get(manifestPath, context => {
if (!DisableMonitoring) {
Logger.Debug("Monitoring virtual path \"{0}\"", manifestPath);
context.Monitor(_webSiteFolder.WhenPathChanges(manifestPath));
}
var manifestText = _webSiteFolder.ReadFile(manifestPath);
if (manifestText == null) {
if (manifestIsOptional) {
manifestText = string.Format("Id: {0}", extensionId);
}
else {
return null;
}
}
return GetDescriptorForExtension(locationPath, extensionId, extensionType, manifestText);
});
}
private static Dictionary<string, string> ParseManifest(string manifestText) {
var manifest = new Dictionary<string, string>();
using (StringReader reader = new StringReader(manifestText)) {
string line;
while ((line = reader.ReadLine()) != null) {
string[] field = line.Split(new[] { ":" }, 2, StringSplitOptions.None);
int fieldLength = field.Length;
if (fieldLength != 2)
continue;
for (int i = 0; i < fieldLength; i++) {
field[i] = field[i].Trim();
}
switch (field[0].ToLowerInvariant()) {
case NameSection:
manifest.Add(NameSection, field[1]);
break;
case PathSection:
manifest.Add(PathSection, field[1]);
break;
case DescriptionSection:
manifest.Add(DescriptionSection, field[1]);
break;
case VersionSection:
manifest.Add(VersionSection, field[1]);
break;
case OrchardVersionSection:
manifest.Add(OrchardVersionSection, field[1]);
break;
case AuthorSection:
manifest.Add(AuthorSection, field[1]);
break;
case WebsiteSection:
manifest.Add(WebsiteSection, field[1]);
break;
case TagsSection:
manifest.Add(TagsSection, field[1]);
break;
case AntiForgerySection:
manifest.Add(AntiForgerySection, field[1]);
break;
case ZonesSection:
manifest.Add(ZonesSection, field[1]);
break;
case BaseThemeSection:
manifest.Add(BaseThemeSection, field[1]);
break;
case DependenciesSection:
manifest.Add(DependenciesSection, field[1]);
break;
case CategorySection:
manifest.Add(CategorySection, field[1]);
break;
case FeatureDescriptionSection:
manifest.Add(FeatureDescriptionSection, field[1]);
break;
case FeatureNameSection:
manifest.Add(FeatureNameSection, field[1]);
break;
case PrioritySection:
manifest.Add(PrioritySection, field[1]);
break;
case SessionStateSection:
manifest.Add(SessionStateSection, field[1]);
break;
case LifecycleStatusSection:
manifest.Add(LifecycleStatusSection, field[1]);
break;
case FeaturesSection:
manifest.Add(FeaturesSection, reader.ReadToEnd());
break;
}
}
}
return manifest;
}
private static IEnumerable<FeatureDescriptor> GetFeaturesForExtension(IDictionary<string, string> manifest, ExtensionDescriptor extensionDescriptor) {
var featureDescriptors = new List<FeatureDescriptor>();
// Default feature
FeatureDescriptor defaultFeature = new FeatureDescriptor {
Id = extensionDescriptor.Id,
Name = GetValue(manifest, FeatureNameSection) ?? extensionDescriptor.Name,
Priority = GetValue(manifest, PrioritySection) != null ? int.Parse(GetValue(manifest, PrioritySection)) : 0,
Description = GetValue(manifest, FeatureDescriptionSection) ?? GetValue(manifest, DescriptionSection) ?? string.Empty,
Dependencies = ParseFeatureDependenciesEntry(GetValue(manifest, DependenciesSection)),
Extension = extensionDescriptor,
Category = GetValue(manifest, CategorySection)
};
featureDescriptors.Add(defaultFeature);
// Remaining features
string featuresText = GetValue(manifest, FeaturesSection);
if (featuresText != null) {
FeatureDescriptor featureDescriptor = null;
using (StringReader reader = new StringReader(featuresText)) {
string line;
while ((line = reader.ReadLine()) != null) {
if (IsFeatureDeclaration(line)) {
if (featureDescriptor != null) {
if (!featureDescriptor.Equals(defaultFeature)) {
featureDescriptors.Add(featureDescriptor);
}
featureDescriptor = null;
}
string[] featureDeclaration = line.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
string featureDescriptorId = featureDeclaration[0].Trim();
if (String.Equals(featureDescriptorId, extensionDescriptor.Id, StringComparison.OrdinalIgnoreCase)) {
featureDescriptor = defaultFeature;
featureDescriptor.Name = extensionDescriptor.Name;
}
else {
featureDescriptor = new FeatureDescriptor {
Id = featureDescriptorId,
Extension = extensionDescriptor
};
}
}
else if (IsFeatureFieldDeclaration(line)) {
if (featureDescriptor != null) {
string[] featureField = line.Split(new[] { ":" }, 2, StringSplitOptions.None);
int featureFieldLength = featureField.Length;
if (featureFieldLength != 2)
continue;
for (int i = 0; i < featureFieldLength; i++) {
featureField[i] = featureField[i].Trim();
}
switch (featureField[0].ToLowerInvariant()) {
case NameSection:
featureDescriptor.Name = featureField[1];
break;
case DescriptionSection:
featureDescriptor.Description = featureField[1];
break;
case CategorySection:
featureDescriptor.Category = featureField[1];
break;
case PrioritySection:
featureDescriptor.Priority = int.Parse(featureField[1]);
break;
case DependenciesSection:
featureDescriptor.Dependencies = ParseFeatureDependenciesEntry(featureField[1]);
break;
}
}
else {
string message = string.Format("The line {0} in manifest for extension {1} was ignored", line, extensionDescriptor.Id);
throw new ArgumentException(message);
}
}
else {
string message = string.Format("The line {0} in manifest for extension {1} was ignored", line, extensionDescriptor.Id);
throw new ArgumentException(message);
}
}
if (featureDescriptor != null && !featureDescriptor.Equals(defaultFeature))
featureDescriptors.Add(featureDescriptor);
}
}
return featureDescriptors;
}
private static bool IsFeatureFieldDeclaration(string line) {
if (line.StartsWith("\t\t") ||
line.StartsWith("\t ") ||
line.StartsWith(" ") ||
line.StartsWith(" \t"))
return true;
return false;
}
private static bool IsFeatureDeclaration(string line) {
int lineLength = line.Length;
if (line.StartsWith("\t") && lineLength >= 2) {
return !Char.IsWhiteSpace(line[1]);
}
if (line.StartsWith(" ") && lineLength >= 5)
return !Char.IsWhiteSpace(line[4]);
return false;
}
private static IEnumerable<string> ParseFeatureDependenciesEntry(string dependenciesEntry) {
if (string.IsNullOrEmpty(dependenciesEntry))
return Enumerable.Empty<string>();
var dependencies = new List<string>();
foreach (var s in dependenciesEntry.Split(',')) {
dependencies.Add(s.Trim());
}
return dependencies;
}
private static string GetValue(IDictionary<string, string> fields, string key) {
string value;
return fields.TryGetValue(key, out value) ? value : null;
}
private static T GetValue<T>(IDictionary<string, string> fields, string key, T defaultValue = default(T)) {
var value = GetValue(fields, key);
return String.IsNullOrWhiteSpace(value) ? defaultValue : XmlHelper.Parse<T>(value);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.Land
{
/// <summary>
/// Keeps track of a specific piece of land's information
/// </summary>
public class LandObject : ILandObject
{
#region Member Variables
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#pragma warning disable 0429
private const int landArrayMax = ((int)((int)Constants.RegionSize / 4) >= 64) ? (int)((int)Constants.RegionSize / 4) : 64;
#pragma warning restore 0429
private bool[,] m_landBitmap = new bool[landArrayMax,landArrayMax];
private int m_lastSeqId = 0;
protected LandData m_landData = new LandData();
protected Scene m_scene;
protected List<SceneObjectGroup> primsOverMe = new List<SceneObjectGroup>();
public bool[,] LandBitmap
{
get { return m_landBitmap; }
set { m_landBitmap = value; }
}
#endregion
#region ILandObject Members
public LandData LandData
{
get { return m_landData; }
set { m_landData = value; }
}
public UUID RegionUUID
{
get { return m_scene.RegionInfo.RegionID; }
}
#region Constructors
public LandObject(UUID owner_id, bool is_group_owned, Scene scene)
{
m_scene = scene;
LandData.OwnerID = owner_id;
if (is_group_owned)
LandData.GroupID = owner_id;
else
LandData.GroupID = UUID.Zero;
LandData.IsGroupOwned = is_group_owned;
}
#endregion
#region Member Functions
#region General Functions
/// <summary>
/// Checks to see if this land object contains a point
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>Returns true if the piece of land contains the specified point</returns>
public bool ContainsPoint(int x, int y)
{
if (x >= 0 && y >= 0 && x <= Constants.RegionSize && x <= Constants.RegionSize)
{
return (LandBitmap[x / 4, y / 4] == true);
}
else
{
return false;
}
}
public ILandObject Copy()
{
ILandObject newLand = new LandObject(LandData.OwnerID, LandData.IsGroupOwned, m_scene);
//Place all new variables here!
newLand.LandBitmap = (bool[,]) (LandBitmap.Clone());
newLand.LandData = LandData.Copy();
return newLand;
}
static overrideParcelMaxPrimCountDelegate overrideParcelMaxPrimCount;
static overrideSimulatorMaxPrimCountDelegate overrideSimulatorMaxPrimCount;
public void SetParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel)
{
overrideParcelMaxPrimCount = overrideDel;
}
public void SetSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel)
{
overrideSimulatorMaxPrimCount = overrideDel;
}
public int GetParcelMaxPrimCount(ILandObject thisObject)
{
if (overrideParcelMaxPrimCount != null)
{
return overrideParcelMaxPrimCount(thisObject);
}
else
{
// Normal Calculations
return (int)Math.Round(((float)LandData.Area / 65536.0f) * (float)m_scene.objectCapacity * (float)m_scene.RegionInfo.RegionSettings.ObjectBonus);
}
}
public int GetSimulatorMaxPrimCount(ILandObject thisObject)
{
if (overrideSimulatorMaxPrimCount != null)
{
return overrideSimulatorMaxPrimCount(thisObject);
}
else
{
//Normal Calculations
return m_scene.objectCapacity;
}
}
#endregion
#region Packet Request Handling
public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, IClientAPI remote_client)
{
IEstateModule estateModule = m_scene.RequestModuleInterface<IEstateModule>();
uint regionFlags = 336723974 & ~((uint)(RegionFlags.AllowLandmark | RegionFlags.AllowSetHome));
if (estateModule != null)
regionFlags = estateModule.GetRegionFlags();
// In a perfect world, this would have worked.
//
// if ((landData.Flags & (uint)ParcelFlags.AllowLandmark) != 0)
// regionFlags |= (uint)RegionFlags.AllowLandmark;
// if (landData.OwnerID == remote_client.AgentId)
// regionFlags |= (uint)RegionFlags.AllowSetHome;
int seq_id;
if (snap_selection && (sequence_id == 0))
{
seq_id = m_lastSeqId;
}
else
{
seq_id = sequence_id;
m_lastSeqId = seq_id;
}
remote_client.SendLandProperties(seq_id,
snap_selection, request_result, LandData,
(float)m_scene.RegionInfo.RegionSettings.ObjectBonus,
GetParcelMaxPrimCount(this),
GetSimulatorMaxPrimCount(this), regionFlags);
}
public void UpdateLandProperties(LandUpdateArgs args, IClientAPI remote_client)
{
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId,this))
{
//Needs later group support
bool snap_selection = false;
LandData newData = LandData.Copy();
if (args.AuthBuyerID != newData.AuthBuyerID || args.SalePrice != newData.SalePrice)
{
if (m_scene.Permissions.CanSellParcel(remote_client.AgentId, this))
{
newData.AuthBuyerID = args.AuthBuyerID;
newData.SalePrice = args.SalePrice;
snap_selection = true;
}
}
newData.Category = args.Category;
newData.Description = args.Desc;
newData.GroupID = args.GroupID;
newData.LandingType = args.LandingType;
newData.MediaAutoScale = args.MediaAutoScale;
newData.MediaID = args.MediaID;
newData.MediaURL = args.MediaURL;
newData.MusicURL = args.MusicURL;
newData.Name = args.Name;
newData.Flags = args.ParcelFlags;
newData.PassHours = args.PassHours;
newData.PassPrice = args.PassPrice;
newData.SnapshotID = args.SnapshotID;
newData.UserLocation = args.UserLocation;
newData.UserLookAt = args.UserLookAt;
m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData);
SendLandUpdateToAvatarsOverMe(snap_selection);
}
}
public void UpdateLandSold(UUID avatarID, UUID groupID, bool groupOwned, uint AuctionID, int claimprice, int area)
{
LandData newData = LandData.Copy();
newData.OwnerID = avatarID;
newData.GroupID = groupID;
newData.IsGroupOwned = groupOwned;
//newData.auctionID = AuctionID;
newData.ClaimDate = Util.UnixTimeSinceEpoch();
newData.ClaimPrice = claimprice;
newData.SalePrice = 0;
newData.AuthBuyerID = UUID.Zero;
newData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects);
m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData);
SendLandUpdateToAvatarsOverMe(true);
}
public void DeedToGroup(UUID groupID)
{
LandData newData = LandData.Copy();
newData.OwnerID = groupID;
newData.GroupID = groupID;
newData.IsGroupOwned = true;
m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData);
SendLandUpdateToAvatarsOverMe(true);
}
public bool IsEitherBannedOrRestricted(UUID avatar)
{
if (IsBannedFromLand(avatar))
{
return true;
}
else if (IsRestrictedFromLand(avatar))
{
return true;
}
return false;
}
public bool IsBannedFromLand(UUID avatar)
{
if ((LandData.Flags & (uint) ParcelFlags.UseBanList) > 0)
{
ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry();
entry.AgentID = avatar;
entry.Flags = AccessList.Ban;
entry.Time = new DateTime();
if (LandData.ParcelAccessList.Contains(entry))
{
//They are banned, so lets send them a notice about this parcel
return true;
}
}
return false;
}
public bool IsRestrictedFromLand(UUID avatar)
{
if ((LandData.Flags & (uint) ParcelFlags.UseAccessList) > 0)
{
ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry();
entry.AgentID = avatar;
entry.Flags = AccessList.Access;
entry.Time = new DateTime();
if (!LandData.ParcelAccessList.Contains(entry))
{
//They are not allowed in this parcel, but not banned, so lets send them a notice about this parcel
return true;
}
}
return false;
}
public void SendLandUpdateToClient(IClientAPI remote_client)
{
SendLandProperties(0, false, 0, remote_client);
}
public void SendLandUpdateToClient(bool snap_selection, IClientAPI remote_client)
{
SendLandProperties(0, snap_selection, 0, remote_client);
}
public void SendLandUpdateToAvatarsOverMe()
{
SendLandUpdateToAvatarsOverMe(false);
}
public void SendLandUpdateToAvatarsOverMe(bool snap_selection)
{
List<ScenePresence> avatars = m_scene.GetAvatars();
ILandObject over = null;
for (int i = 0; i < avatars.Count; i++)
{
try
{
over =
m_scene.LandChannel.GetLandObject(Util.Clamp<int>((int)Math.Round(avatars[i].AbsolutePosition.X), 0, ((int)Constants.RegionSize - 1)),
Util.Clamp<int>((int)Math.Round(avatars[i].AbsolutePosition.Y), 0, ((int)Constants.RegionSize - 1)));
}
catch (Exception)
{
m_log.Warn("[LAND]: " + "unable to get land at x: " + Math.Round(avatars[i].AbsolutePosition.X) + " y: " +
Math.Round(avatars[i].AbsolutePosition.Y));
}
if (over != null)
{
if (over.LandData.LocalID == LandData.LocalID)
{
if (((over.LandData.Flags & (uint)ParcelFlags.AllowDamage) != 0) &&
m_scene.RegionInfo.RegionSettings.AllowDamage)
avatars[i].Invulnerable = false;
else
avatars[i].Invulnerable = true;
SendLandUpdateToClient(snap_selection, avatars[i].ControllingClient);
}
}
}
}
#endregion
#region AccessList Functions
public List<UUID> CreateAccessListArrayByFlag(AccessList flag)
{
List<UUID> list = new List<UUID>();
foreach (ParcelManager.ParcelAccessEntry entry in LandData.ParcelAccessList)
{
if (entry.Flags == flag)
{
list.Add(entry.AgentID);
}
}
if (list.Count == 0)
{
list.Add(UUID.Zero);
}
return list;
}
public void SendAccessList(UUID agentID, UUID sessionID, uint flags, int sequenceID,
IClientAPI remote_client)
{
if (flags == (uint) AccessList.Access || flags == (uint) AccessList.Both)
{
List<UUID> avatars = CreateAccessListArrayByFlag(AccessList.Access);
remote_client.SendLandAccessListData(avatars,(uint) AccessList.Access,LandData.LocalID);
}
if (flags == (uint) AccessList.Ban || flags == (uint) AccessList.Both)
{
List<UUID> avatars = CreateAccessListArrayByFlag(AccessList.Ban);
remote_client.SendLandAccessListData(avatars, (uint)AccessList.Ban, LandData.LocalID);
}
}
public void UpdateAccessList(uint flags, List<ParcelManager.ParcelAccessEntry> entries, IClientAPI remote_client)
{
LandData newData = LandData.Copy();
if (entries.Count == 1 && entries[0].AgentID == UUID.Zero)
{
entries.Clear();
}
List<ParcelManager.ParcelAccessEntry> toRemove = new List<ParcelManager.ParcelAccessEntry>();
foreach (ParcelManager.ParcelAccessEntry entry in newData.ParcelAccessList)
{
if (entry.Flags == (AccessList)flags)
{
toRemove.Add(entry);
}
}
foreach (ParcelManager.ParcelAccessEntry entry in toRemove)
{
newData.ParcelAccessList.Remove(entry);
}
foreach (ParcelManager.ParcelAccessEntry entry in entries)
{
ParcelManager.ParcelAccessEntry temp = new ParcelManager.ParcelAccessEntry();
temp.AgentID = entry.AgentID;
temp.Time = new DateTime(); //Pointless? Yes.
temp.Flags = (AccessList)flags;
if (!newData.ParcelAccessList.Contains(temp))
{
newData.ParcelAccessList.Add(temp);
}
}
m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData);
}
#endregion
#region Update Functions
public void UpdateLandBitmapByteArray()
{
LandData.Bitmap = ConvertLandBitmapToBytes();
}
/// <summary>
/// Update all settings in land such as area, bitmap byte array, etc
/// </summary>
public void ForceUpdateLandInfo()
{
UpdateAABBAndAreaValues();
UpdateLandBitmapByteArray();
}
public void SetLandBitmapFromByteArray()
{
LandBitmap = ConvertBytesToLandBitmap();
}
/// <summary>
/// Updates the AABBMin and AABBMax values after area/shape modification of the land object
/// </summary>
private void UpdateAABBAndAreaValues()
{
int min_x = 64;
int min_y = 64;
int max_x = 0;
int max_y = 0;
int tempArea = 0;
int x, y;
for (x = 0; x < 64; x++)
{
for (y = 0; y < 64; y++)
{
if (LandBitmap[x, y] == true)
{
if (min_x > x) min_x = x;
if (min_y > y) min_y = y;
if (max_x < x) max_x = x;
if (max_y < y) max_y = y;
tempArea += 16; //16sqm peice of land
}
}
}
int tx = min_x * 4;
if (tx > ((int)Constants.RegionSize - 1))
tx = ((int)Constants.RegionSize - 1);
int ty = min_y * 4;
if (ty > ((int)Constants.RegionSize - 1))
ty = ((int)Constants.RegionSize - 1);
LandData.AABBMin =
new Vector3((float) (min_x * 4), (float) (min_y * 4),
(float) m_scene.Heightmap[tx, ty]);
tx = max_x * 4;
if (tx > ((int)Constants.RegionSize - 1))
tx = ((int)Constants.RegionSize - 1);
ty = max_y * 4;
if (ty > ((int)Constants.RegionSize - 1))
ty = ((int)Constants.RegionSize - 1);
LandData.AABBMax =
new Vector3((float) (max_x * 4), (float) (max_y * 4),
(float) m_scene.Heightmap[tx, ty]);
LandData.Area = tempArea;
}
#endregion
#region Land Bitmap Functions
/// <summary>
/// Sets the land's bitmap manually
/// </summary>
/// <param name="bitmap">64x64 block representing where this land is on a map</param>
public void SetLandBitmap(bool[,] bitmap)
{
if (bitmap.GetLength(0) != 64 || bitmap.GetLength(1) != 64 || bitmap.Rank != 2)
{
//Throw an exception - The bitmap is not 64x64
//throw new Exception("Error: Invalid Parcel Bitmap");
}
else
{
//Valid: Lets set it
LandBitmap = bitmap;
ForceUpdateLandInfo();
}
}
/// <summary>
/// Gets the land's bitmap manually
/// </summary>
/// <returns></returns>
public bool[,] GetLandBitmap()
{
return LandBitmap;
}
/// <summary>
/// Full sim land object creation
/// </summary>
/// <returns></returns>
public bool[,] BasicFullRegionLandBitmap()
{
return GetSquareLandBitmap(0, 0, (int) Constants.RegionSize, (int) Constants.RegionSize);
}
/// <summary>
/// Used to modify the bitmap between the x and y points. Points use 64 scale
/// </summary>
/// <param name="start_x"></param>
/// <param name="start_y"></param>
/// <param name="end_x"></param>
/// <param name="end_y"></param>
/// <returns></returns>
public bool[,] GetSquareLandBitmap(int start_x, int start_y, int end_x, int end_y)
{
bool[,] tempBitmap = new bool[64,64];
tempBitmap.Initialize();
tempBitmap = ModifyLandBitmapSquare(tempBitmap, start_x, start_y, end_x, end_y, true);
return tempBitmap;
}
/// <summary>
/// Change a land bitmap at within a square and set those points to a specific value
/// </summary>
/// <param name="land_bitmap"></param>
/// <param name="start_x"></param>
/// <param name="start_y"></param>
/// <param name="end_x"></param>
/// <param name="end_y"></param>
/// <param name="set_value"></param>
/// <returns></returns>
public bool[,] ModifyLandBitmapSquare(bool[,] land_bitmap, int start_x, int start_y, int end_x, int end_y,
bool set_value)
{
if (land_bitmap.GetLength(0) != 64 || land_bitmap.GetLength(1) != 64 || land_bitmap.Rank != 2)
{
//Throw an exception - The bitmap is not 64x64
//throw new Exception("Error: Invalid Parcel Bitmap in modifyLandBitmapSquare()");
}
int x, y;
for (y = 0; y < 64; y++)
{
for (x = 0; x < 64; x++)
{
if (x >= start_x / 4 && x < end_x / 4
&& y >= start_y / 4 && y < end_y / 4)
{
land_bitmap[x, y] = set_value;
}
}
}
return land_bitmap;
}
/// <summary>
/// Join the true values of 2 bitmaps together
/// </summary>
/// <param name="bitmap_base"></param>
/// <param name="bitmap_add"></param>
/// <returns></returns>
public bool[,] MergeLandBitmaps(bool[,] bitmap_base, bool[,] bitmap_add)
{
if (bitmap_base.GetLength(0) != 64 || bitmap_base.GetLength(1) != 64 || bitmap_base.Rank != 2)
{
//Throw an exception - The bitmap is not 64x64
throw new Exception("Error: Invalid Parcel Bitmap - Bitmap_base in mergeLandBitmaps");
}
if (bitmap_add.GetLength(0) != 64 || bitmap_add.GetLength(1) != 64 || bitmap_add.Rank != 2)
{
//Throw an exception - The bitmap is not 64x64
throw new Exception("Error: Invalid Parcel Bitmap - Bitmap_add in mergeLandBitmaps");
}
int x, y;
for (y = 0; y < 64; y++)
{
for (x = 0; x < 64; x++)
{
if (bitmap_add[x, y])
{
bitmap_base[x, y] = true;
}
}
}
return bitmap_base;
}
/// <summary>
/// Converts the land bitmap to a packet friendly byte array
/// </summary>
/// <returns></returns>
private byte[] ConvertLandBitmapToBytes()
{
byte[] tempConvertArr = new byte[512];
byte tempByte = 0;
int x, y, i, byteNum = 0;
i = 0;
for (y = 0; y < 64; y++)
{
for (x = 0; x < 64; x++)
{
tempByte = Convert.ToByte(tempByte | Convert.ToByte(LandBitmap[x, y]) << (i++ % 8));
if (i % 8 == 0)
{
tempConvertArr[byteNum] = tempByte;
tempByte = (byte) 0;
i = 0;
byteNum++;
}
}
}
return tempConvertArr;
}
private bool[,] ConvertBytesToLandBitmap()
{
bool[,] tempConvertMap = new bool[landArrayMax, landArrayMax];
tempConvertMap.Initialize();
byte tempByte = 0;
int x = 0, y = 0, i = 0, bitNum = 0;
for (i = 0; i < 512; i++)
{
tempByte = LandData.Bitmap[i];
for (bitNum = 0; bitNum < 8; bitNum++)
{
bool bit = Convert.ToBoolean(Convert.ToByte(tempByte >> bitNum) & (byte) 1);
tempConvertMap[x, y] = bit;
x++;
if (x > 63)
{
x = 0;
y++;
}
}
}
return tempConvertMap;
}
#endregion
#region Object Select and Object Owner Listing
public void SendForceObjectSelect(int local_id, int request_type, List<UUID> returnIDs, IClientAPI remote_client)
{
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId, this))
{
List<uint> resultLocalIDs = new List<uint>();
try
{
lock (primsOverMe)
{
foreach (SceneObjectGroup obj in primsOverMe)
{
if (obj.LocalId > 0)
{
if (request_type == LandChannel.LAND_SELECT_OBJECTS_OWNER && obj.OwnerID == LandData.OwnerID)
{
resultLocalIDs.Add(obj.LocalId);
}
else if (request_type == LandChannel.LAND_SELECT_OBJECTS_GROUP && obj.GroupID == LandData.GroupID && LandData.GroupID != UUID.Zero)
{
resultLocalIDs.Add(obj.LocalId);
}
else if (request_type == LandChannel.LAND_SELECT_OBJECTS_OTHER &&
obj.OwnerID != remote_client.AgentId)
{
resultLocalIDs.Add(obj.LocalId);
}
else if (request_type == (int)ObjectReturnType.List && returnIDs.Contains(obj.OwnerID))
{
resultLocalIDs.Add(obj.LocalId);
}
}
}
}
} catch (InvalidOperationException)
{
m_log.Error("[LAND]: Unable to force select the parcel objects. Arr.");
}
remote_client.SendForceClientSelectObjects(resultLocalIDs);
}
}
/// <summary>
/// Notify the parcel owner each avatar that owns prims situated on their land. This notification includes
/// aggreagete details such as the number of prims.
///
/// </summary>
/// <param name="remote_client">
/// A <see cref="IClientAPI"/>
/// </param>
public void SendLandObjectOwners(IClientAPI remote_client)
{
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId, this))
{
Dictionary<UUID, int> primCount = new Dictionary<UUID, int>();
List<UUID> groups = new List<UUID>();
lock (primsOverMe)
{
try
{
foreach (SceneObjectGroup obj in primsOverMe)
{
try
{
if (!primCount.ContainsKey(obj.OwnerID))
{
primCount.Add(obj.OwnerID, 0);
}
}
catch (NullReferenceException)
{
m_log.Info("[LAND]: " + "Got Null Reference when searching land owners from the parcel panel");
}
try
{
primCount[obj.OwnerID] += obj.PrimCount;
}
catch (KeyNotFoundException)
{
m_log.Error("[LAND]: Unable to match a prim with it's owner.");
}
if (obj.OwnerID == obj.GroupID && (!groups.Contains(obj.OwnerID)))
groups.Add(obj.OwnerID);
}
}
catch (InvalidOperationException)
{
m_log.Error("[LAND]: Unable to Enumerate Land object arr.");
}
}
remote_client.SendLandObjectOwners(LandData, groups, primCount);
}
}
public Dictionary<UUID, int> GetLandObjectOwners()
{
Dictionary<UUID, int> ownersAndCount = new Dictionary<UUID, int>();
lock (primsOverMe)
{
try
{
foreach (SceneObjectGroup obj in primsOverMe)
{
if (!ownersAndCount.ContainsKey(obj.OwnerID))
{
ownersAndCount.Add(obj.OwnerID, 0);
}
ownersAndCount[obj.OwnerID] += obj.PrimCount;
}
}
catch (InvalidOperationException)
{
m_log.Error("[LAND]: Unable to enumerate land owners. arr.");
}
}
return ownersAndCount;
}
#endregion
#region Object Returning
public void ReturnObject(SceneObjectGroup obj)
{
SceneObjectGroup[] objs = new SceneObjectGroup[1];
objs[0] = obj;
m_scene.returnObjects(objs, obj.OwnerID);
}
public void ReturnLandObjects(uint type, UUID[] owners, UUID[] tasks, IClientAPI remote_client)
{
Dictionary<UUID,List<SceneObjectGroup>> returns =
new Dictionary<UUID,List<SceneObjectGroup>>();
lock (primsOverMe)
{
if (type == (uint)ObjectReturnType.Owner)
{
foreach (SceneObjectGroup obj in primsOverMe)
{
if (obj.OwnerID == m_landData.OwnerID)
{
if (!returns.ContainsKey(obj.OwnerID))
returns[obj.OwnerID] =
new List<SceneObjectGroup>();
returns[obj.OwnerID].Add(obj);
}
}
}
else if (type == (uint)ObjectReturnType.Group && m_landData.GroupID != UUID.Zero)
{
foreach (SceneObjectGroup obj in primsOverMe)
{
if (obj.GroupID == m_landData.GroupID)
{
if (!returns.ContainsKey(obj.OwnerID))
returns[obj.OwnerID] =
new List<SceneObjectGroup>();
returns[obj.OwnerID].Add(obj);
}
}
}
else if (type == (uint)ObjectReturnType.Other)
{
foreach (SceneObjectGroup obj in primsOverMe)
{
if (obj.OwnerID != m_landData.OwnerID &&
(obj.GroupID != m_landData.GroupID ||
m_landData.GroupID == UUID.Zero))
{
if (!returns.ContainsKey(obj.OwnerID))
returns[obj.OwnerID] =
new List<SceneObjectGroup>();
returns[obj.OwnerID].Add(obj);
}
}
}
else if (type == (uint)ObjectReturnType.List)
{
List<UUID> ownerlist = new List<UUID>(owners);
foreach (SceneObjectGroup obj in primsOverMe)
{
if (ownerlist.Contains(obj.OwnerID))
{
if (!returns.ContainsKey(obj.OwnerID))
returns[obj.OwnerID] =
new List<SceneObjectGroup>();
returns[obj.OwnerID].Add(obj);
}
}
}
}
foreach (List<SceneObjectGroup> ol in returns.Values)
{
if (m_scene.Permissions.CanUseObjectReturn(this, type, remote_client, ol))
m_scene.returnObjects(ol.ToArray(), remote_client.AgentId);
}
}
#endregion
#region Object Adding/Removing from Parcel
public void ResetLandPrimCounts()
{
LandData.GroupPrims = 0;
LandData.OwnerPrims = 0;
LandData.OtherPrims = 0;
LandData.SelectedPrims = 0;
lock (primsOverMe)
primsOverMe.Clear();
}
public void AddPrimToCount(SceneObjectGroup obj)
{
UUID prim_owner = obj.OwnerID;
int prim_count = obj.PrimCount;
if (obj.IsSelected)
{
LandData.SelectedPrims += prim_count;
}
else
{
if (prim_owner == LandData.OwnerID)
{
LandData.OwnerPrims += prim_count;
}
else if ((obj.GroupID == LandData.GroupID ||
prim_owner == LandData.GroupID) &&
LandData.GroupID != UUID.Zero)
{
LandData.GroupPrims += prim_count;
}
else
{
LandData.OtherPrims += prim_count;
}
}
lock (primsOverMe)
primsOverMe.Add(obj);
}
public void RemovePrimFromCount(SceneObjectGroup obj)
{
lock (primsOverMe)
{
if (primsOverMe.Contains(obj))
{
UUID prim_owner = obj.OwnerID;
int prim_count = obj.PrimCount;
if (prim_owner == LandData.OwnerID)
{
LandData.OwnerPrims -= prim_count;
}
else if (obj.GroupID == LandData.GroupID ||
prim_owner == LandData.GroupID)
{
LandData.GroupPrims -= prim_count;
}
else
{
LandData.OtherPrims -= prim_count;
}
primsOverMe.Remove(obj);
}
}
}
#endregion
#endregion
#endregion
/// <summary>
/// Set the media url for this land parcel
/// </summary>
/// <param name="url"></param>
public void SetMediaUrl(string url)
{
LandData.MediaURL = url;
SendLandUpdateToAvatarsOverMe();
}
/// <summary>
/// Set the music url for this land parcel
/// </summary>
/// <param name="url"></param>
public void SetMusicUrl(string url)
{
LandData.MusicURL = url;
SendLandUpdateToAvatarsOverMe();
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Extensions;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Database;
using Realms;
#nullable enable
namespace osu.Game.Tests.Database
{
public class RealmLiveTests : RealmTest
{
[Test]
public void TestLiveEquality()
{
RunTestWithRealm((realm, _) =>
{
Live<BeatmapInfo> beatmap = realm.Run(r => r.Write(_ => r.Add(new BeatmapInfo(CreateRuleset(), new BeatmapDifficulty(), new BeatmapMetadata()))).ToLive(realm));
Live<BeatmapInfo> beatmap2 = realm.Run(r => r.All<BeatmapInfo>().First().ToLive(realm));
Assert.AreEqual(beatmap, beatmap2);
});
}
[Test]
public void TestAccessAfterStorageMigrate()
{
RunTestWithRealm((realm, storage) =>
{
var beatmap = new BeatmapInfo(CreateRuleset(), new BeatmapDifficulty(), new BeatmapMetadata());
Live<BeatmapInfo>? liveBeatmap = null;
realm.Run(r =>
{
r.Write(_ => r.Add(beatmap));
liveBeatmap = beatmap.ToLive(realm);
});
using (var migratedStorage = new TemporaryNativeStorage("realm-test-migration-target"))
{
migratedStorage.DeleteDirectory(string.Empty);
using (realm.BlockAllOperations())
{
storage.Migrate(migratedStorage);
}
Assert.IsFalse(liveBeatmap?.PerformRead(l => l.Hidden));
}
});
}
[Test]
public void TestAccessAfterAttach()
{
RunTestWithRealm((realm, _) =>
{
var beatmap = new BeatmapInfo(CreateRuleset(), new BeatmapDifficulty(), new BeatmapMetadata());
var liveBeatmap = beatmap.ToLive(realm);
realm.Run(r => r.Write(_ => r.Add(beatmap)));
Assert.IsFalse(liveBeatmap.PerformRead(l => l.Hidden));
});
}
[Test]
public void TestAccessNonManaged()
{
var beatmap = new BeatmapInfo(CreateRuleset(), new BeatmapDifficulty(), new BeatmapMetadata());
var liveBeatmap = beatmap.ToLiveUnmanaged();
Assert.IsFalse(beatmap.Hidden);
Assert.IsFalse(liveBeatmap.Value.Hidden);
Assert.IsFalse(liveBeatmap.PerformRead(l => l.Hidden));
Assert.Throws<InvalidOperationException>(() => liveBeatmap.PerformWrite(l => l.Hidden = true));
Assert.IsFalse(beatmap.Hidden);
Assert.IsFalse(liveBeatmap.Value.Hidden);
Assert.IsFalse(liveBeatmap.PerformRead(l => l.Hidden));
}
[Test]
public void TestScopedReadWithoutContext()
{
RunTestWithRealm((realm, _) =>
{
Live<BeatmapInfo>? liveBeatmap = null;
Task.Factory.StartNew(() =>
{
realm.Run(threadContext =>
{
var beatmap = threadContext.Write(r => r.Add(new BeatmapInfo(CreateRuleset(), new BeatmapDifficulty(), new BeatmapMetadata())));
liveBeatmap = beatmap.ToLive(realm);
});
}, TaskCreationOptions.LongRunning | TaskCreationOptions.HideScheduler).WaitSafely();
Debug.Assert(liveBeatmap != null);
Task.Factory.StartNew(() =>
{
liveBeatmap.PerformRead(beatmap =>
{
Assert.IsTrue(beatmap.IsValid);
Assert.IsFalse(beatmap.Hidden);
});
}, TaskCreationOptions.LongRunning | TaskCreationOptions.HideScheduler).WaitSafely();
});
}
[Test]
public void TestScopedWriteWithoutContext()
{
RunTestWithRealm((realm, _) =>
{
Live<BeatmapInfo>? liveBeatmap = null;
Task.Factory.StartNew(() =>
{
realm.Run(threadContext =>
{
var beatmap = threadContext.Write(r => r.Add(new BeatmapInfo(CreateRuleset(), new BeatmapDifficulty(), new BeatmapMetadata())));
liveBeatmap = beatmap.ToLive(realm);
});
}, TaskCreationOptions.LongRunning | TaskCreationOptions.HideScheduler).WaitSafely();
Debug.Assert(liveBeatmap != null);
Task.Factory.StartNew(() =>
{
liveBeatmap.PerformWrite(beatmap => { beatmap.Hidden = true; });
liveBeatmap.PerformRead(beatmap => { Assert.IsTrue(beatmap.Hidden); });
}, TaskCreationOptions.LongRunning | TaskCreationOptions.HideScheduler).WaitSafely();
});
}
[Test]
public void TestValueAccessNonManaged()
{
RunTestWithRealm((realm, _) =>
{
var beatmap = new BeatmapInfo(CreateRuleset(), new BeatmapDifficulty(), new BeatmapMetadata());
var liveBeatmap = beatmap.ToLive(realm);
Assert.DoesNotThrow(() =>
{
var __ = liveBeatmap.Value;
});
});
}
[Test]
public void TestValueAccessWithOpenContextFails()
{
RunTestWithRealm((realm, _) =>
{
Live<BeatmapInfo>? liveBeatmap = null;
Task.Factory.StartNew(() =>
{
realm.Run(threadContext =>
{
var beatmap = threadContext.Write(r => r.Add(new BeatmapInfo(CreateRuleset(), new BeatmapDifficulty(), new BeatmapMetadata())));
liveBeatmap = beatmap.ToLive(realm);
});
}, TaskCreationOptions.LongRunning | TaskCreationOptions.HideScheduler).WaitSafely();
Debug.Assert(liveBeatmap != null);
Task.Factory.StartNew(() =>
{
// Can't be used, without a valid context.
Assert.Throws<InvalidOperationException>(() =>
{
var __ = liveBeatmap.Value;
});
// Can't be used, even from within a valid context.
realm.Run(threadContext =>
{
Assert.Throws<InvalidOperationException>(() =>
{
var __ = liveBeatmap.Value;
});
});
}, TaskCreationOptions.LongRunning | TaskCreationOptions.HideScheduler).WaitSafely();
});
}
[Test]
public void TestValueAccessWithoutOpenContextFails()
{
RunTestWithRealm((realm, _) =>
{
Live<BeatmapInfo>? liveBeatmap = null;
Task.Factory.StartNew(() =>
{
realm.Run(threadContext =>
{
var beatmap = threadContext.Write(r => r.Add(new BeatmapInfo(CreateRuleset(), new BeatmapDifficulty(), new BeatmapMetadata())));
liveBeatmap = beatmap.ToLive(realm);
});
}, TaskCreationOptions.LongRunning | TaskCreationOptions.HideScheduler).WaitSafely();
Debug.Assert(liveBeatmap != null);
Task.Factory.StartNew(() =>
{
Assert.Throws<InvalidOperationException>(() =>
{
var unused = liveBeatmap.Value;
});
}, TaskCreationOptions.LongRunning | TaskCreationOptions.HideScheduler).WaitSafely();
});
}
[Test]
public void TestLiveAssumptions()
{
RunTestWithRealm((realm, _) =>
{
int changesTriggered = 0;
realm.RegisterCustomSubscription(outerRealm =>
{
outerRealm.All<BeatmapInfo>().QueryAsyncWithNotifications(gotChange);
Live<BeatmapInfo>? liveBeatmap = null;
Task.Factory.StartNew(() =>
{
realm.Run(innerRealm =>
{
var ruleset = CreateRuleset();
var beatmap = innerRealm.Write(r => r.Add(new BeatmapInfo(ruleset, new BeatmapDifficulty(), new BeatmapMetadata())));
// add a second beatmap to ensure that a full refresh occurs below.
// not just a refresh from the resolved Live.
innerRealm.Write(r => r.Add(new BeatmapInfo(ruleset, new BeatmapDifficulty(), new BeatmapMetadata())));
liveBeatmap = beatmap.ToLive(realm);
});
}, TaskCreationOptions.LongRunning | TaskCreationOptions.HideScheduler).WaitSafely();
Debug.Assert(liveBeatmap != null);
// not yet seen by main context
Assert.AreEqual(0, outerRealm.All<BeatmapInfo>().Count());
Assert.AreEqual(0, changesTriggered);
liveBeatmap.PerformRead(resolved =>
{
// retrieval causes an implicit refresh. even changes that aren't related to the retrieval are fired at this point.
// ReSharper disable once AccessToDisposedClosure
Assert.AreEqual(2, outerRealm.All<BeatmapInfo>().Count());
Assert.AreEqual(1, changesTriggered);
// can access properties without a crash.
Assert.IsFalse(resolved.Hidden);
// ReSharper disable once AccessToDisposedClosure
outerRealm.Write(r =>
{
// can use with the main context.
r.Remove(resolved);
});
});
return null;
});
void gotChange(IRealmCollection<BeatmapInfo> sender, ChangeSet changes, Exception error)
{
changesTriggered++;
}
});
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
namespace Ctrip.Log4.Core
{
/// <summary>
/// Defines the default set of levels recognized by the system.
/// </summary>
/// <remarks>
/// <para>
/// Each <see cref="LoggingEvent"/> has an associated <see cref="Level"/>.
/// </para>
/// <para>
/// Levels have a numeric <see cref="Level.Value"/> that defines the relative
/// ordering between levels. Two Levels with the same <see cref="Level.Value"/>
/// are deemed to be equivalent.
/// </para>
/// <para>
/// The levels that are recognized by Ctrip are set for each <see cref="Ctrip.Log4.Repository.ILoggerRepository"/>
/// and each repository can have different levels defined. The levels are stored
/// in the <see cref="Ctrip.Log4.Repository.ILoggerRepository.LevelMap"/> on the repository. Levels are
/// looked up by name from the <see cref="Ctrip.Log4.Repository.ILoggerRepository.LevelMap"/>.
/// </para>
/// <para>
/// When logging at level INFO the actual level used is not <see cref="Level.Info"/> but
/// the value of <c>LoggerRepository.LevelMap["INFO"]</c>. The default value for this is
/// <see cref="Level.Info"/>, but this can be changed by reconfiguring the level map.
/// </para>
/// <para>
/// Each level has a <see cref="DisplayName"/> in addition to its <see cref="Name"/>. The
/// <see cref="DisplayName"/> is the string that is written into the output log. By default
/// the display name is the same as the level name, but this can be used to alias levels
/// or to localize the log output.
/// </para>
/// <para>
/// Some of the predefined levels recognized by the system are:
/// </para>
/// <list type="bullet">
/// <item>
/// <description><see cref="Off"/>.</description>
/// </item>
/// <item>
/// <description><see cref="Fatal"/>.</description>
/// </item>
/// <item>
/// <description><see cref="Error"/>.</description>
/// </item>
/// <item>
/// <description><see cref="Warn"/>.</description>
/// </item>
/// <item>
/// <description><see cref="Info"/>.</description>
/// </item>
/// <item>
/// <description><see cref="Debug"/>.</description>
/// </item>
/// <item>
/// <description><see cref="All"/>.</description>
/// </item>
/// </list>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
#if !NETCF
[Serializable]
#endif
sealed public class Level : IComparable
{
#region Public Instance Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="level">Integer value for this level, higher values represent more severe levels.</param>
/// <param name="levelName">The string name of this level.</param>
/// <param name="displayName">The display name for this level. This may be localized or otherwise different from the name</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="Level" /> class with
/// the specified level name and value.
/// </para>
/// </remarks>
public Level(int level, string levelName, string displayName)
{
if (levelName == null)
{
throw new ArgumentNullException("levelName");
}
if (displayName == null)
{
throw new ArgumentNullException("displayName");
}
m_levelValue = level;
m_levelName = string.Intern(levelName);
m_levelDisplayName = displayName;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="level">Integer value for this level, higher values represent more severe levels.</param>
/// <param name="levelName">The string name of this level.</param>
/// <remarks>
/// <para>
/// Initializes a new instance of the <see cref="Level" /> class with
/// the specified level name and value.
/// </para>
/// </remarks>
public Level(int level, string levelName) : this(level, levelName, levelName)
{
}
#endregion Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets the name of this level.
/// </summary>
/// <value>
/// The name of this level.
/// </value>
/// <remarks>
/// <para>
/// Gets the name of this level.
/// </para>
/// </remarks>
public string Name
{
get { return m_levelName; }
}
/// <summary>
/// Gets the value of this level.
/// </summary>
/// <value>
/// The value of this level.
/// </value>
/// <remarks>
/// <para>
/// Gets the value of this level.
/// </para>
/// </remarks>
public int Value
{
get { return m_levelValue; }
}
/// <summary>
/// Gets the display name of this level.
/// </summary>
/// <value>
/// The display name of this level.
/// </value>
/// <remarks>
/// <para>
/// Gets the display name of this level.
/// </para>
/// </remarks>
public string DisplayName
{
get { return m_levelDisplayName; }
}
#endregion Public Instance Properties
#region Override implementation of Object
/// <summary>
/// Returns the <see cref="string" /> representation of the current
/// <see cref="Level" />.
/// </summary>
/// <returns>
/// A <see cref="string" /> representation of the current <see cref="Level" />.
/// </returns>
/// <remarks>
/// <para>
/// Returns the level <see cref="Name"/>.
/// </para>
/// </remarks>
override public string ToString()
{
return m_levelName;
}
/// <summary>
/// Compares levels.
/// </summary>
/// <param name="o">The object to compare against.</param>
/// <returns><c>true</c> if the objects are equal.</returns>
/// <remarks>
/// <para>
/// Compares the levels of <see cref="Level" /> instances, and
/// defers to base class if the target object is not a <see cref="Level" />
/// instance.
/// </para>
/// </remarks>
override public bool Equals(object o)
{
Level otherLevel = o as Level;
if (otherLevel != null)
{
return m_levelValue == otherLevel.m_levelValue;
}
else
{
return base.Equals(o);
}
}
/// <summary>
/// Returns a hash code
/// </summary>
/// <returns>A hash code for the current <see cref="Level" />.</returns>
/// <remarks>
/// <para>
/// Returns a hash code suitable for use in hashing algorithms and data
/// structures like a hash table.
/// </para>
/// <para>
/// Returns the hash code of the level <see cref="Value"/>.
/// </para>
/// </remarks>
override public int GetHashCode()
{
return m_levelValue;
}
#endregion Override implementation of Object
#region Implementation of IComparable
/// <summary>
/// Compares this instance to a specified object and returns an
/// indication of their relative values.
/// </summary>
/// <param name="r">A <see cref="Level"/> instance or <see langword="null" /> to compare with this instance.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the
/// values compared. The return value has these meanings:
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <description>Meaning</description>
/// </listheader>
/// <item>
/// <term>Less than zero</term>
/// <description>This instance is less than <paramref name="r" />.</description>
/// </item>
/// <item>
/// <term>Zero</term>
/// <description>This instance is equal to <paramref name="r" />.</description>
/// </item>
/// <item>
/// <term>Greater than zero</term>
/// <description>
/// <para>This instance is greater than <paramref name="r" />.</para>
/// <para>-or-</para>
/// <para><paramref name="r" /> is <see langword="null" />.</para>
/// </description>
/// </item>
/// </list>
/// </returns>
/// <remarks>
/// <para>
/// <paramref name="r" /> must be an instance of <see cref="Level" />
/// or <see langword="null" />; otherwise, an exception is thrown.
/// </para>
/// </remarks>
/// <exception cref="ArgumentException"><paramref name="r" /> is not a <see cref="Level" />.</exception>
public int CompareTo(object r)
{
Level target = r as Level;
if (target != null)
{
return Compare(this, target);
}
throw new ArgumentException("Parameter: r, Value: [" + r + "] is not an instance of Level");
}
#endregion Implementation of IComparable
#region Operators
/// <summary>
/// Returns a value indicating whether a specified <see cref="Level" />
/// is greater than another specified <see cref="Level" />.
/// </summary>
/// <param name="l">A <see cref="Level" /></param>
/// <param name="r">A <see cref="Level" /></param>
/// <returns>
/// <c>true</c> if <paramref name="l" /> is greater than
/// <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator > (Level l, Level r)
{
return l.m_levelValue > r.m_levelValue;
}
/// <summary>
/// Returns a value indicating whether a specified <see cref="Level" />
/// is less than another specified <see cref="Level" />.
/// </summary>
/// <param name="l">A <see cref="Level" /></param>
/// <param name="r">A <see cref="Level" /></param>
/// <returns>
/// <c>true</c> if <paramref name="l" /> is less than
/// <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator < (Level l, Level r)
{
return l.m_levelValue < r.m_levelValue;
}
/// <summary>
/// Returns a value indicating whether a specified <see cref="Level" />
/// is greater than or equal to another specified <see cref="Level" />.
/// </summary>
/// <param name="l">A <see cref="Level" /></param>
/// <param name="r">A <see cref="Level" /></param>
/// <returns>
/// <c>true</c> if <paramref name="l" /> is greater than or equal to
/// <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator >= (Level l, Level r)
{
return l.m_levelValue >= r.m_levelValue;
}
/// <summary>
/// Returns a value indicating whether a specified <see cref="Level" />
/// is less than or equal to another specified <see cref="Level" />.
/// </summary>
/// <param name="l">A <see cref="Level" /></param>
/// <param name="r">A <see cref="Level" /></param>
/// <returns>
/// <c>true</c> if <paramref name="l" /> is less than or equal to
/// <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator <= (Level l, Level r)
{
return l.m_levelValue <= r.m_levelValue;
}
/// <summary>
/// Returns a value indicating whether two specified <see cref="Level" />
/// objects have the same value.
/// </summary>
/// <param name="l">A <see cref="Level" /> or <see langword="null" />.</param>
/// <param name="r">A <see cref="Level" /> or <see langword="null" />.</param>
/// <returns>
/// <c>true</c> if the value of <paramref name="l" /> is the same as the
/// value of <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator == (Level l, Level r)
{
if (((object)l) != null && ((object)r) != null)
{
return l.m_levelValue == r.m_levelValue;
}
else
{
return ((object) l) == ((object) r);
}
}
/// <summary>
/// Returns a value indicating whether two specified <see cref="Level" />
/// objects have different values.
/// </summary>
/// <param name="l">A <see cref="Level" /> or <see langword="null" />.</param>
/// <param name="r">A <see cref="Level" /> or <see langword="null" />.</param>
/// <returns>
/// <c>true</c> if the value of <paramref name="l" /> is different from
/// the value of <paramref name="r" />; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static bool operator != (Level l, Level r)
{
return !(l==r);
}
#endregion Operators
#region Public Static Methods
/// <summary>
/// Compares two specified <see cref="Level"/> instances.
/// </summary>
/// <param name="l">The first <see cref="Level"/> to compare.</param>
/// <param name="r">The second <see cref="Level"/> to compare.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the
/// two values compared. The return value has these meanings:
/// <list type="table">
/// <listheader>
/// <term>Value</term>
/// <description>Meaning</description>
/// </listheader>
/// <item>
/// <term>Less than zero</term>
/// <description><paramref name="l" /> is less than <paramref name="r" />.</description>
/// </item>
/// <item>
/// <term>Zero</term>
/// <description><paramref name="l" /> is equal to <paramref name="r" />.</description>
/// </item>
/// <item>
/// <term>Greater than zero</term>
/// <description><paramref name="l" /> is greater than <paramref name="r" />.</description>
/// </item>
/// </list>
/// </returns>
/// <remarks>
/// <para>
/// Compares two levels.
/// </para>
/// </remarks>
public static int Compare(Level l, Level r)
{
// Reference equals
if ((object)l == (object)r)
{
return 0;
}
if (l == null && r == null)
{
return 0;
}
if (l == null)
{
return -1;
}
if (r == null)
{
return 1;
}
return l.m_levelValue.CompareTo(r.m_levelValue);
}
#endregion Public Static Methods
#region Public Static Fields
/// <summary>
/// The <see cref="Off" /> level designates a higher level than all the rest.
/// </summary>
public readonly static Level Off = new Level(int.MaxValue, "OFF");
/// <summary>
/// The <see cref="Emergency" /> level designates very severe error events.
/// System unusable, emergencies.
/// </summary>
public readonly static Level Log4Net_Debug = new Level(120000, "Ctrip:DEBUG");
/// <summary>
/// The <see cref="Emergency" /> level designates very severe error events.
/// System unusable, emergencies.
/// </summary>
public readonly static Level Emergency = new Level(120000, "EMERGENCY");
/// <summary>
/// The <see cref="Fatal" /> level designates very severe error events
/// that will presumably lead the application to abort.
/// </summary>
public readonly static Level Fatal = new Level(110000, "FATAL");
/// <summary>
/// The <see cref="Alert" /> level designates very severe error events.
/// Take immediate action, alerts.
/// </summary>
public readonly static Level Alert = new Level(100000, "ALERT");
/// <summary>
/// The <see cref="Critical" /> level designates very severe error events.
/// Critical condition, critical.
/// </summary>
public readonly static Level Critical = new Level(90000, "CRITICAL");
/// <summary>
/// The <see cref="Severe" /> level designates very severe error events.
/// </summary>
public readonly static Level Severe = new Level(80000, "SEVERE");
/// <summary>
/// The <see cref="Error" /> level designates error events that might
/// still allow the application to continue running.
/// </summary>
public readonly static Level Error = new Level(70000, "ERROR");
/// <summary>
/// The <see cref="Warn" /> level designates potentially harmful
/// situations.
/// </summary>
public readonly static Level Warn = new Level(60000, "WARN");
/// <summary>
/// The <see cref="Notice" /> level designates informational messages
/// that highlight the progress of the application at the highest level.
/// </summary>
public readonly static Level Notice = new Level(50000, "NOTICE");
/// <summary>
/// The <see cref="Info" /> level designates informational messages that
/// highlight the progress of the application at coarse-grained level.
/// </summary>
public readonly static Level Info = new Level(40000, "INFO");
/// <summary>
/// The <see cref="Debug" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Debug = new Level(30000, "DEBUG");
/// <summary>
/// The <see cref="Fine" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Fine = new Level(30000, "FINE");
/// <summary>
/// The <see cref="Trace" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Trace = new Level(20000, "TRACE");
/// <summary>
/// The <see cref="Finer" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Finer = new Level(20000, "FINER");
/// <summary>
/// The <see cref="Verbose" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Verbose = new Level(10000, "VERBOSE");
/// <summary>
/// The <see cref="Finest" /> level designates fine-grained informational
/// events that are most useful to debug an application.
/// </summary>
public readonly static Level Finest = new Level(10000, "FINEST");
/// <summary>
/// The <see cref="All" /> level designates the lowest level possible.
/// </summary>
public readonly static Level All = new Level(int.MinValue, "ALL");
#endregion Public Static Fields
#region Private Instance Fields
private readonly int m_levelValue;
private readonly string m_levelName;
private readonly string m_levelDisplayName;
#endregion Private Instance Fields
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Localisation;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Screens.Play.HUD;
using osu.Game.Screens.Ranking.Expanded.Accuracy;
using osu.Game.Screens.Ranking.Expanded.Statistics;
using osuTK;
namespace osu.Game.Screens.Ranking.Expanded
{
/// <summary>
/// The content that appears in the middle section of the <see cref="ScorePanel"/>.
/// </summary>
public class ExpandedPanelMiddleContent : CompositeDrawable
{
private const float padding = 10;
private readonly ScoreInfo score;
private readonly bool withFlair;
private readonly List<StatisticDisplay> statisticDisplays = new List<StatisticDisplay>();
private FillFlowContainer starAndModDisplay;
private RollingCounter<long> scoreCounter;
[Resolved]
private ScoreManager scoreManager { get; set; }
/// <summary>
/// Creates a new <see cref="ExpandedPanelMiddleContent"/>.
/// </summary>
/// <param name="score">The score to display.</param>
/// <param name="withFlair">Whether to add flair for a new score being set.</param>
public ExpandedPanelMiddleContent(ScoreInfo score, bool withFlair = false)
{
this.score = score;
this.withFlair = withFlair;
RelativeSizeAxes = Axes.Both;
Masking = true;
Padding = new MarginPadding(padding);
}
[BackgroundDependencyLoader]
private void load(BeatmapDifficultyCache beatmapDifficultyCache)
{
var beatmap = score.Beatmap;
var metadata = beatmap.BeatmapSet?.Metadata ?? beatmap.Metadata;
var creator = metadata.Author?.Username;
var topStatistics = new List<StatisticDisplay>
{
new AccuracyStatistic(score.Accuracy),
new ComboStatistic(score.MaxCombo, !score.Statistics.TryGetValue(HitResult.Miss, out var missCount) || missCount == 0),
new PerformanceStatistic(score),
};
var bottomStatistics = new List<HitResultStatistic>();
foreach (var result in score.GetStatisticsForDisplay())
bottomStatistics.Add(new HitResultStatistic(result));
statisticDisplays.AddRange(topStatistics);
statisticDisplays.AddRange(bottomStatistics);
var starDifficulty = beatmapDifficultyCache.GetDifficultyAsync(beatmap, score.Ruleset, score.Mods).Result;
InternalChildren = new Drawable[]
{
new FillFlowContainer
{
RelativeSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Spacing = new Vector2(20),
Children = new Drawable[]
{
new FillFlowContainer
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new OsuSpriteText
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Text = new RomanisableString(metadata.TitleUnicode, metadata.Title),
Font = OsuFont.Torus.With(size: 20, weight: FontWeight.SemiBold),
MaxWidth = ScorePanel.EXPANDED_WIDTH - padding * 2,
Truncate = true,
},
new OsuSpriteText
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Text = new RomanisableString(metadata.ArtistUnicode, metadata.Artist),
Font = OsuFont.Torus.With(size: 14, weight: FontWeight.SemiBold),
MaxWidth = ScorePanel.EXPANDED_WIDTH - padding * 2,
Truncate = true,
},
new Container
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Margin = new MarginPadding { Top = 40 },
RelativeSizeAxes = Axes.X,
Height = 230,
Child = new AccuracyCircle(score, withFlair)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fit,
}
},
scoreCounter = new TotalScoreCounter
{
Margin = new MarginPadding { Top = 0, Bottom = 5 },
Current = { Value = 0 },
Alpha = 0,
AlwaysPresent = true
},
starAndModDisplay = new FillFlowContainer
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
AutoSizeAxes = Axes.Both,
Spacing = new Vector2(5, 0),
Children = new Drawable[]
{
new StarRatingDisplay(starDifficulty)
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft
},
}
},
new FillFlowContainer
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Direction = FillDirection.Vertical,
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new OsuSpriteText
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Text = beatmap.Version,
Font = OsuFont.Torus.With(size: 16, weight: FontWeight.SemiBold),
},
new OsuTextFlowContainer(s => s.Font = OsuFont.Torus.With(size: 12))
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
}.With(t =>
{
if (!string.IsNullOrEmpty(creator))
{
t.AddText("mapped by ");
t.AddText(creator, s => s.Font = s.Font.With(weight: FontWeight.SemiBold));
}
})
}
},
}
},
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 5),
Children = new Drawable[]
{
new GridContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Content = new[] { topStatistics.Cast<Drawable>().ToArray() },
RowDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
}
},
new GridContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Content = new[] { bottomStatistics.Where(s => s.Result <= HitResult.Perfect).ToArray() },
RowDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
}
},
new GridContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Content = new[] { bottomStatistics.Where(s => s.Result > HitResult.Perfect).ToArray() },
RowDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
}
}
}
}
}
},
new OsuSpriteText
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
Font = OsuFont.GetFont(size: 10, weight: FontWeight.SemiBold),
Text = $"Played on {score.Date.ToLocalTime():d MMMM yyyy HH:mm}"
}
};
if (score.Mods.Any())
{
starAndModDisplay.Add(new ModDisplay
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
ExpansionMode = ExpansionMode.AlwaysExpanded,
Scale = new Vector2(0.5f),
Current = { Value = score.Mods }
});
}
}
protected override void LoadComplete()
{
base.LoadComplete();
// Score counter value setting must be scheduled so it isn't transferred instantaneously
ScheduleAfterChildren(() =>
{
using (BeginDelayedSequence(AccuracyCircle.ACCURACY_TRANSFORM_DELAY, true))
{
scoreCounter.FadeIn();
scoreCounter.Current = scoreManager.GetBindableTotalScore(score);
double delay = 0;
foreach (var stat in statisticDisplays)
{
using (BeginDelayedSequence(delay, true))
stat.Appear();
delay += 200;
}
}
if (!withFlair)
FinishTransforms(true);
});
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using SampleMetadata;
using Xunit;
namespace System.Reflection.Tests
{
public static partial class CustomAttributeTests
{
[Fact]
public static void CustomAttributeTest1()
{
Type t = typeof(AttributeHolder1); // Intentionally not projected. We're reflecting on this (and Invoking it) to get the validation baseline data.
foreach (Type nt in t.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic))
{
SampleCustomAttribute attr = nt.GetCustomAttribute<SampleCustomAttribute>(inherit: false);
CustomAttributeData cad = nt.CustomAttributes.Single(c => c.AttributeType == typeof(SampleCustomAttribute));
object value = attr.Argument; // Capture the actual value passed to the SampleCustomAttribute constructor.
Type parameterType = cad.Constructor.GetParameters()[0].ParameterType; // Capture the formal parameter type of the constructor.
Type ntProjected = nt.Project();
CustomAttributeData cadProjected = ntProjected.CustomAttributes.Single(c => c.AttributeType == typeof(SampleCustomAttribute).Project());
Assert.Equal(typeof(SampleCustomAttribute).Project(), cadProjected.AttributeType);
Assert.Equal(1, cadProjected.ConstructorArguments.Count);
cadProjected.ConstructorArguments[0].Validate(parameterType, value);
}
}
[Fact]
public static void CustomAttributeInAnotherAssembly()
{
Type t = typeof(HoldsAttributeDefinedInAnotherAssembly).Project();
CustomAttributeData cad = t.CustomAttributes.Single();
Assert.Equal(typeof(GuidAttribute).Project(), cad.AttributeType);
}
[Fact]
public static void CustomAttributeNamedArguments_Field()
{
Type t = typeof(HoldsCaWithNamedArguments.N1).Project();
CustomAttributeData cad = t.CustomAttributes.Single();
Assert.Equal(typeof(CaWithNamedArguments).Project(), cad.AttributeType);
Assert.Equal(0, cad.ConstructorArguments.Count);
Assert.Equal(1, cad.NamedArguments.Count);
CustomAttributeNamedArgument can = cad.NamedArguments[0];
Assert.True(can.IsField);
Assert.Equal(typeof(CaWithNamedArguments).Project().GetField("MyField"), can.MemberInfo);
can.TypedValue.Validate(typeof(int).Project(), 4);
}
[Fact]
public static void CustomAttributeNamedArguments_Property()
{
Type t = typeof(HoldsCaWithNamedArguments.N2).Project();
CustomAttributeData cad = t.CustomAttributes.Single();
Assert.Equal(typeof(CaWithNamedArguments).Project(), cad.AttributeType);
Assert.Equal(0, cad.ConstructorArguments.Count);
Assert.Equal(1, cad.NamedArguments.Count);
CustomAttributeNamedArgument can = cad.NamedArguments[0];
Assert.False(can.IsField);
Assert.Equal(typeof(CaWithNamedArguments).Project().GetProperty("MyProperty"), can.MemberInfo);
can.TypedValue.Validate(typeof(int).Project(), 8);
}
private static object UnwrapEnum(this Enum e)
{
FieldInfo f = e.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly).First();
return f.GetValue(e);
}
private static void Validate(this CustomAttributeTypedArgument cat, Type parameterType, object value)
{
if (value == null)
{
Assert.Null(cat.Value);
if (parameterType == typeof(object))
{
// Why "string?" That's what NETFX has always put here for this corner case.
Assert.Equal(typeof(string).Project(), cat.ArgumentType);
}
else
{
Assert.Equal(parameterType.Project(), cat.ArgumentType);
}
}
else if (value is Enum)
{
Assert.Equal(value.GetType().Project(), cat.ArgumentType);
Assert.Equal(((Enum)value).UnwrapEnum(), cat.Value);
}
else if (value is Type valueAsType)
{
Assert.Equal(typeof(Type).Project(), cat.ArgumentType);
Assert.Equal(valueAsType.Project(), cat.Value);
}
else if (value is Array valueAsArray)
{
Assert.Equal(value.GetType().Project(), cat.ArgumentType);
Assert.True(cat.Value is ReadOnlyCollection<CustomAttributeTypedArgument>);
IList<CustomAttributeTypedArgument> cats = (IList<CustomAttributeTypedArgument>)(cat.Value);
Assert.Equal(valueAsArray.Length, cats.Count);
for (int i = 0; i < cats.Count; i++)
{
cats[i].Validate(valueAsArray.GetType().GetElementType(), valueAsArray.GetValue(i));
}
}
else
{
Assert.Equal(value.GetType().Project(), cat.ArgumentType);
Assert.Equal(value, cat.Value);
}
}
internal static void ValidateCustomAttributesAllocatesFreshObjectsEachTime(Func<IEnumerable<CustomAttributeData>> action)
{
IEnumerable<CustomAttributeData> cads1 = action();
IEnumerable<CustomAttributeData> cads2 = action();
cads1.ValidateEqualButFreshlyAllocated(cads2);
}
internal static void ValidateEqualButFreshlyAllocated(this IEnumerable<CustomAttributeData> cads1, IEnumerable<CustomAttributeData> cads2)
{
CustomAttributeData[] acads1 = cads1.ToArray();
CustomAttributeData[] acads2 = cads2.ToArray();
Assert.Equal(acads1.Length, acads2.Length);
if (acads1.Length != 0)
{
Assert.NotSame(cads1, cads2);
}
for (int i = 0; i < acads1.Length; i++)
{
CustomAttributeData cad1 = acads1[i];
CustomAttributeData cad2 = acads2[i];
Assert.Equal(cad1.AttributeType, cad2.AttributeType);
Assert.Equal(cad1.Constructor, cad2.Constructor);
Assert.Equal(cad1.ConstructorArguments.Count, cad2.ConstructorArguments.Count);
if (cad1.ConstructorArguments.Count != 0)
{
Assert.NotSame(cad1.ConstructorArguments, cad2.ConstructorArguments);
}
Assert.True(cad1.ConstructorArguments is ReadOnlyCollection<CustomAttributeTypedArgument>);
Assert.True(cad2.ConstructorArguments is ReadOnlyCollection<CustomAttributeTypedArgument>);
for (int j = 0; j < cad1.ConstructorArguments.Count; j++)
{
cad1.ConstructorArguments[j].ValidateEqualButFreshlyAllocated(cad2.ConstructorArguments[j]);
}
Assert.Equal(cad1.NamedArguments.Count, cad2.NamedArguments.Count);
if (cad1.NamedArguments.Count != 0)
{
Assert.NotSame(cad1.NamedArguments, cad2.NamedArguments);
}
Assert.True(cad1.NamedArguments is ReadOnlyCollection<CustomAttributeNamedArgument>);
Assert.True(cad2.NamedArguments is ReadOnlyCollection<CustomAttributeNamedArgument>);
for (int j = 0; j < cad1.NamedArguments.Count; j++)
{
cad1.NamedArguments[j].TypedValue.ValidateEqualButFreshlyAllocated(cad2.NamedArguments[j].TypedValue);
}
}
}
private static void ValidateEqualButFreshlyAllocated(this CustomAttributeTypedArgument cat1, CustomAttributeTypedArgument cat2)
{
Assert.Equal(cat1.ArgumentType, cat2.ArgumentType);
if (cat1.Value == null && cat2.Value == null)
return;
if (!cat1.ArgumentType.IsArray)
{
Assert.Equal(cat1.Value, cat2.Value);
return;
}
Assert.True(cat1.Value is ReadOnlyCollection<CustomAttributeTypedArgument>);
Assert.True(cat2.Value is ReadOnlyCollection<CustomAttributeTypedArgument>);
IList<CustomAttributeTypedArgument> cats1 = (IList<CustomAttributeTypedArgument>)cat1.Value;
IList<CustomAttributeTypedArgument> cats2 = (IList<CustomAttributeTypedArgument>)cat2.Value;
Assert.NotSame(cats1, cats2);
Assert.Equal(cats1.Count, cats2.Count);
for (int i = 0; i < cats1.Count; i++)
{
cats1[i].ValidateEqualButFreshlyAllocated(cats2[i]);
}
}
// @todo: https://github.com/dotnet/corefxlab/issues/2460
// This test only exists to provide code coverage for the fast-path AttributeType implementation while we're stuck in a netstandard-only build
// configuration. It should be removed once both of these conditions are true:
//
// - We have an official on-going build and CI of a netcore configuration of System.Reflection.MetadataLoadContext.
// - That build is consuming corefx contracts where CustomAttributeData.AttributeType is virtual (see https://github.com/dotnet/corefx/issues/31614)
//
// Once these conditions are satisfied, it is no longer necessary to resort to Reflection to invoke the fast-path AttributeType code.
// Invoking CustomAttributeData.AttributeType the normal way will do the trick.
//
[Fact]
public static void TestVirtualAttributeTypeProperty()
{
{
Type t = typeof(AttributeHolder1.N1).Project();
CustomAttributeData[] cads = t.CustomAttributes.ToArray();
Assert.Equal(1, cads.Length);
CustomAttributeData cad = cads[0];
Type attributeType = cad.CallUsingReflection<Type>("get_AttributeType");
Assert.Equal(typeof(SampleCustomAttribute).Project(), attributeType);
}
{
Type t = typeof(HoldsAttributeDefinedInAnotherAssembly).Project();
CustomAttributeData[] cads = t.CustomAttributes.ToArray();
Assert.Equal(1, cads.Length);
CustomAttributeData cad = cads[0];
Type attributeType = cad.CallUsingReflection<Type>("get_AttributeType");
Assert.Equal(typeof(GuidAttribute).Project(), attributeType);
}
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2014 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit mindtouch.com;
* please review the licensing section.
*
* 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.Data;
using MindTouch.Dream;
using MindTouch.Xml;
namespace MindTouch.Data {
/// <summary>
/// Provides a database catalog abstraction.
/// </summary>
public interface IDataCatalog {
/// <summary>
/// Create a new query command.
/// </summary>
/// <param name="query">SQL query string.</param>
/// <returns>Query instance.</returns>
IDataCommand NewQuery(string query);
/// <summary>
/// Create new a read-only query command.
/// </summary>
/// <param name="query">SQL query string.</param>
/// <returns>Query instance.</returns>
IDataCommand NewReadOnlyQuery(string query);
/// <summary>
/// Create a new query command.
/// </summary>
/// <param name="query">SQL query string.</param>
/// <param name="readonly"><see langword="True"/> if the query is read-only.</param>
/// <returns>New Query instance.</returns>
IDataCommand NewQuery(string query, bool @readonly);
/// <summary>
/// Test the database connection.
/// </summary>
void TestConnection();
/// <summary>
/// Test the read-only database connection.
/// </summary>
/// <param name="readonly"></param>
void TestConnection(bool @readonly);
/// <summary>
/// Notification of execution completion of an <see cref="DataCommand"/> created by this instance.
/// </summary>
event Action<IDataCommand> OnQueryFinished;
}
/// <summary>
/// Provides a database catalog abstraction.
/// </summary>
public class DataCatalog : IDataCatalog {
//--- Fields ---
private readonly DataFactory _factory;
private readonly string _connection;
private readonly string _readonlyconnection;
private readonly bool _slowSqlWarningEnabled;
//--- Constructors ---
/// <summary>
/// Create a new instance.
/// </summary>
/// <param name="factory">Factory to use for command construction and query execution.</param>
/// <param name="connectionString">Database connection string.</param>
/// <param name="slowSqlWarningEnabled">A value indicating whether the slow SQL warning is enabled.</param>
public DataCatalog(DataFactory factory, string connectionString, bool slowSqlWarningEnabled = true) {
if(factory == null) {
throw new ArgumentNullException("factory");
}
if(connectionString == null) {
throw new ArgumentNullException("connectionString");
}
this._factory = factory;
_connection = connectionString;
_slowSqlWarningEnabled = slowSqlWarningEnabled;
}
/// <summary>
/// This constructor is deprecated, please use use the constructor requiring a connectionString instead
/// </summary>
[Obsolete("This constructor is deprecated, please use use the constructor requiring a connectionString instead")]
public DataCatalog(DataFactory factory, XDoc config) {
if(factory == null) {
throw new ArgumentNullException("factory");
}
if(config == null) {
throw new ArgumentNullException("config");
}
_factory = factory;
// compose connection string from config document
string server = config["db-server"].AsText ?? "localhost";
int port = config["db-port"].AsInt ?? 3306;
string catalog = config["db-catalog"].AsText;
string user = config["db-user"].AsText;
string password = config["db-password"].AsText ?? string.Empty;
string options = config["db-options"].AsText;
if(string.IsNullOrEmpty(catalog)) {
throw new ArgumentNullException("config/catalog");
}
if(string.IsNullOrEmpty(user)) {
throw new ArgumentNullException("config/user");
}
_connection = string.Format("Server={0};Port={1};Database={2};Uid={3};Pwd={4};{5}", server, port, catalog, user, password, options);
_slowSqlWarningEnabled = config["db-slow-sql-warning-enabled"].AsBool ?? true;
// compose read-only connection string
string readonly_server = config["db-readonly-server"].AsText ?? server;
int readonly_port = config["db-readonly-port"].AsInt ?? port;
string readonly_catalog = config["db-readonly-catalog"].AsText ?? catalog;
string readonly_user = config["db-readonly-user"].AsText ?? user;
string readonly_password = config["db-readonly-password"].AsText ?? password;
string readonly_options = config["db-readonly-options"].AsText ?? options;
_readonlyconnection = string.Format("Server={0};Port={1};Database={2};Uid={3};Pwd={4};{5}", readonly_server, readonly_port, readonly_catalog, readonly_user, readonly_password, readonly_options);
}
//--- Properties ---
/// <summary>
/// This property bypasses the safety measures provided by MindTouch.Data objects. Please avoid using it if possible.
/// </summary>
[Obsolete("This property bypasses the safety measures provided by MindTouch.Data objects. Please avoid using it if possible.")]
public string ConnectionString { get { return _connection; } }
//--- Events ---
/// <summary>
/// Notification of execution completion of an <see cref="DataCommand"/> created by this instance.
/// </summary>
public event Action<IDataCommand> OnQueryFinished;
//--- Methods ---
/// <summary>
/// Create a new query command.
/// </summary>
/// <param name="query">SQL query string.</param>
/// <returns>Query instance.</returns>
public DataCommand NewQuery(string query) {
return NewQuery(query, false);
}
IDataCommand IDataCatalog.NewQuery(string query) {
return NewQuery(query, false);
}
/// <summary>
/// Create new a read-only query command.
/// </summary>
/// <param name="query">SQL query string.</param>
/// <returns>Query instance.</returns>
public DataCommand NewReadOnlyQuery(string query) {
return NewQuery(query, true);
}
IDataCommand IDataCatalog.NewReadOnlyQuery(string query) {
return NewReadOnlyQuery(query);
}
/// <summary>
/// Create a new query command.
/// </summary>
/// <param name="query">SQL query string.</param>
/// <param name="readonly"><see langword="True"/> if the query is read-only.</param>
/// <returns>New Query instance.</returns>
public DataCommand NewQuery(string query, bool @readonly) {
if(@readonly && string.IsNullOrEmpty(_readonlyconnection)) {
throw new DreamException("No read-only connection string has been defined.");
}
return new DataCommand(_factory, this, @readonly ? _readonlyconnection : _connection, _factory.CreateQuery(query), _slowSqlWarningEnabled);
}
IDataCommand IDataCatalog.NewQuery(string query, bool @readonly) {
return NewQuery(query, @readonly);
}
/// <summary>
/// Test the database connection.
/// </summary>
public void TestConnection() {
TestConnection(false);
}
/// <summary>
/// Test the read-only database connection.
/// </summary>
/// <param name="readonly"></param>
public void TestConnection(bool @readonly) {
using(IDbConnection testConnection = _factory.OpenConnection(@readonly ? _readonlyconnection : _connection)) {
testConnection.Close();
}
}
internal void FireQueryFinished(IDataCommand cmd) {
if(OnQueryFinished != null) {
OnQueryFinished(cmd);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Glipho.OAuth.Providers.WebApiSample.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
public class ReflectionFx : MonoBehaviour
{
public Transform[] reflectiveObjects;
public LayerMask reflectionMask;
public Material[] reflectiveMaterials;
private Transform reflectiveSurfaceHeight;
public Shader replacementShader;
private bool highQuality = false;
public Color clearColor = Color.black;
public System.String reflectionSampler = "_ReflectionTex";
public float clipPlaneOffset = 0.07F;
private Vector3 oldpos = Vector3.zero;
private Camera reflectionCamera;
private Dictionary<Camera, bool> helperCameras = null;
private Texture[] initialReflectionTextures;
public void Start()
{
initialReflectionTextures = new Texture2D[reflectiveMaterials.Length];
for (int i = 0; i < reflectiveMaterials.Length; i++)
{
initialReflectionTextures[i] = reflectiveMaterials[i].GetTexture(reflectionSampler);
}
if (!SystemInfo.supportsRenderTextures)
this.enabled = false;
}
public void OnDisable()
{
if (initialReflectionTextures == null)
return;
// restore initial reflection textures
for (int i = 0; i < reflectiveMaterials.Length; i++)
{
reflectiveMaterials[i].SetTexture(reflectionSampler, initialReflectionTextures[i]);
}
}
private Camera CreateReflectionCameraFor(Camera cam)
{
System.String reflName = gameObject.name + "Reflection" + cam.name;
Debug.Log ("AngryBots: created internal reflection camera " + reflName);
GameObject go = GameObject.Find(reflName);
if(!go)
go = new GameObject(reflName, typeof(Camera));
if(!go.GetComponent(typeof(Camera)))
go.AddComponent(typeof(Camera));
Camera reflectCamera = go.camera;
reflectCamera.backgroundColor = clearColor;
reflectCamera.clearFlags = CameraClearFlags.SolidColor;
SetStandardCameraParameter(reflectCamera, reflectionMask);
if(!reflectCamera.targetTexture)
reflectCamera.targetTexture = CreateTextureFor(cam);
return reflectCamera;
}
public void HighQuality ()
{
highQuality = true;
}
private void SetStandardCameraParameter(Camera cam, LayerMask mask)
{
cam.backgroundColor = Color.black;
cam.enabled = false;
cam.cullingMask = reflectionMask;
}
private RenderTexture CreateTextureFor(Camera cam)
{
RenderTextureFormat rtFormat = RenderTextureFormat.RGB565;
if (!SystemInfo.SupportsRenderTextureFormat (rtFormat))
rtFormat = RenderTextureFormat.Default;
float rtSizeMul = highQuality ? 0.75f : 0.5f;
RenderTexture rt = new RenderTexture(Mathf.FloorToInt(cam.pixelWidth * rtSizeMul), Mathf.FloorToInt(cam.pixelHeight * rtSizeMul), 24, rtFormat);
rt.hideFlags = HideFlags.DontSave;
return rt;
}
public void RenderHelpCameras (Camera currentCam)
{
if(null == helperCameras)
helperCameras = new Dictionary<Camera, bool>();
if(!helperCameras.ContainsKey(currentCam)) {
helperCameras.Add(currentCam, false);
}
if(helperCameras[currentCam]) {
return;
}
if(!reflectionCamera) {
reflectionCamera = CreateReflectionCameraFor (currentCam);
foreach (Material m in reflectiveMaterials) {
m.SetTexture (reflectionSampler, reflectionCamera.targetTexture);
}
}
RenderReflectionFor(currentCam, reflectionCamera);
helperCameras[currentCam] = true;
}
public void LateUpdate ()
{
// find the closest reflective surface and use that as our
// reference for reflection height etc.
Transform closest = null;
float closestDist = Mathf.Infinity;
Vector3 pos = Camera.main.transform.position;
foreach (Transform t in reflectiveObjects) {
if (t.renderer.isVisible) {
float dist = (pos - t.position).sqrMagnitude;
if (dist < closestDist) {
closestDist = dist;
closest = t;
}
}
}
if(!closest)
return;
ObjectBeingRendered (closest, Camera.main);
if (null != helperCameras)
helperCameras.Clear();
}
private void ObjectBeingRendered (Transform tr, Camera currentCam)
{
if (null == tr)
return;
reflectiveSurfaceHeight = tr;
RenderHelpCameras (currentCam);
}
private void RenderReflectionFor (Camera cam, Camera reflectCamera)
{
if(!reflectCamera)
return;
SaneCameraSettings(reflectCamera);
reflectCamera.backgroundColor = clearColor;
GL.SetRevertBackfacing(true);
Transform reflectiveSurface = reflectiveSurfaceHeight;
Vector3 eulerA = cam.transform.eulerAngles;
reflectCamera.transform.eulerAngles = new Vector3(-eulerA.x, eulerA.y, eulerA.z);
reflectCamera.transform.position = cam.transform.position;
Vector3 pos = reflectiveSurface.transform.position;
pos.y = reflectiveSurface.position.y;
Vector3 normal = reflectiveSurface.transform.up;
float d = -Vector3.Dot(normal, pos) - clipPlaneOffset;
Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d);
Matrix4x4 reflection = Matrix4x4.zero;
reflection = CalculateReflectionMatrix(reflection, reflectionPlane);
oldpos = cam.transform.position;
Vector3 newpos = reflection.MultiplyPoint (oldpos);
reflectCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;
Vector4 clipPlane = CameraSpacePlane(reflectCamera, pos, normal, 1.0f);
Matrix4x4 projection = cam.projectionMatrix;
projection = CalculateObliqueMatrix(projection, clipPlane);
reflectCamera.projectionMatrix = projection;
reflectCamera.transform.position = newpos;
Vector3 euler = cam.transform.eulerAngles;
reflectCamera.transform.eulerAngles = new Vector3(-euler.x, euler.y, euler.z);
reflectCamera.RenderWithShader (replacementShader, "Reflection");
GL.SetRevertBackfacing(false);
}
private void SaneCameraSettings(Camera helperCam)
{
helperCam.depthTextureMode = DepthTextureMode.None;
helperCam.backgroundColor = Color.black;
helperCam.clearFlags = CameraClearFlags.SolidColor;
helperCam.renderingPath = RenderingPath.Forward;
}
static Matrix4x4 CalculateObliqueMatrix (Matrix4x4 projection, Vector4 clipPlane)
{
Vector4 q = projection.inverse * new Vector4(
sgn(clipPlane.x),
sgn(clipPlane.y),
1.0F,
1.0F
);
Vector4 c = clipPlane * (2.0F / (Vector4.Dot (clipPlane, q)));
// third row = clip plane - fourth row
projection[2] = c.x - projection[3];
projection[6] = c.y - projection[7];
projection[10] = c.z - projection[11];
projection[14] = c.w - projection[15];
return projection;
}
// Helper function for getting the reflection matrix that will be multiplied with camera matrix
static Matrix4x4 CalculateReflectionMatrix (Matrix4x4 reflectionMat, Vector4 plane)
{
reflectionMat.m00 = (1.0F - 2.0F*plane[0]*plane[0]);
reflectionMat.m01 = ( - 2.0F*plane[0]*plane[1]);
reflectionMat.m02 = ( - 2.0F*plane[0]*plane[2]);
reflectionMat.m03 = ( - 2.0F*plane[3]*plane[0]);
reflectionMat.m10 = ( - 2.0F*plane[1]*plane[0]);
reflectionMat.m11 = (1.0F - 2.0F*plane[1]*plane[1]);
reflectionMat.m12 = ( - 2.0F*plane[1]*plane[2]);
reflectionMat.m13 = ( - 2.0F*plane[3]*plane[1]);
reflectionMat.m20 = ( - 2.0F*plane[2]*plane[0]);
reflectionMat.m21 = ( - 2.0F*plane[2]*plane[1]);
reflectionMat.m22 = (1.0F - 2.0F*plane[2]*plane[2]);
reflectionMat.m23 = ( - 2.0F*plane[3]*plane[2]);
reflectionMat.m30 = 0.0F;
reflectionMat.m31 = 0.0F;
reflectionMat.m32 = 0.0F;
reflectionMat.m33 = 1.0F;
return reflectionMat;
}
// Extended sign: returns -1, 0 or 1 based on sign of a
static float sgn (float a) {
if (a > 0.0F) return 1.0F;
if (a < 0.0F) return -1.0F;
return 0.0F;
}
// Given position/normal of the plane, calculates plane in camera space.
private Vector4 CameraSpacePlane (Camera cam, Vector3 pos, Vector3 normal, float sideSign)
{
Vector3 offsetPos = pos + normal * clipPlaneOffset;
Matrix4x4 m = cam.worldToCameraMatrix;
Vector3 cpos = m.MultiplyPoint (offsetPos);
Vector3 cnormal = m.MultiplyVector (normal).normalized * sideSign;
return new Vector4 (cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot (cpos,cnormal));
}
}
| |
// 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.Data.Common;
using System.Data.SqlTypes;
using System.IO;
using System.Linq;
using System.Text;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public static class SqlServerTypesTest
{
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void GetSchemaTableTest()
{
using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
using (SqlCommand cmd = new SqlCommand("select hierarchyid::Parse('/1/') as col0", conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.KeyInfo))
{
DataTable schemaTable = reader.GetSchemaTable();
DataTestUtility.AssertEqualsWithDescription(1, schemaTable.Rows.Count, "Unexpected schema table row count.");
string columnName = (string)(string)schemaTable.Rows[0][schemaTable.Columns["ColumnName"]];
DataTestUtility.AssertEqualsWithDescription("col0", columnName, "Unexpected column name.");
string dataTypeName = (string)schemaTable.Rows[0][schemaTable.Columns["DataTypeName"]];
DataTestUtility.AssertEqualsWithDescription("Northwind.sys.hierarchyid", dataTypeName, "Unexpected data type name.");
string udtAssemblyName = (string)schemaTable.Rows[0][schemaTable.Columns["UdtAssemblyQualifiedName"]];
Assert.True(udtAssemblyName?.StartsWith("Microsoft.SqlServer.Types.SqlHierarchyId"), "Unexpected UDT assembly name: " + udtAssemblyName);
}
}
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void GetValueTest()
{
using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
using (SqlCommand cmd = new SqlCommand("select hierarchyid::Parse('/1/') as col0", conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
Assert.True(reader.Read());
// SqlHierarchyId is part of Microsoft.SqlServer.Types, which is not supported in Core
Assert.Throws<FileNotFoundException>(() => reader.GetValue(0));
Assert.Throws<FileNotFoundException>(() => reader.GetSqlValue(0));
}
}
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void TestUdtZeroByte()
{
using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = "select hierarchyid::Parse('/') as col0";
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.True(reader.Read());
Assert.False(reader.IsDBNull(0));
SqlBytes sqlBytes = reader.GetSqlBytes(0);
Assert.False(sqlBytes.IsNull, "Expected a zero length byte array");
Assert.True(sqlBytes.Length == 0, "Expected a zero length byte array");
}
}
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void TestUdtSqlDataReaderGetSqlBytesSequentialAccess()
{
TestUdtSqlDataReaderGetSqlBytes(CommandBehavior.SequentialAccess);
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void TestUdtSqlDataReaderGetSqlBytes()
{
TestUdtSqlDataReaderGetSqlBytes(CommandBehavior.Default);
}
private static void TestUdtSqlDataReaderGetSqlBytes(CommandBehavior behavior)
{
using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = "select hierarchyid::Parse('/1/1/3/') as col0, geometry::Parse('LINESTRING (100 100, 20 180, 180 180)') as col1, geography::Parse('LINESTRING(-122.360 47.656, -122.343 47.656)') as col2";
using (SqlDataReader reader = command.ExecuteReader(behavior))
{
Assert.True(reader.Read());
SqlBytes sqlBytes = null;
sqlBytes = reader.GetSqlBytes(0);
Assert.Equal("5ade", ToHexString(sqlBytes.Value));
sqlBytes = reader.GetSqlBytes(1);
Assert.Equal("0000000001040300000000000000000059400000000000005940000000000000344000000000008066400000000000806640000000000080664001000000010000000001000000ffffffff0000000002", ToHexString(sqlBytes.Value));
sqlBytes = reader.GetSqlBytes(2);
Assert.Equal("e610000001148716d9cef7d34740d7a3703d0a975ec08716d9cef7d34740cba145b6f3955ec0", ToHexString(sqlBytes.Value));
if (behavior == CommandBehavior.Default)
{
sqlBytes = reader.GetSqlBytes(0);
Assert.Equal("5ade", ToHexString(sqlBytes.Value));
}
}
}
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void TestUdtSqlDataReaderGetBytesSequentialAccess()
{
TestUdtSqlDataReaderGetBytes(CommandBehavior.SequentialAccess);
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void TestUdtSqlDataReaderGetBytes()
{
TestUdtSqlDataReaderGetBytes(CommandBehavior.Default);
}
private static void TestUdtSqlDataReaderGetBytes(CommandBehavior behavior)
{
using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = "select hierarchyid::Parse('/1/1/3/') as col0, geometry::Parse('LINESTRING (100 100, 20 180, 180 180)') as col1, geography::Parse('LINESTRING(-122.360 47.656, -122.343 47.656)') as col2";
using (SqlDataReader reader = command.ExecuteReader(behavior))
{
Assert.True(reader.Read());
int byteCount = 0;
byte[] bytes = null;
byteCount = (int)reader.GetBytes(0, 0, null, 0, 0);
Assert.True(byteCount > 0);
bytes = new byte[byteCount];
reader.GetBytes(0, 0, bytes, 0, bytes.Length);
Assert.Equal("5ade", ToHexString(bytes));
byteCount = (int)reader.GetBytes(1, 0, null, 0, 0);
Assert.True(byteCount > 0);
bytes = new byte[byteCount];
reader.GetBytes(1, 0, bytes, 0, bytes.Length);
Assert.Equal("0000000001040300000000000000000059400000000000005940000000000000344000000000008066400000000000806640000000000080664001000000010000000001000000ffffffff0000000002", ToHexString(bytes));
byteCount = (int)reader.GetBytes(2, 0, null, 0, 0);
Assert.True(byteCount > 0);
bytes = new byte[byteCount];
reader.GetBytes(2, 0, bytes, 0, bytes.Length);
Assert.Equal("e610000001148716d9cef7d34740d7a3703d0a975ec08716d9cef7d34740cba145b6f3955ec0", ToHexString(bytes));
if (behavior == CommandBehavior.Default)
{
byteCount = (int)reader.GetBytes(0, 0, null, 0, 0);
Assert.True(byteCount > 0);
bytes = new byte[byteCount];
reader.GetBytes(0, 0, bytes, 0, bytes.Length);
Assert.Equal("5ade", ToHexString(bytes));
}
}
}
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void TestUdtSqlDataReaderGetStreamSequentialAccess()
{
TestUdtSqlDataReaderGetStream(CommandBehavior.SequentialAccess);
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void TestUdtSqlDataReaderGetStream()
{
TestUdtSqlDataReaderGetStream(CommandBehavior.Default);
}
private static void TestUdtSqlDataReaderGetStream(CommandBehavior behavior)
{
using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = "select hierarchyid::Parse('/1/1/3/') as col0, geometry::Parse('LINESTRING (100 100, 20 180, 180 180)') as col1, geography::Parse('LINESTRING(-122.360 47.656, -122.343 47.656)') as col2";
using (SqlDataReader reader = command.ExecuteReader(behavior))
{
Assert.True(reader.Read());
MemoryStream buffer = null;
byte[] bytes = null;
buffer = new MemoryStream();
using (Stream stream = reader.GetStream(0))
{
stream.CopyTo(buffer);
}
bytes = buffer.ToArray();
Assert.Equal("5ade", ToHexString(bytes));
buffer = new MemoryStream();
using (Stream stream = reader.GetStream(1))
{
stream.CopyTo(buffer);
}
bytes = buffer.ToArray();
Assert.Equal("0000000001040300000000000000000059400000000000005940000000000000344000000000008066400000000000806640000000000080664001000000010000000001000000ffffffff0000000002", ToHexString(bytes));
buffer = new MemoryStream();
using (Stream stream = reader.GetStream(2))
{
stream.CopyTo(buffer);
}
bytes = buffer.ToArray();
Assert.Equal("e610000001148716d9cef7d34740d7a3703d0a975ec08716d9cef7d34740cba145b6f3955ec0", ToHexString(bytes));
if (behavior == CommandBehavior.Default)
{
buffer = new MemoryStream();
using (Stream stream = reader.GetStream(0))
{
stream.CopyTo(buffer);
}
bytes = buffer.ToArray();
Assert.Equal("5ade", ToHexString(bytes));
}
}
}
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void TestUdtSchemaMetadata()
{
using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = "select hierarchyid::Parse('/1/1/3/') as col0, geometry::Parse('LINESTRING (100 100, 20 180, 180 180)') as col1, geography::Parse('LINESTRING(-122.360 47.656, -122.343 47.656)') as col2";
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SchemaOnly))
{
ReadOnlyCollection<DbColumn> columns = reader.GetColumnSchema();
DbColumn column = null;
// Validate Microsoft.SqlServer.Types.SqlHierarchyId, Microsoft.SqlServer.Types, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91
column = columns[0];
Assert.Equal(column.ColumnName, "col0");
Assert.True(column.DataTypeName.EndsWith(".hierarchyid"), $"Unexpected DataTypeName \"{column.DataTypeName}\"");
Assert.NotNull(column.UdtAssemblyQualifiedName);
AssertSqlUdtAssemblyQualifiedName(column.UdtAssemblyQualifiedName, "Microsoft.SqlServer.Types.SqlHierarchyId");
// Validate Microsoft.SqlServer.Types.SqlGeometry, Microsoft.SqlServer.Types, Version = 11.0.0.0, Culture = neutral, PublicKeyToken = 89845dcd8080cc91
column = columns[1];
Assert.Equal(column.ColumnName, "col1");
Assert.True(column.DataTypeName.EndsWith(".geometry"), $"Unexpected DataTypeName \"{column.DataTypeName}\"");
Assert.NotNull(column.UdtAssemblyQualifiedName);
AssertSqlUdtAssemblyQualifiedName(column.UdtAssemblyQualifiedName, "Microsoft.SqlServer.Types.SqlGeometry");
// Validate Microsoft.SqlServer.Types.SqlGeography, Microsoft.SqlServer.Types, Version = 11.0.0.0, Culture = neutral, PublicKeyToken = 89845dcd8080cc91
column = columns[2];
Assert.Equal(column.ColumnName, "col2");
Assert.True(column.DataTypeName.EndsWith(".geography"), $"Unexpected DataTypeName \"{column.DataTypeName}\"");
Assert.NotNull(column.UdtAssemblyQualifiedName);
AssertSqlUdtAssemblyQualifiedName(column.UdtAssemblyQualifiedName, "Microsoft.SqlServer.Types.SqlGeography");
}
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
public static void TestUdtParameterSetSqlByteValue()
{
const string ExpectedPointValue = "POINT (1 1)";
SqlBytes geometrySqlBytes = null;
string actualtPointValue = null;
using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = $"SELECT geometry::Parse('{ExpectedPointValue}')";
using (var reader = command.ExecuteReader())
{
reader.Read();
geometrySqlBytes = reader.GetSqlBytes(0);
}
}
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT @geometry.STAsText()";
var parameter = command.Parameters.AddWithValue("@geometry", geometrySqlBytes);
parameter.SqlDbType = SqlDbType.Udt;
parameter.UdtTypeName = "geometry";
actualtPointValue = Convert.ToString(command.ExecuteScalar());
}
Assert.Equal(ExpectedPointValue, actualtPointValue);
}
}
[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
public static void TestUdtParameterSetRawByteValue()
{
const string ExpectedPointValue = "POINT (1 1)";
byte[] geometryBytes = null;
string actualtPointValue = null;
using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = $"SELECT geometry::Parse('{ExpectedPointValue}')";
using (var reader = command.ExecuteReader())
{
reader.Read();
geometryBytes = reader.GetSqlBytes(0).Buffer;
}
}
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT @geometry.STAsText()";
var parameter = command.Parameters.AddWithValue("@geometry", geometryBytes);
parameter.SqlDbType = SqlDbType.Udt;
parameter.UdtTypeName = "geometry";
actualtPointValue = Convert.ToString(command.ExecuteScalar());
}
Assert.Equal(ExpectedPointValue, actualtPointValue);
}
}
private static void AssertSqlUdtAssemblyQualifiedName(string assemblyQualifiedName, string expectedType)
{
List<string> parts = assemblyQualifiedName.Split(',').Select(x => x.Trim()).ToList();
string type = parts[0];
string assembly = parts.Count < 2 ? string.Empty : parts[1];
string version = parts.Count < 3 ? string.Empty : parts[2];
string culture = parts.Count < 4 ? string.Empty : parts[3];
string token = parts.Count < 5 ? string.Empty : parts[4];
Assert.Equal(expectedType, type);
Assert.Equal("Microsoft.SqlServer.Types", assembly);
Assert.True(version.StartsWith("Version"));
Assert.True(culture.StartsWith("Culture"));
Assert.True(token.StartsWith("PublicKeyToken"));
}
private static string ToHexString(byte[] bytes)
{
StringBuilder hex = new StringBuilder(bytes.Length * 2);
foreach (byte b in bytes)
{
hex.AppendFormat("{0:x2}", b);
}
return hex.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
namespace Archichect.ConstraintSolving {
public class NumericVariable {
private static int _globalCt;
protected readonly int _varIndex = _globalCt++;
public string Definition { get; }
public float Interpolate { get; }
public string ShortName { get; }
[NotNull]
private readonly SimpleConstraintSolver _solver;
[ItemNotNull]
private readonly List<AbstractConstraint> _dependentConstraints = new List<AbstractConstraint>();
private int _lastChangedAt = 1;
public bool Fixed { get; private set; }
public string Name { get; private set; }
internal NumericVariable([NotNull] string shortName, [NotNull] string definition, [NotNull] SimpleConstraintSolver solver, double? lo, double? hi, float interpolate) {
if (shortName.Length > 1000) {
throw new ArgumentException("string too long", nameof(shortName));
}
if (definition.Length > 1000) {
throw new ArgumentException("string too long", nameof(definition));
}
Definition = definition;
Name = ShortName = shortName;
_solver = solver;
Interpolate = interpolate;
Value = new Range(lo ?? double.NegativeInfinity, hi ?? double.PositiveInfinity, solver.Eps);
}
public NumericVariable AlsoNamed(string name) {
Name += ";" + name;
return this;
}
public int LastChangedAt => _lastChangedAt;
[NotNull]
public Range Value { get; private set; }
/// <summary>
/// Compute a current estimate of the variable as follows: If either of the current estimate's
/// boundaries is infinity, the other boundary is returned. If both boundaries are defined,
/// the interpolated value between them (as defined by <see cref="Interpolate"/>) is used;
/// <c>Interpolate</c> == 0 means that the lower boundary is returned, <c>Inpterpolate</c> == 1
/// returns the upper bound, and in general, <c>(1 - Interpolate) * Value.Lo + Interpolate * Value.Hi</c>
/// is returned.
/// </summary>
/// <returns>Current estimate of the variable</returns>
public double GetValue() {
if (double.IsInfinity(Value.Hi)) {
return Value.Lo;
} else if (double.IsInfinity(Value.Lo)) {
return Value.Hi;
} else {
return (1 - Interpolate) * Value.Lo + Interpolate * Value.Hi;
}
}
public SimpleConstraintSolver Solver => _solver;
public IEnumerable<AbstractConstraint> DependentConstraints => _dependentConstraints;
public IEnumerable<AbstractConstraint> ActiveConstraints => _dependentConstraints.Where(c => !c.IsSubsumed);
public int VarIndex => _varIndex;
[ExcludeFromCodeCoverage]
public override string ToString() {
return $".{_varIndex} '{ShortName}'={Value} {(Fixed?'F':' ')} Definition={Definition} lastChange@{_lastChangedAt}";
}
public static NumericVariable operator +(NumericVariable left, NumericVariable right) {
NumericVariable result = left.DeriveVariable("-Sum0rh", $".{left.VarIndex} + .{right.VarIndex}");
SumIs0Constraint.CreateSumIs0Constraint(left, right, -result);
return result;
}
private NumericVariable DeriveVariable([NotNull] string shortName, string definition) {
return Solver.GetOrCreateVariable(shortName, definition, null, null, Interpolate);
}
public static NumericVariable operator -(NumericVariable left, NumericVariable right) {
NumericVariable result = left.DeriveVariable("+Sum0rh", $".{left.VarIndex}-.{right.VarIndex}");
SumIs0Constraint.CreateSumIs0Constraint(-left, right, result);
return result;
}
public static NumericVariable operator +(NumericVariable left, double right) {
return left + left.CreateConstant(right);
}
private NumericVariable CreateConstant(double d) {
return Solver.GetOrCreateVariable("const", "" + d, d, d, 0);
}
public static NumericVariable operator +(double left, NumericVariable right) {
return right.CreateConstant(left) + right;
}
public static NumericVariable operator -(NumericVariable left, double right) {
return left + -right;
}
public static NumericVariable operator -(double left, NumericVariable right) {
return left + -right;
}
public static NumericVariable operator *(NumericVariable v, double d) {
NumericVariable result = v.DeriveVariable("Prop*rh", $".{v.VarIndex}*{d}");
ProportionalConstraint.CreateProportionalConstraint(d, v, result);
return result;
}
public static NumericVariable operator *(double d, NumericVariable v) {
return v * d;
}
public static NumericVariable operator /(NumericVariable v, double d) {
NumericVariable result = v.DeriveVariable("Prop/rh", $".{v.VarIndex}/{d}");
ProportionalConstraint.CreateProportionalConstraint(d, result, v);
return result;
}
public static NumericVariable operator -(NumericVariable v) {
NumericVariable result = v.DeriveVariable("Invrh", $"-.{v.VarIndex}");
IsInverseConstraint.CreateIsInverseConstraint(v, result);
return result;
}
/// <summary>
/// The variable's minimum is restricted to the (eventual) value of another variable.
/// </summary>
/// <returns><c>this</c></returns>
public NumericVariable Min(NumericVariable value) {
AtLeastConstraint.CreateAtLeastConstraint(this, value);
return this;
}
/// <summary>
/// The variable's value is restricted to be equal to the (eventual) value of another variable.
/// </summary>
/// <returns><c>this</c></returns>
public NumericVariable Set(NumericVariable value) {
EqualityConstraint.CreateEqualityConstraint(this, value);
return this;
}
/// <summary>
/// The variable's maximum is restricted to the (eventual) value of another variable.
/// </summary>
/// <returns><c>this</c></returns>
public NumericVariable Max(NumericVariable value) {
AtLeastConstraint.CreateAtLeastConstraint(value, this);
return this;
}
/// <summary>
///
/// </summary>
/// <param name="lo"></param>
/// <param name="hi"></param>
/// <param name="d">Factor multipled into lo and hi; with a negative factor, the meaning of lo and hi is reversed;
/// e.g., RestrictRange(3, 4, -2) restricts the variable to the range [-8..-6]</param>
/// <returns>true if the current range estimate has been changed by the new restriction.</returns>
public bool RestrictRange(double lo, double hi, double d = 1) {
double loD, hiD;
if (d >= 0) {
loD = lo * d;
hiD = hi * d;
} else {
loD = hi * d;
hiD = lo * d;
}
Range oldValue = Value;
Range newValue = oldValue.Intersect(loD, hiD);
//if (newValue.IsEmpty && oldValue.IsSingleValue) {
// newValue = new Range(oldValue.Lo - Math.Abs(oldValue.Lo) * 1e-5, oldValue.Hi + Math.Abs(oldValue.Hi) * 1e-5, 1e-5).Intersect(loD, hiD);
//}
if (newValue.IsEmpty) {
throw new SolverException("No possible solution for variable " + this);
}
if (Equals(newValue, oldValue)) {
return false;
} else {
Value = newValue;
_lastChangedAt = _solver.Now;
return true;
}
}
/// <summary>
/// The variable's value is restricted to a fixed range.
/// </summary>
/// <returns><c>true</c> if the current range estimate has been changed by the new restriction.</returns>
public bool RestrictRange(Range range) {
return RestrictRange(range.Lo, range.Hi);
}
/// <summary>
/// The variable's minimum is restricted to a fixed value.
/// </summary>
/// <returns>The variable if its current range estimate has been changed by the new restriction</returns>
public NumericVariable Min(double value) {
return RestrictRange(value, double.PositiveInfinity) ? this : null;
}
/// <summary>
/// The variable's value is restricted to a fixed value.
/// </summary>
/// <returns>The variable if its current range estimate has been changed by the new restriction</returns>
public NumericVariable Set(double value) {
return RestrictRange(value, value) ? this : null;
}
/// <summary>
/// The variable's maximum is restricted to a fixed value.
/// </summary>
/// <returns>The variable if its current range estimate has been changed by the new restriction</returns>
public NumericVariable Max(double value) {
return RestrictRange(double.NegativeInfinity, value) ? this : null;
}
/// <summary>
/// The variable is restricted to the value of <see cref="GetValue"/> if that value is finite.
/// </summary>
/// <returns><c>true</c> if the current range estimate has been changed by the new restriction.</returns>
public bool Fix() {
double fixedValue = GetValue();
bool changed = !double.IsInfinity(fixedValue) && RestrictRange(fixedValue, fixedValue);
if (changed) {
Fixed = true;
}
return changed;
}
internal void AddAsDependentConstraintForUseInConstraintConstructorOnly(AbstractConstraint constraint) {
_dependentConstraints.Add(constraint);
}
internal void MarkAllConstraintsDirty() {
foreach (var c in _dependentConstraints) {
c.MarkDirty();
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2014-2015 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Reflection;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal.Builders
{
/// <summary>
/// NUnitTestFixtureBuilder is able to build a fixture given
/// a class marked with a TestFixtureAttribute or an unmarked
/// class containing test methods. In the first case, it is
/// called by the attribute and in the second directly by
/// NUnitSuiteBuilder.
/// </summary>
public class NUnitTestFixtureBuilder
{
#region Static Fields
static readonly string NO_TYPE_ARGS_MSG =
"Fixture type contains generic parameters. You must either provide " +
"Type arguments or specify constructor arguments that allow NUnit " +
"to deduce the Type arguments.";
#endregion
#region Instance Fields
private ITestCaseBuilder _testBuilder = new DefaultTestCaseBuilder();
#endregion
#region Public Methods
/// <summary>
/// Build a TestFixture from type provided. A non-null TestSuite
/// must always be returned, since the method is generally called
/// because the user has marked the target class as a fixture.
/// If something prevents the fixture from being used, it should
/// be returned nonetheless, labelled as non-runnable.
/// </summary>
/// <param name="typeInfo">An ITypeInfo for the fixture to be used.</param>
/// <returns>A TestSuite object or one derived from TestSuite.</returns>
// TODO: This should really return a TestFixture, but that requires changes to the Test hierarchy.
public TestSuite BuildFrom(ITypeInfo typeInfo)
{
var fixture = new TestFixture(typeInfo);
if (fixture.RunState != RunState.NotRunnable)
CheckTestFixtureIsValid(fixture);
fixture.ApplyAttributesToTest(typeInfo.Type.GetTypeInfo());
AddTestCasesToFixture(fixture);
return fixture;
}
/// <summary>
/// Overload of BuildFrom called by tests that have arguments.
/// Builds a fixture using the provided type and information
/// in the ITestFixtureData object.
/// </summary>
/// <param name="typeInfo">The TypeInfo for which to construct a fixture.</param>
/// <param name="testFixtureData">An object implementing ITestFixtureData or null.</param>
/// <returns></returns>
public TestSuite BuildFrom(ITypeInfo typeInfo, ITestFixtureData testFixtureData)
{
Guard.ArgumentNotNull(testFixtureData, "testFixtureData");
object[] arguments = testFixtureData.Arguments;
if (typeInfo.ContainsGenericParameters)
{
Type[] typeArgs = testFixtureData.TypeArgs;
if (typeArgs.Length == 0)
{
int cnt = 0;
foreach (object o in arguments)
if (o is Type) cnt++;
else break;
typeArgs = new Type[cnt];
for (int i = 0; i < cnt; i++)
typeArgs[i] = (Type)arguments[i];
if (cnt > 0)
{
object[] args = new object[arguments.Length - cnt];
for (int i = 0; i < args.Length; i++)
args[i] = arguments[cnt + i];
arguments = args;
}
}
if (typeArgs.Length > 0 ||
TypeHelper.CanDeduceTypeArgsFromArgs(typeInfo.Type, arguments, ref typeArgs))
{
typeInfo = typeInfo.MakeGenericType(typeArgs);
}
}
var fixture = new TestFixture(typeInfo);
if (arguments != null && arguments.Length > 0)
{
string name = fixture.Name = typeInfo.GetDisplayName(arguments);
string nspace = typeInfo.Namespace;
fixture.FullName = nspace != null && nspace != ""
? nspace + "." + name
: name;
fixture.Arguments = arguments;
}
if (fixture.RunState != RunState.NotRunnable)
fixture.RunState = testFixtureData.RunState;
foreach (string key in testFixtureData.Properties.Keys)
foreach (object val in testFixtureData.Properties[key])
fixture.Properties.Add(key, val);
if (fixture.RunState != RunState.NotRunnable)
CheckTestFixtureIsValid(fixture);
fixture.ApplyAttributesToTest(typeInfo.Type.GetTypeInfo());
AddTestCasesToFixture(fixture);
return fixture;
}
#endregion
#region Helper Methods
/// <summary>
/// Method to add test cases to the newly constructed fixture.
/// </summary>
/// <param name="fixture">The fixture to which cases should be added</param>
private void AddTestCasesToFixture(TestFixture fixture)
{
// TODO: Check this logic added from Neil's build.
if (fixture.TypeInfo.ContainsGenericParameters)
{
fixture.MakeInvalid(NO_TYPE_ARGS_MSG);
return;
}
var methods = fixture.TypeInfo.GetMethods(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (IMethodInfo method in methods)
{
Test test = BuildTestCase(method, fixture);
if (test != null)
{
fixture.Add(test);
}
}
}
/// <summary>
/// Method to create a test case from a MethodInfo and add
/// it to the fixture being built. It first checks to see if
/// any global TestCaseBuilder addin wants to build the
/// test case. If not, it uses the internal builder
/// collection maintained by this fixture builder.
///
/// The default implementation has no test case builders.
/// Derived classes should add builders to the collection
/// in their constructor.
/// </summary>
/// <param name="method">The method for which a test is to be created</param>
/// <param name="suite">The test suite being built.</param>
/// <returns>A newly constructed Test</returns>
private Test BuildTestCase(IMethodInfo method, TestSuite suite)
{
return _testBuilder.CanBuildFrom(method, suite)
? _testBuilder.BuildFrom(method, suite)
: null;
}
private static void CheckTestFixtureIsValid(TestFixture fixture)
{
if (fixture.TypeInfo.ContainsGenericParameters)
{
fixture.MakeInvalid(NO_TYPE_ARGS_MSG);
}
else if (!fixture.TypeInfo.IsStaticClass)
{
Type[] argTypes = Reflect.GetTypeArray(fixture.Arguments);
if (!fixture.TypeInfo.HasConstructor(argTypes))
{
fixture.MakeInvalid("No suitable constructor was found");
}
}
}
private static bool IsStaticClass(Type type)
{
return type.GetTypeInfo().IsAbstract && type.GetTypeInfo().IsSealed;
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Server.Base;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalGridServicesConnector")]
public class LocalGridServicesConnector : ISharedRegionModule, IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private static string LogHeader = "[LOCAL GRID SERVICE CONNECTOR]";
private IGridService m_GridService;
private Dictionary<UUID, RegionCache> m_LocalCache = new Dictionary<UUID, RegionCache>();
private bool m_Enabled;
public LocalGridServicesConnector()
{
m_log.DebugFormat("{0} LocalGridServicesConnector no parms.", LogHeader);
}
public LocalGridServicesConnector(IConfigSource source)
{
m_log.DebugFormat("{0} LocalGridServicesConnector instantiated directly.", LogHeader);
InitialiseService(source);
}
#region ISharedRegionModule
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LocalGridServicesConnector"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("GridServices", "");
if (name == Name)
{
InitialiseService(source);
m_log.Info("[LOCAL GRID SERVICE CONNECTOR]: Local grid connector enabled");
}
}
}
private void InitialiseService(IConfigSource source)
{
IConfig assetConfig = source.Configs["GridService"];
if (assetConfig == null)
{
m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: GridService missing from OpenSim.ini");
return;
}
string serviceDll = assetConfig.GetString("LocalServiceModule",
String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: No LocalServiceModule named in section GridService");
return;
}
Object[] args = new Object[] { source };
m_GridService =
ServerUtils.LoadPlugin<IGridService>(serviceDll,
args);
if (m_GridService == null)
{
m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: Can't load grid service");
return;
}
m_Enabled = true;
}
public void PostInitialise()
{
// FIXME: We will still add this command even if we aren't enabled since RemoteGridServiceConnector
// will have instantiated us directly.
MainConsole.Instance.Commands.AddCommand("Regions", false, "show neighbours",
"show neighbours",
"Shows the local regions' neighbours", HandleShowNeighboursCommand);
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.RegisterModuleInterface<IGridService>(this);
lock (m_LocalCache)
{
if (m_LocalCache.ContainsKey(scene.RegionInfo.RegionID))
m_log.ErrorFormat("[LOCAL GRID SERVICE CONNECTOR]: simulator seems to have more than one region with the same UUID. Please correct this!");
else
m_LocalCache.Add(scene.RegionInfo.RegionID, new RegionCache(scene));
}
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_LocalCache)
{
m_LocalCache[scene.RegionInfo.RegionID].Clear();
m_LocalCache.Remove(scene.RegionInfo.RegionID);
}
}
public void RegionLoaded(Scene scene)
{
}
#endregion
#region IGridService
public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
return m_GridService.RegisterRegion(scopeID, regionInfo);
}
public bool DeregisterRegion(UUID regionID)
{
return m_GridService.DeregisterRegion(regionID);
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
return m_GridService.GetNeighbours(scopeID, regionID);
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
return m_GridService.GetRegionByUUID(scopeID, regionID);
}
// Get a region given its base coordinates.
// NOTE: this is NOT 'get a region by some point in the region'. The coordinate MUST
// be the base coordinate of the region.
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
GridRegion region = null;
// First see if it's a neighbour, even if it isn't on this sim.
// Neighbour data is cached in memory, so this is fast
lock (m_LocalCache)
{
foreach (RegionCache rcache in m_LocalCache.Values)
{
region = rcache.GetRegionByPosition(x, y);
if (region != null)
{
// m_log.DebugFormat("{0} GetRegionByPosition. Found region {1} in cache. Pos=<{2},{3}>",
// LogHeader, region.RegionName, x, y);
break;
}
}
}
// Then try on this sim (may be a lookup in DB if this is using MySql).
if (region == null)
{
region = m_GridService.GetRegionByPosition(scopeID, x, y);
if (region == null)
m_log.DebugFormat("{0} GetRegionByPosition. Region not found by grid service. Pos=<{1},{2}>",
LogHeader, x, y);
else
m_log.DebugFormat("{0} GetRegionByPosition. Requested region {1} from grid service. Pos=<{2},{3}>",
LogHeader, region.RegionName, x, y);
}
return region;
}
public GridRegion GetRegionByName(UUID scopeID, string regionName)
{
return m_GridService.GetRegionByName(scopeID, regionName);
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
return m_GridService.GetRegionsByName(scopeID, name, maxNumber);
}
public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
return m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax);
}
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
return m_GridService.GetDefaultRegions(scopeID);
}
public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID)
{
return m_GridService.GetDefaultHypergridRegions(scopeID);
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
return m_GridService.GetFallbackRegions(scopeID, x, y);
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
return m_GridService.GetHyperlinks(scopeID);
}
public int GetRegionFlags(UUID scopeID, UUID regionID)
{
return m_GridService.GetRegionFlags(scopeID, regionID);
}
#endregion
public void HandleShowNeighboursCommand(string module, string[] cmdparams)
{
System.Text.StringBuilder caps = new System.Text.StringBuilder();
lock (m_LocalCache)
{
foreach (KeyValuePair<UUID, RegionCache> kvp in m_LocalCache)
{
caps.AppendFormat("*** Neighbours of {0} ({1}) ***\n", kvp.Value.RegionName, kvp.Key);
List<GridRegion> regions = kvp.Value.GetNeighbours();
foreach (GridRegion r in regions)
caps.AppendFormat(" {0} @ {1}-{2}\n", r.RegionName, Util.WorldToRegionLoc((uint)r.RegionLocX), Util.WorldToRegionLoc((uint)r.RegionLocY));
}
}
MainConsole.Instance.Output(caps.ToString());
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using System.Linq;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Video.V1
{
/// <summary>
/// Returns a single Composition resource identified by a Composition SID.
/// </summary>
public class FetchCompositionOptions : IOptions<CompositionResource>
{
/// <summary>
/// The SID that identifies the resource to fetch
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchCompositionOptions
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
public FetchCompositionOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// List of all Recording compositions.
/// </summary>
public class ReadCompositionOptions : ReadOptions<CompositionResource>
{
/// <summary>
/// Read only Composition resources with this status
/// </summary>
public CompositionResource.StatusEnum Status { get; set; }
/// <summary>
/// Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone
/// </summary>
public DateTime? DateCreatedAfter { get; set; }
/// <summary>
/// Read only Composition resources created before this ISO 8601 date-time with time zone
/// </summary>
public DateTime? DateCreatedBefore { get; set; }
/// <summary>
/// Read only Composition resources with this Room SID
/// </summary>
public string RoomSid { get; set; }
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Status != null)
{
p.Add(new KeyValuePair<string, string>("Status", Status.ToString()));
}
if (DateCreatedAfter != null)
{
p.Add(new KeyValuePair<string, string>("DateCreatedAfter", Serializers.DateTimeIso8601(DateCreatedAfter)));
}
if (DateCreatedBefore != null)
{
p.Add(new KeyValuePair<string, string>("DateCreatedBefore", Serializers.DateTimeIso8601(DateCreatedBefore)));
}
if (RoomSid != null)
{
p.Add(new KeyValuePair<string, string>("RoomSid", RoomSid.ToString()));
}
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// Delete a Recording Composition resource identified by a Composition SID.
/// </summary>
public class DeleteCompositionOptions : IOptions<CompositionResource>
{
/// <summary>
/// The SID that identifies the resource to delete
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new DeleteCompositionOptions
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to delete </param>
public DeleteCompositionOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// CreateCompositionOptions
/// </summary>
public class CreateCompositionOptions : IOptions<CompositionResource>
{
/// <summary>
/// The SID of the Group Room with the media tracks to be used as composition sources
/// </summary>
public string RoomSid { get; }
/// <summary>
/// An object that describes the video layout of the composition
/// </summary>
public object VideoLayout { get; set; }
/// <summary>
/// An array of track names from the same group room to merge
/// </summary>
public List<string> AudioSources { get; set; }
/// <summary>
/// An array of track names to exclude
/// </summary>
public List<string> AudioSourcesExcluded { get; set; }
/// <summary>
/// A string that describes the columns (width) and rows (height) of the generated composed video in pixels
/// </summary>
public string Resolution { get; set; }
/// <summary>
/// The container format of the composition's media files
/// </summary>
public CompositionResource.FormatEnum Format { get; set; }
/// <summary>
/// The URL we should call to send status information to your application
/// </summary>
public Uri StatusCallback { get; set; }
/// <summary>
/// The HTTP method we should use to call status_callback
/// </summary>
public Twilio.Http.HttpMethod StatusCallbackMethod { get; set; }
/// <summary>
/// Whether to clip the intervals where there is no active media in the composition
/// </summary>
public bool? Trim { get; set; }
/// <summary>
/// Construct a new CreateCompositionOptions
/// </summary>
/// <param name="roomSid"> The SID of the Group Room with the media tracks to be used as composition sources </param>
public CreateCompositionOptions(string roomSid)
{
RoomSid = roomSid;
AudioSources = new List<string>();
AudioSourcesExcluded = new List<string>();
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (RoomSid != null)
{
p.Add(new KeyValuePair<string, string>("RoomSid", RoomSid.ToString()));
}
if (VideoLayout != null)
{
p.Add(new KeyValuePair<string, string>("VideoLayout", Serializers.JsonObject(VideoLayout)));
}
if (AudioSources != null)
{
p.AddRange(AudioSources.Select(prop => new KeyValuePair<string, string>("AudioSources", prop)));
}
if (AudioSourcesExcluded != null)
{
p.AddRange(AudioSourcesExcluded.Select(prop => new KeyValuePair<string, string>("AudioSourcesExcluded", prop)));
}
if (Resolution != null)
{
p.Add(new KeyValuePair<string, string>("Resolution", Resolution));
}
if (Format != null)
{
p.Add(new KeyValuePair<string, string>("Format", Format.ToString()));
}
if (StatusCallback != null)
{
p.Add(new KeyValuePair<string, string>("StatusCallback", Serializers.Url(StatusCallback)));
}
if (StatusCallbackMethod != null)
{
p.Add(new KeyValuePair<string, string>("StatusCallbackMethod", StatusCallbackMethod.ToString()));
}
if (Trim != null)
{
p.Add(new KeyValuePair<string, string>("Trim", Trim.Value.ToString().ToLower()));
}
return p;
}
}
}
| |
/*
* 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.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Timers;
using OpenMetaverse;
using Nini.Config;
using OpenSim.Framework.Servers.HttpServer;
using log4net;
namespace OpenSim.Framework.Console
{
// A console that uses REST interfaces
//
public class RemoteConsole : CommandConsole
{
// Connection specific data, indexed by a session ID
// we create when a client connects.
protected class ConsoleConnection
{
// Last activity from the client
public int last;
// Last line of scrollback posted to this client
public long lastLineSeen;
// True if this is a new connection, e.g. has never
// displayed a prompt to the user.
public bool newConnection = true;
}
// A line in the scrollback buffer.
protected class ScrollbackEntry
{
// The line number of this entry
public long lineNumber;
// The text to send to the client
public string text;
// The level this should be logged as. Omitted for
// prompts and input echo.
public string level;
// True if the text above is a prompt, e.g. the
// client should turn on the cursor / accept input
public bool isPrompt;
// True if the requested input is a command. A
// client may offer help or validate input if
// this is set. If false, input should be sent
// as typed.
public bool isCommand;
// True if this text represents a line of text that
// was input in response to a prompt. A client should
// turn off the cursor and refrain from sending commands
// until a new prompt is received.
public bool isInput;
}
// Data that is relevant to all connections
// The scrollback buffer
protected List<ScrollbackEntry> m_Scrollback = new List<ScrollbackEntry>();
// Monotonously incrementing line number. This may eventually
// wrap. No provision is made for that case because 64 bits
// is a long, long time.
protected long m_lineNumber = 0;
// These two variables allow us to send the correct
// information about the prompt status to the client,
// irrespective of what may have run off the top of the
// scrollback buffer;
protected bool m_expectingInput = false;
protected bool m_expectingCommand = true;
protected string m_lastPromptUsed;
// This is the list of things received from clients.
// Note: Race conditions can happen. If a client sends
// something while nothing is expected, it will be
// intepreted as input to the next prompt. For
// commands this is largely correct. For other prompts,
// YMMV.
// TODO: Find a better way to fix this
protected List<string> m_InputData = new List<string>();
// Event to allow ReadLine to wait synchronously even though
// everthing else is asynchronous here.
protected ManualResetEvent m_DataEvent = new ManualResetEvent(false);
// The list of sessions we maintain. Unlike other console types,
// multiple users on the same console are explicitly allowed.
protected Dictionary<UUID, ConsoleConnection> m_Connections =
new Dictionary<UUID, ConsoleConnection>();
// Timer to control expiration of sessions that have been
// disconnected.
protected System.Timers.Timer m_expireTimer = new System.Timers.Timer(5000);
// The less interesting stuff that makes the actual server
// work.
protected IHttpServer m_Server = null;
protected IConfigSource m_Config = null;
protected string m_UserName = String.Empty;
protected string m_Password = String.Empty;
protected string m_AllowedOrigin = String.Empty;
public RemoteConsole(string defaultPrompt) : base(defaultPrompt)
{
// There is something wrong with this architecture.
// A prompt is sent on every single input, so why have this?
// TODO: Investigate and fix.
m_lastPromptUsed = defaultPrompt;
// Start expiration of sesssions.
m_expireTimer.Elapsed += DoExpire;
m_expireTimer.Start();
}
public void ReadConfig(IConfigSource config)
{
m_Config = config;
// We're pulling this from the 'Network' section for legacy
// compatibility. However, this is so essentially insecure
// that TLS and client certs should be used instead of
// a username / password.
IConfig netConfig = m_Config.Configs["Network"];
if (netConfig == null)
return;
// Get the username and password.
m_UserName = netConfig.GetString("ConsoleUser", String.Empty);
m_Password = netConfig.GetString("ConsolePass", String.Empty);
// Woefully underdocumented, this is what makes javascript
// console clients work. Set to "*" for anywhere or (better)
// to specific addresses.
m_AllowedOrigin = netConfig.GetString("ConsoleAllowedOrigin", String.Empty);
}
public void SetServer(IHttpServer server)
{
// This is called by the framework to give us the server
// instance (means: port) to work with.
m_Server = server;
// Add our handlers
m_Server.AddHTTPHandler("/StartSession/", HandleHttpStartSession);
m_Server.AddHTTPHandler("/CloseSession/", HandleHttpCloseSession);
m_Server.AddHTTPHandler("/SessionCommand/", HandleHttpSessionCommand);
}
public override void Output(string text, string level)
{
Output(text, level, false, false, false);
}
protected void Output(string text, string level, bool isPrompt, bool isCommand, bool isInput)
{
// Increment the line number. It was 0 and they start at 1
// so we need to pre-increment.
m_lineNumber++;
// Create and populate the new entry.
ScrollbackEntry newEntry = new ScrollbackEntry();
newEntry.lineNumber = m_lineNumber;
newEntry.text = text;
newEntry.level = level;
newEntry.isPrompt = isPrompt;
newEntry.isCommand = isCommand;
newEntry.isInput = isInput;
// Add a line to the scrollback. In some cases, that may not
// actually be a line of text.
lock (m_Scrollback)
{
// Prune the scrollback to the length se send as connect
// burst to give the user some context.
while (m_Scrollback.Count >= 1000)
m_Scrollback.RemoveAt(0);
m_Scrollback.Add(newEntry);
}
// Let the rest of the system know we have output something.
FireOnOutput(text.Trim());
// Also display it for debugging.
System.Console.WriteLine(text.Trim());
}
public override void Output(string text)
{
// Output plain (non-logging style) text.
Output(text, String.Empty, false, false, false);
}
public override string ReadLine(string p, bool isCommand, bool e)
{
// Output the prompt an prepare to wait. This
// is called on a dedicated console thread and
// needs to be synchronous. Old architecture but
// not worth upgrading.
if (isCommand)
{
m_expectingInput = true;
m_expectingCommand = true;
Output(p, String.Empty, true, true, false);
m_lastPromptUsed = p;
}
else
{
m_expectingInput = true;
Output(p, String.Empty, true, false, false);
}
// Here is where we wait for the user to input something.
m_DataEvent.WaitOne();
string cmdinput;
// Check for empty input. Read input if not empty.
lock (m_InputData)
{
if (m_InputData.Count == 0)
{
m_DataEvent.Reset();
m_expectingInput = false;
m_expectingCommand = false;
return "";
}
cmdinput = m_InputData[0];
m_InputData.RemoveAt(0);
if (m_InputData.Count == 0)
m_DataEvent.Reset();
}
m_expectingInput = false;
m_expectingCommand = false;
// Echo to all the other users what we have done. This
// will also go to ourselves.
Output (cmdinput, String.Empty, false, false, true);
// If this is a command, we need to resolve and execute it.
if (isCommand)
{
// This call will actually execute the command and create
// any output associated with it. The core just gets an
// empty string so it will call again immediately.
string[] cmd = Commands.Resolve(Parser.Parse(cmdinput));
if (cmd.Length != 0)
{
int i;
for (i=0 ; i < cmd.Length ; i++)
{
if (cmd[i].Contains(" "))
cmd[i] = "\"" + cmd[i] + "\"";
}
return String.Empty;
}
}
// Return the raw input string if not a command.
return cmdinput;
}
// Very simplistic static access control header.
protected Hashtable CheckOrigin(Hashtable result)
{
if (!string.IsNullOrEmpty(m_AllowedOrigin))
result["access_control_allow_origin"] = m_AllowedOrigin;
return result;
}
/* TODO: Figure out how PollServiceHTTPHandler can access the request headers
* in order to use m_AllowedOrigin as a regular expression
protected Hashtable CheckOrigin(Hashtable headers, Hashtable result)
{
if (!string.IsNullOrEmpty(m_AllowedOrigin))
{
if (headers.ContainsKey("origin"))
{
string origin = headers["origin"].ToString();
if (Regex.IsMatch(origin, m_AllowedOrigin))
result["access_control_allow_origin"] = origin;
}
}
return result;
}
*/
protected void DoExpire(Object sender, ElapsedEventArgs e)
{
// Iterate the list of console connections and find those we
// haven't heard from for longer then the longpoll interval.
// Remove them.
List<UUID> expired = new List<UUID>();
lock (m_Connections)
{
// Mark the expired ones
foreach (KeyValuePair<UUID, ConsoleConnection> kvp in m_Connections)
{
if (System.Environment.TickCount - kvp.Value.last > 500000)
expired.Add(kvp.Key);
}
// Delete them
foreach (UUID id in expired)
{
m_Connections.Remove(id);
CloseConnection(id);
}
}
}
// Start a new session.
protected Hashtable HandleHttpStartSession(Hashtable request)
{
// The login is in the form of a http form post
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 401;
reply["content_type"] = "text/plain";
// Check user name and password
if (m_UserName == String.Empty)
return reply;
if (post["USER"] == null || post["PASS"] == null)
return reply;
if (m_UserName != post["USER"].ToString() ||
m_Password != post["PASS"].ToString())
{
return reply;
}
// Set up the new console connection record
ConsoleConnection c = new ConsoleConnection();
c.last = System.Environment.TickCount;
c.lastLineSeen = 0;
// Assign session ID
UUID sessionID = UUID.Random();
// Add connection to list.
lock (m_Connections)
{
m_Connections[sessionID] = c;
}
// This call is a CAP. The URL is the authentication.
string uri = "/ReadResponses/" + sessionID.ToString() + "/";
m_Server.AddPollServiceHTTPHandler(
uri, new PollServiceEventArgs(null, uri, HasEvents, GetEvents, NoEvents, sessionID,25000)); // 25 secs timeout
// Our reply is an XML document.
// TODO: Change this to Linq.Xml
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
XmlElement id = xmldoc.CreateElement("", "SessionID", "");
id.AppendChild(xmldoc.CreateTextNode(sessionID.ToString()));
rootElement.AppendChild(id);
XmlElement prompt = xmldoc.CreateElement("", "Prompt", "");
prompt.AppendChild(xmldoc.CreateTextNode(m_lastPromptUsed));
rootElement.AppendChild(prompt);
rootElement.AppendChild(MainConsole.Instance.Commands.GetXml(xmldoc));
// Set up the response and check origin
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
reply = CheckOrigin(reply);
return reply;
}
// Client closes session. Clean up.
protected Hashtable HandleHttpCloseSession(Hashtable request)
{
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 404;
reply["content_type"] = "text/plain";
if (post["ID"] == null)
return reply;
UUID id;
if (!UUID.TryParse(post["ID"].ToString(), out id))
return reply;
lock (m_Connections)
{
if (m_Connections.ContainsKey(id))
{
m_Connections.Remove(id);
CloseConnection(id);
}
}
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
XmlElement res = xmldoc.CreateElement("", "Result", "");
res.AppendChild(xmldoc.CreateTextNode("OK"));
rootElement.AppendChild(res);
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
reply = CheckOrigin(reply);
return reply;
}
// Command received from the client.
protected Hashtable HandleHttpSessionCommand(Hashtable request)
{
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 404;
reply["content_type"] = "text/plain";
// Check the ID
if (post["ID"] == null)
return reply;
UUID id;
if (!UUID.TryParse(post["ID"].ToString(), out id))
return reply;
// Find the connection for that ID.
lock (m_Connections)
{
if (!m_Connections.ContainsKey(id))
return reply;
}
// Empty post. Just error out.
if (post["COMMAND"] == null)
return reply;
// Place the input data in the buffer.
lock (m_InputData)
{
m_DataEvent.Set();
m_InputData.Add(post["COMMAND"].ToString());
}
// Create the XML reply document.
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
XmlElement res = xmldoc.CreateElement("", "Result", "");
res.AppendChild(xmldoc.CreateTextNode("OK"));
rootElement.AppendChild(res);
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
reply = CheckOrigin(reply);
return reply;
}
// Decode a HTTP form post to a Hashtable
protected Hashtable DecodePostString(string data)
{
Hashtable result = new Hashtable();
string[] terms = data.Split(new char[] {'&'});
foreach (string term in terms)
{
string[] elems = term.Split(new char[] {'='});
if (elems.Length == 0)
continue;
string name = System.Web.HttpUtility.UrlDecode(elems[0]);
string value = String.Empty;
if (elems.Length > 1)
value = System.Web.HttpUtility.UrlDecode(elems[1]);
result[name] = value;
}
return result;
}
// Close the CAP receiver for the responses for a given client.
public void CloseConnection(UUID id)
{
try
{
string uri = "/ReadResponses/" + id.ToString() + "/";
m_Server.RemovePollServiceHTTPHandler("", uri);
}
catch (Exception)
{
}
}
// Check if there is anything to send. Return true if this client has
// lines pending.
protected bool HasEvents(UUID RequestID, UUID sessionID)
{
ConsoleConnection c = null;
lock (m_Connections)
{
if (!m_Connections.ContainsKey(sessionID))
return false;
c = m_Connections[sessionID];
}
c.last = System.Environment.TickCount;
if (c.lastLineSeen < m_lineNumber)
return true;
return false;
}
// Send all pending output to the client.
protected Hashtable GetEvents(UUID RequestID, UUID sessionID)
{
// Find the connection that goes with this client.
ConsoleConnection c = null;
lock (m_Connections)
{
if (!m_Connections.ContainsKey(sessionID))
return NoEvents(RequestID, UUID.Zero);
c = m_Connections[sessionID];
}
// If we have nothing to send, send the no events response.
c.last = System.Environment.TickCount;
if (c.lastLineSeen >= m_lineNumber)
return NoEvents(RequestID, UUID.Zero);
Hashtable result = new Hashtable();
// Create the response document.
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
//if (c.newConnection)
//{
// c.newConnection = false;
// Output("+++" + DefaultPrompt);
//}
lock (m_Scrollback)
{
long startLine = m_lineNumber - m_Scrollback.Count;
long sendStart = startLine;
if (sendStart < c.lastLineSeen)
sendStart = c.lastLineSeen;
for (long i = sendStart ; i < m_lineNumber ; i++)
{
ScrollbackEntry e = m_Scrollback[(int)(i - startLine)];
XmlElement res = xmldoc.CreateElement("", "Line", "");
res.SetAttribute("Number", e.lineNumber.ToString());
res.SetAttribute("Level", e.level);
// Don't include these for the scrollback, we'll send the
// real state later.
if (!c.newConnection)
{
res.SetAttribute("Prompt", e.isPrompt ? "true" : "false");
res.SetAttribute("Command", e.isCommand ? "true" : "false");
res.SetAttribute("Input", e.isInput ? "true" : "false");
}
else if (i == m_lineNumber - 1) // Last line for a new connection
{
res.SetAttribute("Prompt", m_expectingInput ? "true" : "false");
res.SetAttribute("Command", m_expectingCommand ? "true" : "false");
res.SetAttribute("Input", (!m_expectingInput) ? "true" : "false");
}
else
{
res.SetAttribute("Input", e.isInput ? "true" : "false");
}
res.AppendChild(xmldoc.CreateTextNode(e.text));
rootElement.AppendChild(res);
}
}
c.lastLineSeen = m_lineNumber;
c.newConnection = false;
xmldoc.AppendChild(rootElement);
result["str_response_string"] = xmldoc.InnerXml;
result["int_response_code"] = 200;
result["content_type"] = "application/xml";
result["keepalive"] = false;
result["reusecontext"] = false;
result = CheckOrigin(result);
return result;
}
// This is really just a no-op. It generates what is sent
// to the client if the poll times out without any events.
protected Hashtable NoEvents(UUID RequestID, UUID id)
{
Hashtable result = new Hashtable();
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
result["str_response_string"] = xmldoc.InnerXml;
result["int_response_code"] = 200;
result["content_type"] = "text/xml";
result["keepalive"] = false;
result["reusecontext"] = false;
result = CheckOrigin(result);
return result;
}
}
}
| |
using System;
using System.Collections;
using Server;
using Server.Gumps;
using Server.Spells;
using Server.Spells.Fifth;
using Server.Spells.Seventh;
using Server.Spells.Necromancy;
using Server.Mobiles;
using Server.Network;
using Server.SkillHandlers;
namespace Server.Items
{
public class DisguiseKit : Item
{
public override int LabelNumber{ get{ return 1041078; } } // a disguise kit
[Constructable]
public DisguiseKit() : base( 0xE05 )
{
Weight = 1.0;
}
public DisguiseKit( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
public bool ValidateUse( Mobile from )
{
PlayerMobile pm = from as PlayerMobile;
if ( !IsChildOf( from.Backpack ) )
{
// That must be in your pack for you to use it.
from.SendLocalizedMessage( 1042001 );
}
else if ( pm == null || pm.NpcGuild != NpcGuild.ThievesGuild )
{
// Only Members of the thieves guild are trained to use this item.
from.SendLocalizedMessage( 501702 );
}
else if ( Stealing.SuspendOnMurder && pm.Kills > 0 )
{
// You are currently suspended from the thieves guild. They would frown upon your actions.
from.SendLocalizedMessage( 501703 );
}
else if ( !from.CanBeginAction( typeof( IncognitoSpell ) ) )
{
// You cannot disguise yourself while incognitoed.
from.SendLocalizedMessage( 501704 );
}
else if ( Factions.Sigil.ExistsOn( from ) )
{
from.SendLocalizedMessage( 1010465 ); // You cannot disguise yourself while holding a sigil
}
else if ( TransformationSpellHelper.UnderTransformation( from ) )
{
// You cannot disguise yourself while in that form.
from.SendLocalizedMessage( 1061634 );
}
else if ( from.BodyMod == 183 || from.BodyMod == 184 )
{
// You cannot disguise yourself while wearing body paint
from.SendLocalizedMessage( 1040002 );
}
else if ( !from.CanBeginAction( typeof( PolymorphSpell ) ) || from.IsBodyMod )
{
// You cannot disguise yourself while polymorphed.
from.SendLocalizedMessage( 501705 );
}
else
{
return true;
}
return false;
}
public override void OnDoubleClick( Mobile from )
{
if ( ValidateUse( from ) )
from.SendGump( new DisguiseGump( from, this, true, false ) );
}
}
public class DisguiseGump : Gump
{
private Mobile m_From;
private DisguiseKit m_Kit;
private bool m_Used;
public DisguiseGump( Mobile from, DisguiseKit kit, bool startAtHair, bool used ) : base( 50, 50 )
{
m_From = from;
m_Kit = kit;
m_Used = used;
from.CloseGump( typeof( DisguiseGump ) );
AddPage( 0 );
AddBackground( 100, 10, 400, 385, 2600 );
// <center>THIEF DISGUISE KIT</center>
AddHtmlLocalized( 100, 25, 400, 35, 1011045, false, false );
AddButton( 140, 353, 4005, 4007, 0, GumpButtonType.Reply, 0 );
AddHtmlLocalized( 172, 355, 90, 35, 1011036, false, false ); // OKAY
AddButton( 257, 353, 4005, 4007, 1, GumpButtonType.Reply, 0 );
AddHtmlLocalized( 289, 355, 90, 35, 1011046, false, false ); // APPLY
if ( from.Female || from.Body.IsFemale )
{
DrawEntries( 0, 1, -1, m_HairEntries, -1 );
}
else if ( startAtHair )
{
DrawEntries( 0, 1, 2, m_HairEntries, 1011056 );
DrawEntries( 1, 2, 1, m_BeardEntries, 1011059 );
}
else
{
DrawEntries( 1, 1, 2, m_BeardEntries, 1011059 );
DrawEntries( 0, 2, 1, m_HairEntries, 1011056 );
}
}
private void DrawEntries( int index, int page, int nextPage, DisguiseEntry[] entries, int nextNumber )
{
AddPage( page );
if ( nextPage != -1 )
{
AddButton( 155, 320, 250 + (index*2), 251 + (index*2), 0, GumpButtonType.Page, nextPage );
AddHtmlLocalized( 180, 320, 150, 35, nextNumber, false, false );
}
for ( int i = 0; i < entries.Length; ++i )
{
DisguiseEntry entry = entries[i];
if ( entry == null )
continue;
int x = (i % 2) * 205;
int y = (i / 2) * 55;
if ( entry.m_GumpID != 0 )
{
AddBackground( 220 + x, 60 + y, 50, 50, 2620 );
AddImage( 153 + x + entry.m_OffsetX, 15 + y + entry.m_OffsetY, entry.m_GumpID );
}
AddHtmlLocalized( 140 + x, 72 + y, 80, 35, entry.m_Number, false, false );
AddRadio( 118 + x, 73 + y, 208, 209, false, (i * 2) + index );
}
}
public override void OnResponse( NetState sender, RelayInfo info )
{
if ( info.ButtonID == 0 )
{
if ( m_Used )
m_From.SendLocalizedMessage( 501706 ); // Disguises wear off after 2 hours.
else
m_From.SendLocalizedMessage( 501707 ); // You're looking good.
return;
}
int[] switches = info.Switches;
if ( switches.Length == 0 )
return;
int switched = switches[0];
int type = switched % 2;
int index = switched / 2;
bool hair = ( type == 0 );
DisguiseEntry[] entries = ( hair ? m_HairEntries : m_BeardEntries );
if ( index >= 0 && index < entries.Length )
{
DisguiseEntry entry = entries[index];
if ( entry == null )
return;
if ( !m_Kit.ValidateUse( m_From ) )
return;
if ( !hair && (m_From.Female || m_From.Body.IsFemale) )
return;
m_From.NameMod = NameList.RandomName( m_From.Female ? "female" : "male" );
if ( m_From is PlayerMobile )
{
PlayerMobile pm = (PlayerMobile)m_From;
if ( hair )
pm.SetHairMods( entry.m_ItemID, -2 );
else
pm.SetHairMods( -2, entry.m_ItemID );
}
m_From.SendGump( new DisguiseGump( m_From, m_Kit, hair, true ) );
DisguiseTimers.RemoveTimer( m_From );
DisguiseTimers.CreateTimer( m_From, TimeSpan.FromHours( 2.0 ) );
DisguiseTimers.StartTimer( m_From );
}
}
private static DisguiseEntry[] m_HairEntries = new DisguiseEntry[]
{
new DisguiseEntry( 8251, 50700, 0, 5, 1011052 ), // Short
new DisguiseEntry( 8261, 60710, 0, 3, 1011047 ), // Pageboy
new DisguiseEntry( 8252, 60708, 0,- 5, 1011053 ), // Long
new DisguiseEntry( 8264, 60901, 0, 5, 1011048 ), // Receding
new DisguiseEntry( 8253, 60702, 0,- 5, 1011054 ), // Ponytail
new DisguiseEntry( 8265, 60707, 0,- 5, 1011049 ), // 2-tails
new DisguiseEntry( 8260, 50703, 0, 5, 1011055 ), // Mohawk
new DisguiseEntry( 8266, 60713, 0, 10, 1011050 ), // Topknot
null,
new DisguiseEntry( 0, 0, 0, 0, 1011051 ) // None
};
private static DisguiseEntry[] m_BeardEntries = new DisguiseEntry[]
{
new DisguiseEntry( 8269, 50906, 0, 0, 1011401 ), // Vandyke
new DisguiseEntry( 8257, 50808, 0,- 2, 1011062 ), // Mustache
new DisguiseEntry( 8255, 50802, 0, 0, 1011060 ), // Short beard
new DisguiseEntry( 8268, 50905, 0,-10, 1011061 ), // Long beard
new DisguiseEntry( 8267, 50904, 0, 0, 1011060 ), // Short beard
new DisguiseEntry( 8254, 50801, 0,-10, 1011061 ), // Long beard
null,
new DisguiseEntry( 0, 0, 0, 0, 1011051 ) // None
};
private class DisguiseEntry
{
public int m_Number;
public int m_ItemID;
public int m_GumpID;
public int m_OffsetX;
public int m_OffsetY;
public DisguiseEntry( int itemID, int gumpID, int ox, int oy, int name )
{
m_ItemID = itemID;
m_GumpID = gumpID;
m_OffsetX = ox;
m_OffsetY = oy;
m_Number = name;
}
}
}
public class DisguiseTimers
{
public static void Initialize()
{
new DisguisePersistance();
}
private class InternalTimer : Timer
{
private Mobile m_Player;
public InternalTimer( Mobile m, TimeSpan delay ) : base( delay )
{
m_Player = m;
Priority = TimerPriority.OneMinute;
}
protected override void OnTick()
{
m_Player.NameMod = null;
if ( m_Player is PlayerMobile )
((PlayerMobile)m_Player).SetHairMods( -1, -1 );
DisguiseTimers.RemoveTimer( m_Player );
}
}
public static void CreateTimer( Mobile m, TimeSpan delay )
{
if ( m != null )
if ( !m_Timers.Contains( m ) )
m_Timers[m] = new InternalTimer( m, delay );
}
public static void StartTimer( Mobile m )
{
Timer t = (Timer)m_Timers[m];
if ( t != null )
t.Start();
}
public static bool IsDisguised( Mobile m )
{
return m_Timers.Contains( m );
}
public static bool StopTimer( Mobile m )
{
Timer t = (Timer)m_Timers[m];
if ( t != null )
{
t.Delay = t.Next - DateTime.Now;
t.Stop();
}
return ( t != null );
}
public static bool RemoveTimer( Mobile m )
{
Timer t = (Timer)m_Timers[m];
if ( t != null )
{
t.Stop();
m_Timers.Remove( m );
}
return ( t != null );
}
public static TimeSpan TimeRemaining( Mobile m )
{
Timer t = (Timer)m_Timers[m];
if ( t != null )
{
return t.Next - DateTime.Now;
}
return TimeSpan.Zero;
}
private static Hashtable m_Timers = new Hashtable();
public static Hashtable Timers
{
get { return m_Timers; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Relational.Migrations.Infrastructure;
using Portfolio.Models;
namespace Portfolio.Migrations
{
[ContextType(typeof(ApplicationDbContext))]
partial class CreateIdentitySchema
{
public override string Id
{
get { return "00000000000000_CreateIdentitySchema"; }
}
public override string ProductVersion
{
get { return "7.0.0-beta5"; }
}
public override void BuildTargetModel(ModelBuilder builder)
{
builder
.Annotation("SqlServer:ValueGeneration", "Identity");
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Name")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("NormalizedName")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity)
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity)
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ProviderKey")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ProviderDisplayName")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 1);
b.Key("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
builder.Entity("Portfolio.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<int>("AccessFailedCount")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 2);
b.Property<string>("Email")
.Annotation("OriginalValueIndex", 3);
b.Property<bool>("EmailConfirmed")
.Annotation("OriginalValueIndex", 4);
b.Property<bool>("LockoutEnabled")
.Annotation("OriginalValueIndex", 5);
b.Property<DateTimeOffset?>("LockoutEnd")
.Annotation("OriginalValueIndex", 6);
b.Property<string>("NormalizedEmail")
.Annotation("OriginalValueIndex", 7);
b.Property<string>("NormalizedUserName")
.Annotation("OriginalValueIndex", 8);
b.Property<string>("PasswordHash")
.Annotation("OriginalValueIndex", 9);
b.Property<string>("PhoneNumber")
.Annotation("OriginalValueIndex", 10);
b.Property<bool>("PhoneNumberConfirmed")
.Annotation("OriginalValueIndex", 11);
b.Property<string>("SecurityStamp")
.Annotation("OriginalValueIndex", 12);
b.Property<bool>("TwoFactorEnabled")
.Annotation("OriginalValueIndex", 13);
b.Property<string>("UserName")
.Annotation("OriginalValueIndex", 14);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUsers");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Reference("Portfolio.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Reference("Portfolio.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
b.Reference("Portfolio.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
}
}
}
| |
// 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 BlendVariableByte()
{
var test = new SimpleTernaryOpTest__BlendVariableByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local 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 SimpleTernaryOpTest__BlendVariableByte
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Byte);
private const int Op2ElementCount = VectorSize / sizeof(Byte);
private const int Op3ElementCount = VectorSize / sizeof(Byte);
private const int RetElementCount = VectorSize / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Byte[] _data3 = new Byte[Op3ElementCount];
private static Vector256<Byte> _clsVar1;
private static Vector256<Byte> _clsVar2;
private static Vector256<Byte> _clsVar3;
private Vector256<Byte> _fld1;
private Vector256<Byte> _fld2;
private Vector256<Byte> _fld3;
private SimpleTernaryOpTest__DataTable<Byte, Byte, Byte, Byte> _dataTable;
static SimpleTernaryOpTest__BlendVariableByte()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (byte)(((i % 2) == 0) ? 128 : 1); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar3), ref Unsafe.As<Byte, byte>(ref _data3[0]), VectorSize);
}
public SimpleTernaryOpTest__BlendVariableByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (byte)(((i % 2) == 0) ? 128 : 1); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld3), ref Unsafe.As<Byte, byte>(ref _data3[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (byte)(((i % 2) == 0) ? 128 : 1); }
_dataTable = new SimpleTernaryOpTest__DataTable<Byte, Byte, Byte, Byte>(_data1, _data2, _data3, new Byte[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.BlendVariable(
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.BlendVariable(
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.BlendVariable(
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.BlendVariable), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.BlendVariable), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.BlendVariable), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.BlendVariable(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr);
var secondOp = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr);
var thirdOp = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray3Ptr);
var result = Avx2.BlendVariable(firstOp, secondOp, thirdOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, secondOp, thirdOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr));
var secondOp = Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr));
var thirdOp = Avx.LoadVector256((Byte*)(_dataTable.inArray3Ptr));
var result = Avx2.BlendVariable(firstOp, secondOp, thirdOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, secondOp, thirdOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr));
var secondOp = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr));
var thirdOp = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray3Ptr));
var result = Avx2.BlendVariable(firstOp, secondOp, thirdOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, secondOp, thirdOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleTernaryOpTest__BlendVariableByte();
var result = Avx2.BlendVariable(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.BlendVariable(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Byte> firstOp, Vector256<Byte> secondOp, Vector256<Byte> thirdOp, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] inArray3 = new Byte[Op3ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), firstOp);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), secondOp);
Unsafe.Write(Unsafe.AsPointer(ref inArray3[0]), thirdOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* firstOp, void* secondOp, void* thirdOp, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] inArray3 = new Byte[Op3ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(thirdOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Byte[] firstOp, Byte[] secondOp, Byte[] thirdOp, Byte[] result, [CallerMemberName] string method = "")
{
if (((thirdOp[0] >> 7) & 1) == 1 ? secondOp[0] != result[0] : firstOp[0] != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (((thirdOp[i] >> 7) & 1) == 1 ? secondOp[i] != result[i] : firstOp[i] != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.BlendVariable)}<Byte>(Vector256<Byte>, Vector256<Byte>, Vector256<Byte>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" secondOp: ({string.Join(", ", secondOp)})");
Console.WriteLine($" thirdOp: ({string.Join(", ", thirdOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.Lambda.Core;
using Alexa.NET.Request;
using Alexa.NET.Response;
using Alexa.NET.Request.Type;
using Newtonsoft.Json;
using StackExchange.API;
namespace StackExchange.Alexa
{
public partial class Service
{
private const string WelcomeText = "<p>Welcome to Stack Exchange!</p>";
private const string MainMenuOptions = "<p>Please say: inbox, hot questions, or help.</p>";
private const string AccountLinkingInfo = "<p>To enable account linking for the Stack Exchange skill, open the Amazon Alexa mobile app, or go to Alexa.amazon.com</p>";
private const string HelpText = @"<p>Stack Exchange is a network of 150+ Q and A communities including Stack Overflow,"
+@"the preeminent site for programmers to find, ask, and answer questions about software development. "
+@"To learn more, please go to stackexchange.com or stackoverflow.com. In order to check your "
+@"inbox, add favorite questions, and cast votes, you need to set up account linking. </p>" + AccountLinkingInfo;
private async Task<SkillResponse> GetLaunchRequestResponse()
{
return CreateResponse(WelcomeText + await GetMainMenu());
}
private async Task<SkillResponse> GetInboxIntentResponse()
{
if (!_client.IsLoggedIn) return CreateResponse("<p>In order to check your inbox, please set up account linking.</p>" + AccountLinkingInfo, shouldEndSession:true, displayLinkAccountCard: true);
var apiResponse = await _client.GetInbox(true);
if (!apiResponse.Success) return CreateResponse("<p>In order to check your inbox, please enable account linking.</p>" + AccountLinkingInfo, shouldEndSession:true, displayLinkAccountCard: true);
var sb = new StringBuilder();
if (apiResponse.items.Count() == 0)
{
sb.AppendLine("<p>There are no unread items in your inbox.</p>");
apiResponse = await _client.GetInbox(false);
if (apiResponse.items.Count() > 0)
{
sb.AppendLine("<p>Here are some recent messages which you probably already saw:</p>");
apiResponse.items = apiResponse.items.Take(5);
}
}
else
{
sb.AppendLine($"<p>There are {apiResponse.items.Count()} unread items in your inbox.</p>");
}
if (apiResponse.items.Count() > 0)
{
var i = 0;
foreach (var item in apiResponse.items)
{
i++;
sb.Append($"<p>{item.summary}</p>");
sb.AppendLine("<break time=\"1s\"/>");
}
}
sb.AppendLine(MainMenuOptions);
return CreateResponse(sb.ToString());
}
private async Task<SkillResponse> GetHotQuestionIntentResponse()
{
var rand = new Random();
var networkUsers = await _client.GetNetworkUsers();
var sitesWhereUserHasAccount = networkUsers.items.Select(m => m.site_url).ToList();
var sites = (await _client.GetSites())
.items
.Where(m => m.site_type == "main_site" && m.site_state == "normal")
.ToList(); // TODO cache this somwehere, maybe Redis
var userHasAccountOnSite = false;
if ((networkUsers.items != null) && (networkUsers.items.Any()))
{
if (rand.Next(100)<25) // 25% of questions from sites where user does NOT have an account yet
{
sites = sites.Where(m => !sitesWhereUserHasAccount.Contains(m.site_url)).ToList();
}
else
{
sites = sites.Where(m => sitesWhereUserHasAccount.Contains(m.site_url)).ToList();
userHasAccountOnSite = true;
}
}
var randomSite = sites[rand.Next(sites.Count)];
_state.site = randomSite.api_site_parameter;
const int NumberOfHotQuestions = 5;
var questions = (await _client.GetHotQuestions(_state.site, NumberOfHotQuestions)).items.ToList();
var question = questions[rand.Next(questions.Count)];
_state.question_id = question.question_id;
var sb = new StringBuilder();
sb.Append($"<p>Here's a hot question from {randomSite.name}:</p>");
sb.Append($"<p>{question.title}</p>");
sb.AppendLine("<break time=\"1s\"/>");
if (!userHasAccountOnSite)
{
sb.Append($"<p>By the way, you do not have an account on {randomSite.name} yet. If you like, you can create one on {randomSite.short_site_url}.</p>");
}
sb.Append($"<p>Say: more details, next question, or I'm done.</p>");
return CreateResponse(sb.ToString(), false);
}
private async Task<SkillResponse> GetHotQuestionDetailsIntentResponse()
{
if ((_state?.site == null) || (_state?.question_id == null)) return await GetHotQuestionIntentResponse();
var apiResponse = await _client.GetQuestionDetails(_state.site, _state.question_id.Value);
if (!apiResponse.Success) return CreateResponse("Sorry. There was a technical issue. Please try again later.");
var question = apiResponse.items.First();
var sb = new StringBuilder();
if ((question.tags != null) && (question.tags.Any()))
{
if (question.tags.Count() == 1)
{
sb.AppendLine("<p>The question has a single tag:</p>");
sb.AppendLine($"<p>{question.tags.First()}</p>");
}
else
{
sb.AppendLine($"<p>The question has {question.tags.Count()} tags:</p>");
foreach (var tag in question.tags)
{
sb.AppendLine($"<p>{tag}</p>");
}
}
sb.AppendLine("<break time=\"1s\"/>");
}
sb.AppendLine($"<p>Here's the full question:</p>");
sb.AppendLine($"<p>{question.bodyNoHtml}</p>");
sb.AppendLine("<break time=\"2s\"/>");
sb.AppendLine("<p>Please say: upvote, downvote, favorite, answers, next question, or I'm done.</p>");
return CreateResponse(sb.ToString(), false);
}
private async Task<SkillResponse> GetHotQuestionAnswersIntentResponse()
{
if ((_state?.site == null) || (_state?.question_id == null)) return await GetHotQuestionIntentResponse();
var answers = await _client.GetAnswers(_state.site, _state.question_id.Value);
if (!answers.Success) return CreateResponse("Sorry. There was a technical issue. Please try again later.");
if (!answers.items.Any())
{
return CreateResponse("<p>Actually, there aren't any answers for this question yet.</p>");
}
var answer = answers.items.First();
var sb = new StringBuilder();
if (answers.items.Count() == 1)
{
sb.AppendLine("<p>This question has one answer. It is:</p>");
}
else
{
sb.AppendLine($"<p>This question has {answers.items.Count()} answers. Here's the top answer:</p>");
}
sb.AppendLine($"<p>{answer.bodyNoHtml}</p>");
sb.AppendLine("<break time=\"2s\"/>");
sb.AppendLine("<p>Please say: upvote, downvote, next question, or I'm done.</p>");
// TODO need to vote on answer, not question
return CreateResponse(sb.ToString(), false);
}
enum VoteType
{
Upvote = 0,
Downvote = 1
}
private async Task<SkillResponse> GetUpvoteIntentResponse()
{
return await GetVoteIntentResponse(VoteType.Upvote);
}
private async Task<SkillResponse> GetDownvoteIntentResponse()
{
return await GetVoteIntentResponse(VoteType.Downvote);
}
private async Task<SkillResponse> GetVoteIntentResponse(VoteType voteType)
{
if (!_client.IsLoggedIn) return CreateResponse("<p>In order to vote on questions and answers, please set up account linking.</p>" + AccountLinkingInfo, shouldEndSession:true, displayLinkAccountCard: true);
if ((_state?.site == null) || (_state?.question_id == null)) return await GetHotQuestionIntentResponse();
var response = voteType == VoteType.Downvote ?
await _client.Downvote(_state.site, _state.question_id.Value) :
await _client.Upvote(_state.site, _state.question_id.Value);
if (!response.Success)
{
return CreateResponse($"<p>{response.error_message}</p>");
}
var score = response.items.First().score;
return CreateResponse($"<p>Ok! After your vote, the question now has a score of {score}.</p>", false);
}
private async Task<SkillResponse> GetFavoriteIntentResponse()
{
if (!_client.IsLoggedIn) return CreateResponse("<p>In order to add favorite questions, please set up account linking.</p>" + AccountLinkingInfo, shouldEndSession:true, displayLinkAccountCard: true);
if ((_state?.site == null) || (_state?.question_id == null)) return await GetHotQuestionIntentResponse();
var response = await _client.Favorite(_state.site, _state.question_id.Value);
if (!response.Success)
{
return CreateResponse($"<p>{response.error_message}</p>");
}
return CreateResponse($"<p>Ok! The question has been added to your favorites, so you can find it again later.</p>", false);
}
private async Task<string> GetMainMenu()
{
var sb = new StringBuilder();
var apiRequest = await _client.GetInbox();
if (apiRequest.Success)
{
var newMessages = apiRequest.items.Count();
if (newMessages == 0)
{
sb.AppendLine("<p>You have no unread messages.</p>");
}
else
{
sb.AppendLine($"<p>You have {newMessages} unread messages.</p>");
}
}
sb.AppendLine(MainMenuOptions);
return sb.ToString();
}
}
}
| |
//
// Tag.cs:
//
// Author:
// Guy Taylor (s0700260@sms.ed.ac.uk) (thebigguy.co.uk@gmail.com)
//
// Original Source:
// Id3v1/Tag.cs from TagLib-sharp
//
// Copyright (C) 2009 Guy Taylor (Original Implementation)
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// 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.Generic;
namespace TagLib.Audible
{
/// <summary>
/// This class extends <see cref="Tag" /> to provide support for
/// reading tags stored in the Audible Metadata format.
/// </summary>
public class Tag : TagLib.Tag
{
#region Private Fields
private List<KeyValuePair<string, string>> tags;
#endregion
#region Constructors
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="Tag" /> with no contents.
/// </summary>
public Tag ()
{
Clear ();
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="Tag" /> by reading the contents from a specified
/// position in a specified file.
/// </summary>
/// <param name="file">
/// A <see cref="File" /> object containing the file from
/// which the contents of the new instance is to be read.
/// </param>
/// <param name="position">
/// A <see cref="long" /> value specify at what position to
/// read the tag.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="file" /> is <see langword="null" />.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="position" /> is less than zero or greater
/// than the size of the file.
/// </exception>
/// <exception cref="CorruptFileException">
/// The file does not contain <see cref="FileIdentifier" />
/// at the given position.
/// </exception>
public Tag (File file, long position)
{
// TODO: can we read from file
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="Tag" /> by reading the contents from a specified
/// <see cref="ByteVector" /> object.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector" /> object to read the tag from.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="data" /> is <see langword="null" />.
/// </exception>
/// <exception cref="CorruptFileException">
/// <paramref name="data" /> is less than 128 bytes or does
/// not start with <see cref="FileIdentifier" />.
/// </exception>
public Tag (ByteVector data)
{
if (data == null)
throw new ArgumentNullException ("data");
Clear ();
Parse (data);
}
#endregion
#region Private Methods
/// <summary>
/// Populates the current instance by parsing the contents of
/// a raw AudibleMetadata tag.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector" /> object containing the whole tag
/// object
/// </param>
/// <exception cref="CorruptFileException">
/// <paramref name="data" /> is less than 128 bytes or does
/// not start with <see cref="FileIdentifier" />.
/// </exception>
private void Parse (ByteVector data)
{
String currentKey, currentValue;
int keyLen, valueLen;
try
{
do
{
keyLen = (int) data.ToUInt(true);
data.RemoveRange (0, 4);
valueLen = (int) data.ToUInt(true);
data.RemoveRange (0, 4);
currentKey = data.ToString ( TagLib.StringType.UTF8, 0, keyLen );
data.RemoveRange (0, keyLen);
currentValue = data.ToString ( TagLib.StringType.UTF8, 0, valueLen );
data.RemoveRange (0, valueLen);
tags.Add( new KeyValuePair<string, string>(currentKey, currentValue) );
//StringHandle (currentKey, currentValue);
// if it is not the last item remove the end byte (null terminated)
if (data.Count != 0)
data.RemoveRange(0,1);
}
while (data.Count >= 4);
}
catch (Exception)
{
//
}
if (data.Count != 0)
throw new CorruptFileException();
}
void setTag (string tagName, string value) {
for (int i = 0; i < tags.Count; i ++) {
if(tags[i].Key == tagName)
tags [i] = new KeyValuePair<string, string> (tags [i].Key, value);
}
}
private string getTag(string tagName){
foreach( KeyValuePair<string, string> tag in tags) {
if(tag.Key == tagName)
return tag.Value;
}
return null;
}
/*
/// <summary>
/// Given a key and value pair it will update the
/// present metadata.
/// </summary>
/// <param name="key">
/// A <see cref="String" /> containing the key.
/// </param>
/// <param name="strValue">
/// A <see cref="String" /> containing the value.
/// </param>
private void StringHandle (String key, String strValue)
{
switch (key)
{
case "title":
title = strValue;
break;
case "author":
artist = strValue;
break;
case "provider":
album = strValue;
break;
}
}
*/
#endregion
#region TagLib.Tag
/// <summary>
/// Gets the tag types contained in the current instance.
/// </summary>
/// <value>
/// Always <see cref="TagTypes.AudibleMetadata" />.
/// </value>
public override TagTypes TagTypes {
get {return TagTypes.AudibleMetadata;}
}
public string Author {
get {
return getTag ("author");
}
}
public override string Copyright {
get {
return getTag ("copyright");
}
set {
setTag ("copyright", value);
}
}
public string Description {
get { return getTag ("description"); }
}
public string Narrator {
get {
return getTag ("narrator");
}
}
/// <summary>
/// Gets the title for the media described by the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="string" /> object containing the title for
/// the media described by the current instance or <see
/// langword="null" /> if no value is present.
/// </value>
public override string Title {
get {
return getTag("title");
}
}
/// <summary>
/// Gets the album for the media described by the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="string" /> object containing the album for
/// the media described by the current instance or <see
/// langword="null" /> if no value is present.
/// </value>
public override string Album {
get {
return getTag("provider");
//return string.IsNullOrEmpty (album) ?
// null : album;
}
}
/// <summary>
/// Gets the album artist for the media described by the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="string[]" /> object containing a single
/// artist described by the current instance or <see
/// langword="null" /> if no value is present.
/// </value>
public override string[] AlbumArtists {
get {
String artist = getTag("provider");
return string.IsNullOrEmpty (artist) ?
null : new string[] {artist};
}
}
/// <summary>
/// Clears the values stored in the current instance.
/// </summary>
public override void Clear ()
{
tags = new List<KeyValuePair<string, string>>();
}
#endregion
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.WindowsAzure.Commands.Tools.Vhd.Model;
using Microsoft.WindowsAzure.Commands.Tools.Vhd.Model.Persistence;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Microsoft.WindowsAzure.Commands.Sync.Upload
{
internal static class CloudPageBlobExtensions
{
public static void SetUploadMetaData(this CloudPageBlob blob, LocalMetaData metaData)
{
if (metaData == null)
{
throw new ArgumentNullException("metaData");
}
blob.Metadata[LocalMetaData.MetaDataKey] = SerializationUtil.GetSerializedString(metaData);
}
public static void CleanUpUploadMetaData(this CloudPageBlob blob)
{
blob.Metadata.Remove(LocalMetaData.MetaDataKey);
}
public static LocalMetaData GetUploadMetaData(this CloudPageBlob blob)
{
if (blob.Metadata.Keys.Contains(LocalMetaData.MetaDataKey))
{
return SerializationUtil.GetObjectFromSerializedString<LocalMetaData>(blob.Metadata[LocalMetaData.MetaDataKey]);
}
return null;
}
public static byte[] GetBlobMd5Hash(this CloudPageBlob blob)
{
blob.FetchAttributes();
if (String.IsNullOrEmpty(blob.Properties.ContentMD5))
{
return null;
}
return Convert.FromBase64String(blob.Properties.ContentMD5);
}
public static byte[] GetBlobMd5Hash(this CloudPageBlob blob, BlobRequestOptions requestOptions)
{
blob.FetchAttributes(new AccessCondition(), requestOptions);
if (String.IsNullOrEmpty(blob.Properties.ContentMD5))
{
return null;
}
return Convert.FromBase64String(blob.Properties.ContentMD5);
}
public static void SetBlobMd5Hash(this CloudPageBlob blob, byte[] md5Hash)
{
var base64String = Convert.ToBase64String(md5Hash);
blob.Properties.ContentMD5 = base64String;
}
public static void RemoveBlobMd5Hash(this CloudPageBlob blob)
{
blob.Properties.ContentMD5 = null;
}
public static VhdFooter GetVhdFooter(this CloudPageBlob basePageBlob)
{
var vhdFileFactory = new VhdFileFactory();
using (var file = vhdFileFactory.Create(basePageBlob.OpenRead()))
{
return file.Footer;
}
}
public static bool Exists(this CloudPageBlob blob)
{
var listBlobItems = blob.Container.ListBlobs();
var blobToUpload = listBlobItems.FirstOrDefault(b => b.Uri == blob.Uri);
if (blobToUpload is CloudBlockBlob)
{
var message = String.Format(" CsUpload is expecting a page blob, however a block blob was found: '{0}'.", blob.Uri);
throw new InvalidOperationException(message);
}
return blobToUpload != null;
}
public static bool Exists(this CloudPageBlob blob, BlobRequestOptions options)
{
var listBlobItems = blob.Container.ListBlobs(null, false, BlobListingDetails.UncommittedBlobs, options);
var blobToUpload = listBlobItems.FirstOrDefault(b => b.Uri == blob.Uri);
if (blobToUpload is CloudBlockBlob)
{
var message = String.Format(" CsUpload is expecting a page blob, however a block blob was found: '{0}'.", blob.Uri);
throw new InvalidOperationException(message);
}
return blobToUpload != null;
}
}
internal static class StringExtensions
{
public static string ToString<T>(this IEnumerable<T> source, string separator)
{
return "[" + string.Join(",", source.Select(s => s.ToString()).ToArray()) + "]";
}
}
public class VhdFilePath
{
public VhdFilePath(string absolutePath, string relativePath)
{
AbsolutePath = absolutePath;
RelativePath = relativePath;
}
public string AbsolutePath { get; private set; }
public string RelativePath { get; private set; }
}
internal static class VhdFileExtensions
{
public static IEnumerable<Guid> GetChildrenIds(this VhdFile vhdFile, Guid uniqueId)
{
var identityChain = vhdFile.GetIdentityChain();
if (!identityChain.Contains(uniqueId))
{
yield break;
}
foreach (var id in identityChain.TakeWhile(id => id != uniqueId))
{
yield return id;
}
}
public static VhdFilePath GetFilePathBy(this VhdFile vhdFile, Guid uniqueId)
{
VhdFilePath result = null;
string baseVhdPath = String.Empty;
var newBlocksOwners = new List<Guid> { Guid.Empty };
var current = vhdFile;
while (current != null && current.Footer.UniqueId != uniqueId)
{
newBlocksOwners.Add(current.Footer.UniqueId);
if (current.Parent != null)
{
result = new VhdFilePath(current.Header.GetAbsoluteParentPath(),
current.Header.GetRelativeParentPath());
}
current = current.Parent;
}
if (result == null)
{
string message = String.Format("There is no parent VHD file with with the id '{0}'", uniqueId);
throw new InvalidOperationException(message);
}
return result;
}
}
public static class UriExtensions
{
/// <summary>
/// Normalizes a URI for use as a blob URI.
/// </summary>
/// <remarks>
/// Ensures that the container name is lower-case.
/// </remarks>
public static Uri NormalizeBlobUri(this Uri uri)
{
var ub = new UriBuilder(uri);
var parts = ub.Path
.Split(new char[] { '/' }, StringSplitOptions.None)
.Select((p, i) => i == 1 ? p.ToLowerInvariant() : p)
.ToArray();
ub.Path = string.Join("/", parts);
return ub.Uri;
}
}
public static class ExceptionUtil
{
public static string DumpStorageExceptionErrorDetails(StorageException storageException)
{
if (storageException == null)
{
return string.Empty;
}
var message = new StringBuilder();
message.AppendLine("StorageException details");
message.Append("Error.Code:").AppendLine(storageException.RequestInformation.ExtendedErrorInformation.ErrorCode);
message.Append("ErrorMessage:").AppendLine(storageException.RequestInformation.ExtendedErrorInformation.ErrorMessage);
foreach (var key in storageException.RequestInformation.ExtendedErrorInformation.AdditionalDetails.Keys)
{
message.Append(key).Append(":").Append(storageException.RequestInformation.ExtendedErrorInformation.AdditionalDetails[key]);
}
return message.ToString();
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
public class ReflectionFx : MonoBehaviour
{
public Transform[] reflectiveObjects;
public LayerMask reflectionMask;
public Material[] reflectiveMaterials;
private Transform reflectiveSurfaceHeight;
public Shader replacementShader;
private bool highQuality = false;
public Color clearColor = Color.black;
public System.String reflectionSampler = "_ReflectionTex";
public float clipPlaneOffset = 0.07F;
private Vector3 oldpos = Vector3.zero;
private Camera reflectionCamera;
private Dictionary<Camera, bool> helperCameras = null;
private Texture[] initialReflectionTextures;
public void Start()
{
initialReflectionTextures = new Texture2D[reflectiveMaterials.Length];
for (int i = 0; i < reflectiveMaterials.Length; i++)
{
initialReflectionTextures[i] = reflectiveMaterials[i].GetTexture(reflectionSampler);
}
if (!SystemInfo.supportsRenderTextures)
this.enabled = false;
}
public void OnDisable()
{
if (initialReflectionTextures == null)
return;
// restore initial reflection textures
for (int i = 0; i < reflectiveMaterials.Length; i++)
{
reflectiveMaterials[i].SetTexture(reflectionSampler, initialReflectionTextures[i]);
}
}
private Camera CreateReflectionCameraFor(Camera cam)
{
System.String reflName = gameObject.name + "Reflection" + cam.name;
Debug.Log ("AngryBots: created internal reflection camera " + reflName);
GameObject go = GameObject.Find(reflName);
if(!go)
go = new GameObject(reflName, typeof(Camera));
if(!go.GetComponent(typeof(Camera)))
go.AddComponent(typeof(Camera));
Camera reflectCamera = go.GetComponent<Camera>();
reflectCamera.backgroundColor = clearColor;
reflectCamera.clearFlags = CameraClearFlags.SolidColor;
SetStandardCameraParameter(reflectCamera, reflectionMask);
if(!reflectCamera.targetTexture)
reflectCamera.targetTexture = CreateTextureFor(cam);
return reflectCamera;
}
public void HighQuality ()
{
highQuality = true;
}
private void SetStandardCameraParameter(Camera cam, LayerMask mask)
{
cam.backgroundColor = Color.black;
cam.enabled = false;
cam.cullingMask = reflectionMask;
}
private RenderTexture CreateTextureFor(Camera cam)
{
RenderTextureFormat rtFormat = RenderTextureFormat.RGB565;
if (!SystemInfo.SupportsRenderTextureFormat (rtFormat))
rtFormat = RenderTextureFormat.Default;
float rtSizeMul = highQuality ? 0.75f : 0.5f;
RenderTexture rt = new RenderTexture(Mathf.FloorToInt(cam.pixelWidth * rtSizeMul), Mathf.FloorToInt(cam.pixelHeight * rtSizeMul), 24, rtFormat);
rt.hideFlags = HideFlags.DontSave;
return rt;
}
public void RenderHelpCameras (Camera currentCam)
{
if(null == helperCameras)
helperCameras = new Dictionary<Camera, bool>();
if(!helperCameras.ContainsKey(currentCam)) {
helperCameras.Add(currentCam, false);
}
if(helperCameras[currentCam]) {
return;
}
if(!reflectionCamera) {
reflectionCamera = CreateReflectionCameraFor (currentCam);
foreach (Material m in reflectiveMaterials) {
m.SetTexture (reflectionSampler, reflectionCamera.targetTexture);
}
}
RenderReflectionFor(currentCam, reflectionCamera);
helperCameras[currentCam] = true;
}
public void LateUpdate ()
{
// find the closest reflective surface and use that as our
// reference for reflection height etc.
Transform closest = null;
float closestDist = Mathf.Infinity;
Vector3 pos = Camera.main.transform.position;
foreach (Transform t in reflectiveObjects) {
if (t.GetComponent<Renderer>().isVisible) {
float dist = (pos - t.position).sqrMagnitude;
if (dist < closestDist) {
closestDist = dist;
closest = t;
}
}
}
if(!closest)
return;
ObjectBeingRendered (closest, Camera.main);
if (null != helperCameras)
helperCameras.Clear();
}
private void ObjectBeingRendered (Transform tr, Camera currentCam)
{
if (null == tr)
return;
reflectiveSurfaceHeight = tr;
RenderHelpCameras (currentCam);
}
private void RenderReflectionFor (Camera cam, Camera reflectCamera)
{
if(!reflectCamera)
return;
SaneCameraSettings(reflectCamera);
reflectCamera.backgroundColor = clearColor;
GL.SetRevertBackfacing(true);
Transform reflectiveSurface = reflectiveSurfaceHeight;
Vector3 eulerA = cam.transform.eulerAngles;
reflectCamera.transform.eulerAngles = new Vector3(-eulerA.x, eulerA.y, eulerA.z);
reflectCamera.transform.position = cam.transform.position;
Vector3 pos = reflectiveSurface.transform.position;
pos.y = reflectiveSurface.position.y;
Vector3 normal = reflectiveSurface.transform.up;
float d = -Vector3.Dot(normal, pos) - clipPlaneOffset;
Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d);
Matrix4x4 reflection = Matrix4x4.zero;
reflection = CalculateReflectionMatrix(reflection, reflectionPlane);
oldpos = cam.transform.position;
Vector3 newpos = reflection.MultiplyPoint (oldpos);
reflectCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;
Vector4 clipPlane = CameraSpacePlane(reflectCamera, pos, normal, 1.0f);
Matrix4x4 projection = cam.projectionMatrix;
projection = CalculateObliqueMatrix(projection, clipPlane);
reflectCamera.projectionMatrix = projection;
reflectCamera.transform.position = newpos;
Vector3 euler = cam.transform.eulerAngles;
reflectCamera.transform.eulerAngles = new Vector3(-euler.x, euler.y, euler.z);
reflectCamera.RenderWithShader (replacementShader, "Reflection");
GL.SetRevertBackfacing(false);
}
private void SaneCameraSettings(Camera helperCam)
{
helperCam.depthTextureMode = DepthTextureMode.None;
helperCam.backgroundColor = Color.black;
helperCam.clearFlags = CameraClearFlags.SolidColor;
helperCam.renderingPath = RenderingPath.Forward;
}
static Matrix4x4 CalculateObliqueMatrix (Matrix4x4 projection, Vector4 clipPlane)
{
Vector4 q = projection.inverse * new Vector4(
sgn(clipPlane.x),
sgn(clipPlane.y),
1.0F,
1.0F
);
Vector4 c = clipPlane * (2.0F / (Vector4.Dot (clipPlane, q)));
// third row = clip plane - fourth row
projection[2] = c.x - projection[3];
projection[6] = c.y - projection[7];
projection[10] = c.z - projection[11];
projection[14] = c.w - projection[15];
return projection;
}
// Helper function for getting the reflection matrix that will be multiplied with camera matrix
static Matrix4x4 CalculateReflectionMatrix (Matrix4x4 reflectionMat, Vector4 plane)
{
reflectionMat.m00 = (1.0F - 2.0F*plane[0]*plane[0]);
reflectionMat.m01 = ( - 2.0F*plane[0]*plane[1]);
reflectionMat.m02 = ( - 2.0F*plane[0]*plane[2]);
reflectionMat.m03 = ( - 2.0F*plane[3]*plane[0]);
reflectionMat.m10 = ( - 2.0F*plane[1]*plane[0]);
reflectionMat.m11 = (1.0F - 2.0F*plane[1]*plane[1]);
reflectionMat.m12 = ( - 2.0F*plane[1]*plane[2]);
reflectionMat.m13 = ( - 2.0F*plane[3]*plane[1]);
reflectionMat.m20 = ( - 2.0F*plane[2]*plane[0]);
reflectionMat.m21 = ( - 2.0F*plane[2]*plane[1]);
reflectionMat.m22 = (1.0F - 2.0F*plane[2]*plane[2]);
reflectionMat.m23 = ( - 2.0F*plane[3]*plane[2]);
reflectionMat.m30 = 0.0F;
reflectionMat.m31 = 0.0F;
reflectionMat.m32 = 0.0F;
reflectionMat.m33 = 1.0F;
return reflectionMat;
}
// Extended sign: returns -1, 0 or 1 based on sign of a
static float sgn (float a) {
if (a > 0.0F) return 1.0F;
if (a < 0.0F) return -1.0F;
return 0.0F;
}
// Given position/normal of the plane, calculates plane in camera space.
private Vector4 CameraSpacePlane (Camera cam, Vector3 pos, Vector3 normal, float sideSign)
{
Vector3 offsetPos = pos + normal * clipPlaneOffset;
Matrix4x4 m = cam.worldToCameraMatrix;
Vector3 cpos = m.MultiplyPoint (offsetPos);
Vector3 cnormal = m.MultiplyVector (normal).normalized * sideSign;
return new Vector4 (cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot (cpos,cnormal));
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using RoboSharp.DefaultConfigurations;
namespace RoboSharp
{
/// <summary>
/// Setup the ErrorToken and the path to RoboCopy.exe.
/// </summary>
/// <remarks>
/// <see href="https://github.com/tjscience/RoboSharp/wiki/RoboSharpConfiguration"/>
/// </remarks>
public class RoboSharpConfiguration : ICloneable
{
#region Constructors
/// <summary>
/// Create new LoggingOptions with Default Settings
/// </summary>
public RoboSharpConfiguration() { }
/// <summary>
/// Clone a RoboSharpConfiguration Object
/// </summary>
/// <param name="options">RoboSharpConfiguration object to clone</param>
public RoboSharpConfiguration(RoboSharpConfiguration options)
{
errorToken = options.errorToken;
errorTokenRegex = options.errorTokenRegex;
roboCopyExe = options.roboCopyExe;
#region < File Tokens >
newFileToken = options.newFileToken;
olderToken = options.olderToken;
newerToken = options.newerToken;
sameToken = options.sameToken;
extraToken = options.extraToken;
mismatchToken = options.mismatchToken;
failedToken = options.failedToken;
#endregion
#region < Directory Tokens >
newerDirToken = options.newerDirToken;
extraDirToken = options.extraDirToken;
existingDirToken = options.existingDirToken;
#endregion
}
/// <inheritdoc cref="RoboSharpConfiguration.RoboSharpConfiguration(RoboSharpConfiguration)"/>
public RoboSharpConfiguration Clone() => new RoboSharpConfiguration(this);
object ICloneable.Clone() => Clone();
#endregion
private static readonly IDictionary<string, RoboSharpConfiguration>
defaultConfigurations = new Dictionary<string, RoboSharpConfiguration>()
{
{"en", new RoboSharpConfig_EN() }, //en uses Defaults for LogParsing properties
{"de", new RoboSharpConfig_DE() },
};
/// <summary>
/// Error Token Identifier -- EN = "ERROR", DE = "FEHLER", etc <br/>
/// Leave as / Set to null to use system default.
/// </summary>
public string ErrorToken
{
get { return errorToken ?? GetDefaultConfiguration().ErrorToken; }
set
{
if (value != errorToken) ErrRegexInitRequired = true;
errorToken = value;
}
}
/// <summary> field backing <see cref="ErrorToken"/> property - Protected to allow DefaultConfig derived classes to set within constructor </summary>
protected string errorToken = null;
/// <summary>
/// Regex to identify Error Tokens with during LogLine parsing
/// </summary>
public Regex ErrorTokenRegex
{
get
{
if (ErrRegexInitRequired) goto RegenRegex; //Regex Generation Required
else if (errorTokenRegex != null) return errorTokenRegex; //field already assigned -> return the field
else
{
//Try get default, if default has regex defined, use that.
errorTokenRegex = GetDefaultConfiguration().errorTokenRegex;
if (errorTokenRegex != null) return errorTokenRegex;
}
// Generate a new Regex Statement
RegenRegex:
errorTokenRegex = ErrorTokenRegexGenerator(ErrorToken); //new Regex($" {this.ErrorToken} " + @"(\d{1,3}) \(0x\d{8}\) ");
ErrRegexInitRequired = false;
return errorTokenRegex;
}
}
/// <summary> Field backing <see cref="ErrorTokenRegex"/> property - Protected to allow DefaultConfig derived classes to set within constructor </summary>
protected Regex errorTokenRegex;
private bool ErrRegexInitRequired = false;
/// <summary>
/// Generate a new ErrorTokenRegex object from by insterting the <see cref="ErrorToken"/> into a standardized pattern.
/// </summary>
/// <param name="errorToken">Language Specific <see cref="ErrorToken"/></param>
/// <returns></returns>
internal static Regex ErrorTokenRegexGenerator(string errorToken)
{
Regex BaseErrTokenRegex = new Regex("(?<Date>.*?)\\s+IDENTIFIER\\s+(?<ErrCode>[0-9]+)\\s+(?<SignedErrCode>\\([0-9Xx]+\\))\\s+(?<Descrip>[\\w\\s]+(?!:))(?<Path>.*)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture);
string pattern = BaseErrTokenRegex.ToString().Replace("IDENTIFIER", errorToken);
return new Regex(pattern, BaseErrTokenRegex.Options);
}
#region < Tokens for Log Parsing >
#region < File Tokens >
/// <summary>
/// Log Lines starting with this string indicate : New File -> Source FILE Exists, Destination does not
/// </summary>
public string LogParsing_NewFile
{
get { return newFileToken ?? GetDefaultConfiguration().newFileToken ?? "New File"; }
set { newFileToken = value; }
}
private string newFileToken;
/// <summary>
/// Log Lines starting with this string indicate : Destination File newer than Source
/// </summary>
public string LogParsing_OlderFile
{
get { return olderToken ?? GetDefaultConfiguration().olderToken ?? "Older"; }
set { olderToken = value; }
}
private string olderToken;
/// <summary>
/// Log Lines starting with this string indicate : Source File newer than Destination
/// </summary>
public string LogParsing_NewerFile
{
get { return newerToken ?? GetDefaultConfiguration().newerToken ?? "Newer"; }
set { newerToken = value; }
}
private string newerToken;
/// <summary>
/// Log Lines starting with this string indicate : Source FILE is identical to Destination File
/// </summary>
public string LogParsing_SameFile
{
get { return sameToken ?? GetDefaultConfiguration().sameToken ?? "same"; }
set { sameToken = value; }
}
private string sameToken;
/// <summary>
/// Log Lines starting with this string indicate : EXTRA FILE -> Destination Exists, but Source does not
/// </summary>
public string LogParsing_ExtraFile
{
get { return extraToken ?? GetDefaultConfiguration().extraToken ?? "*EXTRA File"; }
set { extraToken = value; }
}
private string extraToken;
/// <summary>
/// Log Lines starting with this string indicate : MISMATCH FILE
/// </summary>
public string LogParsing_MismatchFile
{
get { return mismatchToken ?? GetDefaultConfiguration().mismatchToken ?? "*Mismatch"; } // TODO: Needs Verification
set { mismatchToken = value; }
}
private string mismatchToken;
/// <summary>
/// Log Lines starting with this string indicate : File Failed to Copy
/// </summary>
public string LogParsing_FailedFile
{
get { return failedToken ?? GetDefaultConfiguration().failedToken ?? "*Failed"; } // TODO: Needs Verification
set { failedToken = value; }
}
private string failedToken;
/// <summary>
/// Log Lines starting with this string indicate : File was excluded by <see cref="SelectionOptions.ExcludedFiles"/> filters
/// </summary>
public string LogParsing_FileExclusion
{
get { return fileExcludedToken ?? GetDefaultConfiguration().fileExcludedToken ?? "named"; } // TODO: Needs Verification
set { fileExcludedToken = value; }
}
private string fileExcludedToken;
/// <summary>
/// Log Lines starting with this string indicate : File was excluded by <see cref="SelectionOptions.ExcludeAttributes"/> or <see cref="SelectionOptions.IncludeAttributes"/> filters
/// </summary>
public string LogParsing_AttribExclusion
{
get { return attribExcludedToken ?? GetDefaultConfiguration().attribExcludedToken ?? "attrib"; }
set { attribExcludedToken = value; }
}
private string attribExcludedToken;
/// <summary>
/// Log Lines starting with this string indicate : File was excluded by <see cref="SelectionOptions.MaxFileSize"/> filters
/// </summary>
public string LogParsing_MaxFileSizeExclusion
{
get { return maxfilesizeExcludedToken ?? GetDefaultConfiguration().maxfilesizeExcludedToken ?? "large"; }
set { maxfilesizeExcludedToken = value; }
}
private string maxfilesizeExcludedToken;
/// <summary>
/// Log Lines starting with this string indicate : File was excluded by <see cref="SelectionOptions.MinFileSize"/> filters
/// </summary>
public string LogParsing_MinFileSizeExclusion
{
get { return minfilesizeExcludedToken ?? GetDefaultConfiguration().minfilesizeExcludedToken ?? "small"; }
set { minfilesizeExcludedToken = value; }
}
private string minfilesizeExcludedToken;
/// <summary>
/// Log Lines starting with this string indicate : File was excluded by <see cref="SelectionOptions.MaxFileAge"/> or <see cref="SelectionOptions.MaxLastAccessDate"/>filters
/// </summary>
public string LogParsing_MaxAgeOrAccessExclusion
{
get { return maxageoraccessExcludedToken ?? GetDefaultConfiguration().maxageoraccessExcludedToken ?? "too old"; }
set { maxageoraccessExcludedToken = value; }
}
private string maxageoraccessExcludedToken;
/// <summary>
/// Log Lines starting with this string indicate : File was excluded by <see cref="SelectionOptions.MinFileAge"/> or <see cref="SelectionOptions.MinLastAccessDate"/>filters
/// </summary>
public string LogParsing_MinAgeOrAccessExclusion
{
get { return minageoraccessExcludedToken ?? GetDefaultConfiguration().minageoraccessExcludedToken ?? "too new"; }
set { minageoraccessExcludedToken = value; }
}
private string minageoraccessExcludedToken;
/// <summary>
/// Log Lines starting with this string indicate : File was excluded by <see cref="SelectionOptions.ExcludeChanged"/> filters
/// </summary>
public string LogParsing_ChangedExclusion
{
get { return changedExcludedToken ?? GetDefaultConfiguration().changedExcludedToken ?? "changed"; }
set { changedExcludedToken = value; }
}
private string changedExcludedToken;
/// <summary>
/// Log Lines starting with this string indicate : File was included by <see cref="SelectionOptions.IncludeTweaked"/> filters
/// </summary>
public string LogParsing_TweakedInclusion
{
get { return tweakedIncludedToken ?? GetDefaultConfiguration().tweakedIncludedToken ?? "tweaked"; }
set { tweakedIncludedToken = value; }
}
private string tweakedIncludedToken;
#endregion
#region < Directory Tokens >
/// <summary>
/// Log Lines starting with this string indicate : New Dir -> Directory will be copied to Destination
/// </summary>
public string LogParsing_NewDir
{
get { return newerDirToken ?? GetDefaultConfiguration().newerDirToken ?? "New Dir"; }
set { newerDirToken = value; }
}
private string newerDirToken;
/// <summary>
/// Log Lines starting with this string indicate : Extra Dir -> Does not exist in source
/// </summary>
public string LogParsing_ExtraDir
{
get { return extraDirToken ?? GetDefaultConfiguration().extraDirToken ?? "*EXTRA Dir"; }
set { extraDirToken = value; }
}
private string extraDirToken;
/// <summary>
/// Existing Dirs do not have an identifier on the line. Instead, this string will be used when creating the <see cref="ProcessedFileInfo"/> object to indicate an Existing Directory.
/// </summary>
public string LogParsing_ExistingDir
{
get { return existingDirToken ?? GetDefaultConfiguration().existingDirToken ?? "Existing Dir"; }
set { existingDirToken = value; }
}
private string existingDirToken;
/// <summary>
/// Log Lines starting with this string indicate : Folder was excluded by <see cref="SelectionOptions.ExcludedDirectories"/> filters
/// </summary>
public string LogParsing_DirectoryExclusion
{
get { return dirExcludedToken ?? GetDefaultConfiguration().dirExcludedToken ?? "named"; } // TODO: Needs Verification
set { dirExcludedToken = value; }
}
private string dirExcludedToken;
#endregion
#endregion </ Tokens for Log Parsing >
/// <summary>
/// Specify the path to RoboCopy.exe here. If not set, use the default copy.
/// </summary>
public string RoboCopyExe
{
get { return roboCopyExe ?? "Robocopy.exe"; }
set { roboCopyExe = value; }
}
private string roboCopyExe = null;
/// <Remarks>Default is retrieved from the OEMCodePage</Remarks>
/// <inheritdoc cref="System.Diagnostics.ProcessStartInfo.StandardOutputEncoding" path="/summary"/>
public System.Text.Encoding StandardOutputEncoding { get; set; } = System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.OEMCodePage);
/// <Remarks>Default is retrieved from the OEMCodePage</Remarks>
/// <inheritdoc cref="System.Diagnostics.ProcessStartInfo.StandardErrorEncoding" path="/summary"/>
public System.Text.Encoding StandardErrorEncoding { get; set; } = System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.OEMCodePage);
private RoboSharpConfiguration defaultConfig = null;
private RoboSharpConfiguration GetDefaultConfiguration()
{
if (defaultConfig != null) return defaultConfig;
// check for default with language Tag xx-YY (e.g. en-US)
var currentLanguageTag = System.Globalization.CultureInfo.CurrentUICulture.IetfLanguageTag;
if (defaultConfigurations.ContainsKey(currentLanguageTag))
{
defaultConfig = defaultConfigurations[currentLanguageTag];
}
else
{
// check for default with language Tag xx (e.g. en)
var match = Regex.Match(currentLanguageTag, @"^\w+", RegexOptions.Compiled);
if (match.Success)
{
var currentMainLanguageTag = match.Value;
if (defaultConfigurations.ContainsKey(currentMainLanguageTag))
{
defaultConfig = defaultConfigurations[currentMainLanguageTag];
}
}
}
// no match, fallback to en
return defaultConfig ?? defaultConfigurations["en"];
}
}
}
| |
using UnityEngine;
using System.Collections;
namespace RootMotion.FinalIK {
/// <summary>
/// Rotates a hierarchy of bones to face a target.
/// </summary>
[System.Serializable]
public class IKSolverLookAt : IKSolver {
#region Main Interface
/// <summary>
/// The target Transform.
/// </summary>
public Transform target;
/// <summary>
/// The spine hierarchy.
/// </summary>
public LookAtBone[] spine = new LookAtBone[0];
/// <summary>
/// The head bone.
/// </summary>
public LookAtBone head = new LookAtBone();
/// <summary>
/// The eye bones.
/// </summary>
public LookAtBone[] eyes = new LookAtBone[0];
/// <summary>
/// The body weight.
/// </summary>
[Range(0f, 1f)]
public float bodyWeight = 0.5f;
/// <summary>
/// The head weight.
/// </summary>
[Range(0f, 1f)]
public float headWeight = 0.5f;
/// <summary>
/// The eyes weight.
/// </summary>
[Range(0f, 1f)]
public float eyesWeight = 1f;
/// <summary>
/// Clamp weight for the body.
/// </summary>
[Range(0f, 1f)]
public float clampWeight = 0.5f;
/// <summary>
/// Clamp weight for the head.
/// </summary>
[Range(0f, 1f)]
public float clampWeightHead = 0.5f;
/// <summary>
/// Clamp weight for the eyes.
/// </summary>
[Range(0f, 1f)]
public float clampWeightEyes = 0.5f;
/// <summary>
/// Number of sine smoothing iterations applied on clamping to make the clamping point smoother.
/// </summary>
[Range(0, 2)]
public int clampSmoothing = 2;
/// <summary>
/// Weight distribution between the spine bones.
/// </summary>
public AnimationCurve spineWeightCurve = new AnimationCurve(new Keyframe[2] { new Keyframe(0f, 0.3f), new Keyframe(1f, 1f) });
/// <summary>
/// Sets the look at weight. NOTE: You are welcome edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
}
/// <summary>
/// Sets the look at weight. NOTE: You are welcome to edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight, float bodyWeight) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
this.bodyWeight = Mathf.Clamp(bodyWeight, 0f, 1f);
}
/// <summary>
/// Sets the look at weight. NOTE: You are welcome to edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight, float bodyWeight, float headWeight) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
this.bodyWeight = Mathf.Clamp(bodyWeight, 0f, 1f);
this.headWeight = Mathf.Clamp(headWeight, 0f, 1f);
}
/// <summary>
/// Sets the look at weight. NOTE: You are welcome to edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight, float bodyWeight, float headWeight, float eyesWeight) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
this.bodyWeight = Mathf.Clamp(bodyWeight, 0f, 1f);
this.headWeight = Mathf.Clamp(headWeight, 0f, 1f);
this.eyesWeight = Mathf.Clamp(eyesWeight, 0f, 1f);
}
/// <summary>
/// Sets the look at weight. NOTE: You are welcome to edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight, float bodyWeight, float headWeight, float eyesWeight, float clampWeight) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
this.bodyWeight = Mathf.Clamp(bodyWeight, 0f, 1f);
this.headWeight = Mathf.Clamp(headWeight, 0f, 1f);
this.eyesWeight = Mathf.Clamp(eyesWeight, 0f, 1f);
this.clampWeight = Mathf.Clamp(clampWeight, 0f, 1f);
this.clampWeightHead = this.clampWeight;
this.clampWeightEyes = this.clampWeight;
}
/// <summary>
/// Sets the look at weight. NOTE: You are welcome to edit the weights directly, this method is here only to match the Unity's built in %IK API.
/// </summary>
public void SetLookAtWeight(float weight, float bodyWeight = 0f, float headWeight = 1f, float eyesWeight = 0.5f, float clampWeight = 0.5f, float clampWeightHead = 0.5f, float clampWeightEyes = 0.3f) {
this.IKPositionWeight = Mathf.Clamp(weight, 0f, 1f);
this.bodyWeight = Mathf.Clamp(bodyWeight, 0f, 1f);
this.headWeight = Mathf.Clamp(headWeight, 0f, 1f);
this.eyesWeight = Mathf.Clamp(eyesWeight, 0f, 1f);
this.clampWeight = Mathf.Clamp(clampWeight, 0f, 1f);
this.clampWeightHead = Mathf.Clamp(clampWeightHead, 0f, 1f);
this.clampWeightEyes = Mathf.Clamp(clampWeightEyes, 0f, 1f);
}
public override void StoreDefaultLocalState() {
for (int i = 0; i < spine.Length; i++) spine[i].StoreDefaultLocalState();
for (int i = 0; i < eyes.Length; i++) eyes[i].StoreDefaultLocalState();
if (head != null && head.transform != null) head.StoreDefaultLocalState();
}
public override void FixTransforms() {
for (int i = 0; i < spine.Length; i++) spine[i].FixTransform();
for (int i = 0; i < eyes.Length; i++) eyes[i].FixTransform();
if (head != null && head.transform != null) head.FixTransform();
}
public override bool IsValid (ref string message) {
if (!spineIsValid) {
message = "IKSolverLookAt spine setup is invalid. Can't initiate solver.";
return false;
}
if (!headIsValid) {
message = "IKSolverLookAt head transform is null. Can't initiate solver.";
return false;
}
if (!eyesIsValid) {
message = "IKSolverLookAt eyes setup is invalid. Can't initiate solver.";
return false;
}
if (spineIsEmpty && headIsEmpty && eyesIsEmpty) {
message = "IKSolverLookAt eyes setup is invalid. Can't initiate solver.";
return false;
}
Transform spineDuplicate = ContainsDuplicateBone(spine);
if (spineDuplicate != null) {
message = spineDuplicate.name + " is represented multiple times in a single IK chain. Can't initiate solver.";
return false;
}
Transform eyeDuplicate = ContainsDuplicateBone(eyes);
if (eyeDuplicate != null) {
message = eyeDuplicate.name + " is represented multiple times in a single IK chain. Can't initiate solver.";
return false;
}
return true;
}
public override IKSolver.Point[] GetPoints() {
IKSolver.Point[] allPoints = new IKSolver.Point[spine.Length + eyes.Length + (head.transform != null? 1: 0)];
for (int i = 0; i < spine.Length; i++) allPoints[i] = spine[i] as IKSolver.Point;
int eye = 0;
for (int i = spine.Length; i < allPoints.Length; i++) {
allPoints[i] = eyes[eye] as IKSolver.Point;
eye ++;
}
if (head.transform != null) allPoints[allPoints.Length - 1] = head as IKSolver.Point;
return allPoints;
}
public override IKSolver.Point GetPoint(Transform transform) {
foreach (IKSolverLookAt.LookAtBone b in spine) if (b.transform == transform) return b as IKSolver.Point;
foreach (IKSolverLookAt.LookAtBone b in eyes) if (b.transform == transform) return b as IKSolver.Point;
if (head.transform == transform) return head as IKSolver.Point;
return null;
}
/// <summary>
/// Look At bone class.
/// </summary>
[System.Serializable]
public class LookAtBone: IKSolver.Bone {
#region Public methods
public LookAtBone() {}
/*
* Custom constructor
* */
public LookAtBone(Transform transform) {
this.transform = transform;
}
/*
* Initiates the bone, precalculates values.
* */
public void Initiate(Transform root) {
if (transform == null) return;
axis = Quaternion.Inverse(transform.rotation) * root.forward;
}
/*
* Rotates the bone to look at a world direction.
* */
public void LookAt(Vector3 direction, float weight) {
Quaternion fromTo = Quaternion.FromToRotation(forward, direction);
Quaternion r = transform.rotation;
transform.rotation = Quaternion.Lerp(r, fromTo * r, weight);
}
/*
* Gets the local axis to goal in world space.
* */
public Vector3 forward {
get {
return transform.rotation * axis;
}
}
#endregion Public methods
}
/// <summary>
/// Reinitiate the solver with new bone Transforms.
/// </summary>
/// <returns>
/// Returns true if the new chain is valid.
/// </returns>
public bool SetChain(Transform[] spine, Transform head, Transform[] eyes, Transform root) {
// Spine
SetBones(spine, ref this.spine);
// Head
this.head = new LookAtBone(head);
// Eyes
SetBones(eyes, ref this.eyes);
Initiate(root);
return initiated;
}
#endregion Main Interface
private Vector3[] spineForwards = new Vector3[0];
private Vector3[] headForwards = new Vector3[1];
private Vector3[] eyeForward = new Vector3[1];
protected override void OnInitiate() {
// Set IKPosition to default value
if (firstInitiation || !Application.isPlaying) {
if (spine.Length > 0) IKPosition = spine[spine.Length - 1].transform.position + root.forward * 3f;
else if (head.transform != null) IKPosition = head.transform.position + root.forward * 3f;
else if (eyes.Length > 0 && eyes[0].transform != null) IKPosition = eyes[0].transform.position + root.forward * 3f;
}
// Initiating the bones
foreach (LookAtBone s in spine) s.Initiate(root);
if (head != null) head.Initiate(root);
foreach (LookAtBone eye in eyes) eye.Initiate(root);
if (spineForwards == null || spineForwards.Length != spine.Length) spineForwards = new Vector3[spine.Length];
if (headForwards == null) headForwards = new Vector3[1];
if (eyeForward == null) eyeForward = new Vector3[1];
}
protected override void OnUpdate() {
if (IKPositionWeight <= 0) return;
IKPositionWeight = Mathf.Clamp(IKPositionWeight, 0f, 1f);
if (target != null) IKPosition = target.position;
// Solving the hierarchies
SolveSpine();
SolveHead();
SolveEyes();
}
private bool spineIsValid {
get {
if (spine == null) return false;
if (spine.Length == 0) return true;
for (int i = 0; i < spine.Length; i++) if (spine[i] == null || spine[i].transform == null) return false;
return true;
}
}
private bool spineIsEmpty { get { return spine.Length == 0; }}
// Solving the spine hierarchy
private void SolveSpine() {
if (bodyWeight <= 0) return;
if (spineIsEmpty) return;
// Get the look at vectors for each bone
//Vector3 targetForward = Vector3.Lerp(spine[0].forward, (IKPosition - spine[spine.Length - 1].transform.position).normalized, bodyWeight * IKPositionWeight).normalized;
Vector3 targetForward = (IKPosition - spine[spine.Length - 1].transform.position).normalized;
GetForwards(ref spineForwards, spine[0].forward, targetForward, spine.Length, clampWeight);
// Rotate each bone to face their look at vectors
for (int i = 0; i < spine.Length; i++) {
spine[i].LookAt(spineForwards[i], bodyWeight * IKPositionWeight);
}
}
private bool headIsValid {
get {
if (head == null) return false;
return true;
}
}
private bool headIsEmpty { get { return head.transform == null; }}
// Solving the head rotation
private void SolveHead() {
if (headWeight <= 0) return;
if (headIsEmpty) return;
// Get the look at vector for the head
Vector3 baseForward = spine.Length > 0 && spine[spine.Length - 1].transform != null? spine[spine.Length - 1].forward: head.forward;
Vector3 targetForward = Vector3.Lerp(baseForward, (IKPosition - head.transform.position).normalized, headWeight * IKPositionWeight).normalized;
GetForwards(ref headForwards, baseForward, targetForward, 1, clampWeightHead);
// Rotate the head to face its look at vector
head.LookAt(headForwards[0], headWeight * IKPositionWeight);
}
private bool eyesIsValid {
get {
if (eyes == null) return false;
if (eyes.Length == 0) return true;
for (int i = 0; i < eyes.Length; i++) if (eyes[i] == null || eyes[i].transform == null) return false;
return true;
}
}
private bool eyesIsEmpty { get { return eyes.Length == 0; }}
// Solving the eye rotations
private void SolveEyes() {
if (eyesWeight <= 0) return;
if (eyesIsEmpty) return;
for (int i = 0; i < eyes.Length; i++) {
// Get the look at vector for the eye
Vector3 baseForward = head.transform != null? head.forward: eyes[i].forward;
GetForwards(ref eyeForward, baseForward, (IKPosition - eyes[i].transform.position).normalized, 1, clampWeightEyes);
// Rotate the eye to face its look at vector
eyes[i].LookAt(eyeForward[0], eyesWeight * IKPositionWeight);
}
}
/*
* Returns forwards for a number of bones rotating from baseForward to targetForward.
* NB! Make sure baseForward and targetForward are normalized.
* */
private Vector3[] GetForwards(ref Vector3[] forwards, Vector3 baseForward, Vector3 targetForward, int bones, float clamp) {
// If clamp >= 1 make all the forwards match the base
if (clamp >= 1 || IKPositionWeight <= 0) {
for (int i = 0; i < forwards.Length; i++) forwards[i] = baseForward;
return forwards;
}
// Get normalized dot product.
float angle = Vector3.Angle(baseForward, targetForward);
float dot = 1f - (angle / 180f);
// Clamping the targetForward so it doesn't exceed clamp
float targetClampMlp = clamp > 0? Mathf.Clamp(1f - ((clamp - dot) / (1f - dot)), 0f, 1f): 1f;
// Calculating the clamp multiplier
float clampMlp = clamp > 0? Mathf.Clamp(dot / clamp, 0f, 1f): 1f;
for (int i = 0; i < clampSmoothing; i++) {
float sinF = clampMlp * Mathf.PI * 0.5f;
clampMlp = Mathf.Sin(sinF);
}
// Rotation amount for 1 bone
if (forwards.Length == 1) {
forwards[0] = Vector3.Slerp(baseForward, targetForward, clampMlp * targetClampMlp);
} else {
float step = 1f / (float)(forwards.Length - 1);
// Calculate the forward for each bone
for (int i = 0; i < forwards.Length; i++) {
forwards[i] = Vector3.Slerp(baseForward, targetForward, spineWeightCurve.Evaluate(step * i) * clampMlp * targetClampMlp);
}
}
return forwards;
}
/*
* Build LookAtBone[] array of a Transform array
* */
private void SetBones(Transform[] array, ref LookAtBone[] bones) {
if (array == null) {
bones = new LookAtBone[0];
return;
}
if (bones.Length != array.Length) bones = new LookAtBone[array.Length];
for (int i = 0; i < array.Length; i++) {
if (bones[i] == null) bones[i] = new LookAtBone(array[i]);
}
}
}
}
| |
/*
* 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.Impl
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Text;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Memory;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Impl.Unmanaged.Jni;
using Apache.Ignite.Core.Log;
/// <summary>
/// Native interface manager.
/// </summary>
internal static class IgniteManager
{
/** Java Command line argument: Xms. Case sensitive. */
private const string CmdJvmMinMemJava = "-Xms";
/** Java Command line argument: Xmx. Case sensitive. */
private const string CmdJvmMaxMemJava = "-Xmx";
/** Monitor for DLL load synchronization. */
private static readonly object SyncRoot = new object();
/** Configuration used on JVM start. */
private static JvmConfiguration _jvmCfg;
/** Memory manager. */
private static readonly PlatformMemoryManager Mem = new PlatformMemoryManager(1024);
/// <summary>
/// Create JVM.
/// </summary>
/// <param name="cfg">Configuration.</param>
/// <param name="log">Logger</param>
/// <returns>Callback context.</returns>
internal static UnmanagedCallbacks CreateJvmContext(IgniteConfiguration cfg, ILogger log)
{
lock (SyncRoot)
{
// 1. Warn about possible configuration inconsistency.
JvmConfiguration jvmCfg = JvmConfig(cfg);
if (!cfg.SuppressWarnings && _jvmCfg != null)
{
if (!_jvmCfg.Equals(jvmCfg))
{
log.Warn("Attempting to start Ignite node with different Java " +
"configuration; current Java configuration will be ignored (consider " +
"starting node in separate process) [oldConfig=" + _jvmCfg +
", newConfig=" + jvmCfg + ']');
}
}
// 2. Create unmanaged pointer.
var jvm = CreateJvm(cfg);
if (cfg.RedirectJavaConsoleOutput)
{
jvm.EnableJavaConsoleWriter();
}
var cbs = new UnmanagedCallbacks(log, jvm);
jvm.RegisterCallbacks(cbs);
// 3. If this is the first JVM created, preserve configuration.
if (_jvmCfg == null)
{
_jvmCfg = jvmCfg;
}
return cbs;
}
}
/// <summary>
/// Memory manager attached to currently running JVM.
/// </summary>
internal static PlatformMemoryManager Memory
{
get { return Mem; }
}
/// <summary>
/// Create JVM.
/// </summary>
/// <returns>JVM.</returns>
private static Jvm CreateJvm(IgniteConfiguration cfg)
{
var cp = Classpath.CreateClasspath(cfg);
var jvmOpts = GetMergedJvmOptions(cfg);
jvmOpts.Add(cp);
return Jvm.GetOrCreate(jvmOpts);
}
/// <summary>
/// Gets JvmOptions collection merged with individual properties (Min/Max mem, etc) according to priority.
/// </summary>
private static IList<string> GetMergedJvmOptions(IgniteConfiguration cfg)
{
var jvmOpts = cfg.JvmOptions == null ? new List<string>() : cfg.JvmOptions.ToList();
// JvmInitialMemoryMB / JvmMaxMemoryMB have lower priority than CMD_JVM_OPT
if (!jvmOpts.Any(opt => opt.StartsWith(CmdJvmMinMemJava, StringComparison.OrdinalIgnoreCase)) &&
cfg.JvmInitialMemoryMb != IgniteConfiguration.DefaultJvmInitMem)
jvmOpts.Add(string.Format(CultureInfo.InvariantCulture, "{0}{1}m", CmdJvmMinMemJava, cfg.JvmInitialMemoryMb));
if (!jvmOpts.Any(opt => opt.StartsWith(CmdJvmMaxMemJava, StringComparison.OrdinalIgnoreCase)) &&
cfg.JvmMaxMemoryMb != IgniteConfiguration.DefaultJvmMaxMem)
jvmOpts.Add(string.Format(CultureInfo.InvariantCulture, "{0}{1}m", CmdJvmMaxMemJava, cfg.JvmMaxMemoryMb));
return jvmOpts;
}
/// <summary>
/// Create JVM configuration value object.
/// </summary>
/// <param name="cfg">Configuration.</param>
/// <returns>JVM configuration.</returns>
private static JvmConfiguration JvmConfig(IgniteConfiguration cfg)
{
return new JvmConfiguration
{
Home = cfg.IgniteHome,
Dll = cfg.JvmDllPath,
Classpath = cfg.JvmClasspath,
Options = cfg.JvmOptions
};
}
/// <summary>
/// JVM configuration.
/// </summary>
private class JvmConfiguration
{
/// <summary>
/// Gets or sets the home.
/// </summary>
public string Home { get; set; }
/// <summary>
/// Gets or sets the DLL.
/// </summary>
public string Dll { get; set; }
/// <summary>
/// Gets or sets the cp.
/// </summary>
public string Classpath { get; set; }
/// <summary>
/// Gets or sets the options.
/// </summary>
public ICollection<string> Options { get; set; }
/** <inheritDoc /> */
public override int GetHashCode()
{
return 0;
}
/** <inheritDoc /> */
[SuppressMessage("ReSharper", "FunctionComplexityOverflow")]
public override bool Equals(object obj)
{
JvmConfiguration other = obj as JvmConfiguration;
if (other == null)
return false;
if (!string.Equals(Home, other.Home, StringComparison.OrdinalIgnoreCase))
return false;
if (!string.Equals(Classpath, other.Classpath, StringComparison.OrdinalIgnoreCase))
return false;
if (!string.Equals(Dll, other.Dll, StringComparison.OrdinalIgnoreCase))
return false;
return (Options == null && other.Options == null) ||
(Options != null && other.Options != null && Options.Count == other.Options.Count
&& !Options.Except(other.Options).Any());
}
/** <inheritDoc /> */
public override string ToString()
{
var sb = new StringBuilder("[IgniteHome=" + Home + ", JvmDllPath=" + Dll);
if (Options != null && Options.Count > 0)
{
sb.Append(", JvmOptions=[");
bool first = true;
foreach (string opt in Options)
{
if (first)
first = false;
else
sb.Append(", ");
sb.Append(opt);
}
sb.Append(']');
}
sb.Append(", Classpath=" + Classpath + ']');
return sb.ToString();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using IfacesEnumsStructsClasses;
namespace DemoApp
{
#region ToolStripHtmlColorSelector Control
//Add a ToolStripHtmlColorSelector control
//Add a toolstrip, a dropdownbutton
//Set the drop-down on the ToolStripDropDownButton to
//ToolStripHtmlColorSelector
//Subscribe to HtmlColorSelector events for color changing,...
public class ToolStripHtmlColorSelector : ToolStripDropDown
{
private HtmlColorSelector m_Control = new HtmlColorSelector();
public ToolStripHtmlColorSelector()
{
Items.Add(new ToolStripControlHost(m_Control));
this.m_Control.SelectionChanged += new HtmlColorSelectorEventHandler(m_Control_SelectionChanged);
this.m_Control.SelectionCancelled += new EventHandler(m_Control_SelectionCancelled);
}
void m_Control_SelectionCancelled(object sender, EventArgs e)
{
this.Close(ToolStripDropDownCloseReason.CloseCalled);
}
void m_Control_SelectionChanged(object sender, HtmlColorSelectorEventArgs e)
{
this.Close(ToolStripDropDownCloseReason.CloseCalled);
}
public HtmlColorSelector Selector
{
get { return m_Control; }
}
protected override void OnOpened(EventArgs e)
{
base.OnOpened(e);
//set focus to control for keyboard processing
//left, right, up, down, cancel, na denter keys are handled
this.m_Control.Focus();
}
}
#endregion
#region HtmlColorSelector
public class HtmlColorSelectorEventArgs : EventArgs
{
public Color SelectedColor;
public HtmlColorSelectorEventArgs()
{
this.SelectedColor = Color.Empty;
}
}
public delegate void HtmlColorSelectorEventHandler(object sender, HtmlColorSelectorEventArgs e);
public class HtmlColorSelector : Control
{
public event HtmlColorSelectorEventHandler SelectionChanged;
//Cancel key is accounted for
public event EventHandler SelectionCancelled;
private HtmlColorSelectorEventArgs m_eventArgs = new HtmlColorSelectorEventArgs();
public HtmlColorSelector()
{
//To stop flickering
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.CacheText, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.UserPaint, true);
LoadColorBoxs();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if ((components != null))
components.Dispose();
}
base.Dispose(disposing);
}
public override Size MinimumSize
{
get
{
//return base.MinimumSize;
return new Size((MAX_COLS * m_ColorBoxDimensions) + (m_Spacing * (MAX_COLS + 1)), 0);
}
set
{
base.MinimumSize = value;
}
}
private class ColorBox
{
public Color BoxColor;
public Rectangle BoxRectangle;
public int Index; // zero based
public ColorBox()
{
this.BoxColor = Color.Empty;
this.BoxRectangle = Rectangle.Empty;
this.Index = -1;
}
public ColorBox(Color _BoxColor, Rectangle _BoxRectangle, int _Index)
{
this.BoxColor = _BoxColor;
this.BoxRectangle = _BoxRectangle;
this.Index = _Index;
}
}
private System.ComponentModel.IContainer components = null;
private List<ColorBox> m_ColorBoxs = new List<ColorBox>();
private ColorBox m_SelectedBox = null;
private ColorBox m_HoveredBox = null;
private int m_ColorBoxDimensions = 15; //pixel
private int m_Spacing = 2; //pixel
private const int MAX_COLS = 20;
private Brush m_BackgroundBrush = new SolidBrush(SystemColors.Control);
private Rectangle m_paintrect = Rectangle.Empty;
private Brush m_boxbrush = new SolidBrush(Color.Empty);
private Pen m_highlightpen = new Pen(Color.Black, 2);
private string m_paintstring = string.Empty;
private Rectangle m_rectboxs = Rectangle.Empty;
private Rectangle m_recttext = Rectangle.Empty;
private const string DEFAULT_TEXT_COLOR = "Reset to default color";
private Rectangle m_rectdefaultcolor = Rectangle.Empty;
private bool m_overdefaultcolor = false;
private Color m_DefaultColor = Color.Empty;
public Color SelectedColor
{
get
{
if (m_SelectedBox != null)
return m_SelectedBox.BoxColor;
else
return Color.Empty;
}
set
{
m_SelectedBox = null;
if (value == Color.Empty)
return;
foreach (ColorBox box in m_ColorBoxs)
{
if ((box.BoxColor.R == value.R) &&
(box.BoxColor.G == value.G) &&
(box.BoxColor.B == value.B))
{
m_SelectedBox = box;
break;
}
}
}
}
public Color DefaultColor
{
get { return m_DefaultColor; }
set
{
m_DefaultColor = value;
Invalidate();
}
}
private void LoadColorBoxs()
{
int x = m_Spacing;
int y = m_Spacing;
int movewpos = m_ColorBoxDimensions + m_Spacing;
Array knownColors = Enum.GetValues(typeof(System.Drawing.KnownColor));
int curcol = 1;
int index = 0;
bool gotit = false;
List<Color> mycolors = new List<Color>();
foreach (KnownColor k in knownColors)
{
Color c = Color.FromKnownColor(k);
if (!c.IsSystemColor && (c.A > 0))
{
gotit = false;
for (index = 0; index < mycolors.Count; index++)
{
//Sort by brightness
if (c.GetBrightness() > mycolors[index].GetBrightness())
{
gotit = true;
break;
}
}
if (gotit)
mycolors.Insert(index, c);
else
mycolors.Add(c);
}
}
foreach (Color item in mycolors)
{
Rectangle rect = new Rectangle(
x, y,
m_ColorBoxDimensions,
m_ColorBoxDimensions);
ColorBox box = new ColorBox(item, rect, m_ColorBoxs.Count);
m_ColorBoxs.Add(box);
curcol++;
//New row
if (curcol > MAX_COLS)
{
curcol = 1;
x = m_Spacing;
y += movewpos;
}
else
{
x += movewpos;
}
}
//Adjust height, account for status and reset default text
this.Height = y + (movewpos * 2);
}
private void SetupHighlightPen(Color c)
{
int nThreshold = 105;
int bgDelta = Convert.ToInt32((c.R * 0.299) + (c.G * 0.587) +
(c.B * 0.114));
Color foreColor = (255 - bgDelta < nThreshold) ? Color.Black : Color.White;
m_highlightpen = new Pen(foreColor, 2);
//if ((c.G > 128) &&
// (c.B > 128))
//{
// m_highlightpen = new Pen(Color.Black, 2);
//}
//else
// m_highlightpen = new Pen(Color.White, 2);
}
protected override void OnPaint(PaintEventArgs e)
{
//Fill background
e.Graphics.FillRectangle(m_BackgroundBrush, e.ClipRectangle);
m_paintstring = string.Empty;
//Draw boxs
foreach (ColorBox box in m_ColorBoxs)
{
m_paintrect = new Rectangle(
e.ClipRectangle.X + box.BoxRectangle.X,
e.ClipRectangle.Y + box.BoxRectangle.Y,
m_ColorBoxDimensions, m_ColorBoxDimensions);
m_boxbrush = new SolidBrush(box.BoxColor);
e.Graphics.FillRectangle(m_boxbrush, m_paintrect);
//Selected or hovered box
if ((m_SelectedBox != null) && (m_SelectedBox.Index == box.Index))
{
SetupHighlightPen(box.BoxColor);
e.Graphics.DrawRectangle(m_highlightpen, m_paintrect);
//System.Windows.Forms.ControlPaint.DrawBorder3D(e.Graphics, m_paintrect, Border3DStyle.Raised);
}
else if ((m_HoveredBox != null) && (m_HoveredBox.Index == box.Index))
{
SetupHighlightPen(box.BoxColor);
e.Graphics.DrawRectangle(m_highlightpen, m_paintrect);
m_paintstring = box.BoxColor.Name + " (" + box.BoxColor.R.ToString() + ", " + box.BoxColor.G.ToString() + ", " + box.BoxColor.B.ToString() + ")";
}
}
//Get the rectangle for boxs
m_rectboxs = e.ClipRectangle;
m_rectboxs.X += m_Spacing;
m_rectboxs.Y += m_Spacing;
m_rectboxs.Height -= (m_ColorBoxDimensions + m_Spacing);
//No text, see if a box has been selected
if ((string.IsNullOrEmpty(m_paintstring)) && (m_SelectedBox != null))
m_paintstring = m_SelectedBox.BoxColor.Name + " (" + m_SelectedBox.BoxColor.R.ToString() + ", " + m_SelectedBox.BoxColor.G.ToString() + ", " + m_SelectedBox.BoxColor.B.ToString() + ")";
m_recttext = new Rectangle(e.ClipRectangle.X + m_Spacing,
e.ClipRectangle.Y + (this.Height - ((m_ColorBoxDimensions + m_Spacing) * 2)),
e.ClipRectangle.Width - (m_Spacing * 2), m_ColorBoxDimensions);
e.Graphics.FillRectangle(Brushes.White, m_recttext);
e.Graphics.DrawString(m_paintstring, this.Font, Brushes.Black,
new PointF(
(float)m_recttext.X,
(float)m_recttext.Y));
//Draw default text
m_rectdefaultcolor = new Rectangle(
m_recttext.X, m_recttext.Y + m_recttext.Height + m_Spacing, m_recttext.Width, m_ColorBoxDimensions);
if (m_overdefaultcolor)
e.Graphics.FillRectangle(Brushes.LightSkyBlue, m_rectdefaultcolor);
e.Graphics.DrawString(DEFAULT_TEXT_COLOR, this.Font, Brushes.Black,
new PointF(
(float)m_rectdefaultcolor.X,
(float)m_rectdefaultcolor.Y));
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button == MouseButtons.Left)
{
if (m_rectboxs.Contains(e.Location))
{
m_SelectedBox = null;
foreach (ColorBox box in m_ColorBoxs)
{
if (box.BoxRectangle.Contains(e.Location))
{
m_SelectedBox = box;
break;
}
}
//this.Invalidate();
if ((m_SelectedBox != null) && (SelectionChanged != null))
{
m_eventArgs.SelectedColor = m_SelectedBox.BoxColor;
SelectionChanged(this, m_eventArgs);
}
}
else if (m_rectdefaultcolor.Contains(e.Location))
{
m_SelectedBox = null;
//this.Invalidate();
if (SelectionChanged != null)
{
m_eventArgs.SelectedColor = m_DefaultColor;
SelectionChanged(this, m_eventArgs);
}
}
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
m_HoveredBox = null;
m_overdefaultcolor = false;
if (m_rectboxs.Contains(e.Location))
{
foreach (ColorBox box in m_ColorBoxs)
{
if (box.BoxRectangle.Contains(e.Location))
{
m_HoveredBox = box;
break;
}
}
}
else if (m_rectdefaultcolor.Contains(e.Location))
{
m_overdefaultcolor = true;
}
this.Invalidate();
}
protected override void OnMouseLeave(EventArgs e)
{
m_HoveredBox = null;
m_overdefaultcolor = false;
base.OnMouseLeave(e);
this.Invalidate();
}
private const int WM_KEYDOWN = 0x0100;
private void ProcessKeyDownEvent()
{
if (m_HoveredBox == null)
{
m_HoveredBox = m_ColorBoxs[0];
}
else
{
if ((m_HoveredBox.Index + MAX_COLS) < m_ColorBoxs.Count)
{
m_HoveredBox = m_ColorBoxs[m_HoveredBox.Index + MAX_COLS];
}
}
Invalidate();
}
private void ProcessKeyUpEvent()
{
if (m_HoveredBox == null)
{
m_HoveredBox = m_ColorBoxs[0];
}
else
{
if ((m_HoveredBox.Index - MAX_COLS) > -1)
{
m_HoveredBox = m_ColorBoxs[m_HoveredBox.Index - MAX_COLS];
}
}
Invalidate();
}
private void ProcessKeyLeftEvent()
{
if (m_HoveredBox == null)
{
m_HoveredBox = m_ColorBoxs[0];
}
else
{
//Anything before
if ((m_HoveredBox.Index - 1) > -1)
{
m_HoveredBox = m_ColorBoxs[m_HoveredBox.Index - 1];
}
else //Start from End
{
m_HoveredBox = m_ColorBoxs[m_ColorBoxs.Count - 1];
}
}
Invalidate();
}
private void ProcessKeyRightEvent()
{
if (m_HoveredBox == null)
{
m_HoveredBox = m_ColorBoxs[0];
}
else
{
//ColorBox index is zero based
//Anything after
if ((m_HoveredBox.Index + 1) < m_ColorBoxs.Count)
{
m_HoveredBox = m_ColorBoxs[m_HoveredBox.Index + 1];
}
else //Start from beginning
{
m_HoveredBox = m_ColorBoxs[0];
}
}
Invalidate();
}
private int m_msgkey = 0;
public override bool PreProcessMessage(ref Message msg)
{
if (msg.Msg == WM_KEYDOWN)
{
m_msgkey = (int)msg.WParam;
if (((Keys)m_msgkey) == Keys.Up)
{
ProcessKeyUpEvent();
return true;
}
else if (((Keys)m_msgkey) == Keys.Down)
{
ProcessKeyDownEvent();
return true;
}
else if (((Keys)m_msgkey) == Keys.Left)
{
ProcessKeyLeftEvent();
return true;
}
else if (((Keys)m_msgkey) == Keys.Right)
{
ProcessKeyRightEvent();
return true;
}
else if (((Keys)m_msgkey) == Keys.Cancel)
{
m_SelectedBox = null;
if (SelectionCancelled != null)
SelectionCancelled(this, EventArgs.Empty);
return true;
}
else if (((Keys)m_msgkey) == Keys.Enter)
{
if ((m_HoveredBox != null) && (SelectionChanged != null))
{
m_SelectedBox = m_HoveredBox;
m_eventArgs.SelectedColor = m_SelectedBox.BoxColor;
SelectionChanged(this, m_eventArgs);
}
return true;
}
else
return base.PreProcessMessage(ref msg);
}
else
return base.PreProcessMessage(ref msg);
}
}
#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 Microsoft.Test.ModuleCore;
using System;
using System.IO;
using System.Text;
using System.Xml;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
public partial class TCReadContentAsBinHex : BridgeHelpers
{
public const string ST_ELEM_NAME1 = "ElemAll";
public const string ST_ELEM_NAME2 = "ElemEmpty";
public const string ST_ELEM_NAME3 = "ElemNum";
public const string ST_ELEM_NAME4 = "ElemText";
public const string ST_ELEM_NAME5 = "ElemNumText";
public const string ST_ELEM_NAME6 = "ElemLong";
public const string strTextBinHex = "ABCDEF";
public const string strNumBinHex = "0123456789";
public override void Init()
{
base.Init();
CreateBinHexTestFile(pBinHexXml);
}
public override void Terminate()
{
base.Terminate();
}
private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
bool bPassed = false;
byte[] buffer = new byte[iBufferSize];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return true;
try
{
DataReader.ReadContentAsBinHex(buffer, iIndex, iCount);
}
catch (Exception e)
{
bPassed = (e.GetType().ToString() == exceptionType.ToString());
if (!bPassed)
{
TestLog.WriteLine("Actual exception:{0}", e.GetType().ToString());
TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString());
}
}
return bPassed;
}
protected void TestInvalidNodeType(XmlNodeType nt)
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnNodeType(DataReader, nt);
string name = DataReader.Name;
string value = DataReader.Value;
byte[] buffer = new byte[1];
if (!DataReader.CanReadBinaryContent) return;
try
{
int nBytes = DataReader.ReadContentAsBinHex(buffer, 0, 1);
}
catch (InvalidOperationException)
{
return;
}
TestLog.Compare(false, "Invalid OP exception not thrown on wrong nodetype");
}
//[Variation("ReadBinHex Element with all valid value")]
public void TestReadBinHex_1()
{
int binhexlen = 0;
byte[] binhex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
binhexlen = DataReader.ReadContentAsBinHex(binhex, 0, binhex.Length);
string strActbinhex = "";
for (int i = 0; i < binhexlen; i = i + 2)
{
strActbinhex += System.BitConverter.ToChar(binhex, i);
}
TestLog.Compare(strActbinhex, (strNumBinHex + strTextBinHex), "1. Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all valid Num value", Priority = 0)]
public void TestReadBinHex_2()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME3);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, strNumBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all valid Text value")]
public void TestReadBinHex_3()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, strTextBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element on CDATA", Priority = 0)]
public void TestReadBinHex_4()
{
int BinHexlen = 0;
byte[] BinHex = new byte[3];
string xmlStr = "<root><![CDATA[ABCDEF]]></root>";
XmlReader DataReader = GetReader(new StringReader(xmlStr));
PositionOnElement(DataReader, "root");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
TestLog.Compare(BinHexlen, 3, "BinHex");
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
TestLog.Compare(BinHexlen, 0, "BinHex");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.None, "Not on none");
}
//[Variation("ReadBinHex Element with all valid value (from concatenation), Priority=0")]
public void TestReadBinHex_5()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME5);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, (strNumBinHex + strTextBinHex), "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all long valid value (from concatenation)")]
public void TestReadBinHex_6()
{
int BinHexlen = 0;
byte[] BinHex = new byte[2000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME6);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
string strExpBinHex = "";
for (int i = 0; i < 10; i++)
strExpBinHex += (strNumBinHex + strTextBinHex);
TestLog.Compare(strActBinHex, strExpBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex with count > buffer size")]
public void TestReadBinHex_7()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 6, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with count < 0")]
public void TestReadBinHex_8()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 2, -1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index > buffer size")]
public void vReadBinHex_9()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 5, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index < 0")]
public void TestReadBinHex_10()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, -1, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index + count exceeds buffer")]
public void TestReadBinHex_11()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 10, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex index & count =0")]
public void TestReadBinHex_12()
{
byte[] buffer = new byte[5];
int iCount = 0;
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
try
{
iCount = DataReader.ReadContentAsBinHex(buffer, 0, 0);
}
catch (Exception e)
{
TestLog.WriteLine(e.ToString());
throw new TestException(TestResult.Failed, "");
}
TestLog.Compare(iCount, 0, "has to be zero");
}
//[Variation("ReadBinHex Element multiple into same buffer (using offset), Priority=0")]
public void TestReadBinHex_13()
{
int BinHexlen = 10;
byte[] BinHex = new byte[BinHexlen];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
string strActbinhex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
DataReader.ReadContentAsBinHex(BinHex, i, 2);
strActbinhex = (System.BitConverter.ToChar(BinHex, i)).ToString();
TestLog.Compare(String.Compare(strActbinhex, 0, strTextBinHex, i / 2, 1), 0, "Compare All Valid Base64");
}
}
//[Variation("ReadBinHex with buffer == null")]
public void TestReadBinHex_14()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
try
{
DataReader.ReadContentAsBinHex(null, 0, 0);
}
catch (ArgumentNullException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadBinHex after failed ReadBinHex")]
public void TestReadBinHex_15()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemErr");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = 0;
try
{
nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1);
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
int idx = e.Message.IndexOf("a&");
TestLog.Compare(idx >= 0, "msg");
CheckXmlException("Xml_UserException", e, 1, 968);
}
}
//[Variation("Read after partial ReadBinHex")]
public void TestReadBinHex_16()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemNum");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = DataReader.ReadContentAsBinHex(buffer, 0, 8);
TestLog.Compare(nRead, 8, "0");
DataReader.Read();
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, "ElemText", String.Empty), "1vn");
}
//[Variation("Current node on multiple calls")]
public void TestReadBinHex_17()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemNum");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[30];
int nRead = DataReader.ReadContentAsBinHex(buffer, 0, 2);
TestLog.Compare(nRead, 2, "0");
nRead = DataReader.ReadContentAsBinHex(buffer, 0, 19);
TestLog.Compare(nRead, 18, "1");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.EndElement, "ElemNum", String.Empty), "1vn");
}
//[Variation("ReadBinHex with whitespaces")]
public void TestTextReadBinHex_21()
{
byte[] buffer = new byte[1];
string strxml = "<abc> 1 1 B </abc>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1)) > 0)
result += nRead;
TestLog.Compare(result, 1, "res");
TestLog.Compare(buffer[0], (byte)17, "buffer[0]");
}
//[Variation("ReadBinHex with odd number of chars")]
public void TestTextReadBinHex_22()
{
byte[] buffer = new byte[1];
string strxml = "<abc>11B</abc>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1)) > 0)
result += nRead;
TestLog.Compare(result, 1, "res");
TestLog.Compare(buffer[0], (byte)17, "buffer[0]");
}
//[Variation("ReadBinHex when end tag doesn't exist")]
public void TestTextReadBinHex_23()
{
byte[] buffer = new byte[5000];
string strxml = "<B>" + new string('A', 5000);
try
{
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "B");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
DataReader.ReadContentAsBinHex(buffer, 0, 5000);
TestLog.WriteLine("Accepted incomplete element");
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004);
}
}
//[Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes going whIdbey to everett")]
public void TestTextReadBinHex_24()
{
string filename = Path.Combine("TestData", "XmlReader", "Common", "Bug99148.xml");
XmlReader DataReader = GetReader(filename);
DataReader.MoveToContent();
int bytes = -1;
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
StringBuilder output = new StringBuilder();
while (bytes != 0)
{
byte[] bbb = new byte[1024];
bytes = DataReader.ReadContentAsBinHex(bbb, 0, bbb.Length);
for (int i = 0; i < bytes; i++)
{
output.AppendFormat(bbb[i].ToString());
}
}
if (TestLog.Compare(output.ToString().Length, 1735, "Expected Length : 1735"))
return;
else
throw new TestException(TestResult.Failed, "");
}
//[Variation("DebugAssert in ReadContentAsBinHex")]
public void DebugAssertInReadContentAsBinHex()
{
XmlReader DataReader = GetReaderStr(@"<root>
<boo>hey</boo>
</root>");
byte[] buffer = new byte[5];
int iCount = 0;
while (DataReader.Read())
{
if (DataReader.NodeType == XmlNodeType.Element)
break;
}
if (!DataReader.CanReadBinaryContent) return;
DataReader.Read();
iCount = DataReader.ReadContentAsBinHex(buffer, 0, 0);
}
}
//[TestCase(Name = "ReadElementContentAsBinHex", Desc = "ReadElementContentAsBinHex")]
public partial class TCReadElementContentAsBinHex : BridgeHelpers
{
public const string ST_ELEM_NAME1 = "ElemAll";
public const string ST_ELEM_NAME2 = "ElemEmpty";
public const string ST_ELEM_NAME3 = "ElemNum";
public const string ST_ELEM_NAME4 = "ElemText";
public const string ST_ELEM_NAME5 = "ElemNumText";
public const string ST_ELEM_NAME6 = "ElemLong";
public const string strTextBinHex = "ABCDEF";
public const string strNumBinHex = "0123456789";
public override void Init()
{
base.Init();
CreateBinHexTestFile(pBinHexXml);
}
public override void Terminate()
{
base.Terminate();
}
private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
bool bPassed = false;
byte[] buffer = new byte[iBufferSize];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return true;
try
{
DataReader.ReadElementContentAsBinHex(buffer, iIndex, iCount);
}
catch (Exception e)
{
bPassed = (e.GetType().ToString() == exceptionType.ToString());
if (!bPassed)
{
TestLog.WriteLine("Actual exception:{0}", e.GetType().ToString());
TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString());
}
}
return bPassed;
}
protected void TestInvalidNodeType(XmlNodeType nt)
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnNodeType(DataReader, nt);
string name = DataReader.Name;
string value = DataReader.Value;
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[1];
try
{
int nBytes = DataReader.ReadElementContentAsBinHex(buffer, 0, 1);
}
catch (InvalidOperationException)
{
return;
}
TestLog.Compare(false, "Invalid OP exception not thrown on wrong nodetype");
}
//[Variation("ReadBinHex Element with all valid value")]
public void TestReadBinHex_1()
{
int binhexlen = 0;
byte[] binhex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return;
binhexlen = DataReader.ReadElementContentAsBinHex(binhex, 0, binhex.Length);
string strActbinhex = "";
for (int i = 0; i < binhexlen; i = i + 2)
{
strActbinhex += System.BitConverter.ToChar(binhex, i);
}
TestLog.Compare(strActbinhex, (strNumBinHex + strTextBinHex), "1. Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all valid Num value", Priority = 0)]
public void TestReadBinHex_2()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME3);
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, strNumBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all valid Text value")]
public void TestReadBinHex_3()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, strTextBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with Comments and PIs", Priority = 0)]
public void TestReadBinHex_4()
{
int BinHexlen = 0;
byte[] BinHex = new byte[3];
XmlReader DataReader = GetReader(new StringReader("<root>AB<!--Comment-->CD<?pi target?>EF</root>"));
PositionOnElement(DataReader, "root");
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
TestLog.Compare(BinHexlen, 3, "BinHex");
}
//[Variation("ReadBinHex Element with all valid value (from concatenation), Priority=0")]
public void TestReadBinHex_5()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME5);
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, (strNumBinHex + strTextBinHex), "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all long valid value (from concatenation)")]
public void TestReadBinHex_6()
{
int BinHexlen = 0;
byte[] BinHex = new byte[2000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME6);
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
string strExpBinHex = "";
for (int i = 0; i < 10; i++)
strExpBinHex += (strNumBinHex + strTextBinHex);
TestLog.Compare(strActBinHex, strExpBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex with count > buffer size")]
public void TestReadBinHex_7()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 6, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with count < 0")]
public void TestReadBinHex_8()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 2, -1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index > buffer size")]
public void vReadBinHex_9()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 5, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index < 0")]
public void TestReadBinHex_10()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, -1, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index + count exceeds buffer")]
public void TestReadBinHex_11()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 10, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex index & count =0")]
public void TestReadBinHex_12()
{
byte[] buffer = new byte[5];
int iCount = 0;
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return;
try
{
iCount = DataReader.ReadElementContentAsBinHex(buffer, 0, 0);
}
catch (Exception e)
{
TestLog.WriteLine(e.ToString());
throw new TestException(TestResult.Failed, "");
}
TestLog.Compare(iCount, 0, "has to be zero");
}
//[Variation("ReadBinHex Element multiple into same buffer (using offset), Priority=0")]
public void TestReadBinHex_13()
{
int BinHexlen = 10;
byte[] BinHex = new byte[BinHexlen];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
string strActbinhex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
DataReader.ReadElementContentAsBinHex(BinHex, i, 2);
strActbinhex = (System.BitConverter.ToChar(BinHex, i)).ToString();
TestLog.Compare(String.Compare(strActbinhex, 0, strTextBinHex, i / 2, 1), 0, "Compare All Valid Base64");
}
}
//[Variation("ReadBinHex with buffer == null")]
public void TestReadBinHex_14()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
try
{
DataReader.ReadElementContentAsBinHex(null, 0, 0);
}
catch (ArgumentNullException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadBinHex after failed ReadBinHex")]
public void TestReadBinHex_15()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemErr");
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = 0;
try
{
nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1);
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
int idx = e.Message.IndexOf("a&");
TestLog.Compare(idx >= 0, "msg");
CheckXmlException("Xml_UserException", e, 1, 968);
}
}
//[Variation("Read after partial ReadBinHex")]
public void TestReadBinHex_16()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemNum");
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 8);
TestLog.Compare(nRead, 8, "0");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on text node");
}
//[Variation("ReadBinHex with whitespaces")]
public void TestTextReadBinHex_21()
{
byte[] buffer = new byte[1];
string strxml = "<abc> 1 1 B </abc>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1)) > 0)
result += nRead;
TestLog.Compare(result, 1, "res");
TestLog.Compare(buffer[0], (byte)17, "buffer[0]");
}
//[Variation("ReadBinHex with odd number of chars")]
public void TestTextReadBinHex_22()
{
byte[] buffer = new byte[1];
string strxml = "<abc>11B</abc>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1)) > 0)
result += nRead;
TestLog.Compare(result, 1, "res");
TestLog.Compare(buffer[0], (byte)17, "buffer[0]");
}
//[Variation("ReadBinHex when end tag doesn't exist")]
public void TestTextReadBinHex_23()
{
byte[] buffer = new byte[5000];
string strxml = "<B>" + new string('A', 5000);
try
{
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "B");
DataReader.ReadElementContentAsBinHex(buffer, 0, 5000);
TestLog.WriteLine("Accepted incomplete element");
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004);
}
}
//[Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes going whIdbey to everett")]
public void TestTextReadBinHex_24()
{
string filename = Path.Combine("TestData", "XmlReader", "Common", "Bug99148.xml");
XmlReader DataReader = GetReader(filename);
DataReader.MoveToContent();
if (!DataReader.CanReadBinaryContent) return;
int bytes = -1;
StringBuilder output = new StringBuilder();
while (bytes != 0)
{
byte[] bbb = new byte[1024];
bytes = DataReader.ReadElementContentAsBinHex(bbb, 0, bbb.Length);
for (int i = 0; i < bytes; i++)
{
output.AppendFormat(bbb[i].ToString());
}
}
if (TestLog.Compare(output.ToString().Length, 1735, "Expected Length : 1735"))
return;
else
throw new TestException(TestResult.Failed, "");
}
//[Variation("SubtreeReader inserted attributes don't work with ReadContentAsBinHex")]
public void TestTextReadBinHex_25()
{
string strxml = "<root xmlns='0102030405060708090a0B0c'><bar/></root>";
using (XmlReader r = GetReader(new StringReader(strxml)))
{
r.Read();
r.Read();
using (XmlReader sr = r.ReadSubtree())
{
if (!sr.CanReadBinaryContent) return;
sr.Read();
sr.MoveToFirstAttribute();
sr.MoveToFirstAttribute();
byte[] bytes = new byte[4];
while ((sr.ReadContentAsBinHex(bytes, 0, bytes.Length)) > 0) { }
}
}
}
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Workflow.Activities.Design
{
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Net.Security;
using System.Reflection;
using System.Runtime;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Design;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
internal partial class ServiceOperationDetailViewControl : ListItemViewControl
{
static CodeDomProvider csharpProvider = null;
static CodeDomProvider vbProvider = null;
DataGridViewComboBoxColumn directionColumn;
Button formCancelButton = null;
bool isEditable = false;
DataGridViewTextBoxColumn nameColumn;
OperationInfoBase operationInfoBase = null;
TypeChooserCellItem typeChooserCellItem;
DataGridViewComboBoxColumn typeColumn;
public ServiceOperationDetailViewControl()
{
InitializeComponent();
this.protectionLevelComboBox.Items.Add(SR2.GetString(SR2.UseRuntimeDefaults));
this.protectionLevelComboBox.Items.Add(ProtectionLevel.None);
this.protectionLevelComboBox.Items.Add(ProtectionLevel.Sign);
this.protectionLevelComboBox.Items.Add(ProtectionLevel.EncryptAndSign);
}
public override event EventHandler ItemChanged;
private string ParameterTemplateRowName
{
get
{
return SR2.GetString(SR2.ParameterTemplateRowName);
}
}
public override void UpdateView()
{
// set the dialog fonts from vs.
IUIService uisvc = (IUIService) this.ServiceProvider.GetService(typeof(IUIService));
if (uisvc != null)
{
this.Font = (Font) uisvc.Styles["DialogFont"];
}
TypedServiceOperationListItem operationListItem = this.Item as TypedServiceOperationListItem;
WorkflowServiceOperationListItem workflowOperationListItem = this.Item as WorkflowServiceOperationListItem;
if (operationListItem != null)
{
operationInfoBase = operationListItem.Operation;
SetEditability(false);
}
if (workflowOperationListItem != null)
{
operationInfoBase = workflowOperationListItem.Operation;
if (workflowOperationListItem.Operation.HasProtectionLevel)
{
this.protectionLevelComboBox.SelectedItem = workflowOperationListItem.Operation.ProtectionLevel;
}
else
{
this.protectionLevelComboBox.SelectedItem = SR2.GetString(SR2.UseRuntimeDefaults);
}
SetEditability(true);
}
Fx.Assert(operationInfoBase != null, "list Item should be either ReflectedServiceOperationListItem or WorkflowServiceOperationListItem");
this.oneWayCheckBox.Checked = operationInfoBase.GetIsOneWay(ServiceProvider);
Fx.Assert(operationInfoBase != null, "Operation Info should be non-null at this point");
SetupColumns();
PopulateParametersGrid(operationInfoBase);
if (!this.parametersGrid.ReadOnly)
{
this.parametersGrid.Rows.Add(this.ParameterTemplateRowName, null, null);
}
this.operationNameTextBox.Text = operationInfoBase.Name;
this.permissionRoleTextBox.Text = operationInfoBase.PrincipalPermissionRole;
this.permissionNameTextBox.Text = operationInfoBase.PrincipalPermissionName;
this.permissionRoleTextBox.TextChanged += new EventHandler(permissionRoleTextChanged);
if (workflowOperationListItem != null)
{
this.operationNameTextBox.Validating += new CancelEventHandler(operationNameTextBox_Validating);
this.operationNameTextBox.Validated += new EventHandler(operationNameTextBox_Validated);
}
this.oneWayCheckBox.CheckedChanged += new EventHandler(oneWayCheckBoxCheckedChanged);
this.permissionNameTextBox.TextChanged += new EventHandler(permissionNameTextChanged);
this.parametersGrid.SelectionChanged += new EventHandler(parametersGrid_SelectionChanged);
if (!this.parametersGrid.ReadOnly)
{
this.parametersGrid.CellValidating += new DataGridViewCellValidatingEventHandler(parametersGrid_CellValidating);
this.parametersGrid.CellEndEdit += new DataGridViewCellEventHandler(parametersGridCellEndEdit);
this.parametersGrid.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(parametersGrid_EditingControlShowing);
this.parametersGrid.KeyDown += new KeyEventHandler(parametersGrid_KeyDown);
}
this.protectionLevelComboBox.SelectedValueChanged += new System.EventHandler(this.protectionLevelComboBoxSelectedValueChanged);
RefreshParameterOperationButtons();
}
internal static string GetTypeSignature(Type type)
{
Fx.Assert(type != null, "type cannot be null");
if (type.IsPrimitive)
{
return type.Name;
}
if (!type.IsGenericType)
{
return type.FullName;
}
// run time types already have complete signature in type.FullName , we only have to worry about design time types here
if (type.FullName.Contains("["))
{
return type.FullName;
}
StringBuilder signature = new StringBuilder();
signature.Append(type.FullName);
signature.Append("[");
Type[] argumentTypes = type.GetGenericArguments();
for (int index = 0; index < argumentTypes.Length; index++)
{
Type argumentType = argumentTypes[index];
signature.Append(GetTypeSignature(argumentType));
if (index != argumentTypes.Length - 1)
{
signature.Append(", ");
}
}
signature.Append("]");
return signature.ToString();
}
protected override void OnLoad(EventArgs e)
{
this.parametersGrid.ClearSelection();
base.OnLoad(e);
}
private void addParameterButton_Click(object sender, EventArgs e)
{
Fx.Assert(this.parametersGrid.Rows.Count != 0, "parameters grid should have atleast the dummy <add new> item");
this.parametersGrid.Rows.Insert(this.parametersGrid.Rows.Count - 1, GenerateParameterName(), typeof(string), SR2.GetString(SR2.ParameterDirectionIn));
// move focus to newly added cell
this.parametersGrid.CurrentCell = this.parametersGrid.Rows[this.parametersGrid.Rows.Count - 2].Cells[this.nameColumn.Index];
UpdateOperationParameters();
RefreshParameterOperationButtons();
}
private void AddPrimitiveTypesToTypesList()
{
typeColumn.Items.Add(new TypeCellItem(typeof(byte)));
typeColumn.Items.Add(new TypeCellItem(typeof(sbyte)));
typeColumn.Items.Add(new TypeCellItem(typeof(int)));
typeColumn.Items.Add(new TypeCellItem(typeof(uint)));
typeColumn.Items.Add(new TypeCellItem(typeof(short)));
typeColumn.Items.Add(new TypeCellItem(typeof(ushort)));
typeColumn.Items.Add(new TypeCellItem(typeof(long)));
typeColumn.Items.Add(new TypeCellItem(typeof(ulong)));
typeColumn.Items.Add(new TypeCellItem(typeof(float)));
typeColumn.Items.Add(new TypeCellItem(typeof(double)));
typeColumn.Items.Add(new TypeCellItem(typeof(char)));
typeColumn.Items.Add(new TypeCellItem(typeof(bool)));
typeColumn.Items.Add(new TypeCellItem(typeof(object)));
typeColumn.Items.Add(new TypeCellItem(typeof(string)));
typeColumn.Items.Add(new TypeCellItem(typeof(decimal)));
typeColumn.Items.Add(new TypeCellItem(typeof(void)));
}
void AddToTypeList(Type type)
{
Fx.Assert(type != null, "The type should not be null");
foreach (TypeCellItem typeCellItem in this.typeColumn.Items)
{
Fx.Assert(typeCellItem != null, "should never have a null entry in this list");
Fx.Assert(typeCellItem.Type != null, " This object should always hold a valid Type");
if (typeCellItem.Type.Equals(type))
{
return;
}
}
this.typeColumn.Items.Add(new TypeCellItem(type));
}
private void BrowseAndSelectType(DataGridViewCell currentCell)
{
bool doneSelectingType = false;
while (!doneSelectingType)
{
using (TypeBrowserDialog typeBrowserDialog = new TypeBrowserDialog(
this.ServiceProvider as IServiceProvider, new ParameterTypeFilterProvider(), "System.String"))
{
doneSelectingType = TrySelectType(typeBrowserDialog, currentCell);
}
}
}
void comboBox_SelectionChangeCommitted(object sender, EventArgs e)
{
DataGridViewComboBoxEditingControl combo = sender as DataGridViewComboBoxEditingControl;
DataGridViewCell currentCell = this.parametersGrid.Rows[combo.EditingControlRowIndex].Cells[this.typeColumn.Index];
if (combo.DroppedDown && combo.Text.Equals(SR2.GetString(SR2.BrowseType)) && !typeof(TypeChooserCellItem).Equals(currentCell.Value))
{
BrowseAndSelectType(currentCell);
this.parametersGrid.EndEdit();
}
}
void DisableFormCancelButton()
{
formCancelButton = Form.ActiveForm.CancelButton as Button;
Form.ActiveForm.CancelButton = null;
}
void EnableFormCancelButton()
{
if (formCancelButton != null)
{
Form.ActiveForm.CancelButton = formCancelButton;
}
}
private string GenerateParameterName()
{
int index = 0;
string generatedNameBase = SR2.GetString(SR2.GeneratedParameterNameBase);
string generatedName = string.Format(CultureInfo.InvariantCulture, "{0}{1}", generatedNameBase, ++index);
List<string> existingNames = new List<string>();
Fx.Assert(operationInfoBase != null, "operation info base should not be null here");
foreach (OperationParameterInfo paramInfo in operationInfoBase.GetParameters(this.ServiceProvider))
{
existingNames.Add(paramInfo.Name);
}
while (existingNames.Contains(generatedName))
{
generatedName = string.Format(CultureInfo.InvariantCulture, "{0}{1}", generatedNameBase, ++index);
}
return generatedName;
}
bool IsValidIdentifier(string name)
{
if (csharpProvider == null)
{
csharpProvider = new CSharpCodeProvider();
}
if (vbProvider == null)
{
vbProvider = new VBCodeProvider();
}
if (!csharpProvider.IsValidIdentifier(name))
{
return false;
}
if (!vbProvider.IsValidIdentifier(name))
{
return false;
}
return true;
}
private void moveParameterDownButton_Click(object sender, EventArgs e)
{
DataGridViewRow currentRow = this.parametersGrid.CurrentRow;
Fx.Assert((currentRow != null), "current row cannot be null");
int currentRowIndex = currentRow.Index;
Fx.Assert((currentRowIndex >= 0), "must be valid index");
Fx.Assert(currentRowIndex < (this.parametersGrid.Rows.Count - 2), "cant move down the template row or the one above it");
this.parametersGrid.Rows.Remove(currentRow);
this.parametersGrid.Rows.Insert(currentRowIndex + 1, currentRow);
this.parametersGrid.CurrentCell = currentRow.Cells[this.nameColumn.Index];
UpdateOperationParameters();
RefreshParameterOperationButtons();
}
private void moveParameterUpButton_Click(object sender, EventArgs e)
{
DataGridViewRow currentRow = this.parametersGrid.CurrentRow;
Fx.Assert((currentRow != null), "current row cannot be null");
int currentRowIndex = currentRow.Index;
Fx.Assert((currentRowIndex >= 1), "must be seond row or higher");
Fx.Assert(currentRowIndex != (this.parametersGrid.Rows.Count - 1), "cant move up the template row");
this.parametersGrid.Rows.Remove(currentRow);
this.parametersGrid.Rows.Insert(currentRowIndex - 1, currentRow);
this.parametersGrid.CurrentCell = currentRow.Cells[this.nameColumn.Index];
UpdateOperationParameters();
RefreshParameterOperationButtons();
}
void oneWayCheckBoxCheckedChanged(object sender, EventArgs e)
{
WorkflowServiceOperationListItem workflowOperationListItem = this.Item as WorkflowServiceOperationListItem;
Fx.Assert(workflowOperationListItem != null, "this method should only be called on workflowOperations");
workflowOperationListItem.Operation.IsOneWay = this.oneWayCheckBox.Checked;
OnOperationPropertiesChanged();
}
void OnOperationPropertiesChanged()
{
if (this.ItemChanged != null)
{
this.ItemChanged.Invoke(this, null);
}
UpdateImplementingActivities();
}
void operationNameTextBox_Validated(object sender, EventArgs e)
{
WorkflowServiceOperationListItem workflowOperationListItem = this.Item as WorkflowServiceOperationListItem;
Fx.Assert(workflowOperationListItem != null, "this method should only be called on workflowOperations");
workflowOperationListItem.Operation.Name = this.operationNameTextBox.Text;
OnOperationPropertiesChanged();
}
void operationNameTextBox_Validating(object sender, CancelEventArgs e)
{
ServiceOperationListItem operationListItem = (ServiceOperationListItem) this.Item;
string oldName = operationListItem.Name;
operationListItem.Name = this.operationNameTextBox.Text;
if (operationListItem.Validating != null)
{
operationListItem.Validating.Invoke(operationListItem, e);
}
if (e.Cancel)
{
this.operationNameTextBox.Text = oldName;
operationListItem.Name = oldName;
e.Cancel = false;
}
}
void parametersGrid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
string errorString = string.Empty;
bool valid = true;
if (e.ColumnIndex == this.nameColumn.Index)
{
valid = ValidateParamaterName((string) e.FormattedValue, e, out errorString);
}
// void is not valid for parameters other than returnvalue
if (e.ColumnIndex == this.typeColumn.Index)
{
if (typeof(void).ToString().Equals(e.FormattedValue) && !(this.parametersGrid.Rows[e.RowIndex].Cells[this.nameColumn.Index].Value.Equals(SR2.GetString(SR2.ReturnValueString))))
{
valid = false;
errorString = SR2.GetString(SR2.VoidIsNotAValidParameterType);
}
}
if (!valid)
{
e.Cancel = true;
DesignerHelpers.ShowMessage(this.ServiceProvider, errorString, DR.GetString(DR.WorkflowDesignerTitle), MessageBoxButtons.OK,
MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
}
void parametersGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
DisableFormCancelButton();
if (this.parametersGrid.CurrentCell.ColumnIndex == this.typeColumn.Index)
{
DataGridViewComboBoxEditingControl comboBox = e.Control as DataGridViewComboBoxEditingControl;
comboBox.SelectionChangeCommitted -= new EventHandler(comboBox_SelectionChangeCommitted);
comboBox.SelectionChangeCommitted += new EventHandler(comboBox_SelectionChangeCommitted);
}
}
void parametersGrid_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete && this.RemoveParameterButton.Enabled)
{
RemoveParameterButton_Click(this, null);
}
}
void parametersGrid_SelectionChanged(object sender, EventArgs e)
{
RefreshParameterOperationButtons();
}
void parametersGridCellEndEdit(object sender, DataGridViewCellEventArgs e)
{
EnableFormCancelButton();
if (!this.parametersGrid.Rows[this.parametersGrid.RowCount - 1].Cells[this.nameColumn.Index].Value.Equals(this.ParameterTemplateRowName))
{
DataGridViewRow editedRow = this.parametersGrid.Rows[e.RowIndex];
editedRow.Cells[this.typeColumn.Index].Value = typeof(string);
editedRow.Cells[this.directionColumn.Index].Value = SR2.GetString(SR2.ParameterDirectionIn);
// add a new template row to the end of the list.
this.parametersGrid.Rows.Add(this.ParameterTemplateRowName, null, null);
RefreshParameterOperationButtons();
}
DataGridViewCell currentCell = this.parametersGrid.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (typeof(TypeChooserCellItem).Equals(currentCell.Value))
{
// need this check beacuse one of the ways of choosing browse types( keyboard selection from dropdown)
// overwrites the value of the cell with BrowseType.. again after setting the type, thus bringing up the type browser,
// for the second time here.
if (!typeChooserCellItem.TypeChosen)
{
BrowseAndSelectType(currentCell);
}
else
{
currentCell.Value = typeChooserCellItem.ChosenType;
}
}
if (e.ColumnIndex.Equals(this.typeColumn.Index))
{
typeChooserCellItem.Reset();
}
UpdateOperationParameters();
}
void permissionNameTextChanged(object sender, EventArgs e)
{
WorkflowServiceOperationListItem workflowOperationListItem = this.Item as WorkflowServiceOperationListItem;
if (workflowOperationListItem != null)
{
workflowOperationListItem.Operation.PrincipalPermissionName = this.permissionNameTextBox.Text;
}
else
{
TypedServiceOperationListItem reflectedOperationListItem = this.Item as TypedServiceOperationListItem;
if (reflectedOperationListItem != null)
{
reflectedOperationListItem.Operation.PrincipalPermissionName = this.permissionNameTextBox.Text;
}
}
OnOperationPropertiesChanged();
}
void permissionRoleTextChanged(object sender, EventArgs e)
{
WorkflowServiceOperationListItem workflowOperationListItem = this.Item as WorkflowServiceOperationListItem;
if (workflowOperationListItem != null)
{
workflowOperationListItem.Operation.PrincipalPermissionRole = this.permissionRoleTextBox.Text;
}
else
{
TypedServiceOperationListItem reflectedOperationListItem = this.Item as TypedServiceOperationListItem;
if (reflectedOperationListItem != null)
{
reflectedOperationListItem.Operation.PrincipalPermissionRole = this.permissionRoleTextBox.Text;
}
}
OnOperationPropertiesChanged();
}
private void PopulateParametersGrid(OperationInfoBase operationInfoBase)
{
if (operationInfoBase != null)
{
string paramName;
string direction;
Type paramType;
Type returnType = typeof(void);
foreach (OperationParameterInfo paramInfo in operationInfoBase.GetParameters(this.ServiceProvider))
{
paramType = paramInfo.ParameterType;
paramName = paramInfo.Name;
if (paramInfo.Name.Equals(SR2.GetString(SR2.ReturnValueString)))
{
returnType = paramType;
continue;
}
else
{
if (paramInfo.IsOut)
{
if (paramInfo.IsIn)
{
direction = SR2.GetString(SR2.ParameterDirectionRef);
}
else
{
direction = SR2.GetString(SR2.ParameterDirectionOut);
}
}
else if (paramType.IsByRef)
{
direction = SR2.GetString(SR2.ParameterDirectionRef);
}
else
{
// If neither IsOut nor IsByRef is true we assume it is an In parameter.
direction = SR2.GetString(SR2.ParameterDirectionIn);
}
}
//Add this type to list of typeColumn Items
AddToTypeList(paramType);
this.parametersGrid.Rows.Add(new object[] { paramName, paramType, direction });
}
// add the retval as the first parameter
AddToTypeList(returnType);
this.parametersGrid.Rows.Insert(0, new object[] { SR2.GetString(SR2.ReturnValueString), returnType, SR2.GetString(SR2.ParameterDirectionOut) });
DataGridViewRow returnValueRow = this.parametersGrid.Rows[0];
returnValueRow.Cells[this.nameColumn.Index].ReadOnly = true;
returnValueRow.Cells[this.directionColumn.Index].ReadOnly = true;
}
}
void protectionLevelComboBoxSelectedValueChanged(object sender, EventArgs e)
{
WorkflowServiceOperationListItem item = (WorkflowServiceOperationListItem) this.Item;
if (this.protectionLevelComboBox.SelectedItem.Equals(SR2.GetString(SR2.UseRuntimeDefaults)))
{
item.Operation.ResetProtectionLevel();
}
else
{
item.Operation.ProtectionLevel = (ProtectionLevel) this.protectionLevelComboBox.SelectedItem;
}
OnOperationPropertiesChanged();
}
private void RefreshParameterOperationButtons()
{
if (!isEditable)
{
return;
}
DataGridViewRow currentRow = this.parametersGrid.CurrentRow;
// disable move up, move down, remove
moveParameterDownButton.Enabled = false;
moveParameterUpButton.Enabled = false;
RemoveParameterButton.Enabled = false;
if (currentRow == null)
{
return;
}
int currentRowIndex = currentRow.Index;
// dont enable any operation on the template row or the retval row
if (currentRowIndex != (this.parametersGrid.Rows.Count - 1) && (currentRowIndex != 0))
{
RemoveParameterButton.Enabled = true;
if (currentRowIndex > 1)
{
moveParameterUpButton.Enabled = true;
}
if (currentRowIndex < (this.parametersGrid.Rows.Count - 2))
{
moveParameterDownButton.Enabled = true;
}
}
}
private void RemoveParameterButton_Click(object sender, EventArgs e)
{
DataGridViewRow currentRow = this.parametersGrid.CurrentRow;
Fx.Assert((currentRow != null), "current row cannot be null");
int currentRowIndex = currentRow.Index;
Fx.Assert(currentRowIndex != (this.parametersGrid.Rows.Count - 1), "cant delete the template row");
this.parametersGrid.Rows.Remove(currentRow);
UpdateOperationParameters();
RefreshParameterOperationButtons();
}
void SetEditability(bool editable)
{
this.isEditable = editable;
this.addParameterButton.Enabled = editable;
this.RemoveParameterButton.Enabled = editable;
this.moveParameterDownButton.Enabled = editable;
this.moveParameterUpButton.Enabled = editable;
this.oneWayCheckBox.Enabled = editable;
this.operationNameTextBox.Enabled = true;
this.operationNameTextBox.ReadOnly = !editable;
this.parametersGrid.ReadOnly = !editable;
this.protectionLevelComboBox.Enabled = editable;
}
private void SetupColumns()
{
this.parametersGrid.Columns.Clear();
nameColumn = new DataGridViewTextBoxColumn();
nameColumn.HeaderText = SR2.GetString(SR2.ParameterColumnHeaderName);
nameColumn.Name = "Name";
nameColumn.SortMode = DataGridViewColumnSortMode.NotSortable;
this.parametersGrid.Columns.Add(nameColumn);
typeColumn = new DataGridViewComboBoxColumn();
typeColumn.HeaderText = SR2.GetString(SR2.ParameterColumnHeaderType);
typeColumn.Name = "Type";
typeColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
typeColumn.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
typeColumn.AutoComplete = true;
typeColumn.SortMode = DataGridViewColumnSortMode.NotSortable;
typeChooserCellItem = new TypeChooserCellItem();
typeColumn.Items.Add(typeChooserCellItem);
AddPrimitiveTypesToTypesList(); typeColumn.ValueMember = "Type";
typeColumn.DisplayMember = "DisplayString";
this.parametersGrid.Columns.Add(typeColumn);
directionColumn = new DataGridViewComboBoxColumn();
directionColumn.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
directionColumn.AutoComplete = true;
directionColumn.Items.Add(SR2.GetString(SR2.ParameterDirectionIn));
directionColumn.Items.Add(SR2.GetString(SR2.ParameterDirectionOut));
directionColumn.Items.Add(SR2.GetString(SR2.ParameterDirectionRef));
directionColumn.HeaderText = SR2.GetString(SR2.ParameterColumnHeaderDirection);
directionColumn.Name = "Direction";
directionColumn.SortMode = DataGridViewColumnSortMode.NotSortable;
this.parametersGrid.Columns.Add(directionColumn);
this.operationsToolStrip.BackColor = this.parametersTabPage.BackColor;
}
bool TrySelectType(TypeBrowserDialog typeBrowserDialog, DataGridViewCell cell)
{
typeBrowserDialog.ShowDialog();
if (typeBrowserDialog.SelectedType != null)
{
if (!ParameterTypeFilterProvider.IsValidType(typeBrowserDialog.SelectedType))
{
DesignerHelpers.ShowMessage(this.ServiceProvider, SR2.GetString(SR2.InvalidParameterType,
typeBrowserDialog.SelectedType), DR.GetString(DR.WorkflowDesignerTitle), MessageBoxButtons.OK,
MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
return false;
}
AddToTypeList(typeBrowserDialog.SelectedType);
}
typeChooserCellItem.ChosenType = typeBrowserDialog.SelectedType;
cell.Value = typeBrowserDialog.SelectedType;
return true;
}
private void UpdateImplementingActivities()
{
ServiceOperationListItem operationListItem = this.Item as ServiceOperationListItem;
WorkflowServiceOperationListItem workflowOperationListItem = this.Item as WorkflowServiceOperationListItem;
TypedServiceOperationListItem reflectedOperationListItem = this.Item as TypedServiceOperationListItem;
OperationInfoBase operation = null;
if (workflowOperationListItem != null)
{
operation = workflowOperationListItem.Operation;
}
else if (reflectedOperationListItem != null)
{
operation = reflectedOperationListItem.Operation;
}
Fx.Assert(operation != null, "operation should not be null at this point");
// workflow operations list item will complain if some operationInfo objects have different signature than others
// for the same operation name. This will happen when we are updating the activities, since they already have a operation
// object for that operation name, but with a different signature. so make them all point to null first ,then update.
if (workflowOperationListItem != null)
{
foreach (Activity activity in operationListItem.ImplementingActivities)
{
PropertyDescriptorUtils.SetPropertyValue(this.ServiceProvider, ServiceOperationHelpers.GetServiceOperationInfoPropertyDescriptor(activity), activity, null);
}
}
foreach (Activity activity in operationListItem.ImplementingActivities)
{
PropertyDescriptorUtils.SetPropertyValue(this.ServiceProvider, ServiceOperationHelpers.GetServiceOperationInfoPropertyDescriptor(activity), activity, operation.Clone());
}
}
void UpdateOperationParameters()
{
WorkflowServiceOperationListItem workflowOperationListItem = this.Item as WorkflowServiceOperationListItem;
Fx.Assert(workflowOperationListItem != null, "UpdateOperation should only be called on workflowOperations");
workflowOperationListItem.Operation.Parameters.Clear();
int paramPosition = 0;
foreach (DataGridViewRow row in this.parametersGrid.Rows)
{
string name = row.Cells[this.nameColumn.Index].Value as string;
object typeCell = row.Cells[this.typeColumn.Index].Value;
string direction = row.Cells[this.directionColumn.Index].Value as string;
if (string.IsNullOrEmpty(name) || name.Equals(this.ParameterTemplateRowName))
{
continue;
}
if (typeCell == null)
{
continue;
}
if (string.IsNullOrEmpty(direction))
{
continue;
}
OperationParameterInfo operationParameterInfo = new OperationParameterInfo(name);
operationParameterInfo.ParameterType = typeCell as Type;
if (direction.Equals(SR2.GetString(SR2.ParameterDirectionIn)))
{
operationParameterInfo.Attributes |= ParameterAttributes.In;
}
if (direction.Equals(SR2.GetString(SR2.ParameterDirectionOut)))
{
operationParameterInfo.Attributes |= ParameterAttributes.Out;
}
if (direction.Equals(SR2.GetString(SR2.ParameterDirectionRef)))
{
operationParameterInfo.Attributes |= ParameterAttributes.In;
operationParameterInfo.Attributes |= ParameterAttributes.Out;
}
if (name.Equals(SR2.GetString(SR2.ReturnValueString)))
{
operationParameterInfo.Attributes |= ParameterAttributes.Retval;
operationParameterInfo.Position = -1;
}
else
{
operationParameterInfo.Position = paramPosition;
paramPosition++;
}
workflowOperationListItem.Operation.Parameters.Add(operationParameterInfo);
}
UpdateImplementingActivities();
}
private bool ValidateParamaterName(string parameterName, DataGridViewCellValidatingEventArgs e, out string errorString)
{
errorString = string.Empty;
if (string.IsNullOrEmpty(parameterName))
{
errorString = SR2.GetString(SR2.ParameterNameCannotBeEmpty);
return false;
}
foreach (DataGridViewRow row in this.parametersGrid.Rows)
{
if (row.Index == e.RowIndex)
{
continue;
}
if (parameterName.Equals(row.Cells[this.nameColumn.Index].Value.ToString()))
{
errorString = SR2.GetString(SR2.DuplicateOfExistingParameter);
return false;
}
}
if (parameterName.Equals(this.ParameterTemplateRowName) && (e.RowIndex == this.parametersGrid.Rows.Count - 1))
{
return true;
}
if (parameterName.Equals(SR2.GetString(SR2.ReturnValueString)))
{
return true;
}
if (!IsValidIdentifier(parameterName))
{
errorString = SR2.GetString(SR2.ParameterNameIsInvalid);
return false;
}
return true;
}
class ParameterTypeFilterProvider : ITypeFilterProvider
{
string ITypeFilterProvider.FilterDescription
{
get { return SR2.GetString(SR2.ChooseAParameterTypeFromBelow); }
}
// This is a helper method called after a type has been selected to determine whether the type is valid
// for use as a parameter type. This check it too expensive to perform during filtering.
public static bool IsValidType(Type type)
{
bool result = true;
if (!IsExemptType(type))
{
try
{
XsdDataContractExporter exporter = new XsdDataContractExporter();
if (!exporter.CanExport(type))
{
result = false;
}
}
catch (InvalidDataContractException exception)
{
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Warning);
result = false;
}
catch (NotImplementedException exception)
{
// This occurs when a design-time type is involved (for example, as a type parameter), in
// which case we don't want to exclude the type from use as parameter type.
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information);
}
}
return result;
}
bool ITypeFilterProvider.CanFilterType(Type type, bool throwOnError)
{
// We don't perform any actual filtering here because the XsdDataContractExporter validation is too
// expensive to do on the full list of types in all referenced assemblies.
return true;
}
// Exempt types are those not subject to the XsdDataContractExporter validation. Design-time types are
// exempt because the XsdDataContractExporter does not support them. The others are exempt because they
// are serialized by mechanisms other than DataContractSerializer.
static bool IsExemptType(Type type)
{
return (type is DesignTimeType) ||
type.IsDefined(typeof(MessageContractAttribute), true) ||
type.Equals(typeof(System.ServiceModel.Channels.Message)) ||
type.Equals(typeof(System.IO.Stream));
}
}
class TypeCellItem
{
private Type type;
public TypeCellItem(Type type)
{
this.type = type;
}
public virtual string DisplayString
{
get
{
return ServiceOperationDetailViewControl.GetTypeSignature(type);
}
}
public virtual Type Type
{
get { return type; }
set { type = value; }
}
}
class TypeChooserCellItem : TypeCellItem
{
private Type chosenType = null;
private bool typeChosen = false;
public TypeChooserCellItem()
: base(typeof(TypeChooserCellItem))
{
}
public Type ChosenType
{
get { return chosenType; }
set
{
if (value != null)
{
typeChosen = true;
}
chosenType = value;
}
}
public override string DisplayString
{
get
{
return SR2.GetString(SR2.BrowseType);
}
}
public bool TypeChosen
{
get { return typeChosen; }
set { typeChosen = value; }
}
internal void Reset()
{
this.ChosenType = null;
this.TypeChosen = false;
}
}
}
}
| |
using System;
using System.IO;
using Microsoft.Build.Construction;
namespace GodotSharpTools.Project
{
public static class ProjectGenerator
{
public static string GenCoreApiProject(string dir, string[] compileItems)
{
string path = Path.Combine(dir, CoreApiProject + ".csproj");
ProjectPropertyGroupElement mainGroup;
var root = CreateLibraryProject(CoreApiProject, out mainGroup);
mainGroup.AddProperty("DocumentationFile", Path.Combine("$(OutputPath)", "$(AssemblyName).xml"));
mainGroup.SetProperty("RootNamespace", "Godot");
GenAssemblyInfoFile(root, dir, CoreApiProject,
new string[] { "[assembly: InternalsVisibleTo(\"" + EditorApiProject + "\")]" },
new string[] { "System.Runtime.CompilerServices" });
foreach (var item in compileItems)
{
root.AddItem("Compile", item.RelativeToPath(dir).Replace("/", "\\"));
}
root.Save(path);
return root.GetGuid().ToString().ToUpper();
}
public static string GenEditorApiProject(string dir, string coreApiHintPath, string[] compileItems)
{
string path = Path.Combine(dir, EditorApiProject + ".csproj");
ProjectPropertyGroupElement mainGroup;
var root = CreateLibraryProject(EditorApiProject, out mainGroup);
mainGroup.AddProperty("DocumentationFile", Path.Combine("$(OutputPath)", "$(AssemblyName).xml"));
mainGroup.SetProperty("RootNamespace", "Godot");
GenAssemblyInfoFile(root, dir, EditorApiProject);
foreach (var item in compileItems)
{
root.AddItem("Compile", item.RelativeToPath(dir).Replace("/", "\\"));
}
var coreApiRef = root.AddItem("Reference", CoreApiProject);
coreApiRef.AddMetadata("HintPath", coreApiHintPath);
coreApiRef.AddMetadata("Private", "False");
root.Save(path);
return root.GetGuid().ToString().ToUpper();
}
public static string GenGameProject(string dir, string name, string[] compileItems)
{
string path = Path.Combine(dir, name + ".csproj");
ProjectPropertyGroupElement mainGroup;
var root = CreateLibraryProject(name, out mainGroup);
mainGroup.SetProperty("OutputPath", Path.Combine(".mono", "temp", "bin", "$(Configuration)"));
mainGroup.SetProperty("BaseIntermediateOutputPath", Path.Combine(".mono", "temp", "obj"));
mainGroup.SetProperty("IntermediateOutputPath", Path.Combine("$(BaseIntermediateOutputPath)", "$(Configuration)"));
var toolsGroup = root.AddPropertyGroup();
toolsGroup.Condition = " '$(Configuration)|$(Platform)' == 'Tools|AnyCPU' ";
toolsGroup.AddProperty("DebugSymbols", "true");
toolsGroup.AddProperty("DebugType", "portable");
toolsGroup.AddProperty("Optimize", "false");
toolsGroup.AddProperty("DefineConstants", "DEBUG;TOOLS;");
toolsGroup.AddProperty("ErrorReport", "prompt");
toolsGroup.AddProperty("WarningLevel", "4");
toolsGroup.AddProperty("ConsolePause", "false");
var coreApiRef = root.AddItem("Reference", CoreApiProject);
coreApiRef.AddMetadata("HintPath", Path.Combine("$(ProjectDir)", ".mono", "assemblies", CoreApiProject + ".dll"));
coreApiRef.AddMetadata("Private", "False");
var editorApiRef = root.AddItem("Reference", EditorApiProject);
editorApiRef.Condition = " '$(Configuration)' == 'Tools' ";
editorApiRef.AddMetadata("HintPath", Path.Combine("$(ProjectDir)", ".mono", "assemblies", EditorApiProject + ".dll"));
editorApiRef.AddMetadata("Private", "False");
GenAssemblyInfoFile(root, dir, name);
foreach (var item in compileItems)
{
root.AddItem("Compile", item.RelativeToPath(dir).Replace("/", "\\"));
}
root.Save(path);
return root.GetGuid().ToString().ToUpper();
}
public static void GenAssemblyInfoFile(ProjectRootElement root, string dir, string name, string[] assemblyLines = null, string[] usingDirectives = null)
{
string propertiesDir = Path.Combine(dir, "Properties");
if (!Directory.Exists(propertiesDir))
Directory.CreateDirectory(propertiesDir);
string usingDirectivesText = string.Empty;
if (usingDirectives != null)
{
foreach (var usingDirective in usingDirectives)
usingDirectivesText += "\nusing " + usingDirective + ";";
}
string assemblyLinesText = string.Empty;
if (assemblyLines != null)
{
foreach (var assemblyLine in assemblyLines)
assemblyLinesText += string.Join("\n", assemblyLines) + "\n";
}
string content = string.Format(assemblyInfoTemplate, usingDirectivesText, name, assemblyLinesText);
string assemblyInfoFile = Path.Combine(propertiesDir, "AssemblyInfo.cs");
File.WriteAllText(assemblyInfoFile, content);
root.AddItem("Compile", assemblyInfoFile.RelativeToPath(dir).Replace("/", "\\"));
}
public static ProjectRootElement CreateLibraryProject(string name, out ProjectPropertyGroupElement mainGroup)
{
var root = ProjectRootElement.Create();
root.DefaultTargets = "Build";
mainGroup = root.AddPropertyGroup();
mainGroup.AddProperty("Configuration", "Debug").Condition = " '$(Configuration)' == '' ";
mainGroup.AddProperty("Platform", "AnyCPU").Condition = " '$(Platform)' == '' ";
mainGroup.AddProperty("ProjectGuid", "{" + Guid.NewGuid().ToString().ToUpper() + "}");
mainGroup.AddProperty("OutputType", "Library");
mainGroup.AddProperty("OutputPath", Path.Combine("bin", "$(Configuration)"));
mainGroup.AddProperty("RootNamespace", name);
mainGroup.AddProperty("AssemblyName", name);
mainGroup.AddProperty("TargetFrameworkVersion", "v4.5");
var debugGroup = root.AddPropertyGroup();
debugGroup.Condition = " '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ";
debugGroup.AddProperty("DebugSymbols", "true");
debugGroup.AddProperty("DebugType", "portable");
debugGroup.AddProperty("Optimize", "false");
debugGroup.AddProperty("DefineConstants", "DEBUG;");
debugGroup.AddProperty("ErrorReport", "prompt");
debugGroup.AddProperty("WarningLevel", "4");
debugGroup.AddProperty("ConsolePause", "false");
var releaseGroup = root.AddPropertyGroup();
releaseGroup.Condition = " '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ";
releaseGroup.AddProperty("DebugType", "portable");
releaseGroup.AddProperty("Optimize", "true");
releaseGroup.AddProperty("ErrorReport", "prompt");
releaseGroup.AddProperty("WarningLevel", "4");
releaseGroup.AddProperty("ConsolePause", "false");
// References
var referenceGroup = root.AddItemGroup();
referenceGroup.AddItem("Reference", "System");
root.AddImport(Path.Combine("$(MSBuildBinPath)", "Microsoft.CSharp.targets").Replace("/", "\\"));
return root;
}
private static void AddItems(ProjectRootElement elem, string groupName, params string[] items)
{
var group = elem.AddItemGroup();
foreach (var item in items)
{
group.AddItem(groupName, item);
}
}
public const string CoreApiProject = "GodotSharp";
public const string EditorApiProject = "GodotSharpEditor";
private const string assemblyInfoTemplate =
@"using System.Reflection;{0}
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle(""{1}"")]
[assembly: AssemblyDescription("""")]
[assembly: AssemblyConfiguration("""")]
[assembly: AssemblyCompany("""")]
[assembly: AssemblyProduct("""")]
[assembly: AssemblyCopyright("""")]
[assembly: AssemblyTrademark("""")]
[assembly: AssemblyCulture("""")]
// The assembly version has the format ""{{Major}}.{{Minor}}.{{Build}}.{{Revision}}"".
// The form ""{{Major}}.{{Minor}}.*"" will automatically update the build and revision,
// and ""{{Major}}.{{Minor}}.{{Build}}.*"" will update just the revision.
[assembly: AssemblyVersion(""1.0.*"")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("""")]
{2}";
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using MvcNavigation.Configuration.Advanced;
using MvcNavigation.Internal;
namespace MvcNavigation
{
public static class HtmlHelperExtensions
{
#region Menu
public static MvcHtmlString Menu(this HtmlHelper html)
{
return Menu(html, maxLevels: 1, renderAllLevels: false);
}
public static MvcHtmlString Menu(this HtmlHelper html, int maxLevels)
{
return Menu(html, maxLevels, renderAllLevels: false);
}
public static MvcHtmlString Menu(this HtmlHelper html, int maxLevels, bool renderAllLevels)
{
if (NavigationConfiguration.DefaultSitemap == null)
throw new InvalidOperationException("MvcNavigation is not initialised.");
var rootNode = NavigationConfiguration.DefaultSitemap;
return RendererConfiguration.MenuRenderer(html, rootNode, maxLevels, renderAllLevels);
}
public static MvcHtmlString Menu(this HtmlHelper html, string name)
{
return Menu(html, name, maxLevels: 1, renderAllLevels: false);
}
public static MvcHtmlString Menu(this HtmlHelper html, string name, int maxLevels)
{
return Menu(html, name, maxLevels, renderAllLevels: false);
}
public static MvcHtmlString Menu(this HtmlHelper html, string name, int maxLevels, bool renderAllLevels)
{
var namedSitemap = NavigationConfiguration.GetSitemap(name);
if (namedSitemap == null)
throw new InvalidOperationException(string.Format("Sitemap \"{0}\" is not initialised.", name));
return RendererConfiguration.MenuRenderer(html, namedSitemap, maxLevels, renderAllLevels);
}
#endregion
#region Breadcrumb
public static MvcHtmlString Breadcrumb(this HtmlHelper html)
{
if (NavigationConfiguration.DefaultSitemap == null)
throw new InvalidOperationException("MvcNavigation is not initialised.");
var breadcrumbTrail = ConstructBreadcrumbTrail(html, NavigationConfiguration.DefaultSitemap);
return RendererConfiguration.BreadcrumbRenderer(html, breadcrumbTrail);
}
public static MvcHtmlString Breadcrumb(this HtmlHelper html, string name)
{
var namedSitemap = NavigationConfiguration.GetSitemap(name);
if (namedSitemap == null)
throw new InvalidOperationException(string.Format("Sitemap \"{0}\" is not initialised.", name));
var breadcrumbTrail = ConstructBreadcrumbTrail(html, namedSitemap);
return RendererConfiguration.BreadcrumbRenderer(html, breadcrumbTrail);
}
#endregion
public static MvcHtmlString ActionLink(this HtmlHelper html, INode linkTarget)
{
if (html == null)
throw new ArgumentNullException("html");
if (linkTarget == null)
throw new ArgumentNullException("linkTarget");
var htmlAttributes = new Dictionary<string, object>();
if (IsCurrentNode(html, linkTarget) || (IsRootNode(linkTarget) == false && IsAncestorOfCurrentNode(html, linkTarget)))
htmlAttributes.Add("class", NavigationConfiguration.SelectedNodeCssClass);
return html.ActionLink(linkTarget.Title, linkTarget.ActionName, linkTarget.ControllerName, linkTarget.RouteValues, htmlAttributes);
}
public static MvcHtmlString ActionLink(this HtmlHelper html, LinkedListNode<INode> linkTarget)
{
if (html == null)
throw new ArgumentNullException("html");
if (linkTarget == null)
throw new ArgumentNullException("linkTarget");
var node = linkTarget.Value;
return html.ActionLink(node.Title, node.ActionName, node.ControllerName, node.RouteValues, null);
}
public static bool IsCurrentNode(this HtmlHelper html, INode node)
{
if (html == null)
throw new ArgumentNullException("html");
if (node == null)
throw new ArgumentNullException("node");
var viewContext = GetViewContext(html);
var contextControllerName = GetContextControllerName(viewContext);
var contextActionName = GetContextActionName(viewContext);
var additionalRouteData = GetAdditionalRouteData(viewContext);
return IsCurrentNode(node, contextControllerName, contextActionName, additionalRouteData);
}
public static bool IsAncestorOfCurrentNode(this HtmlHelper html, INode node)
{
if (html == null)
throw new ArgumentNullException("html");
if (node == null)
throw new ArgumentNullException("node");
var viewContext = GetViewContext(html);
var contextControllerName = GetContextControllerName(viewContext);
var contextActionName = GetContextActionName(viewContext);
var additionalRouteData = GetAdditionalRouteData(viewContext);
return node.Children.Any() && HasMatchingDescendant(node, contextControllerName, contextActionName, additionalRouteData, (int)html.ViewData["CurrentLevel"], (int)html.ViewData["MaxLevels"]);
}
static bool HasMatchingDescendant(INode currentNode, string contextControllerName, string contextActionName, IEnumerable<KeyValuePair<string, object>> additionalRouteData, int currentLevel, int maxLevels)
{
// check immediate children for match
if (currentNode.Children.Any(childNode => IsCurrentNode(childNode, contextControllerName, contextActionName, additionalRouteData)))
return true;
// ensure scan depth does not exceed specified scan range
if (currentLevel + 1 > maxLevels)
return false;
// check descendants
var nextLevel = currentLevel + 1;
return currentNode.Children.Any(childNode => HasMatchingDescendant(childNode, contextControllerName, contextActionName, additionalRouteData, nextLevel, maxLevels));
}
static bool IsCurrentNode(INode node, string contextControllerName, string contextActionName, IEnumerable<KeyValuePair<string, object>> additionalRouteData)
{
if (string.Equals(contextControllerName, node.ControllerName, StringComparison.OrdinalIgnoreCase) == false || string.Equals(contextActionName, node.ActionName, StringComparison.OrdinalIgnoreCase) == false)
return false;
return additionalRouteData.All(routeDataItem => string.Equals(routeDataItem.Value.ToString(), node.RouteValues[routeDataItem.Key] != null ? node.RouteValues[routeDataItem.Key].ToString() : null, StringComparison.OrdinalIgnoreCase));
}
static ViewContext GetViewContext(HtmlHelper html)
{
return html.ViewContext.IsChildAction ? html.ViewContext.ParentActionViewContext : html.ViewContext;
}
static string GetContextControllerName(ViewContext viewContext)
{
return viewContext.RouteData.Values[RouteDataKeys.Controller].ToString();
}
static string GetContextActionName(ViewContext viewContext)
{
return viewContext.RouteData.Values[RouteDataKeys.Action].ToString();
}
static IEnumerable<KeyValuePair<string, object>> GetAdditionalRouteData(ViewContext viewContext)
{
return viewContext.RouteData.Values.Where(v => v.Key != RouteDataKeys.Controller && v.Key != RouteDataKeys.Action);
}
static bool IsRootNode(INode node)
{
return node.Parent == null;
}
static LinkedList<INode> ConstructBreadcrumbTrail(HtmlHelper html, INode sitemap)
{
var current = FindNode(sitemap, node => IsCurrentNode(html, node));
if (current == null)
return new LinkedList<INode>();
var breadcrumbTrail = new LinkedList<INode>();
breadcrumbTrail.AddLast(current);
while (current.Parent != null)
{
breadcrumbTrail.AddFirst(current.Parent);
current = current.Parent;
}
return breadcrumbTrail;
}
static INode FindNode(INode startNode, Func<INode, bool> predicate)
{
var queue = new Queue<INode>();
queue.Enqueue(startNode);
while (queue.Count > 0)
{
var current = queue.Dequeue();
if (predicate(current))
return current;
foreach (var childNode in current.Children)
queue.Enqueue(childNode);
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
namespace ZombieSmash {
public class Level2Manager : Microsoft.Xna.Framework.DrawableGameComponent {
private Rectangle window;
private ContentManager Content;
private bool goToNextScreen = false;
private bool gameOver = false;
private bool soldierIsInvincible = false;
private bool soldierIsVisible = true;
private int blinkTimer = 0;
private List<Vector2> enemySpawnLocations;
private MousePointer crosshair;
private MouseState prevMS;
private SpriteBatch spriteBatch;
private UserControlledSprite soldier;
private Texture2D jungle_grass;
private Texture2D bush;
private SpriteFont lives;
private Texture2D lives_background;
public Level2Manager(Game game)
: base(game) {
window = Game.Window.ClientBounds;
Content = Game.Content;
}
public override void Initialize() {
// TODO: Add your initialization code here
base.Initialize();
}
protected override void LoadContent() {
spriteBatch = new SpriteBatch(Game.GraphicsDevice);
jungle_grass = Content.Load<Texture2D>("Images/Jungle_Grass");
bush = Content.Load<Texture2D>("Images/bush");
crosshair = new MousePointer(Content.Load<Texture2D>("images/crosshair"), new Point(40, 40),
0, new Vector2(prevMS.X, prevMS.Y));
soldier = new UserControlledSprite(Game.Content.Load<Texture2D>("images/soldier"),
new Point(29, 81), 0, new Vector2(2.5f, 2.5f),
new Vector2(window.Width / 2, window.Height / 2));
prevMS = Mouse.GetState();
enemySpawnLocations = new List<Vector2>();
for (int yPosition = 0; yPosition < window.Height - 50; yPosition += 100) {
enemySpawnLocations.Add(new Vector2(50, yPosition));
enemySpawnLocations.Add(new Vector2(window.Width - 100, yPosition));
}
lives = Content.Load<SpriteFont>("Fonts/SpriteFont2");
lives_background = Content.Load<Texture2D>("Images/lives_background_square");
}
public void initializeEnvironment() {
EnvironmentManager.initializeSelf(window, spriteBatch);
EnvironmentManager.initGameLevel(Content, soldier, enemySpawnLocations, 20, 500);
}
public override void Update(GameTime gameTime) {
gameOver = EnvironmentManager.isGameOver();
soldierIsInvincible = EnvironmentManager.detectCollisions(soldier, soldierIsInvincible, gameTime);
if (EnvironmentManager.allZombiesAreDead()) {
goToNextScreen = true;
}
if (!soldierIsInvincible) {
soldierIsVisible = true;
}
else {
blinkTimer += gameTime.ElapsedGameTime.Milliseconds;
if (blinkTimer > 75) {
blinkTimer = 0;
soldierIsVisible = !soldierIsVisible;
}
}
crosshair.Update(gameTime, window);
soldier.Update(gameTime, window);
EnvironmentManager.Update(gameTime, soldier, Content);
//Spawn a bullet at crosshair position upon left click
MouseState ms = Mouse.GetState();
if (ms.LeftButton == ButtonState.Pressed && prevMS.LeftButton != ButtonState.Pressed) {
Vector2 orientation = new Vector2(crosshair.position.X - soldier.position.X,
crosshair.position.Y - soldier.position.Y);
Vector2 position = new Vector2(soldier.position.X + 10, soldier.position.Y + 15);
EnvironmentManager.spawnBullet(Content, orientation, position);
}
prevMS = ms;
base.Update(gameTime);
}
public bool levelIsComplete() {
return goToNextScreen;
}
public void resetLevel() {
gameOver = false;
goToNextScreen = false;
soldier.position.X = window.Width / 2;
soldier.position.Y = window.Height / 2;
}
public bool playerIsDead() {
return gameOver;
}
public override void Draw(GameTime gameTime) {
spriteBatch.Begin();
spriteBatch.Draw(jungle_grass,
new Vector2(0, 0),
null,
Color.White,
0,
new Vector2(0, 0),
1f,
SpriteEffects.None,
0);
if (soldierIsVisible) {
soldier.Draw(gameTime, spriteBatch);
}
EnvironmentManager.Draw(gameTime);
spriteBatch.Draw(bush,
new Vector2(100, 400),
null,
Color.White,
0,
new Vector2(0, 0),
1.5f,
SpriteEffects.None,
0);
spriteBatch.Draw(bush,
new Vector2(300, 250),
null,
Color.White,
0,
new Vector2(0, 0),
1.5f,
SpriteEffects.None,
0);
spriteBatch.Draw(bush,
new Vector2(500, 400),
null,
Color.White,
0,
new Vector2(0, 0),
1.5f,
SpriteEffects.None,
0);
spriteBatch.Draw(bush,
new Vector2(300, 50),
null,
Color.White,
0,
new Vector2(0, 0),
1.5f,
SpriteEffects.None,
0);
spriteBatch.Draw(lives_background,
new Vector2(630, 15),
null,
Color.White,
0,
new Vector2(0, 0),
1f,
SpriteEffects.None,
0);
spriteBatch.DrawString(lives, "lives: " + EnvironmentManager.player_lives, new Vector2(640, 10), Color.Red);
crosshair.Draw(gameTime, spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
| |
using System;
using System.Xml;
using SharpVectors.Dom.Events;
namespace SharpVectors.Dom
{
/// <summary>
/// Summary description for Document.
/// </summary>
public class Document
: XmlDocument
, IDocument
, INode
, IEventTargetSupport
, IDocumentEvent
{
#region Private Fields
private EventTarget eventTarget;
private bool mutationEvents = false;
#endregion
#region Constructors
public Document()
{
eventTarget = new EventTarget(this);
NodeChanged += new XmlNodeChangedEventHandler(WhenNodeChanged);
NodeChanging += new XmlNodeChangedEventHandler(WhenNodeChanging);
NodeInserted += new XmlNodeChangedEventHandler(WhenNodeInserted);
NodeInserting += new XmlNodeChangedEventHandler(WhenNodeInserting);
NodeRemoved += new XmlNodeChangedEventHandler(WhenNodeRemoved);
NodeRemoving += new XmlNodeChangedEventHandler(WhenNodeRemoving);
}
protected internal Document(
DomImplementation domImplementation)
: base(domImplementation)
{
eventTarget = new EventTarget(this);
}
public Document(
XmlNameTable nameTable)
: base(nameTable)
{
eventTarget = new EventTarget(this);
}
#endregion
#region Document interface
#region Configuration Properties
/// <summary>
/// Enables or disables mutation events.
/// </summary>
public bool MutationEvents
{
get
{
return mutationEvents;
}
set
{
mutationEvents = value;
}
}
#endregion
#region System.Xml events to Dom events
private void WhenNodeChanged(
object sender,
XmlNodeChangedEventArgs e)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
private void WhenNodeChanging(
object sender,
XmlNodeChangedEventArgs e)
{
// Cannot perform ReplaceText/DeleteText/InsertText here because
// System.Xml events do not provide enough information.
if (mutationEvents)
{
throw new NotImplementedException();
}
}
private void WhenNodeInserted(
object sender,
XmlNodeChangedEventArgs e)
{
INode newParent = e.NewParent as INode;
INode node = e.Node as INode;
if (newParent != null && node != null)
{
InsertedNode(newParent, node, false);
}
}
private void WhenNodeInserting(
object sender,
XmlNodeChangedEventArgs e)
{
INode node = e.Node as INode;
if (node != null)
{
InsertingNode(node, false);
}
}
private void WhenNodeRemoved(
object sender,
XmlNodeChangedEventArgs e)
{
INode node = e.Node as INode;
if (node != null)
{
RemovedNode(node, false);
}
}
private void WhenNodeRemoving(
object sender,
XmlNodeChangedEventArgs e)
{
INode oldParent = e.OldParent as INode;
INode node = e.NewParent as INode;
if (oldParent != null && node != null)
{
RemovingNode(oldParent, node, false);
}
}
#endregion
#region Notification Methods
/// <summary>
/// A method to be called when some text was changed in a text node,
/// so that live objects can be notified.
/// </summary>
/// <param name="node">
/// </param>
protected internal virtual void ReplacedText(
INode node)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
/// <summary>
/// A method to be called when some text was deleted from a text node,
/// so that live objects can be notified.
/// </summary>
/// <param name="node">
/// </param>
/// <param name="offset">
/// </param>
/// <param name="count">
/// </param>
protected internal virtual void DeletedText(
INode node,
int offset,
int count)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
/// <summary>
/// A method to be called when some text was inserted into a text node,
/// so that live objects can be notified.
/// </summary>
/// <param name="node">
/// </param>
/// <param name="offset">
/// </param>
/// <param name="count">
/// </param>
protected internal virtual void InsertedText(
INode node,
int offset,
int count)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
/// <summary>
/// A method to be called when a character data node has been modified.
/// </summary>
/// <param name="node">
/// </param>
protected internal virtual void ModifyingCharacterData(
INode node)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
/// <summary>
/// A method to be called when a character data node has been modified.
/// </summary>
/// <param name="node">
/// </param>
/// <param name="oldvalue">
/// </param>
/// <param name="value">
/// </param>
protected internal virtual void ModifiedCharacterData(
INode node,
string oldvalue,
string value)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
/// <summary>
/// A method to be called when a node is about to be inserted in the tree.
/// </summary>
/// <param name="node">
/// </param>
/// <param name="replace">
/// </param>
protected internal virtual void InsertingNode(
INode node,
bool replace)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
/// <summary>
/// A method to be called when a node has been inserted in the tree.
/// </summary>
/// <param name="node">
/// </param>
/// <param name="newInternal">
/// </param>
/// <param name="replace">
/// </param>
protected internal virtual void InsertedNode(
INode node,
INode newInternal,
bool replace)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
/// <summary>
/// A method to be called when a node is about to be removed from the tree.
/// </summary>
/// <param name="node">
/// </param>
/// <param name="oldChild">
/// </param>
/// <param name="replace">
/// </param>
protected internal virtual void RemovingNode(
INode node,
INode oldChild,
bool replace)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
/// <summary>
/// A method to be called when a node has been removed from the tree.
/// </summary>
/// <param name="node"></param>
/// <param name="replace"></param>
protected internal virtual void RemovedNode(
INode node,
bool replace)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
/// <summary>
/// A method to be called when a node is about to be replaced in the tree.
/// </summary>
/// <param name="node">
/// </param>
protected internal virtual void replacingNode(
INode node)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
/// <summary>
/// A method to be called when a node has been replaced in the tree.
/// </summary>
/// <param name="node">
/// </param>
protected internal virtual void ReplacedNode(
INode node)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
/// <summary>
/// A method to be called when an attribute value has been modified.
/// </summary>
/// <param name="attr">
/// </param>
/// <param name="oldvalue">
/// </param>
protected internal virtual void ModifiedAttrValue(
IAttribute attr,
string oldvalue)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
/// <summary>
/// A method to be called when an attribute node has been set.
/// </summary>
/// <param name="attribute">
/// </param>
/// <param name="previous">
/// </param>
protected internal virtual void SetAttrNode(
IAttribute attribute,
IAttribute previous)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
/// <summary>
/// A method to be called when an attribute node has been removed.
/// </summary>
/// <param name="attribute">
/// </param>
/// <param name="oldOwner">
/// </param>
/// <param name="name">
/// </param>
protected internal virtual void RemovedAttrNode(
IAttribute attribute,
INode oldOwner,
string name)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
/// <summary>
/// A method to be called when an attribute node has been renamed.
/// </summary>
/// <param name="oldAttribute">
/// </param>
/// <param name="newAttribute">
/// </param>
protected internal virtual void RenamedAttrNode(
IAttribute oldAttribute,
IAttribute newAttribute)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
/// <summary>
/// A method to be called when an element has been renamed.
/// </summary>
/// <param name="oldElement">
/// </param>
/// <param name="newElement">
/// </param>
protected internal virtual void RenamedElement(
IElement oldElement,
IElement newElement)
{
if (mutationEvents)
{
throw new NotImplementedException();
}
}
#endregion
#endregion
#region XmlDocument interface
public override XmlAttribute CreateAttribute(
string prefix,
string localName,
string namespaceUri)
{
return new Attribute(prefix, localName, namespaceUri, this);
}
public override XmlCDataSection CreateCDataSection(
string data)
{
return new CDataSection(data, this);
}
public override XmlComment CreateComment(
string data)
{
return new Comment(data, this);
}
public override XmlDocumentFragment CreateDocumentFragment()
{
return new DocumentFragment(this);
}
public override XmlDocumentType CreateDocumentType(
string name,
string publicId,
string systemId,
string internalSubset)
{
return new DocumentType(name, publicId, systemId, internalSubset, this);
}
public override XmlElement CreateElement(
string prefix,
string localName,
string namespaceUri)
{
return new Element(prefix, localName, namespaceUri, this);
}
public override XmlEntityReference CreateEntityReference(
string name)
{
return new EntityReference(name, this);
}
public override XmlProcessingInstruction CreateProcessingInstruction(
string target,
string data)
{
return new ProcessingInstruction(target, data, this);
}
public override XmlSignificantWhitespace CreateSignificantWhitespace(
string text)
{
return new SignificantWhitespace(text, this);
}
public override XmlText CreateTextNode(
string text)
{
return new Text(text, this);
}
public override XmlWhitespace CreateWhitespace(
string text)
{
return new Whitespace(text, this);
}
public override XmlDeclaration CreateXmlDeclaration(
string version,
string encoding,
string standalone)
{
return new Declaration(version, encoding, standalone, this);
}
#endregion
#region IEventTarget interface
#region Methods
#region DOM Level 2
void IEventTarget.AddEventListener(
string type,
EventListener listener,
bool useCapture)
{
eventTarget.AddEventListener(type, listener, useCapture);
}
void IEventTarget.RemoveEventListener(
string type,
EventListener listener,
bool useCapture)
{
eventTarget.RemoveEventListener(type, listener, useCapture);
}
bool IEventTarget.DispatchEvent(
IEvent @event)
{
return eventTarget.DispatchEvent(@event);
}
#endregion
#region DOM Level 3 Experimental
void IEventTarget.AddEventListenerNs(
string namespaceUri,
string type,
EventListener listener,
bool useCapture,
object eventGroup)
{
eventTarget.AddEventListenerNs(namespaceUri, type, listener, useCapture, eventGroup);
}
void IEventTarget.RemoveEventListenerNs(
string namespaceUri,
string type,
EventListener listener,
bool useCapture)
{
eventTarget.RemoveEventListenerNs(namespaceUri, type, listener, useCapture);
}
bool IEventTarget.WillTriggerNs(
string namespaceUri,
string type)
{
return eventTarget.WillTriggerNs(namespaceUri, type);
}
bool IEventTarget.HasEventListenerNs(
string namespaceUri,
string type)
{
return eventTarget.HasEventListenerNs(namespaceUri, type);
}
#endregion
#endregion
#endregion
#region IDocument interface
IDocumentType IDocument.Doctype
{
get
{
return (IDocumentType)DocumentType;
}
}
IDomImplementation IDocument.Implementation
{
get
{
throw new DomException(DomExceptionType.NotSupportedErr);
}
}
IElement IDocument.DocumentElement
{
get
{
return (IElement)DocumentElement;
}
}
IElement IDocument.CreateElement(
string tagName)
{
return (IElement)CreateElement(tagName);
}
IDocumentFragment IDocument.CreateDocumentFragment()
{
return (IDocumentFragment)CreateDocumentFragment();
}
IText IDocument.CreateTextNode(
string data)
{
return (IText)CreateTextNode(data);
}
IComment IDocument.CreateComment(
string data)
{
return (IComment)CreateComment(data);
}
ICDataSection IDocument.CreateCDataSection(
string data)
{
return (ICDataSection)CreateCDataSection(data);
}
IProcessingInstruction IDocument.CreateProcessingInstruction(
string target,
string data)
{
return (IProcessingInstruction)CreateProcessingInstruction(target, data);
}
IAttribute IDocument.CreateAttribute(
string name)
{
return (IAttribute)CreateAttribute(name);
}
IEntityReference IDocument.CreateEntityReference(
string name)
{
return (IEntityReference)CreateEntityReference(name);
}
INodeList IDocument.GetElementsByTagName(
string tagname)
{
return new NodeListAdapter(GetElementsByTagName(tagname));
}
INode IDocument.ImportNode(
INode importedNode,
bool deep)
{
return (INode)ImportNode((XmlNode)importedNode, deep);
}
IElement IDocument.CreateElementNs(
string namespaceUri,
string qualifiedName)
{
return (IElement)CreateElement(qualifiedName, namespaceUri);
}
IAttribute IDocument.CreateAttributeNs(
string namespaceUri,
string qualifiedName)
{
return (IAttribute)CreateAttribute(qualifiedName, namespaceUri);
}
INodeList IDocument.GetElementsByTagNameNs(
string namespaceUri,
string localName)
{
return new NodeListAdapter(GetElementsByTagName(localName, namespaceUri));
}
IElement IDocument.GetElementById(
string elementId)
{
object res = GetElementById(elementId);
if (res != null)
return (IElement)res;
else
return null;
}
string IDocument.ActualEncoding
{
get
{
throw new DomException(DomExceptionType.NotSupportedErr);
}
}
string IDocument.XmlEncoding
{
get
{
throw new DomException(DomExceptionType.NotSupportedErr);
}
set
{
throw new DomException(DomExceptionType.NotSupportedErr);
}
}
bool IDocument.XmlStandalone
{
get
{
throw new DomException(DomExceptionType.NotSupportedErr);
}
set
{
throw new DomException(DomExceptionType.NotSupportedErr);
}
}
string IDocument.XmlVersion
{
get
{
throw new DomException(DomExceptionType.NotSupportedErr);
}
set
{
throw new DomException(DomExceptionType.NotSupportedErr);
}
}
bool IDocument.StrictErrorChecking
{
get
{
throw new DomException(DomExceptionType.NotSupportedErr);
}
set
{
throw new DomException(DomExceptionType.NotSupportedErr);
}
}
string IDocument.DocumentUri
{
get
{
return BaseURI;
}
set
{
throw new DomException(DomExceptionType.NotSupportedErr);
}
}
INode IDocument.AdoptNode(
INode source)
{
throw new DomException(DomExceptionType.NotSupportedErr);
}
IDomConfiguration IDocument.Config
{
get
{
throw new NotImplementedException();
}
}
void IDocument.NormalizeDocument()
{
Normalize();
}
INode IDocument.RenameNode(
INode n,
string namespaceUri,
string qualifiedName)
{
throw new DomException(DomExceptionType.NotSupportedErr);
}
#endregion
#region IDocumentEvent interface
#region DOM Level 2
public virtual IEvent CreateEvent(
string eventType)
{
switch (eventType)
{
case "Event":
case "Events":
case "HTMLEvents":
return new Event();
case "MutationEvent":
case "MutationEvents":
return new MutationEvent();
case "UIEvent":
case "UIEvents":
return new UiEvent();
case "MouseEvent":
case "MouseEvents":
return new MouseEvent();
default:
throw new DomException(
DomExceptionType.NotSupportedErr,
"Event type \"" + eventType + "\" not suppoted");
}
}
#endregion
#region DOM Level 3 Experimental
public virtual bool CanDispatch(
string namespaceUri,
string type)
{
throw new NotImplementedException();
}
#endregion
#endregion
#region NON-DOM
void IEventTargetSupport.FireEvent(
IEvent @event)
{
eventTarget.FireEvent(@event);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// LastQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics.Contracts;
namespace System.Linq.Parallel
{
/// <summary>
/// Last tries to discover the last element in the source, optionally matching a
/// predicate. All partitions search in parallel, publish the greatest index for a
/// candidate match, and reach a barrier. Only the partition that "wins" the race,
/// i.e. who found the candidate with the largest index, will yield an element.
///
/// </summary>
/// <typeparam name="TSource"></typeparam>
internal sealed class LastQueryOperator<TSource> : UnaryQueryOperator<TSource, TSource>
{
private readonly Func<TSource, bool> _predicate; // The optional predicate used during the search.
private readonly bool _prematureMergeNeeded; // Whether to prematurely merge the input of this operator.
//---------------------------------------------------------------------------------------
// Initializes a new last operator.
//
// Arguments:
// child - the child whose data we will reverse
//
internal LastQueryOperator(IEnumerable<TSource> child, Func<TSource, bool> predicate)
: base(child)
{
Contract.Assert(child != null, "child data source cannot be null");
_predicate = predicate;
_prematureMergeNeeded = Child.OrdinalIndexState.IsWorseThan(OrdinalIndexState.Increasing);
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the child and wrapping it with
// partitions as needed.
//
internal override QueryResults<TSource> Open(QuerySettings settings, bool preferStriping)
{
QueryResults<TSource> childQueryResults = Child.Open(settings, false);
return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, bool preferStriping, QuerySettings settings)
{
// If the index is not at least increasing, we need to reindex.
if (_prematureMergeNeeded)
{
PartitionedStream<TSource, int> intKeyStream =
ExecuteAndCollectResults(inputStream, inputStream.PartitionCount, Child.OutputOrdered, preferStriping, settings).GetPartitionedStream();
WrapHelper<int>(intKeyStream, recipient, settings);
}
else
{
WrapHelper<TKey>(inputStream, recipient, settings);
}
}
private void WrapHelper<TKey>(PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, QuerySettings settings)
{
int partitionCount = inputStream.PartitionCount;
// Generate the shared data.
LastQueryOperatorState<TKey> operatorState = new LastQueryOperatorState<TKey>();
CountdownEvent sharedBarrier = new CountdownEvent(partitionCount);
PartitionedStream<TSource, int> outputStream =
new PartitionedStream<TSource, int>(partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Shuffled);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new LastQueryOperatorEnumerator<TKey>(
inputStream[i], _predicate, operatorState, sharedBarrier, settings.CancellationState.MergedCancellationToken,
inputStream.KeyComparer, i);
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token)
{
Contract.Assert(false, "This method should never be called as fallback to sequential is handled in ParallelEnumerable.First().");
throw new NotSupportedException();
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
//---------------------------------------------------------------------------------------
// The enumerator type responsible for executing the last operation.
//
class LastQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TSource, int>
{
private QueryOperatorEnumerator<TSource, TKey> _source; // The data source to enumerate.
private Func<TSource, bool> _predicate; // The optional predicate used during the search.
private bool _alreadySearched; // Set once the enumerator has performed the search.
private int _partitionId; // ID of this partition
// Data shared among partitions.
private LastQueryOperatorState<TKey> _operatorState; // The current last candidate and its partition id.
private CountdownEvent _sharedBarrier; // Shared barrier, signaled when partitions find their 1st element.
private CancellationToken _cancellationToken; // Token used to cancel this operator.
private IComparer<TKey> _keyComparer; // Comparer for the order keys
//---------------------------------------------------------------------------------------
// Instantiates a new enumerator.
//
internal LastQueryOperatorEnumerator(
QueryOperatorEnumerator<TSource, TKey> source, Func<TSource, bool> predicate,
LastQueryOperatorState<TKey> operatorState, CountdownEvent sharedBarrier, CancellationToken cancelToken,
IComparer<TKey> keyComparer, int partitionId)
{
Contract.Assert(source != null);
Contract.Assert(operatorState != null);
Contract.Assert(sharedBarrier != null);
Contract.Assert(keyComparer != null);
_source = source;
_predicate = predicate;
_operatorState = operatorState;
_sharedBarrier = sharedBarrier;
_cancellationToken = cancelToken;
_keyComparer = keyComparer;
_partitionId = partitionId;
}
//---------------------------------------------------------------------------------------
// Straightforward IEnumerator<T> methods.
//
internal override bool MoveNext(ref TSource currentElement, ref int currentKey)
{
Contract.Assert(_source != null);
if (_alreadySearched)
{
return false;
}
// Look for the greatest element.
TSource candidate = default(TSource);
TKey candidateKey = default(TKey);
bool candidateFound = false;
try
{
int loopCount = 0; //counter to help with cancellation
TSource value = default(TSource);
TKey key = default(TKey);
while (_source.MoveNext(ref value, ref key))
{
if ((loopCount & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// If the predicate is null or the current element satisfies it, we will remember
// it as the current partition's candidate for the last element, and move on.
if (_predicate == null || _predicate(value))
{
candidate = value;
candidateKey = key;
candidateFound = true;
}
loopCount++;
}
// If we found a candidate element, try to publish it, so long as it's greater.
if (candidateFound)
{
lock (_operatorState)
{
if (_operatorState._partitionId == -1 || _keyComparer.Compare(candidateKey, _operatorState._key) > 0)
{
_operatorState._partitionId = _partitionId;
_operatorState._key = candidateKey;
}
}
}
}
finally
{
// No matter whether we exit due to an exception or normal completion, we must ensure
// that we signal other partitions that we have completed. Otherwise, we can cause deadlocks.
_sharedBarrier.Signal();
}
_alreadySearched = true;
// Only if we have a candidate do we wait.
if (_partitionId == _operatorState._partitionId)
{
_sharedBarrier.Wait(_cancellationToken);
// Now re-read the shared index. If it's the same as ours, we won and return true.
if (_operatorState._partitionId == _partitionId)
{
currentElement = candidate;
currentKey = 0; // 1st (and only) element, so we hardcode the output index to 0.
return true;
}
}
// If we got here, we didn't win. Return false.
return false;
}
protected override void Dispose(bool disposing)
{
_source.Dispose();
}
}
class LastQueryOperatorState<TKey>
{
internal TKey _key;
internal int _partitionId = -1;
}
}
}
| |
// ------------------------------------------------------------------------------------------------
// KingTomato Script
// ------------------------------------------------------------------------------------------------
$King::Version = "2.3";
$KT::Debug = false; // dont worry bout this
// Presto Resolutions Missing
$Presto::screenSize["720x480"] = "720 480";
$Presto::screenSize["720x576"] = "720 576";
$Presto::screenSize["848x480"] = "848 480";
$Presto::screenSize["1152x864"] = "1152 864";
$Presto::screenSize["1280x720"] = "1280 720";
$Presto::screenSize["1280x768"] = "1280 768";
$Presto::screenSize["1280x960"] = "1280 960";
$Presto::screenSize["1280x1024"] = "1280 1024";
$Presto::screenSize["1360x768"] = "1360 768";
$Presto::screenSize["1600x900"] = "1600 900";
$Presto::screenSize["1600x1024"] = "1600 1024";
$Presto::screenSize["1600x1200"] = "1600 1200";
$King::Beta = false; // No need to change this, won't give
// you special features or anything
// ------------------------------------------------------------------------------------------------
// Preferences
//
// This will handle callbacks to the prefs I have set. If its null, or filled with something
// other than false, assume true. >:P
//
function KingPref::Enabled(%setting)
{
if ($KingPref::[%setting] == "")
$KingPref::[%option] = false;
if ($KingPref::[%setting] != false)
return true;
return false;
}
// ------------------------------------------------------------------------------------------------
// Auto Loader
//
// Loads the file in the kingtomato directory, according to the order of their presidence.
// please read SCRIPTORS.TXT under the "File Names" heading for more information.
//
function King::Install::Install()
{
// Load Settings
if (isFile("config\\King_Settings.cs"))
exec("King_Settings.cs");
// Load up preferences file
exec("KingTomato\\KingPrefs.skip.cs"); // Moved down to avoid the prefs bug
if (KingPref::Enabled(Logging))
$Console::LogMode = 1;
if (KingPref::Enabled(NudeWalls))
newObject(WallsVolume, SimVolume, "KingTomato\\vols\\NudeWalls.vol");
if (KingPref::Enabled(RedWalls))
newObject(ForceFieldVolume, SimVolume, "KingTomato\\vols\\RedForceFields.vol");
$King::Install::Count[System] = 0;
$King::Install::Count[Scripts] = 0;
// This File
%this = "KingTomato\\Install.cs";
if ($KT::Debug)
echo("Loading Volumes");
// Volumes
for (%file = File::FindFirst("KingTomato\\*.vol"); %file != ""; %file = File::FindNext("KingTomato\\*.vol"))
{
// Add To List
$KingTomato::Load::Volume[%vol++] = %file;
// Register Volume
%base = File::getBase(File::getBase(%file));
EvalSearchPath::addVol(%base, %file);
newObject(%base, SimVolume, %file);
// Increse Counter
%count[Volume]++;
// Next File
}
if ($KT::Debug)
echo("Loading .sys.cs");
// System Files
for (%file = File::FindFirst("KingTomato\\*.sys.cs"); %file != ""; %file = File::FindNext("KingTomato\\*.sys.cs"))
{
exec(%file);
King::Install::AddFile(%file, System, $Script::Creator, $Script::Version, $Script::Description, $Script::MinVersion);
deleteVariables("$Script::*");
}
if ($KT::Debug)
echo("Loading .cs");
// Other Scripts
for (%file = File::FindFirst("KingTomato\\*.cs"); %file != ""; %file = File::FindNext("KingTomato\\*.cs"))
{
// To avoid an infinite loop, and loading files both already loaded, and
// never to be loaded, we will check what kind of file we have. By testing
// its not this file, we avoid an infitie loop, and stop the program from
// Loading this file, which loads itself again, and again, etc. Also,
// We make sure its not an already loaded sys file, or isn't intended to be
// skipped (.skip.cs).
if (!Match::String(%file, %this) && !Match::String(%file, "*.sys.cs") && !Match::String(%file, "*.skip.cs"))
{
// Load File
exec(%file);
King::Install::AddFile(%file, Script, $Script::Creator, $Script::Version, $Script::Description, $Script::MinVersion);
deleteVariables("$Script::*");
}
}
King::Install::Output();
}
//
// Add files to array
//
function King::Install::AddFile(%file, %type, %creator, %version, %description, %minVer)
{
%count = $King::Install::count[%type]++;
// Check for empty values, and fill them
if (%creator == "") %creator = "unknown Author";
if (%version == "") %version = "?.??";
if (%description == "") %description = "No description given for this item";
$King::Install::File[%count, file] = %file;
$King::Install::File[%count, creator] = %creator;
$King::Install::File[%count, version] = %version;
$King::Install::File[%count, description] = %description;
if ((%minVer != "") && (%minVer > $King::Version))
$King::Install::File[%count, fail] = %minVer;
if ($KT::Debug)
echo("Adding File: " @ %file @ " to load list");
}
//
// Output Installed Scripts
//
function King::Install::Output()
{
%failed = "";
if (!$KT::Debug)
cls();
echo("// --------------------------------------------------------------------------------");
echo("// KingTomato Script");
echo("// Version " @ $King::Version);
echo("// --");
echo("// Presto... Detected (" @ $Presto::Version @ ")");
echo("// NewOpts... Detected (" @ $NewOpts::Version @ ")");
echo("// --");
echo("// Script Files Installed: " @ $King::Install::count[Script]);
echo("// --------------------------------------------------------------------------------");
echo("//");
for (%a = 1; $King::Install::File[%a, file] != ""; %a++)
{
%file = $King::Install::File[%a, file];
%creator = $King::Install::File[%a, creator];
%version = $King::Install::File[%a, version];
%desc = $King::Install::File[%a, description];
%minVer = $King::Install::File[%a, fail];
if (%minVer != "")
%failed = %failed @ %a @ " ";
echo("// " @ File::getBase(%file) @ " (By: " @ %creator @ ", v" @ %version @ ")");
%words = "";
for (%b = 0; %b < String::GetWordCount(%desc); %b++) {
%word = getWord(%desc, %b);
%temp = %words @ %word @ " ";
if (String::Len(%temp) <= 85)
%words = %words @ %word @ " ";
else {
echo("// " @ %words);
%words = %word;
}
}
echo("// " @ %words);
echo("//");
}
if (%failed != "")
{
echo("// --------------------------------------------------------------------------------");
echo("// Warning:");
echo("// Some files did not load correctly.");
echo("// These files include:");
echo("// --------------------------------------------------------------------------------");
echo("//");
for (%a = 0; (%i = getWord(%failed, %a)) != -1; %a++)
{
%file = $King::Install::File[%i, file];
%minVer = $King::Install::File[%i, fail];
echo("// " @ File::getBase(%file));
echo("// File requires KingTomato Pack v" @ %minVer @ " or later");
echo("//");
}
}
echo("// --------------------------------------------------------------------------------");
echo("// Installation Complete");
echo("// --------------------------------------------------------------------------------");
}
if (($Presto::Version != "0.93") || ($NewOpts::version != "0.966"))
{
echo ("KingTomato Script Pack Error");
echo ("-");
echo ("Presto Pack missing or invalid version");
echo ("NewOpts missing or invalid version");
echo ("");
echo ("Please be sure you have Presto Pack 0.93 & NewOpts 0.966");
echo ("");
echo ("Preso Version: " @ $Presto::Version);
echo ("newOpts Version: " @ $newOpts::Version);
}
else
{
King::Install::Install();
Event::Attach(eventConnectionAccepted, King::Install::Advertise);
}
function King::Install::Advertise()
{
if (KingPref::Enabled(Advertise))
{
%msg = "I am using KingTomato Pack v" @ $King::Version @ "!";
if ($King::Beta)
%msg = %msg @ " Coming soon to www.KingTomato.org!";
else
%msg = %msg @ " Get yours at www.KingTomato.org!";
say(0, %msg);
}
}
NewOpts::register("KTPack","KingTomato\\gui\\KTPack.gui","","",TRUE);
| |
// Copyright (c) Jon Thysell <http://jonthysell.com>
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
namespace Chordious.Core
{
public class MarkUtils
{
public static string ToString(int mark)
{
return mark < 0 ? "x" : mark.ToString();
}
public static string ToString(int[] marks)
{
string s = "";
for (int i = 0; i < marks.Length; i++)
{
s += ToString(marks[i]) + ",";
}
s = s.TrimEnd(',');
return s;
}
public static string ToString(IEnumerable<MarkPosition> marks)
{
string s = "";
foreach (MarkPosition mark in marks)
{
s += mark.ToString() + ",";
}
s = s.TrimEnd(',');
return s;
}
public static bool ValidateChord(int[] chordMarks, IChordFinderOptions chordFinderOptions)
{
if (null == chordMarks)
{
throw new ArgumentNullException(nameof(chordMarks));
}
if (null == chordFinderOptions)
{
throw new ArgumentNullException(nameof(chordFinderOptions));
}
MarkAnalysis ma = ChordAnalysis(chordMarks);
bool reachPass = ma.Reach <= chordFinderOptions.MaxReach;
bool openPass = chordFinderOptions.AllowOpenStrings || !ma.HasOpenStrings;
bool mutePass = chordFinderOptions.AllowMutedStrings || !ma.HasMutedStrings;
return reachPass && openPass && mutePass;
}
public static bool ValidateScale(IEnumerable<MarkPosition> scaleMarks, IScaleFinderOptions scaleFinderOptions)
{
if (null == scaleMarks)
{
throw new ArgumentNullException(nameof(scaleMarks));
}
if (null == scaleFinderOptions)
{
throw new ArgumentNullException(nameof(scaleFinderOptions));
}
MarkAnalysis ma = ScaleAnalysis(scaleMarks, scaleFinderOptions.Instrument.NumStrings);
bool reachPass = ma.Reach <= scaleFinderOptions.MaxReach;
bool openPass = scaleFinderOptions.AllowOpenStrings || !ma.HasOpenStrings;
bool mutePass = scaleFinderOptions.AllowMutedStrings || !ma.HasMutedStrings;
return reachPass && openPass && mutePass;
}
public static void MinMaxFrets(int[] marks, out int minFret, out int maxFret)
{
MarkAnalysis ma = ChordAnalysis(marks);
minFret = ma.MinFret;
maxFret = ma.MaxFret;
}
public static BarrePosition AutoBarrePosition(int[] marks, BarreTypeOption barreTypeOption = BarreTypeOption.None, bool leftToRight = false)
{
if (barreTypeOption != BarreTypeOption.None)
{
MarkAnalysis ma = ChordAnalysis(marks);
int targetFret = ma.MinFret;
if (targetFret > 0)
{
int startString;
int endString;
if (leftToRight)
{
startString = 0;
endString = 0;
for (int i = startString; i < marks.Length; i++)
{
if (marks[i] < targetFret)
{
break;
}
if ((barreTypeOption == BarreTypeOption.Full && marks[i] >= targetFret) ||
(barreTypeOption == BarreTypeOption.Partial && marks[i] == targetFret))
{
endString = i;
}
}
}
else
{
startString = marks.Length - 1;
endString = marks.Length - 1;
for (int i = endString; i >= 0; i--)
{
if (marks[i] < targetFret)
{
break;
}
if ((barreTypeOption == BarreTypeOption.Full && marks[i] >= targetFret) ||
(barreTypeOption == BarreTypeOption.Partial && marks[i] == targetFret))
{
startString = i;
}
}
}
if (endString > startString)
{
return new BarrePosition(targetFret, startString + 1, endString + 1);
}
}
}
return null;
}
public static int Compare(int[] marksA, int[] marksB)
{
if (null == marksA)
{
throw new ArgumentNullException(nameof(marksA));
}
if (null == marksB)
{
throw new ArgumentNullException(nameof(marksB));
}
if (marksA.Length != marksB.Length)
{
throw new ArgumentException();
}
MarkAnalysis analysisA = ChordAnalysis(marksA);
MarkAnalysis analysisB = ChordAnalysis(marksB);
return analysisA.CompareTo(analysisB);
}
public static int Compare(IEnumerable<MarkPosition> marksA, IEnumerable<MarkPosition> marksB, int numStrings)
{
if (null == marksA)
{
throw new ArgumentNullException(nameof(marksA));
}
if (null == marksB)
{
throw new ArgumentNullException(nameof(marksB));
}
if (numStrings <= 0)
{
throw new ArgumentOutOfRangeException(nameof(numStrings));
}
MarkAnalysis analysisA = ScaleAnalysis(marksA, numStrings);
MarkAnalysis analysisB = ScaleAnalysis(marksB, numStrings);
return analysisA.CompareTo(analysisB);
}
public static int[] AbsoluteToRelativeMarks(int[] absoluteMarks, out int baseLine, int numFrets)
{
if (null == absoluteMarks)
{
throw new ArgumentNullException(nameof(absoluteMarks));
}
MarkAnalysis ma = ChordAnalysis(absoluteMarks);
if (ma.Reach > numFrets)
{
throw new ArgumentOutOfRangeException(nameof(numFrets));
}
int[] relativeMarks = new int[absoluteMarks.Length];
baseLine = ma.MaxFret > numFrets ? ma.MinFret : 0;
for (int i = 0; i < absoluteMarks.Length; i++)
{
relativeMarks[i] = absoluteMarks[i];
if (relativeMarks[i] > 0 && baseLine > 0)
{
relativeMarks[i] -= (baseLine - 1);
}
}
return relativeMarks;
}
public static InternalNote?[] GetInternalNotes(int[] marks, ITuning tuning)
{
if (null == marks || marks.Length == 0)
{
throw new ArgumentNullException(nameof(marks));
}
if (null == tuning)
{
throw new ArgumentNullException(nameof(tuning));
}
InternalNote?[] notes = new InternalNote?[marks.Length];
for (int i = 0; i < marks.Length; i++)
{
notes[i] = marks[i] == -1 ? null : (InternalNote?)NoteUtils.Shift(tuning.RootNotes[i].InternalNote, marks[i]);
}
return notes;
}
public static IEnumerable<MarkPosition> AbsoluteToRelativeMarks(IEnumerable<MarkPosition> absoluteMarks, out int baseLine, int numFrets, int numStrings)
{
if (null == absoluteMarks)
{
throw new ArgumentNullException(nameof(absoluteMarks));
}
MarkAnalysis ma = ScaleAnalysis(absoluteMarks, numStrings);
if (ma.Reach > numFrets)
{
throw new ArgumentOutOfRangeException(nameof(numFrets));
}
List<MarkPosition> relativeMarks = new List<MarkPosition>();
baseLine = ma.MaxFret > numFrets ? ma.MinFret : 0;
foreach (MarkPosition absoluteMark in absoluteMarks)
{
MarkPosition relativeMark = (MarkPosition)absoluteMark.Clone();
if (relativeMark.Fret > 0 && baseLine > 0)
{
relativeMark = new MarkPosition(relativeMark.String, relativeMark.Fret - (baseLine - 1));
}
relativeMarks.Add(relativeMark);
}
return relativeMarks;
}
protected static MarkAnalysis ChordAnalysis(int[] marks)
{
if (null == marks)
{
throw new ArgumentNullException(nameof(marks));
}
MarkAnalysis ma = new MarkAnalysis();
for (int i = 0; i < marks.Length; i++)
{
if (marks[i] == 0)
{
ma.HasOpenStrings = true;
}
else if (marks[i] < 0)
{
ma.HasMutedStrings = true;
}
else if (marks[i] > 0)
{
ma.MarkCount++;
ma.MeanFret += marks[i];
ma.MinFret = Math.Min(ma.MinFret, marks[i]);
ma.MaxFret = Math.Max(ma.MaxFret, marks[i]);
}
}
ma.MeanFret /= ma.MarkCount;
if (ma.MinFret == int.MaxValue || ma.MaxFret == int.MinValue)
{
ma.MinFret = 0;
ma.MaxFret = 0;
}
ma.Reach = (ma.MaxFret - ma.MinFret) + 1;
return ma;
}
protected static MarkAnalysis ScaleAnalysis(IEnumerable<MarkPosition> marks, int numStrings)
{
if (null == marks)
{
throw new ArgumentNullException(nameof(marks));
}
MarkAnalysis ma = new MarkAnalysis();
// First pass for basic stats
bool[] hasMarks = new bool[numStrings];
foreach (MarkPosition mark in marks)
{
int str = mark.String;
int fret = mark.Fret;
hasMarks[str - 1] = true;
if (fret == 0)
{
ma.HasOpenStrings = true;
}
if (fret > 0)
{
ma.MarkCount++;
ma.MeanFret += fret;
ma.MinFret = Math.Min(ma.MinFret, fret);
ma.MaxFret = Math.Max(ma.MaxFret, fret);
}
}
ma.MeanFret /= ma.MarkCount;
if (ma.MinFret == int.MaxValue || ma.MaxFret == int.MinValue)
{
ma.MinFret = 0;
ma.MaxFret = 0;
}
ma.Reach = (ma.MaxFret - ma.MinFret) + 1;
// Check for muted strings
for (int i = 0; i < hasMarks.Length; i++)
{
if (!hasMarks[i])
{
ma.HasMutedStrings = true;
break;
}
}
return ma;
}
protected class MarkAnalysis : IComparable
{
public int MinFret;
public double MeanFret;
public int MaxFret;
public int Reach;
public int MarkCount;
public bool HasOpenStrings;
public bool HasMutedStrings;
public MarkAnalysis()
{
MinFret = int.MaxValue;
MeanFret = 0.0;
MaxFret = int.MinValue;
Reach = 0;
MarkCount = 0;
HasOpenStrings = false;
HasMutedStrings = false;
}
public int CompareTo(object obj)
{
if (null == obj)
{
throw new ArgumentException();
}
if (!(obj is MarkAnalysis ma))
{
throw new ArgumentException();
}
// Order by presence of muted strings
if (HasMutedStrings && !ma.HasMutedStrings)
{
return 1;
}
else if (ma.HasMutedStrings && !HasMutedStrings)
{
return -1;
}
// Order by mean fret
if (MeanFret < ma.MeanFret)
{
return -1;
}
else if (MeanFret > ma.MeanFret)
{
return 1;
}
// Order by mark count
if (MarkCount < ma.MarkCount)
{
return -1;
}
else if (MarkCount > ma.MarkCount)
{
return 1;
}
// Order by reach
if (Reach < ma.Reach)
{
return -1;
}
else if (Reach > ma.Reach)
{
return 1;
}
// Order by presence of open strings
if (HasOpenStrings && !ma.HasOpenStrings)
{
return -1;
}
else if (ma.HasOpenStrings && !HasOpenStrings)
{
return 1;
}
return 0;
}
}
}
}
| |
using UnityEngine;
using System;
public class Weapon_Block : Weapon
{
private GameObject PreviewBlockInstance;
private BlockObject projectileBlock;
public float CastTestDist = 10;
public delegate void OnHit ( GenerateWorld World, BlockSpawner spawner, RaycastHit hit, Vector3 currentDirection, Vector3 createAt, BlockIndex index);
public Weapon_Block ()
{
}
public override void Start ()
{
base.Start ();
Projectile projectile = Projectile.GetComponentsInChildren<Projectile>(true)[0];
if ( projectile.ProjectilePrefab != null )
{
projectileBlock = projectile.ProjectilePrefab.GetBlock();
PreviewBlockInstance = (GameObject)Instantiate(projectileBlock.PreviewBlock);
PreviewBlockInstance.SetActive(false);
Util.DestroyAllColliders(PreviewBlockInstance);
}
}
/// <summary>
/// Casts the ray and does whatever the action is. (Template Method pattern)
/// </summary>
/// <returns>
/// The ray and do.
/// </returns>
/// <param name='action'>
/// If set to <c>true</c> action.
/// </param>
public bool CastRayAndDo( OnHit action )
{
RaycastHit hit;
Ray cast = getRayCast();
int mask = 1 << LayerMask.NameToLayer("Catwalk");
if ( Physics.Raycast( cast, out hit, CastTestDist, mask ) )
{
var blockSpawner = Projectile.GetComponent<BlockSpawner>();
if ( blockSpawner != null && hit.collider.gameObject.IsProjectile() == false )
{
var worldObj = GameObject.FindGameObjectWithTag("World");
var World = worldObj.GetComponent<GenerateWorld>();
//var createAt = cast.origin + (cast.direction * (hit.distance - 0.1f));
var createAt = hit.point + (hit.normal *(0.5f));
var playerPos = getRayCast().origin;
var futureIndex = World.getIndexOfPoint( ref createAt);
var playerIndexTop = World.getIndexOfPoint( ref playerPos);
var playerIndexBottom = new BlockIndex(playerIndexTop.x, playerIndexTop.y-1, playerIndexTop.z);
//Don't create on top of ourselves:
if ( (playerIndexTop != futureIndex) && (playerIndexBottom != futureIndex) )
{
Vector3 currentDirection = getRayCast().direction.normalized;
action(World, blockSpawner, hit, currentDirection, createAt, futureIndex);
}
}
return true;
}
return false;
}
public override void Update ()
{
//This can be null in some cases.
if ( PreviewBlockInstance == null ) return;
PreviewBlockInstance.SetActive(false);
//Check to see if we should
CastRayAndDo( ( World, spawner, hit, curDir, createAt, futureIndex) =>
{
if ( Input.GetKeyUp(KeyCode.Delete) || Input.GetKeyUp(KeyCode.Backspace) )
{
World.RemoveBlockAt(hit.transform.position);
}
PreviewBlockInstance.SetActive(true);
PreviewBlockInstance.transform.position = World.getPositionOfPoint(ref createAt);
//Orient:
Vector3 rot = Quaternion.FromToRotation(-Vector3.forward, curDir).eulerAngles;
rot.x = 0;
rot.z = 0;
World.SnapRotationToGrid(ref rot);
PreviewBlockInstance.transform.rotation = Quaternion.Euler(rot);
var renderer = PreviewBlockInstance.GetComponentInChildren<Renderer>();
for ( int i = 0; i < renderer.materials.Length; i++ )
{
renderer.materials[i].shader = projectileBlock.PreviewShader;
renderer.materials[i].mainTexture = projectileBlock.PreviewTexture;
renderer.materials[i].color = new Color(1,1,1,0.5f);
}
});
base.Update ();
}
public override void PutAway ()
{
if ( PreviewBlockInstance != null )
{
PreviewBlockInstance.SetActive(false);
}
}
public Quaternion ComputeRotationForPlacement( GenerateWorld World, BlockSpawner spawner, Vector3 normalOfPlacementSurface, Vector3 curDir, BlockIndex futureIndex)
{
Quaternion output = Quaternion.identity;
//Gets the block prefab so we can check its properties:
var block = spawner.SpawnType;
//We only care about the direction, not the inclination:
curDir.y = 0;
curDir.Normalize();
//Due to gimbal lock that can happen along a wall, we use a different axis and then rotate into the axis we want!
//Thus the 270 rotation.
Quaternion wallDirectionAxis = Quaternion.FromToRotation( Vector3.up, normalOfPlacementSurface);
Quaternion upDirectionAxis = Quaternion.FromToRotation( Vector3.right, normalOfPlacementSurface) * Quaternion.Euler(0,270,0);
Quaternion rotationTowardDown = wallDirectionAxis * upDirectionAxis ;
//Is it going on the floor/ceiling: 0.2f episilon
if ( normalOfPlacementSurface.y < -0.2f || normalOfPlacementSurface.y > 0.2f)
{
float angle = Vector3.Angle(Vector3.forward, curDir);
var side = Vector3.Cross( Vector3.up, curDir);
angle *= (side.z < 0) ? 1 : -1;
upDirectionAxis = Quaternion.AngleAxis( angle, normalOfPlacementSurface);
var upDirEuler = upDirectionAxis.eulerAngles;
rotationTowardDown = wallDirectionAxis * upDirectionAxis ;
//This adds the special rotation that the object gets when its on the floor or ceiling.
//This exists because different objects act differently when placed. This covers most cases!
if ( block.SpecialRotateX90) { rotationTowardDown = rotationTowardDown * Quaternion.Euler(90,0,0); }
if ( block.SpecialRotateY90) { rotationTowardDown = rotationTowardDown * Quaternion.Euler(0,90,0); }
if ( block.SpecialRotateZ90) { rotationTowardDown = rotationTowardDown * Quaternion.Euler(0,0,0); }
if ( block.SpecialRotateX270) { rotationTowardDown = rotationTowardDown * Quaternion.Euler(270,0,0); }
if ( block.SpecialRotateY270) { rotationTowardDown = rotationTowardDown * Quaternion.Euler(0,270,0); }
if ( block.SpecialRotateZ270) { rotationTowardDown = rotationTowardDown * Quaternion.Euler(0,0,270); }
}
Vector3 rot = rotationTowardDown.eulerAngles;
//If the object is designed to sit only on the floor remove the x and z rotations:
if( block.RotatesTowardWalls == false )
{
//Take only the y rotation.
rot.x = 0;
rot.z = 0;
}
output = Quaternion.Euler(rot);
return output;
}
//Throw the block like a weapon!!
public override GameObject Fire (GameObject Player)
{
var proj = base.Fire(Player);
if( proj != null )
{
proj.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
}
return proj;
}
//Place the block minecraft style:
public override GameObject Fire2 (GameObject Player)
{
if ( Input.GetButtonDown("Fire2") == false || CurrentCoolDown > 0.0f ) {
return null;
}
//Cast a ray outwards and see if we can place a block at the intersection point:
bool isHit = CastRayAndDo( ( World, spawner, hit, curDir, createAt, futureIndex) =>
{
Quaternion rot = ComputeRotationForPlacement(World, spawner, hit.normal, curDir, futureIndex);
World.CreateBlockAt(createAt, spawner.SpawnType.ObjectID, rot.eulerAngles);
CurrentCoolDown = CoolDown * 2;
});
return null;
}
public override GameObject Fire3 (GameObject Player)
{
if ( CurrentCoolDown > 0.0f ) {
return null;
}
var World = GenerateWorld.World;
var blockSpawner = Projectile.GetComponent<BlockSpawner>();
var newBlockObj = World.BlockTypes[blockSpawner.SpawnType.ObjectID];
var newBlock = newBlockObj.GetBlock();
//Only pathable blocks can be built this way.
if ( newBlock.Pathable == false ) return null;
//Orient:
Ray ray = getRayCast();
var pos = ray.origin;
var dir = ray.direction;
dir.y = 0;
dir.Normalize();
var normal = -getRayCast().direction.normalized;
Vector3 rot = Quaternion.FromToRotation(-Vector3.forward, normal).eulerAngles;
rot.x = 0;
rot.z = 0;
World.SnapRotationToGrid(ref rot);
//The camera is 2 units above the "position" of the player ( using the grid position ).
Vector3 currentPos = World.getPositionOfPoint(ref pos);
currentPos.y -= 2;
for ( int i = 0; i < newBlock.MaxPathDistance; i++ )
{
var currentBlock = World.getBlockAtIndex(World.getIndexOfPoint(ref currentPos));
if ( currentBlock != null )
{
//If its a ramp it'll step us up.
currentPos.y += currentBlock.GetBlock().StepDelta * 2.0f;
}
var posBelow = currentPos;
posBelow.y -= 2.0f;
var currentBlockBelow = World.getBlockAtIndex(World.getIndexOfPoint(ref posBelow));
if ( currentBlock == null && currentBlockBelow == null )
{
//Ignore the block we're standing on ( 0th block )
if ( i != 0 )
{
currentPos.y -= 2.0f - ( 2.0f * newBlock.StepDelta);
World.CreateBlockAt(currentPos, blockSpawner.SpawnType.ObjectID, rot);
CurrentCoolDown = CoolDown;
break;
}
}
//Move the path forward (each block in the world is 2 units big)
currentPos += (dir * 2);
}
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;
using System.Collections.Generic;
using Internal.IL;
using Internal.Runtime;
using Internal.Text;
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
using GenericVariance = Internal.Runtime.GenericVariance;
namespace ILCompiler.DependencyAnalysis
{
/// <summary>
/// Given a type, EETypeNode writes an EEType data structure in the format expected by the runtime.
///
/// Format of an EEType:
///
/// Field Size | Contents
/// ----------------+-----------------------------------
/// UInt16 | Component Size. For arrays this is the element type size, for strings it is 2 (.NET uses
/// | UTF16 character encoding), for generic type definitions it is the number of generic parameters,
/// | and 0 for all other types.
/// |
/// UInt16 | EETypeKind (Normal, Array, Pointer type). Flags for: IsValueType, IsCrossModule, HasPointers,
/// | HasOptionalFields, IsInterface, IsGeneric. Top 5 bits are used for enum CorElementType to
/// | record whether it's back by an Int32, Int16 etc
/// |
/// Uint32 | Base size.
/// |
/// [Pointer Size] | Related type. Base type for regular types. Element type for arrays / pointer types.
/// |
/// UInt16 | Number of VTable slots (X)
/// |
/// UInt16 | Number of interfaces implemented by type (Y)
/// |
/// UInt32 | Hash code
/// |
/// [Pointer Size] | Pointer to containing TypeManager indirection cell
/// |
/// X * [Ptr Size] | VTable entries (optional)
/// |
/// Y * [Ptr Size] | Pointers to interface map data structures (optional)
/// |
/// [Pointer Size] | Pointer to finalizer method (optional)
/// |
/// [Pointer Size] | Pointer to optional fields (optional)
/// |
/// [Pointer Size] | Pointer to the generic type argument of a Nullable<T> (optional)
/// |
/// [Pointer Size] | Pointer to the generic type definition EEType (optional)
/// |
/// [Pointer Size] | Pointer to the generic argument and variance info (optional)
/// </summary>
public partial class EETypeNode : ObjectNode, IExportableSymbolNode, IEETypeNode, ISymbolDefinitionNode
{
protected TypeDesc _type;
internal EETypeOptionalFieldsBuilder _optionalFieldsBuilder = new EETypeOptionalFieldsBuilder();
internal EETypeOptionalFieldsNode _optionalFieldsNode;
public EETypeNode(NodeFactory factory, TypeDesc type)
{
if (type.IsCanonicalDefinitionType(CanonicalFormKind.Any))
Debug.Assert(this is CanonicalDefinitionEETypeNode);
else if (type.IsCanonicalSubtype(CanonicalFormKind.Any))
Debug.Assert((this is CanonicalEETypeNode) || (this is NecessaryCanonicalEETypeNode));
Debug.Assert(!type.IsRuntimeDeterminedSubtype);
_type = type;
_optionalFieldsNode = new EETypeOptionalFieldsNode(this);
// Note: The fact that you can't create invalid EETypeNode is used from many places that grab
// an EETypeNode from the factory with the sole purpose of making sure the validation has run
// and that the result of the positive validation is "cached" (by the presence of an EETypeNode).
CheckCanGenerateEEType(factory, type);
}
protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler);
public override bool ShouldSkipEmittingObjectNode(NodeFactory factory)
{
// If there is a constructed version of this node in the graph, emit that instead
if (ConstructedEETypeNode.CreationAllowed(_type))
return factory.ConstructedTypeSymbol(_type).Marked;
return false;
}
public override ObjectNode NodeForLinkage(NodeFactory factory)
{
return (ObjectNode)factory.NecessaryTypeSymbol(_type);
}
public virtual bool IsExported(NodeFactory factory) => factory.CompilationModuleGroup.ExportsType(Type);
public TypeDesc Type => _type;
public override ObjectNodeSection Section
{
get
{
if (_type.Context.Target.IsWindows)
return ObjectNodeSection.ReadOnlyDataSection;
else
return ObjectNodeSection.DataSection;
}
}
public int MinimumObjectSize => _type.Context.Target.PointerSize * 3;
protected virtual bool EmitVirtualSlotsAndInterfaces => false;
internal bool HasOptionalFields
{
get { return _optionalFieldsBuilder.IsAtLeastOneFieldUsed(); }
}
internal byte[] GetOptionalFieldsData(NodeFactory factory)
{
return _optionalFieldsBuilder.GetBytes();
}
public override bool StaticDependenciesAreComputed => true;
public void SetDispatchMapIndex(int index)
{
_optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.DispatchMap, checked((uint)index));
}
public static string GetMangledName(TypeDesc type, NameMangler nameMangler)
{
return nameMangler.NodeMangler.EEType(type);
}
public virtual void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
sb.Append(nameMangler.NodeMangler.EEType(_type));
}
int ISymbolNode.Offset => 0;
int ISymbolDefinitionNode.Offset => GCDescSize;
public override bool IsShareable => IsTypeNodeShareable(_type);
public sealed override bool HasConditionalStaticDependencies
{
get
{
if (!EmitVirtualSlotsAndInterfaces)
return false;
// Since the vtable is dependency driven, generate conditional static dependencies for
// all possible vtable entries
foreach (var method in _type.GetClosestDefType().GetAllMethods())
{
if (method.IsVirtual)
return true;
}
// If the type implements at least one interface, calls against that interface could result in this type's
// implementation being used.
if (_type.RuntimeInterfaces.Length > 0)
return true;
return false;
}
}
public override IEnumerable<CombinedDependencyListEntry> GetConditionalStaticDependencies(NodeFactory factory)
{
Debug.Assert(EmitVirtualSlotsAndInterfaces);
DefType defType = _type.GetClosestDefType();
// If we're producing a full vtable, none of the dependencies are conditional.
if (!factory.VTable(defType).HasFixedSlots)
{
foreach (MethodDesc decl in defType.EnumAllVirtualSlots())
{
// Generic virtual methods are tracked by an orthogonal mechanism.
if (decl.HasInstantiation)
continue;
MethodDesc impl = defType.FindVirtualFunctionTargetMethodOnObjectType(decl);
if (impl.OwningType == defType && !impl.IsAbstract)
{
MethodDesc canonImpl = impl.GetCanonMethodTarget(CanonicalFormKind.Specific);
yield return new CombinedDependencyListEntry(factory.MethodEntrypoint(canonImpl, _type.IsValueType), factory.VirtualMethodUse(decl), "Virtual method");
}
}
Debug.Assert(
_type == defType ||
((System.Collections.IStructuralEquatable)defType.RuntimeInterfaces).Equals(_type.RuntimeInterfaces,
EqualityComparer<DefType>.Default));
// Add conditional dependencies for interface methods the type implements. For example, if the type T implements
// interface IFoo which has a method M1, add a dependency on T.M1 dependent on IFoo.M1 being called, since it's
// possible for any IFoo object to actually be an instance of T.
foreach (DefType interfaceType in defType.RuntimeInterfaces)
{
Debug.Assert(interfaceType.IsInterface);
foreach (MethodDesc interfaceMethod in interfaceType.GetAllMethods())
{
if (interfaceMethod.Signature.IsStatic)
continue;
// Generic virtual methods are tracked by an orthogonal mechanism.
if (interfaceMethod.HasInstantiation)
continue;
MethodDesc implMethod = defType.ResolveInterfaceMethodToVirtualMethodOnType(interfaceMethod);
if (implMethod != null)
{
yield return new CombinedDependencyListEntry(factory.VirtualMethodUse(implMethod), factory.VirtualMethodUse(interfaceMethod), "Interface method");
}
}
}
}
}
public static bool IsTypeNodeShareable(TypeDesc type)
{
return type.IsParameterizedType || type.IsFunctionPointer || type is InstantiatedType;
}
private void AddVirtualMethodUseDependencies(DependencyList dependencyList, NodeFactory factory)
{
DefType closestDefType = _type.GetClosestDefType();
if (_type.RuntimeInterfaces.Length > 0 && !factory.VTable(closestDefType).HasFixedSlots)
{
foreach (var implementedInterface in _type.RuntimeInterfaces)
{
// If the type implements ICastable, the methods are implicitly necessary
if (implementedInterface == factory.ICastableInterface)
{
MethodDesc isInstDecl = implementedInterface.GetKnownMethod("IsInstanceOfInterface", null);
MethodDesc getImplTypeDecl = implementedInterface.GetKnownMethod("GetImplType", null);
MethodDesc isInstMethodImpl = _type.ResolveInterfaceMethodTarget(isInstDecl);
MethodDesc getImplTypeMethodImpl = _type.ResolveInterfaceMethodTarget(getImplTypeDecl);
if (isInstMethodImpl != null)
dependencyList.Add(factory.VirtualMethodUse(isInstMethodImpl), "ICastable IsInst");
if (getImplTypeMethodImpl != null)
dependencyList.Add(factory.VirtualMethodUse(getImplTypeMethodImpl), "ICastable GetImplType");
}
// If any of the implemented interfaces have variance, calls against compatible interface methods
// could result in interface methods of this type being used (e.g. IEnumberable<object>.GetEnumerator()
// can dispatch to an implementation of IEnumerable<string>.GetEnumerator()).
// For now, we will not try to optimize this and we will pretend all interface methods are necessary.
bool allInterfaceMethodsAreImplicitlyUsed = false;
if (implementedInterface.HasVariance)
{
TypeDesc interfaceDefinition = implementedInterface.GetTypeDefinition();
for (int i = 0; i < interfaceDefinition.Instantiation.Length; i++)
{
if (((GenericParameterDesc)interfaceDefinition.Instantiation[i]).Variance != 0 &&
!implementedInterface.Instantiation[i].IsValueType)
{
allInterfaceMethodsAreImplicitlyUsed = true;
break;
}
}
}
if (!allInterfaceMethodsAreImplicitlyUsed &&
(_type.IsArray || _type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType) &&
implementedInterface.HasInstantiation)
{
// NOTE: we need to also do this for generic interfaces on arrays because they have a weird casting rule
// that doesn't require the implemented interface to be variant to consider it castable.
// For value types, we only need this when the array is castable by size (int[] and ICollection<uint>),
// or it's a reference type (Derived[] and ICollection<Base>).
TypeDesc elementType = _type.IsArray ? ((ArrayType)_type).ElementType : _type.Instantiation[0];
allInterfaceMethodsAreImplicitlyUsed =
CastingHelper.IsArrayElementTypeCastableBySize(elementType) ||
(elementType.IsDefType && !elementType.IsValueType);
}
if (allInterfaceMethodsAreImplicitlyUsed)
{
foreach (var interfaceMethod in implementedInterface.GetAllMethods())
{
if (interfaceMethod.Signature.IsStatic)
continue;
// Generic virtual methods are tracked by an orthogonal mechanism.
if (interfaceMethod.HasInstantiation)
continue;
MethodDesc implMethod = closestDefType.ResolveInterfaceMethodToVirtualMethodOnType(interfaceMethod);
if (implMethod != null)
{
dependencyList.Add(factory.VirtualMethodUse(interfaceMethod), "Variant interface method");
dependencyList.Add(factory.VirtualMethodUse(implMethod), "Variant interface method");
}
}
}
}
}
}
protected override DependencyList ComputeNonRelocationBasedDependencies(NodeFactory factory)
{
DependencyList dependencies = new DependencyList();
// Include the optional fields by default. We don't know if optional fields will be needed until
// all of the interface usage has been stabilized. If we end up not needing it, the EEType node will not
// generate any relocs to it, and the optional fields node will instruct the object writer to skip
// emitting it.
dependencies.Add(new DependencyListEntry(_optionalFieldsNode, "Optional fields"));
StaticsInfoHashtableNode.AddStaticsInfoDependencies(ref dependencies, factory, _type);
ReflectionFieldMapNode.AddReflectionFieldMapEntryDependencies(ref dependencies, factory, _type);
if (EmitVirtualSlotsAndInterfaces)
{
AddVirtualMethodUseDependencies(dependencies, factory);
}
return dependencies;
}
public override ObjectData GetData(NodeFactory factory, bool relocsOnly)
{
ObjectDataBuilder objData = new ObjectDataBuilder(factory, relocsOnly);
objData.RequireInitialPointerAlignment();
objData.AddSymbol(this);
ComputeOptionalEETypeFields(factory, relocsOnly);
OutputGCDesc(ref objData);
OutputComponentSize(ref objData);
OutputFlags(factory, ref objData);
OutputBaseSize(ref objData);
OutputRelatedType(factory, ref objData);
// Number of vtable slots will be only known later. Reseve the bytes for it.
var vtableSlotCountReservation = objData.ReserveShort();
// Number of interfaces will only be known later. Reserve the bytes for it.
var interfaceCountReservation = objData.ReserveShort();
objData.EmitInt(_type.GetHashCode());
objData.EmitPointerReloc(factory.TypeManagerIndirection);
if (EmitVirtualSlotsAndInterfaces)
{
// Emit VTable
Debug.Assert(objData.CountBytes - ((ISymbolDefinitionNode)this).Offset == GetVTableOffset(objData.TargetPointerSize));
SlotCounter virtualSlotCounter = SlotCounter.BeginCounting(ref /* readonly */ objData);
OutputVirtualSlots(factory, ref objData, _type, _type, _type, relocsOnly);
// Update slot count
int numberOfVtableSlots = virtualSlotCounter.CountSlots(ref /* readonly */ objData);
objData.EmitShort(vtableSlotCountReservation, checked((short)numberOfVtableSlots));
// Emit interface map
SlotCounter interfaceSlotCounter = SlotCounter.BeginCounting(ref /* readonly */ objData);
OutputInterfaceMap(factory, ref objData);
// Update slot count
int numberOfInterfaceSlots = interfaceSlotCounter.CountSlots(ref /* readonly */ objData);
objData.EmitShort(interfaceCountReservation, checked((short)numberOfInterfaceSlots));
}
else
{
// If we're not emitting any slots, the number of slots is zero.
objData.EmitShort(vtableSlotCountReservation, 0);
objData.EmitShort(interfaceCountReservation, 0);
}
OutputFinalizerMethod(factory, ref objData);
OutputOptionalFields(factory, ref objData);
OutputNullableTypeParameter(factory, ref objData);
OutputGenericInstantiationDetails(factory, ref objData);
return objData.ToObjectData();
}
/// <summary>
/// Returns the offset within an EEType of the beginning of VTable entries
/// </summary>
/// <param name="pointerSize">The size of a pointer in bytes in the target architecture</param>
public static int GetVTableOffset(int pointerSize)
{
return 16 + 2 * pointerSize;
}
protected virtual int GCDescSize => 0;
protected virtual void OutputGCDesc(ref ObjectDataBuilder builder)
{
// Non-constructed EETypeNodes get no GC Desc
Debug.Assert(GCDescSize == 0);
}
private void OutputComponentSize(ref ObjectDataBuilder objData)
{
if (_type.IsArray)
{
TypeDesc elementType = ((ArrayType)_type).ElementType;
if (elementType == elementType.Context.UniversalCanonType)
{
objData.EmitShort(0);
}
else
{
int elementSize = elementType.GetElementSize().AsInt;
// We validated that this will fit the short when the node was constructed. No need for nice messages.
objData.EmitShort((short)checked((ushort)elementSize));
}
}
else if (_type.IsString)
{
objData.EmitShort(StringComponentSize.Value);
}
else
{
objData.EmitShort(0);
}
}
private void OutputFlags(NodeFactory factory, ref ObjectDataBuilder objData)
{
UInt16 flags = EETypeBuilderHelpers.ComputeFlags(_type);
if (_type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType)
{
// Generic array enumerators use special variance rules recognized by the runtime
flags |= (UInt16)EETypeFlags.GenericVarianceFlag;
}
if (factory.TypeSystemContext.IsGenericArrayInterfaceType(_type))
{
// Runtime casting logic relies on all interface types implemented on arrays
// to have the variant flag set (even if all the arguments are non-variant).
// This supports e.g. casting uint[] to ICollection<int>
flags |= (UInt16)EETypeFlags.GenericVarianceFlag;
}
if (!(this is CanonicalDefinitionEETypeNode))
{
foreach (DefType itf in _type.RuntimeInterfaces)
{
if (itf == factory.ICastableInterface)
{
flags |= (UInt16)EETypeFlags.ICastableFlag;
break;
}
}
}
ISymbolNode relatedTypeNode = GetRelatedTypeNode(factory);
// If the related type (base type / array element type / pointee type) is not part of this compilation group, and
// the output binaries will be multi-file (not multiple object files linked together), indicate to the runtime
// that it should indirect through the import address table
if (relatedTypeNode != null && relatedTypeNode.RepresentsIndirectionCell)
{
flags |= (UInt16)EETypeFlags.RelatedTypeViaIATFlag;
}
if (HasOptionalFields)
{
flags |= (UInt16)EETypeFlags.OptionalFieldsFlag;
}
if (this is ClonedConstructedEETypeNode)
{
flags |= (UInt16)EETypeKind.ClonedEEType;
}
objData.EmitShort((short)flags);
}
protected virtual void OutputBaseSize(ref ObjectDataBuilder objData)
{
int pointerSize = _type.Context.Target.PointerSize;
int objectSize;
if (_type.IsDefType)
{
LayoutInt instanceByteCount = ((DefType)_type).InstanceByteCount;
if (instanceByteCount.IsIndeterminate)
{
// Some value must be put in, but the specific value doesn't matter as it
// isn't used for specific instantiations, and the universal canon eetype
// is never associated with an allocated object.
objectSize = pointerSize;
}
else
{
objectSize = pointerSize +
((DefType)_type).InstanceByteCount.AsInt; // +pointerSize for SyncBlock
}
if (_type.IsValueType)
objectSize += pointerSize; // + EETypePtr field inherited from System.Object
}
else if (_type.IsArray)
{
objectSize = 3 * pointerSize; // SyncBlock + EETypePtr + Length
if (_type.IsMdArray)
objectSize +=
2 * sizeof(int) * ((ArrayType)_type).Rank;
}
else if (_type.IsPointer)
{
// These never get boxed and don't have a base size. Use a sentinel value recognized by the runtime.
objData.EmitInt(ParameterizedTypeShapeConstants.Pointer);
return;
}
else if (_type.IsByRef)
{
// These never get boxed and don't have a base size. Use a sentinel value recognized by the runtime.
objData.EmitInt(ParameterizedTypeShapeConstants.ByRef);
return;
}
else
throw new NotImplementedException();
objectSize = AlignmentHelper.AlignUp(objectSize, pointerSize);
objectSize = Math.Max(MinimumObjectSize, objectSize);
if (_type.IsString)
{
// If this is a string, throw away objectSize we computed so far. Strings are special.
// SyncBlock + EETypePtr + length + firstChar
objectSize = 2 * pointerSize +
sizeof(int) +
StringComponentSize.Value;
}
objData.EmitInt(objectSize);
}
protected static TypeDesc GetFullCanonicalTypeForCanonicalType(TypeDesc type)
{
if (type.IsCanonicalSubtype(CanonicalFormKind.Specific))
{
return type.ConvertToCanonForm(CanonicalFormKind.Specific);
}
else if (type.IsCanonicalSubtype(CanonicalFormKind.Universal))
{
return type.ConvertToCanonForm(CanonicalFormKind.Universal);
}
else
{
return type;
}
}
protected virtual ISymbolNode GetBaseTypeNode(NodeFactory factory)
{
return _type.BaseType != null ? factory.NecessaryTypeSymbol(_type.BaseType) : null;
}
private ISymbolNode GetRelatedTypeNode(NodeFactory factory)
{
ISymbolNode relatedTypeNode = null;
if (_type.IsArray || _type.IsPointer || _type.IsByRef)
{
var parameterType = ((ParameterizedType)_type).ParameterType;
relatedTypeNode = factory.NecessaryTypeSymbol(parameterType);
}
else
{
TypeDesc baseType = _type.BaseType;
if (baseType != null)
{
relatedTypeNode = GetBaseTypeNode(factory);
}
}
return relatedTypeNode;
}
protected virtual void OutputRelatedType(NodeFactory factory, ref ObjectDataBuilder objData)
{
ISymbolNode relatedTypeNode = GetRelatedTypeNode(factory);
if (relatedTypeNode != null)
{
objData.EmitPointerReloc(relatedTypeNode);
}
else
{
objData.EmitZeroPointer();
}
}
protected virtual void OutputVirtualSlots(NodeFactory factory, ref ObjectDataBuilder objData, TypeDesc implType, TypeDesc declType, TypeDesc templateType, bool relocsOnly)
{
Debug.Assert(EmitVirtualSlotsAndInterfaces);
declType = declType.GetClosestDefType();
templateType = templateType.ConvertToCanonForm(CanonicalFormKind.Specific);
var baseType = declType.BaseType;
if (baseType != null)
{
Debug.Assert(templateType.BaseType != null);
OutputVirtualSlots(factory, ref objData, implType, baseType, templateType.BaseType, relocsOnly);
}
//
// In the universal canonical types case, we could have base types in the hierarchy that are partial universal canonical types.
// The presence of these types could cause incorrect vtable layouts, so we need to fully canonicalize them and walk the
// hierarchy of the template type of the original input type to detect these cases.
//
// Exmaple: we begin with Derived<__UniversalCanon> and walk the template hierarchy:
//
// class Derived<T> : Middle<T, MyStruct> { } // -> Template is Derived<__UniversalCanon> and needs a dictionary slot
// // -> Basetype tempalte is Middle<__UniversalCanon, MyStruct>. It's a partial
// Universal canonical type, so we need to fully canonicalize it.
//
// class Middle<T, U> : Base<U> { } // -> Template is Middle<__UniversalCanon, __UniversalCanon> and needs a dictionary slot
// // -> Basetype template is Base<__UniversalCanon>
//
// class Base<T> { } // -> Template is Base<__UniversalCanon> and needs a dictionary slot.
//
// If we had not fully canonicalized the Middle class template, we would have ended up with Base<MyStruct>, which does not need
// a dictionary slot, meaning we would have created a vtable layout that the runtime does not expect.
//
// The generic dictionary pointer occupies the first slot of each type vtable slice
if (declType.HasGenericDictionarySlot() || templateType.HasGenericDictionarySlot())
{
// All generic interface types have a dictionary slot, but only some of them have an actual dictionary.
bool isInterfaceWithAnEmptySlot = declType.IsInterface &&
declType.ConvertToCanonForm(CanonicalFormKind.Specific) == declType;
// Note: Canonical type instantiations always have a generic dictionary vtable slot, but it's empty
// Note: If the current EETypeNode represents a universal canonical type, any dictionary slot must be empty
if (declType.IsCanonicalSubtype(CanonicalFormKind.Any)
|| implType.IsCanonicalSubtype(CanonicalFormKind.Universal)
|| factory.LazyGenericsPolicy.UsesLazyGenerics(declType)
|| isInterfaceWithAnEmptySlot)
objData.EmitZeroPointer();
else
objData.EmitPointerReloc(factory.TypeGenericDictionary(declType));
}
// It's only okay to touch the actual list of slots if we're in the final emission phase
// or the vtable is not built lazily.
if (relocsOnly && !factory.VTable(declType).HasFixedSlots)
return;
// Actual vtable slots follow
IReadOnlyList<MethodDesc> virtualSlots = factory.VTable(declType).Slots;
for (int i = 0; i < virtualSlots.Count; i++)
{
MethodDesc declMethod = virtualSlots[i];
// No generic virtual methods can appear in the vtable!
Debug.Assert(!declMethod.HasInstantiation);
MethodDesc implMethod = implType.GetClosestDefType().FindVirtualFunctionTargetMethodOnObjectType(declMethod);
if (!implMethod.IsAbstract)
{
MethodDesc canonImplMethod = implMethod.GetCanonMethodTarget(CanonicalFormKind.Specific);
objData.EmitPointerReloc(factory.MethodEntrypoint(canonImplMethod, implMethod.OwningType.IsValueType));
}
else
{
objData.EmitZeroPointer();
}
}
}
protected virtual IEETypeNode GetInterfaceTypeNode(NodeFactory factory, TypeDesc interfaceType)
{
return factory.NecessaryTypeSymbol(interfaceType);
}
protected virtual void OutputInterfaceMap(NodeFactory factory, ref ObjectDataBuilder objData)
{
Debug.Assert(EmitVirtualSlotsAndInterfaces);
foreach (var itf in _type.RuntimeInterfaces)
{
objData.EmitPointerRelocOrIndirectionReference(GetInterfaceTypeNode(factory, itf));
}
}
private void OutputFinalizerMethod(NodeFactory factory, ref ObjectDataBuilder objData)
{
if (_type.HasFinalizer)
{
MethodDesc finalizerMethod = _type.GetFinalizer();
MethodDesc canonFinalizerMethod = finalizerMethod.GetCanonMethodTarget(CanonicalFormKind.Specific);
objData.EmitPointerReloc(factory.MethodEntrypoint(canonFinalizerMethod));
}
}
private void OutputOptionalFields(NodeFactory factory, ref ObjectDataBuilder objData)
{
if (HasOptionalFields)
{
objData.EmitPointerReloc(_optionalFieldsNode);
}
}
private void OutputNullableTypeParameter(NodeFactory factory, ref ObjectDataBuilder objData)
{
if (_type.IsNullable)
{
objData.EmitPointerReloc(factory.NecessaryTypeSymbol(_type.Instantiation[0]));
}
}
private void OutputGenericInstantiationDetails(NodeFactory factory, ref ObjectDataBuilder objData)
{
if (_type.HasInstantiation && !_type.IsTypeDefinition)
{
objData.EmitPointerRelocOrIndirectionReference(factory.NecessaryTypeSymbol(_type.GetTypeDefinition()));
GenericCompositionDetails details;
if (_type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType)
{
// Generic array enumerators use special variance rules recognized by the runtime
details = new GenericCompositionDetails(_type.Instantiation, new[] { GenericVariance.ArrayCovariant });
}
else if (factory.TypeSystemContext.IsGenericArrayInterfaceType(_type))
{
// Runtime casting logic relies on all interface types implemented on arrays
// to have the variant flag set (even if all the arguments are non-variant).
// This supports e.g. casting uint[] to ICollection<int>
details = new GenericCompositionDetails(_type, forceVarianceInfo: true);
}
else
details = new GenericCompositionDetails(_type);
objData.EmitPointerReloc(factory.GenericComposition(details));
}
}
/// <summary>
/// Populate the OptionalFieldsRuntimeBuilder if any optional fields are required.
/// </summary>
protected internal virtual void ComputeOptionalEETypeFields(NodeFactory factory, bool relocsOnly)
{
ComputeRareFlags(factory);
ComputeNullableValueOffset();
if (!relocsOnly)
ComputeICastableVirtualMethodSlots(factory);
ComputeValueTypeFieldPadding();
}
void ComputeRareFlags(NodeFactory factory)
{
uint flags = 0;
MetadataType metadataType = _type as MetadataType;
if (_type.IsNullable)
{
flags |= (uint)EETypeRareFlags.IsNullableFlag;
// If the nullable type is not part of this compilation group, and
// the output binaries will be multi-file (not multiple object files linked together), indicate to the runtime
// that it should indirect through the import address table
if (factory.NecessaryTypeSymbol(_type.Instantiation[0]).RepresentsIndirectionCell)
flags |= (uint)EETypeRareFlags.NullableTypeViaIATFlag;
}
if (factory.TypeSystemContext.HasLazyStaticConstructor(_type))
{
flags |= (uint)EETypeRareFlags.HasCctorFlag;
}
if (EETypeBuilderHelpers.ComputeRequiresAlign8(_type))
{
flags |= (uint)EETypeRareFlags.RequiresAlign8Flag;
}
if (metadataType != null && metadataType.IsHfa)
{
flags |= (uint)EETypeRareFlags.IsHFAFlag;
}
if (metadataType != null && !_type.IsInterface && metadataType.IsAbstract)
{
flags |= (uint)EETypeRareFlags.IsAbstractClassFlag;
}
if (_type.IsByRefLike)
{
flags |= (uint)EETypeRareFlags.IsByRefLikeFlag;
}
if (flags != 0)
{
_optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.RareFlags, flags);
}
}
/// <summary>
/// To support boxing / unboxing, the offset of the value field of a Nullable type is recorded on the EEType.
/// This is variable according to the alignment requirements of the Nullable<T> type parameter.
/// </summary>
void ComputeNullableValueOffset()
{
if (!_type.IsNullable)
return;
if (!_type.Instantiation[0].IsCanonicalSubtype(CanonicalFormKind.Universal))
{
var field = _type.GetKnownField("value");
// In the definition of Nullable<T>, the first field should be the boolean representing "hasValue"
Debug.Assert(field.Offset.AsInt > 0);
// The contract with the runtime states the Nullable value offset is stored with the boolean "hasValue" size subtracted
// to get a small encoding size win.
_optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.NullableValueOffset, (uint)field.Offset.AsInt - 1);
}
}
/// <summary>
/// ICastable is a special interface whose two methods are not invoked using regular interface dispatch.
/// Instead, their VTable slots are recorded on the EEType of an object implementing ICastable and are
/// called directly.
/// </summary>
protected virtual void ComputeICastableVirtualMethodSlots(NodeFactory factory)
{
if (_type.IsInterface || !EmitVirtualSlotsAndInterfaces)
return;
foreach (DefType itf in _type.RuntimeInterfaces)
{
if (itf == factory.ICastableInterface)
{
MethodDesc isInstDecl = itf.GetKnownMethod("IsInstanceOfInterface", null);
MethodDesc getImplTypeDecl = itf.GetKnownMethod("GetImplType", null);
MethodDesc isInstMethodImpl = _type.ResolveInterfaceMethodTarget(isInstDecl);
MethodDesc getImplTypeMethodImpl = _type.ResolveInterfaceMethodTarget(getImplTypeDecl);
int isInstMethodSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, isInstMethodImpl);
int getImplTypeMethodSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, getImplTypeMethodImpl);
Debug.Assert(isInstMethodSlot != -1 && getImplTypeMethodSlot != -1);
_optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.ICastableIsInstSlot, (uint)isInstMethodSlot);
_optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.ICastableGetImplTypeSlot, (uint)getImplTypeMethodSlot);
}
}
}
protected virtual void ComputeValueTypeFieldPadding()
{
// All objects that can have appreciable which can be derived from size compute ValueTypeFieldPadding.
// Unfortunately, the name ValueTypeFieldPadding is now wrong to avoid integration conflicts.
// Interfaces, sealed types, and non-DefTypes cannot be derived from
if (_type.IsInterface || !_type.IsDefType || (_type.IsSealed() && !_type.IsValueType))
return;
DefType defType = _type as DefType;
Debug.Assert(defType != null);
uint valueTypeFieldPaddingEncoded;
if (defType.InstanceByteCount.IsIndeterminate)
{
valueTypeFieldPaddingEncoded = EETypeBuilderHelpers.ComputeValueTypeFieldPaddingFieldValue(0, 1, _type.Context.Target.PointerSize);
}
else
{
uint valueTypeFieldPadding = checked((uint)(defType.InstanceByteCount.AsInt - defType.InstanceByteCountUnaligned.AsInt));
valueTypeFieldPaddingEncoded = EETypeBuilderHelpers.ComputeValueTypeFieldPaddingFieldValue(valueTypeFieldPadding, (uint)defType.InstanceFieldAlignment.AsInt, _type.Context.Target.PointerSize);
}
if (valueTypeFieldPaddingEncoded != 0)
{
_optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.ValueTypeFieldPadding, valueTypeFieldPaddingEncoded);
}
}
protected override void OnMarked(NodeFactory context)
{
if (!context.IsCppCodegenTemporaryWorkaround)
{
Debug.Assert(_type.IsTypeDefinition || !_type.HasSameTypeDefinition(context.ArrayOfTClass), "Asking for Array<T> EEType");
}
}
/// <summary>
/// Validates that it will be possible to create an EEType for '<paramref name="type"/>'.
/// </summary>
public static void CheckCanGenerateEEType(NodeFactory factory, TypeDesc type)
{
// Don't validate generic definitons
if (type.IsGenericDefinition)
{
return;
}
// System.__Canon or System.__UniversalCanon
if(type.IsCanonicalDefinitionType(CanonicalFormKind.Any))
{
return;
}
// It must be possible to create an EEType for the base type of this type
TypeDesc baseType = type.BaseType;
if (baseType != null)
{
// Make sure EEType can be created for this.
factory.NecessaryTypeSymbol(GetFullCanonicalTypeForCanonicalType(baseType));
}
// We need EETypes for interfaces
foreach (var intf in type.RuntimeInterfaces)
{
// Make sure EEType can be created for this.
factory.NecessaryTypeSymbol(GetFullCanonicalTypeForCanonicalType(intf));
}
// Validate classes, structs, enums, interfaces, and delegates
DefType defType = type as DefType;
if (defType != null)
{
// Ensure we can compute the type layout
defType.ComputeInstanceLayout(InstanceLayoutKind.TypeAndFields);
//
// The fact that we generated an EEType means that someone can call RuntimeHelpers.RunClassConstructor.
// We need to make sure this is possible.
//
if (factory.TypeSystemContext.HasLazyStaticConstructor(defType))
{
defType.ComputeStaticFieldLayout(StaticLayoutKind.StaticRegionSizesAndFields);
}
// Make sure instantiation length matches the expectation
// TODO: it might be more resonable for the type system to enforce this (also for methods)
if (defType.Instantiation.Length != defType.GetTypeDefinition().Instantiation.Length)
{
ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadGeneral, type);
}
foreach (TypeDesc typeArg in defType.Instantiation)
{
// ByRefs, pointers, function pointers, and System.Void are never valid instantiation arguments
if (typeArg.IsByRef
|| typeArg.IsPointer
|| typeArg.IsFunctionPointer
|| typeArg.IsVoid
|| typeArg.IsByRefLike)
{
ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadGeneral, type);
}
// TODO: validate constraints
}
// Check the type doesn't have bogus MethodImpls or overrides and we can get the finalizer.
defType.GetFinalizer();
}
// Validate parameterized types
ParameterizedType parameterizedType = type as ParameterizedType;
if (parameterizedType != null)
{
TypeDesc parameterType = parameterizedType.ParameterType;
// Make sure EEType can be created for this.
factory.NecessaryTypeSymbol(parameterType);
if (parameterizedType.IsArray)
{
if (parameterType.IsFunctionPointer)
{
// Arrays of function pointers are not currently supported
ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadGeneral, type);
}
LayoutInt elementSize = parameterType.GetElementSize();
if (!elementSize.IsIndeterminate && elementSize.AsInt >= ushort.MaxValue)
{
// Element size over 64k can't be encoded in the GCDesc
ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadValueClassTooLarge, parameterType);
}
if (((ArrayType)parameterizedType).Rank > 32)
{
ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadRankTooLarge, type);
}
if (parameterType.IsByRefLike)
{
// Arrays of byref-like types are not allowed
ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadGeneral, type);
}
}
// Validate we're not constructing a type over a ByRef
if (parameterType.IsByRef)
{
// CLR compat note: "ldtoken int32&&" will actually fail with a message about int32&; "ldtoken int32&[]"
// will fail with a message about being unable to create an array of int32&. This is a middle ground.
ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadGeneral, type);
}
// It might seem reasonable to disallow array of void, but the CLR doesn't prevent that too hard.
// E.g. "newarr void" will fail, but "newarr void[]" or "ldtoken void[]" will succeed.
}
// Function pointer EETypes are not currently supported
if (type.IsFunctionPointer)
{
ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadGeneral, type);
}
}
private struct SlotCounter
{
private int _startBytes;
public static SlotCounter BeginCounting(ref /* readonly */ ObjectDataBuilder builder)
=> new SlotCounter { _startBytes = builder.CountBytes };
public int CountSlots(ref /* readonly */ ObjectDataBuilder builder)
{
int bytesEmitted = builder.CountBytes - _startBytes;
Debug.Assert(bytesEmitted % builder.TargetPointerSize == 0);
return bytesEmitted / builder.TargetPointerSize;
}
}
}
}
| |
/* ====================================================================
This file is originally from MS documentation: http://msdn.microsoft.com/en-us/library/system.reflection.binder.aspx
Above license only applies to changes made above and beyond that code.
*/
using System;
using System.Reflection;
using System.Globalization;
namespace Oranikle.Report.Engine
{
public class LaxBinder : Binder
{
public LaxBinder()
: base()
{
}
private class BinderState
{
public object[] args;
}
public override FieldInfo BindToField(
BindingFlags bindingAttr,
FieldInfo[] match,
object value,
CultureInfo culture
)
{
if (match == null)
throw new ArgumentNullException("match");
// Get a field for which the value parameter can be converted to the specified field type.
for (int i = 0; i < match.Length; i++)
if (ChangeType(value, match[i].FieldType, culture) != null)
return match[i];
return null;
}
public override MethodBase BindToMethod(
BindingFlags bindingAttr,
MethodBase[] match,
ref object[] args,
ParameterModifier[] modifiers,
CultureInfo culture,
string[] names,
out object state
)
{
// Store the arguments to the method in a state object.
BinderState myBinderState = new BinderState();
object[] arguments = new Object[args.Length];
args.CopyTo(arguments, 0);
myBinderState.args = arguments;
state = myBinderState;
if (match == null)
throw new ArgumentNullException();
// Find a method that has the same parameters as those of the args parameter.
for (int i = 0; i < match.Length; i++)
{
// Count the number of parameters that match.
int count = 0;
ParameterInfo[] parameters = match[i].GetParameters();
// Go on to the next method if the number of parameters do not match.
if (args.Length != parameters.Length)
continue;
// Match each of the parameters that the user expects the method to have.
for (int j = 0; j < args.Length; j++)
{
// If the names parameter is not null, then reorder args.
if (names != null)
{
if (names.Length != args.Length)
throw new ArgumentException("names and args must have the same number of elements.");
for (int k = 0; k < names.Length; k++)
if (String.Compare(parameters[j].Name, names[k].ToString()) == 0)
args[j] = myBinderState.args[k];
}
// Determine whether the types specified by the user can be converted to the parameter type.
if (ChangeType(args[j], parameters[j].ParameterType, culture) != null)
count += 1;
else
break;
}
// Determine whether the method has been found.
if (count == args.Length)
return match[i];
}
return null;
}
public override object ChangeType(
object value,
Type myChangeType,
CultureInfo culture
)
{
// Determine whether the value parameter can be converted to a value of type myType.
if (CanConvertFrom(value.GetType(), myChangeType))
// Return the converted object.
return Convert.ChangeType(value, myChangeType);
else
// Return null.
return null;
}
public override void ReorderArgumentArray(
ref object[] args,
object state
)
{
// Return the args that had been reordered by BindToMethod.
((BinderState)state).args.CopyTo(args, 0);
}
public override MethodBase SelectMethod(
BindingFlags bindingAttr,
MethodBase[] match,
Type[] types,
ParameterModifier[] modifiers
)
{
if (match == null)
throw new ArgumentNullException("match");
for (int i = 0; i < match.Length; i++)
{
// Count the number of parameters that match.
int count = 0;
ParameterInfo[] parameters = match[i].GetParameters();
// Go on to the next method if the number of parameters do not match.
if (types.Length != parameters.Length)
continue;
// Match each of the parameters that the user expects the method to have.
for (int j = 0; j < types.Length; j++)
// Determine whether the types specified by the user can be converted to parameter type.
if (CanConvertFrom(types[j], parameters[j].ParameterType))
count += 1;
else
break;
// Determine whether the method has been found.
if (count == types.Length)
return match[i];
}
return null;
}
public override PropertyInfo SelectProperty(
BindingFlags bindingAttr,
PropertyInfo[] match,
Type returnType,
Type[] indexes,
ParameterModifier[] modifiers
)
{
if (match == null)
throw new ArgumentNullException("match");
for (int i = 0; i < match.Length; i++)
{
// Count the number of indexes that match.
int count = 0;
ParameterInfo[] parameters = match[i].GetIndexParameters();
// Go on to the next property if the number of indexes do not match.
if (indexes.Length != parameters.Length)
continue;
// Match each of the indexes that the user expects the property to have.
for (int j = 0; j < indexes.Length; j++)
// Determine whether the types specified by the user can be converted to index type.
if (CanConvertFrom(indexes[j], parameters[j].ParameterType))
count += 1;
else
break;
// Determine whether the property has been found.
if (count == indexes.Length)
// Determine whether the return type can be converted to the properties type.
if (CanConvertFrom(returnType, match[i].PropertyType))
return match[i];
else
continue;
}
return null;
}
// Determines whether type1 can be converted to type2. Check only for primitive types.
private bool CanConvertFrom(Type type1, Type type2)
{
if (type1.IsPrimitive && type2.IsPrimitive)
{
TypeCode typeCode1 = Type.GetTypeCode(type1);
TypeCode typeCode2 = Type.GetTypeCode(type2);
// If both type1 and type2 have the same type, return true.
if (typeCode1 == typeCode2)
return true;
// Possible conversions from Char follow.
if (typeCode1 == TypeCode.Char)
switch (typeCode2)
{
case TypeCode.UInt16: return true;
case TypeCode.UInt32: return true;
case TypeCode.Int32: return true;
case TypeCode.UInt64: return true;
case TypeCode.Int64: return true;
case TypeCode.Single: return true;
case TypeCode.Double: return true;
default: return false;
}
// Possible conversions from Byte follow.
if (typeCode1 == TypeCode.Byte)
switch (typeCode2)
{
case TypeCode.Char: return true;
case TypeCode.UInt16: return true;
case TypeCode.Int16: return true;
case TypeCode.UInt32: return true;
case TypeCode.Int32: return true;
case TypeCode.UInt64: return true;
case TypeCode.Int64: return true;
case TypeCode.Single: return true;
case TypeCode.Double: return true;
default: return false;
}
// Possible conversions from SByte follow.
if (typeCode1 == TypeCode.SByte)
switch (typeCode2)
{
case TypeCode.Int16: return true;
case TypeCode.Int32: return true;
case TypeCode.Int64: return true;
case TypeCode.Single: return true;
case TypeCode.Double: return true;
default: return false;
}
// Possible conversions from UInt16 follow.
if (typeCode1 == TypeCode.UInt16)
switch (typeCode2)
{
case TypeCode.UInt32: return true;
case TypeCode.Int32: return true;
case TypeCode.UInt64: return true;
case TypeCode.Int64: return true;
case TypeCode.Single: return true;
case TypeCode.Double: return true;
default: return false;
}
// Possible conversions from Int16 follow.
if (typeCode1 == TypeCode.Int16)
switch (typeCode2)
{
case TypeCode.Int32: return true;
case TypeCode.Int64: return true;
case TypeCode.Single: return true;
case TypeCode.Double: return true;
default: return false;
}
// Possible conversions from UInt32 follow.
if (typeCode1 == TypeCode.UInt32)
switch (typeCode2)
{
case TypeCode.UInt64: return true;
case TypeCode.Int64: return true;
case TypeCode.Single: return true;
case TypeCode.Double: return true;
default: return false;
}
// Possible conversions from Int32 follow.
if (typeCode1 == TypeCode.Int32)
switch (typeCode2)
{
case TypeCode.Int64: return true;
case TypeCode.Single: return true;
case TypeCode.Double: return true;
default: return false;
}
// Possible conversions from UInt64 follow.
if (typeCode1 == TypeCode.UInt64)
switch (typeCode2)
{
case TypeCode.Single: return true;
case TypeCode.Double: return true;
default: return false;
}
// Possible conversions from Int64 follow.
if (typeCode1 == TypeCode.Int64)
switch (typeCode2)
{
case TypeCode.Single: return true;
case TypeCode.Double: return true;
default: return false;
}
// Possible conversions from Single follow.
if (typeCode1 == TypeCode.Single)
switch (typeCode2)
{
case TypeCode.Double: return true;
default: return false;
}
}
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Constants;
using BTCPayServer.Data;
using BTCPayServer.Filters;
using BTCPayServer.Models;
using BTCPayServer.Rating;
using BTCPayServer.Security;
using BTCPayServer.Security.Bitpay;
using BTCPayServer.Services.Rates;
using BTCPayServer.Services.Stores;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace BTCPayServer.Controllers
{
[EnableCors(CorsPolicies.All)]
[Authorize(Policy = ServerPolicies.CanGetRates.Key, AuthenticationSchemes = AuthenticationSchemes.Bitpay)]
public class BitpayRateController : Controller
{
public StoreData CurrentStore
{
get
{
return HttpContext.GetStoreData();
}
}
readonly RateFetcher _RateProviderFactory;
readonly BTCPayNetworkProvider _NetworkProvider;
readonly CurrencyNameTable _CurrencyNameTable;
readonly StoreRepository _StoreRepo;
public TokenRepository TokenRepository { get; }
public BitpayRateController(
RateFetcher rateProviderFactory,
BTCPayNetworkProvider networkProvider,
TokenRepository tokenRepository,
StoreRepository storeRepo,
CurrencyNameTable currencyNameTable)
{
_RateProviderFactory = rateProviderFactory ?? throw new ArgumentNullException(nameof(rateProviderFactory));
_NetworkProvider = networkProvider;
TokenRepository = tokenRepository;
_StoreRepo = storeRepo;
_CurrencyNameTable = currencyNameTable ?? throw new ArgumentNullException(nameof(currencyNameTable));
}
[Route("rates/{baseCurrency}")]
[HttpGet]
[BitpayAPIConstraint]
public async Task<IActionResult> GetBaseCurrencyRates(string baseCurrency, CancellationToken cancellationToken)
{
var supportedMethods = CurrentStore.GetSupportedPaymentMethods(_NetworkProvider);
var currencyCodes = supportedMethods.Where(method => !string.IsNullOrEmpty(method.PaymentId.CryptoCode))
.Select(method => method.PaymentId.CryptoCode).Distinct();
var currencypairs = BuildCurrencyPairs(currencyCodes, baseCurrency);
var result = await GetRates2(currencypairs, null, cancellationToken);
var rates = (result as JsonResult)?.Value as Rate[];
if (rates == null)
return result;
return Json(new DataWrapper<Rate[]>(rates));
}
[Route("rates/{baseCurrency}/{currency}")]
[HttpGet]
[BitpayAPIConstraint]
public async Task<IActionResult> GetCurrencyPairRate(string baseCurrency, string currency, CancellationToken cancellationToken)
{
var result = await GetRates2($"{baseCurrency}_{currency}", null, cancellationToken);
var rates = (result as JsonResult)?.Value as Rate[];
if (rates == null)
return result;
return Json(new DataWrapper<Rate>(rates.First()));
}
[Route("rates")]
[HttpGet]
[BitpayAPIConstraint]
public async Task<IActionResult> GetRates(string currencyPairs, string storeId = null, CancellationToken cancellationToken = default)
{
var result = await GetRates2(currencyPairs, storeId, cancellationToken);
var rates = (result as JsonResult)?.Value as Rate[];
if (rates == null)
return result;
return Json(new DataWrapper<Rate[]>(rates));
}
[Route("api/rates")]
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> GetRates2(string currencyPairs, string storeId, CancellationToken cancellationToken)
{
var store = this.CurrentStore ?? await this._StoreRepo.FindStore(storeId);
if (store == null)
{
var err = Json(new BitpayErrorsModel() { Error = "Store not found" });
err.StatusCode = 404;
return err;
}
if (currencyPairs == null)
{
currencyPairs = store.GetStoreBlob().GetDefaultCurrencyPairString();
if (string.IsNullOrEmpty(currencyPairs))
{
var result = Json(new BitpayErrorsModel() { Error = "You need to setup the default currency pairs in 'Store Settings / Rates' or specify 'currencyPairs' query parameter (eg. BTC_USD,LTC_CAD)." });
result.StatusCode = 400;
return result;
}
}
var rules = store.GetStoreBlob().GetRateRules(_NetworkProvider);
HashSet<CurrencyPair> pairs = new HashSet<CurrencyPair>();
foreach (var currency in currencyPairs.Split(','))
{
if (!CurrencyPair.TryParse(currency, out var pair))
{
var result = Json(new BitpayErrorsModel() { Error = $"Currency pair {currency} uncorrectly formatted" });
result.StatusCode = 400;
return result;
}
pairs.Add(pair);
}
var fetching = _RateProviderFactory.FetchRates(pairs, rules, cancellationToken);
await Task.WhenAll(fetching.Select(f => f.Value).ToArray());
return Json(pairs
.Select(r => (Pair: r, Value: fetching[r].GetAwaiter().GetResult().BidAsk?.Bid))
.Where(r => r.Value.HasValue)
.Select(r =>
new Rate()
{
CryptoCode = r.Pair.Left,
Code = r.Pair.Right,
CurrencyPair = r.Pair.ToString(),
Name = _CurrencyNameTable.GetCurrencyData(r.Pair.Right, true).Name,
Value = r.Value.Value
}).Where(n => n.Name != null).ToArray());
}
private static string BuildCurrencyPairs(IEnumerable<string> currencyCodes, string baseCrypto)
{
StringBuilder currencyPairsBuilder = new StringBuilder();
bool first = true;
foreach (var currencyCode in currencyCodes)
{
if (!first)
currencyPairsBuilder.Append(',');
first = false;
currencyPairsBuilder.Append(CultureInfo.InvariantCulture, $"{baseCrypto}_{currencyCode}");
}
return currencyPairsBuilder.ToString();
}
public class Rate
{
[JsonProperty(PropertyName = "name")]
public string Name
{
get;
set;
}
[JsonProperty(PropertyName = "cryptoCode")]
public string CryptoCode
{
get;
set;
}
[JsonProperty(PropertyName = "currencyPair")]
public string CurrencyPair
{
get;
set;
}
[JsonProperty(PropertyName = "code")]
public string Code
{
get;
set;
}
[JsonProperty(PropertyName = "rate")]
public decimal Value
{
get;
set;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Security;
using System.Text;
using System.Xml;
namespace Microsoft.Build.BuildEngine.Shared
{
/// <remarks>
/// An enumeration defining the different types of projects we might find in an SLN.
/// </remarks>
internal enum SolutionProjectType
{
Unknown, // Everything else besides the below well-known project types.
ManagedProject, // C#, VB, and VJ# projects
VCProject, // VC projects, managed and unmanaged
SolutionFolder, // Not really a project, but persisted as such in the .SLN file.
WebProject, // Venus projects
EtpSubProject // Project inside an Enterprise Template project
}
internal struct AspNetCompilerParameters
{
internal string aspNetVirtualPath; // For Venus projects only, Virtual path for web
internal string aspNetPhysicalPath; // For Venus projects only, Physical path for web
internal string aspNetTargetPath; // For Venus projects only, Target for output files
internal string aspNetForce; // For Venus projects only, Force overwrite of target
internal string aspNetUpdateable; // For Venus projects only, compiled web application is updateable
internal string aspNetDebug; // For Venus projects only, generate symbols, etc.
internal string aspNetKeyFile; // For Venus projects only, strong name key file.
internal string aspNetKeyContainer; // For Venus projects only, strong name key container.
internal string aspNetDelaySign; // For Venus projects only, delay sign strong name.
internal string aspNetAPTCA; // For Venus projects only, AllowPartiallyTrustedCallers.
internal string aspNetFixedNames; // For Venus projects only, generate fixed assembly names.
}
/// <remarks>
/// This class represents a project (or SLN folder) that is read in from a solution file.
/// </remarks>
internal sealed class ProjectInSolution
{
#region Constants
/// <summary>
/// Characters that need to be cleansed from a project name.
/// </summary>
private static readonly char[] charsToCleanse = { '%', '$', '@', ';', '.', '(', ')', '\'' };
/// <summary>
/// Project names that need to be disambiguated when forming a target name
/// </summary>
internal static readonly string[] projectNamesToDisambiguate = { "Build", "Rebuild", "Clean", "Publish" };
/// <summary>
/// Character that will be used to replace 'unclean' ones.
/// </summary>
private const char cleanCharacter = '_';
#endregion
#region Member data
private SolutionProjectType projectType; // For example, ManagedProject, VCProject, WebProject, etc.
private string projectName; // For example, "WindowsApplication1"
private string relativePath; // Relative from .SLN file. For example, "WindowsApplication1\WindowsApplication1.csproj"
private string projectGuid; // The unique Guid assigned to this project or SLN folder.
private ArrayList dependencies; // A list of strings representing the Guids of the dependent projects.
private ArrayList projectReferences; // A list of strings representing the guids of referenced projects.
// This is only used for VC/Venus projects
private string parentProjectGuid; // If this project (or SLN folder) is within a SLN folder, this is the Guid of the parent SLN folder.
private string uniqueProjectName; // For example, "MySlnFolder\MySubSlnFolder\WindowsApplication1"
private Hashtable aspNetConfigurations; // Key is configuration name, value is [struct] AspNetCompilerParameters
private SolutionParser parentSolution; // The parent solution for this project
private int dependencyLevel; // the dependency level of this project. 0 means no dependencies on other projects.
private bool isStaticLibrary; // for VCProjects, is this project a static library?
private bool childReferencesGathered; // Have we gathered the complete set of references for this project?
/// <summary>
/// The project configuration in given solution configuration
/// K: full solution configuration name (cfg + platform)
/// V: project configuration
/// </summary>
private Dictionary<string, ProjectConfigurationInSolution> projectConfigurations;
#endregion
#region Constructors
internal ProjectInSolution(SolutionParser solution)
{
projectType = SolutionProjectType.Unknown;
projectName = null;
relativePath = null;
projectGuid = null;
dependencies = new ArrayList();
projectReferences = new ArrayList();
parentProjectGuid = null;
uniqueProjectName = null;
parentSolution = solution;
dependencyLevel = ProjectInSolution.DependencyLevelUnknown;
isStaticLibrary = false;
childReferencesGathered = false;
// This hashtable stores a AspNetCompilerParameters struct for each configuration name supported.
aspNetConfigurations = new Hashtable(StringComparer.OrdinalIgnoreCase);
projectConfigurations = new Dictionary<string, ProjectConfigurationInSolution>(StringComparer.OrdinalIgnoreCase);
}
#endregion
#region Properties
internal SolutionProjectType ProjectType
{
get { return projectType; }
set { projectType = value; }
}
internal string ProjectName
{
get { return projectName; }
set { projectName = value; }
}
internal string RelativePath
{
get { return relativePath; }
set { relativePath = value; }
}
/// <summary>
/// Returns the absolute path for this project
/// </summary>
/// <returns></returns>
/// <owner>LukaszG</owner>
internal string AbsolutePath
{
get
{
return Path.Combine(this.ParentSolution.SolutionFileDirectory, this.RelativePath);
}
}
internal string ProjectGuid
{
get { return projectGuid; }
set { projectGuid = value; }
}
internal ArrayList Dependencies
{
get { return dependencies; }
}
internal ArrayList ProjectReferences
{
get { return projectReferences; }
}
internal string ParentProjectGuid
{
get { return parentProjectGuid; }
set { parentProjectGuid = value; }
}
internal SolutionParser ParentSolution
{
get { return parentSolution; }
set { parentSolution = value; }
}
internal Hashtable AspNetConfigurations
{
get { return aspNetConfigurations; }
set { aspNetConfigurations = value; }
}
internal Dictionary<string, ProjectConfigurationInSolution> ProjectConfigurations
{
get { return this.projectConfigurations; }
}
internal int DependencyLevel
{
get { return this.dependencyLevel; }
set { this.dependencyLevel = value; }
}
internal bool IsStaticLibrary
{
get { return this.isStaticLibrary; }
set { this.isStaticLibrary = value; }
}
internal bool ChildReferencesGathered
{
get { return this.childReferencesGathered; }
set { this.childReferencesGathered = value; }
}
#endregion
#region Methods
private bool checkedIfCanBeMSBuildProjectFile = false;
private bool canBeMSBuildProjectFile;
private string canBeMSBuildProjectFileErrorMessage;
/// <summary>
/// Looks at the project file node and determines (roughly) if the project file is in the MSBuild format.
/// The results are cached in case this method is called multiple times.
/// </summary>
/// <param name="errorMessage">Detailed error message in case we encounter critical problems reading the file</param>
/// <returns></returns>
internal bool CanBeMSBuildProjectFile(out string errorMessage)
{
if (checkedIfCanBeMSBuildProjectFile)
{
errorMessage = canBeMSBuildProjectFileErrorMessage;
return canBeMSBuildProjectFile;
}
checkedIfCanBeMSBuildProjectFile = true;
canBeMSBuildProjectFile = false;
errorMessage = null;
try
{
// Load the project file and get the first node
XmlDocument projectDocument = new XmlDocument();
projectDocument.Load(this.AbsolutePath);
XmlElement mainProjectElement = null;
// The XML parser will guarantee that we only have one real root element,
// but we need to find it amongst the other types of XmlNode at the root.
foreach (XmlNode childNode in projectDocument.ChildNodes)
{
if (XmlUtilities.IsXmlRootElement(childNode))
{
mainProjectElement = (XmlElement)childNode;
break;
}
}
if (mainProjectElement != null && mainProjectElement.LocalName == "Project")
{
if (String.Compare(mainProjectElement.NamespaceURI, XMakeAttributes.defaultXmlNamespace, StringComparison.OrdinalIgnoreCase) == 0)
{
canBeMSBuildProjectFile = true;
return canBeMSBuildProjectFile;
}
}
}
// catch all sorts of exceptions - if we encounter any problems here, we just assume the project file is not
// in the MSBuild format
// handle errors in path resolution
catch (SecurityException e)
{
canBeMSBuildProjectFileErrorMessage = e.Message;
}
// handle errors in path resolution
catch (NotSupportedException e)
{
canBeMSBuildProjectFileErrorMessage = e.Message;
}
// handle errors in loading project file
catch (IOException e)
{
canBeMSBuildProjectFileErrorMessage = e.Message;
}
// handle errors in loading project file
catch (UnauthorizedAccessException e)
{
canBeMSBuildProjectFileErrorMessage = e.Message;
}
// handle XML parsing errors (when reading project file)
// this is not critical, since the project file doesn't have to be in XML formal
catch (XmlException)
{
}
errorMessage = canBeMSBuildProjectFileErrorMessage;
return canBeMSBuildProjectFile;
}
/// <summary>
/// Find the unique name for this project, e.g. SolutionFolder\SubSolutionFolder\ProjectName
/// </summary>
/// <owner>RGoel</owner>
internal string GetUniqueProjectName()
{
if (this.uniqueProjectName == null)
{
// EtpSubProject and Venus projects have names that are already unique. No need to prepend the SLN folder.
if ((this.ProjectType == SolutionProjectType.WebProject) || (this.ProjectType == SolutionProjectType.EtpSubProject))
{
this.uniqueProjectName = CleanseProjectName(this.ProjectName);
}
else
{
// This is "normal" project, which in this context means anything non-Venus and non-EtpSubProject.
// If this project has a parent SLN folder, first get the full unique name for the SLN folder,
// and tack on trailing backslash.
string uniqueName = String.Empty;
if (this.ParentProjectGuid != null)
{
ProjectInSolution proj = (ProjectInSolution)this.ParentSolution.ProjectsByGuid[this.ParentProjectGuid];
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(proj != null, "SubCategoryForSolutionParsingErrors",
new BuildEventFileInfo(parentSolution.SolutionFile), "SolutionParseNestedProjectError");
uniqueName = proj.GetUniqueProjectName() + "\\";
}
// Now tack on our own project name, and cache it in the ProjectInSolution object for future quick access.
this.uniqueProjectName = CleanseProjectName(uniqueName + this.ProjectName);
}
}
return this.uniqueProjectName;
}
/// <summary>
/// Cleanse the project name, by replacing characters like '@', '$' with '_'
/// </summary>
/// <param name="projectName">The name to be cleansed</param>
/// <returns>string</returns>
/// <owner>KieranMo</owner>
static private string CleanseProjectName(string projectName)
{
ErrorUtilities.VerifyThrow(projectName != null, "Null strings not allowed.");
// If there are no special chars, just return the original string immediately.
// Don't even instantiate the StringBuilder.
int indexOfChar = projectName.IndexOfAny(charsToCleanse);
if (indexOfChar == -1)
{
return projectName;
}
// This is where we're going to work on the final string to return to the caller.
StringBuilder cleanProjectName = new StringBuilder(projectName);
// Replace each unclean character with a clean one
foreach (char uncleanChar in charsToCleanse)
{
cleanProjectName.Replace(uncleanChar, cleanCharacter);
}
return cleanProjectName.ToString();
}
/// <summary>
/// If the unique project name provided collides with one of the standard Solution project
/// entry point targets (Build, Rebuild, Clean, Publish), then disambiguate it by prepending the string "Solution:"
/// </summary>
/// <param name="uniqueProjectName">The unique name for the project</param>
/// <returns>string</returns>
/// <owner>KieranMo</owner>
static internal string DisambiguateProjectTargetName(string uniqueProjectName)
{
// Test our unique project name against those names that collide with Solution
// entry point targets
foreach (string projectName in projectNamesToDisambiguate)
{
if (String.Compare(uniqueProjectName, projectName, StringComparison.OrdinalIgnoreCase) == 0)
{
// Prepend "Solution:" so that the collision is resolved, but the
// log of the solution project still looks reasonable.
return "Solution:" + uniqueProjectName;
}
}
return uniqueProjectName;
}
#endregion
#region Constants
internal const int DependencyLevelUnknown = -1;
internal const int DependencyLevelBeingDetermined = -2;
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.